diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..bd83c3f64 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,457 @@ +name: CI + +on: + push: + paths-ignore: + - 'CHANGES*' + - 'Doc/**' + - 'appveyor.yml' + pull_request: + branches: master + paths-ignore: + - 'CHANGES*' + - 'Doc/**' + - 'appveyor.yml' + +jobs: + build: + + # When continue-on-error is true for an individual build, that build can fail (it'll show red), + # but it won't fail the overall build + continue-on-error: ${{ matrix.continue-on-error || false }} + + runs-on: ${{ matrix.os || 'ubuntu-20.04' }} + + # By default, the name of the build is the language used and SWIG options, but matrix entries + # can define the additional "desc" field with any additional information to include in the name. + name: ${{ matrix.SWIGLANG || 'none' }}${{ matrix.PY3 }} ${{ matrix.ENGINE}} ${{ matrix.VER }} ${{ matrix.SWIG_FEATURES }} ${{ (matrix.compiler || 'gcc') }}${{ matrix.GCC }} ${{ matrix.CPPSTD }} ${{ matrix.CSTD }} ${{ matrix.desc }} ${{ matrix.continue-on-error && '(can fail)' }} + + strategy: + matrix: + include: + - SWIGLANG: "" + - SWIGLANG: "" + GCC: 7 + - SWIGLANG: "" + GCC: 8 + - SWIGLANG: "" + GCC: 9 + - SWIGLANG: "" + GCC: 10 + - SWIGLANG: "" + GCC: 11 + - SWIGLANG: "" + compiler: clang + - SWIGLANG: csharp + # D support can't be enabled because dmd 2.066 fails to build anything + # under Ubuntu 18.04 due to its standard library (libphobos2.a) not + # being compiled with -FPIC, but system gcc using -fpie by default, + # resulting in linking errors for any output. And later versions, such + # as 2.086.1, are not supported and result in errors in SWIG test suite. + # + # - SWIGLANG: d + # VER: '2.066.0' + # os: ubuntu-18.04 # This dlang version doesn't work under 20.04. + - SWIGLANG: go + VER: '1.6' + CSTD: gnu11 + - SWIGLANG: go + VER: '1.8' + - SWIGLANG: go + VER: '1.12' + CSTD: gnu11 + - SWIGLANG: go + VER: '1.17' + - SWIGLANG: guile + - SWIGLANG: java + - SWIGLANG: javascript + ENGINE: node + VER: '6' + CPPSTD: c++11 + os: ubuntu-18.04 + - SWIGLANG: javascript + ENGINE: node + VER: '8' + CPPSTD: c++11 + os: ubuntu-18.04 + - SWIGLANG: javascript + ENGINE: node + VER: '10' + CPPSTD: c++11 + os: ubuntu-18.04 + - SWIGLANG: javascript + ENGINE: node + VER: '12' + CPPSTD: c++11 + - SWIGLANG: javascript + ENGINE: node + VER: '17' + CPPSTD: c++14 + - SWIGLANG: javascript + ENGINE: jsc + - SWIGLANG: lua + - SWIGLANG: lua + VER: '5.3' + - SWIGLANG: octave + CPPSTD: c++11 + - SWIGLANG: octave + VER: '6.4' + CPPSTD: c++11 + - SWIGLANG: perl5 + - SWIGLANG: php + VER: '7.0' + - SWIGLANG: php + VER: '7.1' + - SWIGLANG: php + VER: '7.2' + - SWIGLANG: php + VER: '7.3' + - SWIGLANG: php + VER: '7.4' + - SWIGLANG: php + - SWIGLANG: php + VER: '8.1' + - SWIGLANG: python + - SWIGLANG: python + PY3: 3 + VER: '3.2' + os: ubuntu-18.04 # Python < 3.5 not available for 20.04. + - SWIGLANG: python + PY3: 3 + VER: '3.3' + os: ubuntu-18.04 # Python < 3.5 not available for 20.04. + - SWIGLANG: python + PY3: 3 + VER: '3.4' + os: ubuntu-18.04 # Python < 3.5 not available for 20.04. + - SWIGLANG: python + PY3: 3 + VER: '3.5' + - SWIGLANG: python + PY3: 3 + VER: '3.6' + - SWIGLANG: python + PY3: 3 + VER: '3.7' + - SWIGLANG: python + PY3: 3 + VER: '3.8' + - SWIGLANG: python + PY3: 3 + VER: '3.9' + - SWIGLANG: python + PY3: 3 + VER: '3.10' + - SWIGLANG: python + SWIG_FEATURES: -builtin + - SWIGLANG: python + SWIG_FEATURES: -builtin -O + - SWIGLANG: python + PY3: 3 + SWIG_FEATURES: -builtin + - SWIGLANG: python + PY3: 3 + SWIG_FEATURES: -builtin -O + - SWIGLANG: r + - SWIGLANG: ruby + VER: '1.9' + os: ubuntu-18.04 + - SWIGLANG: ruby + VER: '2.0' + os: ubuntu-18.04 + - SWIGLANG: ruby + VER: '2.1' + os: ubuntu-18.04 + - SWIGLANG: ruby + VER: '2.2' + os: ubuntu-18.04 + - SWIGLANG: ruby + VER: '2.3' + os: ubuntu-18.04 + - SWIGLANG: ruby + VER: '2.4' + - SWIGLANG: ruby + VER: '2.5' + - SWIGLANG: ruby + VER: '2.6' + - SWIGLANG: ruby + VER: '2.7' + - SWIGLANG: ruby + VER: '3.0' + CPPSTD: c++11 + - SWIGLANG: scilab + VER: '5.5.2' + - SWIGLANG: scilab + os: ubuntu-18.04 # scilab 6.0 + - SWIGLANG: scilab + - SWIGLANG: tcl + # c++11 testing + - SWIGLANG: csharp + CPPSTD: c++11 + - SWIGLANG: go + VER: '1.17' + CPPSTD: c++11 + CSTD: gnu11 + - SWIGLANG: guile + CPPSTD: c++11 + - SWIGLANG: java + CPPSTD: c++11 + - SWIGLANG: javascript + ENGINE: node + VER: '14' + CPPSTD: c++11 + - SWIGLANG: lua + CPPSTD: c++11 + - SWIGLANG: perl5 + CPPSTD: c++11 + - SWIGLANG: php + CPPSTD: c++11 + CSTD: gnu11 + - SWIGLANG: python + CPPSTD: c++11 + PY3: 3 + - SWIGLANG: r + CPPSTD: c++11 + - SWIGLANG: ruby + CPPSTD: c++11 + - SWIGLANG: scilab + CPPSTD: c++11 + - SWIGLANG: tcl + CPPSTD: c++11 + # c++14 testing + - SWIGLANG: csharp + CPPSTD: c++14 + - SWIGLANG: go + VER: '1.17' + CPPSTD: c++14 + CSTD: gnu11 + - SWIGLANG: guile + CPPSTD: c++14 + - SWIGLANG: java + CPPSTD: c++14 + - SWIGLANG: javascript + ENGINE: node + VER: '16' + CPPSTD: c++14 + - SWIGLANG: lua + CPPSTD: c++14 + - SWIGLANG: octave + CPPSTD: c++14 + - SWIGLANG: perl5 + CPPSTD: c++14 + - SWIGLANG: php + CPPSTD: c++14 + CSTD: gnu11 + - SWIGLANG: python + CPPSTD: c++14 + PY3: 3 + - SWIGLANG: r + CPPSTD: c++14 + - SWIGLANG: ruby + CPPSTD: c++14 + - SWIGLANG: scilab + CPPSTD: c++14 + - SWIGLANG: tcl + CPPSTD: c++14 + # c++17 testing (using gcc11) + - SWIGLANG: csharp + CPPSTD: c++17 + GCC: 11 + - SWIGLANG: go + VER: '1.17' + CPPSTD: c++17 + GCC: 11 + CSTD: gnu17 + - SWIGLANG: guile + CPPSTD: c++17 + GCC: 11 + - SWIGLANG: java + CPPSTD: c++17 + GCC: 11 + - SWIGLANG: javascript + ENGINE: node + VER: '17' + CPPSTD: c++17 + GCC: 11 + - SWIGLANG: lua + CPPSTD: c++17 + GCC: 11 + - SWIGLANG: octave + CPPSTD: c++17 + GCC: 11 + - SWIGLANG: perl5 + CPPSTD: c++17 + GCC: 11 + - SWIGLANG: php + CPPSTD: c++17 + CSTD: gnu17 + GCC: 11 + - SWIGLANG: python + CPPSTD: c++17 + GCC: 11 + PY3: 3 + - SWIGLANG: r + CPPSTD: c++17 + GCC: 11 + - SWIGLANG: ruby + CPPSTD: c++17 + GCC: 11 + - SWIGLANG: scilab + CPPSTD: c++17 + GCC: 11 + - SWIGLANG: tcl + CPPSTD: c++17 + GCC: 11 + # Experimental languages (these are allowed to fail) + - SWIGLANG: mzscheme + continue-on-error: true + - SWIGLANG: ocaml + continue-on-error: true + os: ubuntu-18.04 # ocaml-4.08 in ubuntu-20.04 not yet working + # Run all of them, as opposed to aborting when one fails + fail-fast: false + + env: + SWIGLANG: ${{ matrix.SWIGLANG }} + PY3: ${{ matrix.PY3 }} + VER: ${{ matrix.VER }} + ENGINE: ${{ matrix.ENGINE }} + SWIG_FEATURES: ${{ matrix.SWIG_FEATURES }} + GCC: ${{ matrix.GCC }} + CSTD: ${{ matrix.CSTD }} + CPPSTD: ${{ matrix.CPPSTD }} + + steps: + - name: Checkout + uses: actions/checkout@v2 + with: + submodules: recursive + + - name: Install CCache + uses: hendrikmuhs/ccache-action@v1 + with: + key: ${{ matrix.os || 'ubuntu-20.04' }}-${{ matrix.compiler || 'gcc' }}${{ matrix.GCC }} + +# Uncomment to debug via ssh, see https://github.com/mxschmitt/action-tmate +# - name: Setup tmate session +# uses: mxschmitt/action-tmate@v3 + + - name: Install Dependencies + run: | + set -x + export PATH="/usr/lib/ccache:/usr/local/opt/ccache/libexec:$PATH" + echo PATH="$PATH" >> $GITHUB_ENV + + source $GITHUB_WORKSPACE/Tools/GHA-linux-install.sh + echo WITHLANG="$WITHLANG" >> $GITHUB_ENV + + case $(uname) in + Linux) + cpu_count=$(nproc) + ;; + + Darwin) + cpu_count=$(sysctl -n hw.ncpu) + ;; + + *) + cpu_count=1 + ;; + esac + + if [[ $cpu_count != 1 ]]; then + echo SWIGJOBS=-j$cpu_count >> $GITHUB_ENV + fi + + if test '${{ matrix.compiler }}' = 'clang'; then + CC="clang" + CXX="clang++" + + CFLAGS="$CFLAGS -fPIE" + CXXFLAGS="$CXXFLAGS -fPIE" + elif test -n "$GCC"; then + CC="gcc-$GCC" + CXX="g++-$GCC" + else + CC="gcc" + CXX="g++" + fi + + export CC CXX + + echo CC="$CC" >> $GITHUB_ENV + echo CXX="$CXX" >> $GITHUB_ENV + + ls -la $(which $CC) $(which $CXX) + $CC --version + $CXX --version + + - name: Configure + run: | + source $GITHUB_WORKSPACE/Tools/CI-linux-environment.sh + set -x + + if [[ -z "$CSTD" ]]; then + case "$CPPSTD" in + c++11) export CSTD=c11 ;; + c++14) export CSTD=c11 ;; + c++17) export CSTD=c17 ;; + esac + echo CSTD="$CSTD" >> $GITHUB_ENV + fi + if test -n "$CPPSTD"; then CONFIGOPTS+=(--enable-cpp11-testing "CXXFLAGS=-std=$CPPSTD $CXXFLAGS"); fi + if test -n "$CSTD"; then CONFIGOPTS+=("CFLAGS=-std=$CSTD $CFLAGS"); fi + if test -n "$SWIGLANG"; then CONFIGOPTS+=(--without-alllang --with-$WITHLANG); fi + echo "${CONFIGOPTS[@]}" + ./autogen.sh && mkdir -p build/build && cd build/build && ../../configure "${CONFIGOPTS[@]}" + + - name: Build + working-directory: build/build + run: | + set -x + make -s $SWIGJOBS + ./swig -version && ./swig -pcreversion + + - name: Test + working-directory: build/build + run: | + source $GITHUB_WORKSPACE/Tools/CI-linux-environment.sh + set -x + + if test -z "$SWIGLANG"; then + make $SWIGJOBS check-ccache + make $SWIGJOBS check-errors-test-suite + else + case "$SWIGLANG" in + javascript) + case "$ENGINE" in + v8 | jsc) + # Running tests using v8 or jsc involves creating a custom + # interpreter in Tools/javascript, which is currently broken + # for parallel builds (we attempt to update this interpreter + # while running, resulting in "Text file busy" error). + unset SWIGJOBS + esac + ;; + esac + + # Stricter compile flags for examples. Various headers and SWIG generated code prevents full use of -pedantic. + cflags=$($GITHUB_WORKSPACE/Tools/testflags.py --language $SWIGLANG --cflags --std=$CSTD --compiler=$CC) + cxxflags=$($GITHUB_WORKSPACE/Tools/testflags.py --language $SWIGLANG --cxxflags --std=$CPPSTD --compiler=$CC) + make check-$SWIGLANG-version + make check-$SWIGLANG-enabled + make $SWIGJOBS check-$SWIGLANG-examples CFLAGS="$cflags" CXXFLAGS="$cxxflags" + make $SWIGJOBS check-$SWIGLANG-test-suite CFLAGS="$cflags" CXXFLAGS="$cxxflags" + fi + + - name: Install + working-directory: build/build + run: | + set -x + if test -z "$SWIGLANG"; then sudo make install && swig -version && ccache-swig -V; fi + + - name: Clean + working-directory: build/build + run: | + set -x + make check-maintainer-clean && ../../configure diff --git a/.gitignore b/.gitignore index 5df510547..b51da0fdf 100644 --- a/.gitignore +++ b/.gitignore @@ -150,6 +150,8 @@ Examples/guile/*/my-guile # Java Examples/test-suite/java/*/ +Examples/test-suite/java/expected.txt +Examples/test-suite/java/got.txt Examples/java/*/*.java !Examples/java/*/runme.java Examples/java/doxygen/javadocs @@ -182,11 +184,8 @@ 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 +Examples/php/pragmas/example.php # Python # Based on https://github.com/github/gitignore/blob/master/Python.gitignore diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index b806c85e0..000000000 --- a/.travis.yml +++ /dev/null @@ -1,536 +0,0 @@ -language: cpp -matrix: - include: - - compiler: clang - os: linux - env: SWIGLANG= - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG= - sudo: required - dist: xenial - - os: linux - env: SWIGLANG= GCC=4.4 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG= GCC=4.6 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG= GCC=4.7 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG= GCC=4.8 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG= GCC=4.9 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG= GCC=6 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG= GCC=7 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG= GCC=8 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG= GCC=9 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=csharp - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=d VER=2.066.0 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=d VER=2.086.1 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=go VER=1.3 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=go VER=1.8 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=go VER=1.12 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=guile - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=java - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=javascript ENGINE=node VER=0.10 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=javascript ENGINE=node VER=4 CPP11=1 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=javascript ENGINE=node VER=6 CPP11=1 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=javascript ENGINE=node VER=8 CPP11=1 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=javascript ENGINE=node VER=10 CPP11=1 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=javascript ENGINE=jsc - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=javascript ENGINE=v8 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=lua - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=lua VER=5.3 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=mzscheme - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=ocaml - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=octave SWIGJOBS=-j2 - sudo: required - dist: xenial # Octave v4.0.0 - - compiler: gcc - os: linux - env: SWIGLANG=octave SWIGJOBS=-j2 CPP11=1 - sudo: required - dist: bionic # Octave v4.2.2 - - compiler: gcc - os: linux - env: SWIGLANG=perl5 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=php VER=7.0 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=php VER=7.1 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=php VER=7.2 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=php VER=7.3 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=python # 2.7 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=python PY3=3 VER=3.2 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=python PY3=3 VER=3.3 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=python PY3=3 VER=3.4 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=python PY3=3 VER=3.5 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=python PY3=3 VER=3.6 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=python PY3=3 VER=3.7 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=python PY3=3 VER=3.8 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=python SWIG_FEATURES=-builtin - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=python SWIG_FEATURES="-builtin -O" - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=python SWIG_FEATURES=-builtin GCC=6 CPP11=1 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=python SWIG_FEATURES=-builtin GCC=6 CPP11=1 PY3=3 VER=3.8 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=python SWIG_FEATURES=-builtin PY3=3 VER=3.4 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=python SWIG_FEATURES=-builtin PY3=3 VER=3.5 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=python SWIG_FEATURES=-builtin PY3=3 VER=3.7 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=python SWIG_FEATURES=-builtin PY3=3 VER=3.8 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=python SWIG_FEATURES="-builtin -O" PY3=3 VER=3.8 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=python SWIG_FEATURES=-builtin PY3=3 VER=3.8 SWIGOPTPY3= - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=python SWIG_FEATURES=-O - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=python SWIG_FEATURES=-O PY3=3 VER=3.8 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=r - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=ruby VER=1.9 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=ruby VER=2.0 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=ruby VER=2.1 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=ruby VER=2.2 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=ruby VER=2.3 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=ruby VER=2.4 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=ruby VER=2.5 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=ruby VER=2.6 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=ruby VER=2.7 - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=scilab - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=tcl - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=csharp CPP11=1 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=go VER=1.6 CPP11=1 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=java CPP11=1 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=python CPP11=1 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=r CPP11=1 # Note: making 'R CMD SHLIB' use a different compiler is non-trivial - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=ruby CPP11=1 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=tcl CPP11=1 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=csharp GCC=6 CPP14=1 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=go VER=1.6 GCC=6 CPP14=1 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=java GCC=6 CPP14=1 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=python GCC=6 CPP14=1 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=ruby GCC=6 CPP14=1 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=tcl GCC=6 CPP14=1 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=java GCC=7 CPP14=1 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=python GCC=7 CPP14=1 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=csharp GCC=8 CPP17=1 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=java GCC=8 CPP17=1 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=python GCC=8 CPP17=1 PY3=3 VER=3.8 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=csharp GCC=9 CPP17=1 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=java GCC=9 CPP17=1 - sudo: required - dist: xenial - - os: linux - env: SWIGLANG=python GCC=9 CPP17=1 PY3=3 VER=3.8 - sudo: required - dist: xenial - - os: linux - arch: s390x - env: SWIGLANG=ruby CPP11=1 - sudo: required - dist: xenial - - compiler: gcc - os: osx - env: SWIGLANG= - - compiler: clang - os: osx - env: SWIGLANG= - - compiler: clang - os: osx - env: SWIGLANG=csharp - - compiler: clang - os: osx - env: SWIGLANG=go - - compiler: clang - os: osx - env: SWIGLANG=guile CSTD=c11 - - compiler: clang - os: osx - env: SWIGLANG=java - - compiler: clang - os: osx - env: SWIGLANG=lua - - compiler: clang - os: osx - env: SWIGLANG=octave SWIGJOBS=-j2 CPP11=1 - - compiler: clang - os: osx - env: SWIGLANG=perl5 - - compiler: clang - os: osx - env: SWIGLANG=python - - compiler: clang - os: osx - env: SWIGLANG=python PY3=3 - - compiler: clang - os: osx - env: SWIGLANG=ruby - - compiler: clang - os: osx - env: SWIGLANG=tcl - - compiler: clang - os: osx - env: SWIGLANG=java CPP17=1 - osx_image: xcode10.2 - - compiler: clang - os: osx - env: SWIGLANG=python PY3=3 CPP17=1 - osx_image: xcode10.2 - - allow_failures: - # Newer version of D not yet working/supported - - compiler: gcc - os: linux - env: SWIGLANG=d VER=2.086.1 - sudo: required - dist: xenial - # seg fault in director_basic testcase - - compiler: gcc - os: linux - env: SWIGLANG=php VER=7.2 - sudo: required - dist: xenial - # Experimental languages - - compiler: gcc - os: linux - env: SWIGLANG=mzscheme - sudo: required - dist: xenial - - compiler: gcc - os: linux - env: SWIGLANG=ocaml - sudo: required - dist: xenial - -before_install: - - date -u - - uname -a - - if test "$TRAVIS_OS_NAME" = "linux"; then lscpu; grep "model name" /proc/cpuinfo || echo 'Unknown CPU model'; grep "MemTotal" /proc/meminfo || echo 'Unknown system memory amount'; fi - - if test "$TRAVIS_OS_NAME" = "osx"; then sysctl -a | grep brand_string; fi - # Travis overrides CC environment with compiler predefined values - - if test -n "$GCC"; then export CC="gcc-$GCC" && export CXX="g++-$GCC"; fi -install: - - if test "$TRAVIS_OS_NAME" = "linux"; then source Tools/travis-linux-install.sh; fi - - if test "$TRAVIS_OS_NAME" = "osx"; then source Tools/travis-osx-install.sh; fi - - ls -la $(which $CC) $(which $CXX) && $CC --version && $CXX --version -script: - - echo 'Configuring...' && echo -en 'travis_fold:start:script.1\\r' - - 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 - - if test -n "$CPP17"; then CONFIGOPTS+=(--enable-cpp11-testing --without-maximum-compile-warnings "CXXFLAGS=-std=c++17 -Wall -Wextra" "CFLAGS=-std=c17 -Wall -Wextra") && export CSTD=c17 && export CPPSTD=c++17; fi - - if test -n "$SWIGLANG"; then CONFIGOPTS+=(--without-alllang --with-$WITHLANG); fi - - 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 - - if test -z "$SWIGLANG"; then make -s $SWIGJOBS check-ccache; fi - - if test -z "$SWIGLANG"; then make -s $SWIGJOBS check-errors-test-suite; fi - - echo 'Installing...' && echo -en 'travis_fold:start:script.2\\r' - - if test -z "$SWIGLANG"; then sudo make -s install && swig -version && ccache-swig -V; fi - - echo -en 'travis_fold:end:script.2\\r' - # Stricter compile flags for examples. Various headers and SWIG generated code prevents full use of -pedantic. - - if test -n "$SWIGLANG"; then cflags=$($TRAVIS_BUILD_DIR/Tools/testflags.py --language $SWIGLANG --cflags --std=$CSTD --compiler=$CC) && echo $cflags; fi - - if test -n "$SWIGLANG"; then cxxflags=$($TRAVIS_BUILD_DIR/Tools/testflags.py --language $SWIGLANG --cxxflags --std=$CPPSTD --compiler=$CC) && echo $cxxflags; fi - - if test -n "$SWIGLANG"; then make -s check-$SWIGLANG-version; fi - - if test -n "$SWIGLANG"; then make check-$SWIGLANG-enabled; fi - - if test -n "$SWIGLANG"; then make $SWIGJOBS check-$SWIGLANG-examples CFLAGS="$cflags" CXXFLAGS="$cxxflags"; fi - - if test -n "$SWIGLANG"; then make $SWIGJOBS check-$SWIGLANG-test-suite CFLAGS="$cflags" CXXFLAGS="$cxxflags"; fi - - echo 'Cleaning...' && echo -en 'travis_fold:start:script.3\\r' - - make check-maintainer-clean && ../../configure $CONFIGOPTS - - echo -en 'travis_fold:end:script.3\\r' diff --git a/ANNOUNCE b/ANNOUNCE index e50bcd463..e78be2268 100644 --- a/ANNOUNCE +++ b/ANNOUNCE @@ -25,11 +25,11 @@ Availability ============ The release is available for download on Sourceforge at - http://prdownloads.sourceforge.net/swig/swig-4.1.0.tar.gz + https://prdownloads.sourceforge.net/swig/swig-4.1.0.tar.gz A Windows version is also available at - http://prdownloads.sourceforge.net/swig/swigwin-4.1.0.zip + https://prdownloads.sourceforge.net/swig/swigwin-4.1.0.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/README.swig b/CCache/README.swig index aea0f3d82..82055d146 100644 --- a/CCache/README.swig +++ b/CCache/README.swig @@ -2,7 +2,7 @@ This directory contains a version of ccache. The initial version was based on cc debian patches 01-02, 04-14, see the debian/patches subdirectory. The ccache-win32-2.4 modifications to ccache-2.4 have also been merged in. -Changes have been made to support cacheing the output from SWIG. The ability to cache c/c++ compiler +Changes have been made to support caching the output from SWIG. The ability to cache c/c++ compiler output has been retained. Additional features added are the CCACHE_VERBOSE and CCACHE_SWIG environment variables, see docs. diff --git a/CCache/configure.ac b/CCache/configure.ac index e1c761860..2db3553ce 100644 --- a/CCache/configure.ac +++ b/CCache/configure.ac @@ -1,12 +1,12 @@ dnl Process this file with autoconf to produce a configure script. -AC_INIT([ccache-swig], [0.0]) # Get version from SWIG in ccache_swig_config.h.in -AC_PREREQ(2.52) +AC_INIT([ccache-swig],[0.0]) # Get version from SWIG in ccache_swig_config.h.in +AC_PREREQ([2.60]) AC_CONFIG_SRCDIR([ccache.h]) AC_MSG_NOTICE([Configuring ccache]) -AC_CONFIG_HEADER(config.h) +AC_CONFIG_HEADERS([config.h]) AC_CONFIG_FILES([config_win32.h]) dnl Checks for programs. @@ -41,7 +41,7 @@ else fi AC_HEADER_DIRENT -AC_HEADER_TIME + AC_HEADER_SYS_WAIT AC_CHECK_HEADERS(ctype.h strings.h stdlib.h string.h pwd.h sys/time.h) @@ -51,19 +51,16 @@ AC_CHECK_FUNCS(gethostname getpwuid) AC_CHECK_FUNCS(utimes) AC_CACHE_CHECK([for compar_fn_t in stdlib.h],ccache_cv_COMPAR_FN_T, [ - AC_TRY_COMPILE( -[#include ], -[ + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[ void test_fn(void) { qsort(NULL, 0, 0, (__compar_fn_t)NULL); } -], - ccache_cv_COMPAR_FN_T=yes,ccache_cv_COMPAR_FN_T=no)]) +]])],[ccache_cv_COMPAR_FN_T=yes],[ccache_cv_COMPAR_FN_T=no])]) if test x"$ccache_cv_COMPAR_FN_T" = x"yes"; then AC_DEFINE(HAVE_COMPAR_FN_T, 1, [ ]) fi dnl Note: This could be replaced by AC_FUNC_SNPRINTF() in the autoconf macro archive AC_CACHE_CHECK([for C99 vsnprintf],ccache_cv_HAVE_C99_VSNPRINTF,[ -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include #include void foo(const char *format, ...) { @@ -81,8 +78,7 @@ void foo(const char *format, ...) { exit(0); } main() { foo("hello"); } -], -ccache_cv_HAVE_C99_VSNPRINTF=yes,ccache_cv_HAVE_C99_VSNPRINTF=no,ccache_cv_HAVE_C99_VSNPRINTF=cross)]) +]])],[ccache_cv_HAVE_C99_VSNPRINTF=yes],[ccache_cv_HAVE_C99_VSNPRINTF=no],[ccache_cv_HAVE_C99_VSNPRINTF=cross])]) if test x"$ccache_cv_HAVE_C99_VSNPRINTF" = x"yes"; then AC_DEFINE(HAVE_C99_VSNPRINTF, 1, [ ]) fi diff --git a/CCache/execute.c b/CCache/execute.c index 6df025e95..8c65e0ce0 100644 --- a/CCache/execute.c +++ b/CCache/execute.c @@ -137,7 +137,7 @@ int execute(char **argv, _dup2(fd, 2); _close(fd); - /* Spawn process (_exec* familly doesn't return) */ + /* Spawn process (_exec* family doesn't return) */ status = _spawnv(_P_WAIT, argv[0], (const char **)argv); /* Restore descriptors */ diff --git a/CCache/snprintf.c b/CCache/snprintf.c index 9bf8a817b..1a76c7d1b 100644 --- a/CCache/snprintf.c +++ b/CCache/snprintf.c @@ -16,7 +16,7 @@ * for string length. This covers a nasty loophole. * * The other functions are there to prevent NULL pointers from - * causing nast effects. + * causing nasty effects. * * More Recently: * Brandon Long 9/15/96 for mutt 0.43 @@ -30,7 +30,7 @@ * probably requires libm on most operating systems. Don't yet * support the exponent (e,E) and sigfig (g,G). Also, fmtint() * was pretty badly broken, it just wasn't being exercised in ways - * which showed it, so that's been fixed. Also, formated the code + * which showed it, so that's been fixed. Also, formatted the code * to mutt conventions, and removed dead code left over from the * original. Also, there is now a builtin-test, just compile with: * gcc -DTEST_SNPRINTF -o snprintf snprintf.c -lm diff --git a/CCache/web/index.html b/CCache/web/index.html index 4af839135..bc46916d2 100644 --- a/CCache/web/index.html +++ b/CCache/web/index.html @@ -34,7 +34,7 @@ on the new options.

You can get this release from the download directory -

NOTE! This release changes the hash input slighly, so you will +

NOTE! This release changes the hash input slightly, so you will probably find that you will not get any hits against your existing cache when you upgrade. diff --git a/CHANGES.current b/CHANGES.current index a82db8b04..1dc7709da 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -7,3 +7,552 @@ the issue number to the end of the URL: https://github.com/swig/swig/issues/ Version 4.1.0 (in progress) =========================== +2022-02-27: wsfulton + [Python] #735 #1561 Function annotations containing C/C++ types are no longer + generated when using the -py3 option. Function annotations support has been + moved to a feature to provide finer grained control. It can be turned on + globally by adding: + + %feature("python:annotations", "c"); + + or by using the command line argument: + + -features python:annotations=c + + *** POTENTIAL INCOMPATIBILITY *** + +2022-02-26: wsfulton + #655 #1840 Add new warning WARN_LANG_USING_NAME_DIFFERENT to warn when a + method introduced by a using declaration in a derived class cannot + be used due to a conflict in names. + +2022-02-24: olly + #1465 An invalid preprocessor expression is reported as a pair of + warnings with the second giving a more detailed message from the + expression evaluator. Previously SWIG prefixed the second message + with "Error:" - that was confusing as it's actually only a warning + by default so we've now dropped this prefix. + + Before: + + x.i:1: Warning 202: Could not evaluate expression '1.2' + x.i:1: Warning 202: Error: 'Floating point constant in preprocessor expression' + + Now: + + x.i:1: Warning 202: Could not evaluate expression '1.2' + x.i:1: Warning 202: Floating point constant in preprocessor expression + +2022-02-23: olly + #1384 Fix a preprocessor expression evaluation bug. A + subexpression in parentheses lost its string/int type flag and + instead used whatever type was left in the stack entry from + previous use. In practice we mostly got away with this because + most preprocessor expressions are integer, but it could have + resulted in a preprocessor expression incorrectly evaluating as + zero. If -Wextra was in use you got a warning: + + Warning 202: Error: 'Can't mix strings and integers in expression' + +2022-02-21: davidcl + [Scilab] Improve 5.5.2, 6.0.0 and 6.1.0 support. + + For Scilab 5, long names are reduced to small names preserving the + class prefix and accessor suffix (get or set). + + For Scilab 6, long names with the class prefix and accessor suffix + should be used on the user code. + + The `-targetversion` option has been removed as the generated code + now detects the Scilab version in loader.sce or builder.sce. + + *** POTENTIAL INCOMPATIBILITY *** + +2022-02-20: wsfulton + Fix %warnfilter warning suppress for warning 315 SWIGWARN_PARSE_USING_UNDEF. + +2022-02-17: olly + [PHP] https://sourceforge.net/p/swig/bugs/1211/ + Fix to call cleanup code in exception situations and not to invoke + the freearg typemap twice in certain situations. + +2022-02-15: olly + #300 #368 Improve parser handling of % followed immediately by + an identifier. If it's not a recognised directive the scanner + now emits MODULO and then rescans what follows, and if the parser + then gives a syntax error we report it as an unknown directive. + This means that `a%b` is now allowed in an expression, and that + things like `%std::vector` now give an error rather + than being quietly ignored. + +2022-02-10: olly + [Tcl] https://sourceforge.net/p/swig/bugs/1207/ + https://sourceforge.net/p/swig/bugs/1213/ + + Fix Tcl generic input typemap for std::vector. + +2022-02-07: sethrj + #2196 Add alternative syntax for specifying fragments in typemaps. + + New syntax: + %typemap("in", fragment="frag1", fragment="frag2", fragment="frag3") {...} + which is equivalent to: + %typemap(in, fragment="frag1,frag2,frag3") {...} + + +2022-02-07: olly + #1806 Remove support for the "command" encoder, which was mostly + intended for use in `%rename` - most uses can be achieved using + the "regex" encoder, so we recommend using that instead. + + The "command" encoder suffers from a number of issues - as the + documentation for it admitted, "[it] is extremely slow compared to + all the other [encoders] as it involves spawning a separate process + and using it for many declarations is not recommended" and that it + "should generally be avoided because of performance + considerations". + + But it's also not portable. The design assumes that `/bin/sh` + supports `<<<` but that's a bash-specific feature so it doesn't + work on platforms where `/bin/sh` is not bash - it fails on + Debian, Ubuntu and probably some other Linux distros, plus most + non-Linux platforms. Microsoft Windows doesn't even have a + /bin/sh as standard. + + Finally, no escaping of the passed string is done, so it has + potential security issues (though at least with %rename the input + is limited to valid C/C++ symbol names). + +2022-02-06: olly + #2193 -DFOO on the SWIG command line now sets FOO to 1 for + consistency with C/C++ compiler preprocessors. Previously + SWIG set FOO to an empty value. + +2022-02-06: sethrj + #2194 Classes that are non-assignable due to const data or const + reference members are now automatically detected. + +2022-02-04: friedrichatgc + [Octave] #1672 Fix for isobject for Octave 4.4 - 6.0. + +2022-02-03: olly + [C#] #283 #998 Fix memory leak in directorin typemap for + std::string. + +2022-02-03: olly + [Python] #967 Make `self` parameter available to user typemaps. + +2022-02-03: teythoon + [Python] #801 Fix -Wunused-parameter warnings with builtin, + +2022-02-03: teythoon + #801 Fix -Wstrict-prototypes warnings in generated pointer + functions. + +2022-02-03: olly + #660 https://sourceforge.net/p/swig/bugs/1081/ + Default parameter values containing method calls are now parsed and + handled - e.g. `x->foo(3,4)` and `y.z()`. + +2022-02-02: olly + [Ruby] https://sourceforge.net/p/swig/bugs/1136/ Fix remove of prefix + from method name to only remove it at the start. + +2022-02-01: olly + #231 Handle returning an object by reference in a C++ trailing + return type. + +2022-02-01: davidcl + [Scilab] #745 use SWIG__Init() as a C module init function. + +2022-02-01: olly + [OCaml] #2083 Fix to work when CAML_SAFE_STRING is on, which it is + by default in recent Ocaml releases. + +2022-01-31: mreeez + https://sourceforge.net/p/swig/bugs/1147/ + Fix copyToR() generated for a struct in a namespace. + +2022-01-29: fschlimb + #655 Better handling of using declarations. + +2022-01-29: dontpanic92 + [Go] #676 Fix code generated for a C++ class with a non-capitalised + name. + +2022-01-26: trex58 + #1919 #1921 #1923 Various fixes for AIX portability. + +2022-01-26: olly + #1935 Don't crash on an unclosed HTML tag in a doxygen comment + when -doxygen is specified. + +2022-01-25: olly + Constant expressions now support member access with `.` such as + `foo.bar`. Previous this only worked in a case like `x->foo.bar`. + +2022-01-25: olly + #2091 Support most cases of `sizeof` applied to an expression + in constant expressions. Previously there was only support for + `sizeof()` and expressions which syntactically look like a + type (such as `sizeof(foo)`). + +2022-01-25: olly + #80 #635 https://sourceforge.net/p/swig/bugs/1139/ + Add support for parsing common cases of `<` and `>` comparisons + in constant expressions. Adding full support for these seems hard + to do without introducing conflicts into the parser grammar, but in + fact all reported cases have had parentheses around the comparison + and we can support that with a few restrictions on the left side of + `<`. + +2022-01-25: wsfulton + New warning 327 for extern templates, eg: + + extern template class std::vector; + extern template void Func(); + + results in warning + + example.i:3: Warning 327: Extern template ignored. + example.i:4: Warning 327: Extern template ignored. + + Extern template classes previously resulted in warning 320. + +2022-01-24: romintomasetti + #2131 #2157 C++11 extern function template parsing error fix. + +2022-01-21: wsfulton + #2120 #2138 Replace legacy PCRE dependency with PCRE2. + This requires changes for building SWIG from source. See updated + html documentation in Preface.html and Windows.html. Updated + instructions are also shown when running ./configure if PCRE2 is not + found. Note that debian based systems can install PCRE2 using: + + apt install libpcre2-dev + + Note that https://github.com/swig/swig/wiki/Getting-Started also has + updated information for building from source. + +2022-01-19: olly + [PHP] #2027 Automatically generate PHP type declarations for PHP 8. + The generate code still compiles for PHP 7.x, but without type + declarations since PHP 7.x has much more limited type declaration + support. + +2022-01-18: olly + [Perl] #1629 Perl 5.8.0 is now the oldest version we aim to support. + +2022-01-14: wsfulton + [Python] Fix %callback and specifying the callback function as a + static member function using Python staticmethod syntax, such as + Klass.memberfunction instead of Klass_memberfunction when using + -builtin and -fastproxy. + +2022-01-11: wsfulton + [Python] Accept keyword arguments accessing static member functions when + using -builtin and kwargs feature and Python class staticmethod syntax. + The missing keyword argument support was only when using the + class staticmethod syntax, such as Klass.memberfunction, and not when + using the flat static method syntax, such as Klass_memberfunction. + +2022-01-04: juierror + [Go] #2045 Add support for std::array in std_array.i. + +2021-12-18: olly + [PHP] Add PHP keyword 'readonly' (added in 8.1) to the list SWIG + knows to automatically rename. This keyword is special in that PHP + allows it to be used as a function (or method) name. + +2021-12-07: vstinner + [Python] #2116 Python 3.11 support: use Py_SET_TYPE() + +2021-12-05: rwf1 + [Octave] #2020 #1893 Add support for Octave 6 up to and including 6.4. + Also add support for compiling with -Bsymbolic which is used by default + by mkoctfile. + +2021-12-02: jsenn + [Python] #2102 Fixed crashes when using embedded Python interpreters. + +2021-11-12: wsfulton + [Javascript] v8 and node only. Fix mismatched new char[] and free() + when wrapping C code char arrays. Now calloc is now used instead of + new char[] in SWIG_AsCharPtrAndSize. + +2021-10-03: ajrh1 + [Perl] #2074: Avoid -Wmisleading-indentation in generated code + when using gcc11. + +2021-10-03: jschueller + [CMake] #2065: Add option to enable or disable PCRE support. + +2021-09-16: ianlancetaylor + [Go] Improved _cgo_panic implementation. + +2021-09-16: ianlancetaylor + [Go] Don't use crosscall2 for panicking. Instead rely on documented + and exported interfaces. + +2021-09-14: ianlancetaylor + [Go] Remove -no-cgo option (long unsupported in Go) + +2021-05-04: olly + [PHP] #2014 Throw PHP exceptions instead of using PHP errors + + PHP exceptions can be caught and handled if desired, but if they + aren't caught then PHP exits in much the same way as it does for a + PHP error. + + In particular this means parameter type errors and some other cases + in SWIG-generated wrappers now throw a PHP exception, which matches + how PHP's native parameter handling deals with similar situations. + + `SWIG_ErrorCode()`, `SWIG_ErrorMsg()`, `SWIG_FAIL()` and `goto thrown;` + are no longer supported (these are really all internal implementation + details and none are documented aside from brief mentions in CHANGES + for the first three). I wasn't able to find any uses in user interface + files at least in FOSS code via code search tools. + + If you are using these: + + Use `SWIG_PHP_Error(code,msg);` instead of `SWIG_ErrorCode(code); + SWIG_ErrorMsg(msg);` (which will throw a PHP exception in SWIG >= 4.1 + and do the same as the individual calls in older SWIG). + + `SWIG_FAIL();` and `goto thrown;` can typically be replaced with + `SWIG_fail;`. This will probably also work with older SWIG, but + please test with your wrappers if this is important to you. + + *** POTENTIAL INCOMPATIBILITY *** + +2021-05-17: adr26 + [Python] #1985 Fix memory leaks: + + 1. Python object references were being incorrectly retained by + SwigPyClientData, causing swig_varlink_dealloc() never to run / free + memory. SwigPyClientData_New() / SwigPyClientData_Del() were updated + to fix the object reference counting, causing swig_varlink_dealloc() + to run and the memory swig_varlink owns to be freed. + + 2. SwigPyClientData itself was not freed by SwigPyClientData_Del(), + causing another heap leak. The required free() was added to + SwigPyClientData_Del() + + 3. Fix reference counting/leak of python cached type query + + 4. Fix reference counting/leak of SwigPyObject dict (-builtin) + + 5. Python object reference counting fixes for out-of-memory + scenarios were added to: SWIG_Python_RaiseOrModifyTypeError(), + SWIG_Python_AppendOutput(), SwigPyClientData_New(), + SwigPyObject_get___dict__() and SwigPyObject_format() + + 6. Add error handling for PyModule_AddObject() to + SWIG_Python_SetModule() (failure could be caused by OOM or a name + clash caused by malicious code) + +2021-05-13: olly + [UFFI] #2009 Remove code for Common Lisp UFFI. We dropped support + for it in SWIG 4.0.0 and nobody has stepped forward to revive it in + over 2 years. + +2021-05-13: olly + [S-EXP] #2009 Remove code for Common Lisp S-Exp. We dropped + support for it in SWIG 4.0.0 and nobody has stepped forward to + revive it in over 2 years. + +2021-05-13: olly + [Pike] #2009 Remove code for Pike. We dropped support for it in + SWIG 4.0.0 and nobody has stepped forward to revive it in over 2 + years. + +2021-05-13: olly + [Modula3] #2009 Remove code for Modula3. We dropped support for it + in SWIG 4.0.0 and nobody has stepped forward to revive it in over 2 + years. + +2021-05-13: olly + [CLISP] #2009 Remove code for GNU Common Lisp. We dropped support + for it in SWIG 4.0.0 and nobody has stepped forward to revive it in + over 2 years. + +2021-05-13: olly + [Chicken] #2009 Remove code for Chicken. We dropped support for it + in SWIG 4.0.0 and nobody has stepped forward to revive it in over 2 + years. + +2021-05-13: olly + [Allegrocl] #2009 Remove code for Allegro Common Lisp. We dropped + support for it in SWIG 4.0.0 and nobody has stepped forward to + revive it in over 2 years. + +2021-05-04: olly + [PHP] #1982 #1457 https://sourceforge.net/p/swig/bugs/1339/ + SWIG now only use PHP's C API to implement its wrappers, and no + longer generates PHP code to define classes. The wrappers should + be almost entirely compatible with those generated before, but + faster and without some previously hard-to-fix bugs. + + The main notable difference is SWIG no longer generates a .php + wrapper at all by default (only if %pragma(php) code=... or + %pragma(php) include=... are specified in the interface file). + This also means you need to load the module via extension=... + in php.ini, rather than letting the dl() in the generated + .php wrapper load it (but dl() has only worked for command-line + PHP for some years now). + + *** POTENTIAL INCOMPATIBILITY *** + +2021-04-30: olly + #1984 Remove support for $source and $target. + These were officially deprecated in 2001, and attempts to use them have + resulted in a warning (including a pointer to what to update them to) + for most if not all of that time. + +2021-04-27: wsfulton + #1987 [Java] Fix %interface family of macros for returning by const + pointer reference. + +2021-04-19: olly + Fix use of uninitialised variable in the generated code for an + empty typecheck typemap, such as the dummy one we include for + std::initializer_list. + +2021-04-12: olly + #1777 [Python] Specifying -py3 now generates a check for Python + version >= 3.0. + +2021-03-26: olly + [PHP] Add PHP keywords 'fn' (added in 7.4) and 'match' (added in + 8.0) to the list SWIG knows to automatically rename. + +2021-03-23: wsfulton + #1942 [Python] Fix compilation error in wrappers when using -builtin + and wrapping varargs in constructors. + +2021-03-22: goto40 + #1977 Fix handling of template template parameters. + +2021-03-21: olly + #1929, #1978 [PHP] Add support for PHP 8. + +2021-03-19: wsfulton + #1610 Remove -ansi from default compilation flags. + +2021-03-19: dot-asm + #1934 [Java] Clean up typemaps for long long arrays. + +2021-03-19: olly + #1527 [PHP] Improve PHP object creation in directorin case. + Reportedly the code we were using in this case gave segfaults in + PHP 7.2 and later - we've been unable to reproduce these, but the + new approach is also simpler and should be bit faster too. + +2021-03-18: olly + #1655 [PHP] Fix char* typecheck typemap to accept PHP Null like the + corresponding in typemap does. + +2021-03-18: olly + #1900, #1905 [PHP] Fix wrapping of overloaded directed methods with + non-void return. + +2021-03-11: murillo128 + #1498 [Javascript] Support type conversion. + +2021-03-06: nshmyrev + #872 [Javascript] Various typemap issues in arrays_javascript.i fixed. + +2021-03-03: vaughamhong + #577 [Javascript] Implemented SetModule/GetModule for JSC to allow type sharing + across modules. + +2021-03-01: xantares, Oliver Buchtala, geographika + #1040 Add support for building SWIG with CMake. See documentation in Windows.html. + +2021-03-01: vadz + #1952 Fix incorrect warning "Unknown Doxygen command: ." + +2021-02-28: p2k + #969 [Javascript] v8/node - prevent crash calling a constructor without new keyword. + +2021-02-28: alecmev + #405 #1121 [Javascript] Fix OUTPUT typemaps on methods that don't return void. + The output value is appended to the return value. + +2021-02-26: murillo128, wsfulton + #1269 [Javascript] Fix handling of large positive unsigned long and + unsigned long long values. + +2021-02-24: tomleavy, yegorich, tungntpham + #1746 [Javascript] Add support for Node v12, v14 and v16. + SWIG support for Node is now for v6 and later only. + +2020-02-09: ZackerySpytz + #1872 Fix typos in attribute2ref macros. + +2020-10-10: wsfulton + [Javascript] Fix so that ccomplex.i interface to file can be used. + +2020-10-10: wsfulton + #252 complex can now be used as a C identifier and doesn't give a syntax error. + +2020-10-10: lpsinger + #1770 Correct C complex support. + _Complex is now parsed as a keyword rather than complex as per the C99 standard. + The complex macro is available in the ccomplex.i library file along with other + complex number handling provided by the complex.h header. + +2020-10-07: ZackerySpytz + [Python] #1812 Fix the error handling for the PyObject_GetBuffer() calls in + pybuffer.i. + +2020-10-07: treitmayr + #1824 Add missing space in director method declaration returning + const pointer. + +2020-10-07: adelva1984 + #1859 Remove all (two) exceptions from SWIG executable. + +2020-09-25: wsfulton + [C#, Java] #1874 Add ability to change the modifiers for the interface + generated when using the %interface macros. + + For C# use the 'csinterfacemodifiers' typemap. + For Java use the 'javainterfacemodifiers' typemap. + + For example: + + %typemap(csinterfacemodifiers) X "internal interface" + + +2020-09-24: geefr + [C#] #1868 Fix wchar_t* csvarout typemap for member variable wrappers. + +2020-08-28: wsfulton + [Java] #1862 Fix crashes in swig_connect_director during director class construction + when using the director class from multiple threads - a race condition initialising + block scope static variables. The fix is guaranteed when using C++11, but most + compilers also fix it when using C++03/C++98. + +2020-08-16: wsfulton + [Python] Add missing initializer for member ‘_heaptypeobject::ht_module’ when using + -builtin to complete Python 3.9 support. + +2020-08-16: wsfulton + [Python] Remove PyEval_InitThreads() call for Python 3.7 and later as Python calls + it automatically now. This removes a deprecation warning when using Python 3.9. + +2020-08-15: wsfulton + [Python] All Python examples and tests are written to be Python 2 and Python 3 + compatible, removing the need for 2to3 to run the examples or test-suite. + +2020-08-13: wsfulton + [C#] Add support for void *VOID_INT_PTR for member variables. + +2020-07-29: chrisburr + #1843 [Python] Compilation error fix in SwigPyBuiltin_SetMetaType when using PyPy. + +2020-06-14: ZackerySpytz + #1642 #1809 Fix virtual comparison operators in director classes - remove incorrect + space in the function name, for example, operator= = is now operator==. diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 000000000..8a8862f63 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,167 @@ +cmake_minimum_required (VERSION 3.2) + +if (NOT DEFINED CMAKE_BUILD_TYPE) + set (CMAKE_BUILD_TYPE Release CACHE STRING "Build type") +endif () + +project (swig) + +if (POLICY CMP0074) + cmake_policy (SET CMP0074 NEW) +endif() + +file (STRINGS configure.ac line LIMIT_COUNT 1 REGEX "AC_INIT\\(.*\\)" ) +if (line MATCHES "AC_INIT\\(\\[(.*)\\],[ \t]*\\[(.*)\\],[ \t]*\\[(.*)\\]\\)" ) + set (SWIG_VERSION ${CMAKE_MATCH_2}) + set (PACKAGE_BUGREPORT ${CMAKE_MATCH_3}) +else () + message (SEND_ERROR "Could not parse version from configure.ac") +endif () + +set (SWIG_ROOT ${PROJECT_SOURCE_DIR}) + +set (SWIG_LIB share/swig/${SWIG_VERSION}) + +# Project wide configuration variables +# ------------------------------------ + +set (SWIG_SOURCE_DIR ${SWIG_ROOT}/Source CACHE INTERNAL "Path of swig sources" FORCE) + +set (PACKAGE_NAME swig) +set (PACKAGE_VERSION ${SWIG_VERSION}) + +# Configure +# --------- + +list (APPEND CMAKE_MODULE_PATH ${SWIG_ROOT}/Tools/cmake) + +include (CheckIncludeFiles) +include (CheckIncludeFile) +include (CheckIncludeFileCXX) +include (CheckTypeSize) +include (CheckSymbolExists) +include (CheckFunctionExists) +include (CheckLibraryExists) +include (CheckCSourceCompiles) + +# HACK: didn't get the bool check working for Visual Studio 2008 +if (MSVC) + set(HAVE_BOOL 1) +else() + set (CMAKE_EXTRA_INCLUDE_FILES stdbool.h) + check_type_size ("bool" HAVE_BOOL) + set (CMAKE_EXTRA_INCLUDE_FILES) +endif() + +check_include_file ("inttypes.h" HAVE_INTTYPES_H) +check_include_file ("stddef.h" HAVE_STDDEF_H) +check_include_file ("stdint.h" HAVE_STDINT_H) +check_include_file ("stdio.h" HAVE_STDIO_H) +check_include_file ("stdlib.h" HAVE_STDLIB_H) +check_include_file ("string.h" HAVE_STRING_H) +check_include_file ("strings.h" HAVE_STRINGS_H) +check_include_file ("sys/stat.h" HAVE_SYS_STAT_H) +check_include_file ("sys/types.h" HAVE_SYS_TYPES_H) +check_include_file ("unistd.h" HAVE_UNISTD_H) +check_include_files ("stdlib.h;stdarg.h;string.h;float.h" STDC_HEADERS) + +check_include_file_cxx ("boost/shared_ptr.hpp" HAVE_BOOST) +check_library_exists (dl dlopen "" HAVE_LIBDL) +check_function_exists (popen HAVE_POPEN) + +if (MSVC) + set (CMAKE_CXX_FLAGS "/EHsc ${CMAKE_CXX_FLAGS}") +endif () + +option (WITH_PCRE "Enable PCRE" ON) +if (WITH_PCRE) + find_package (PCRE2 REQUIRED) + set (HAVE_PCRE 1) + include_directories (${PCRE2_INCLUDE_DIRS}) +endif() + +if (WIN32) + file (TO_NATIVE_PATH ${CMAKE_INSTALL_PREFIX}/${SWIG_LIB} SWIG_LIB_WIN_UNIX) + string (REGEX REPLACE "\\\\" "\\\\\\\\" SWIG_LIB_WIN_UNIX "${SWIG_LIB_WIN_UNIX}") +endif () +configure_file (${SWIG_ROOT}/Tools/cmake/swigconfig.h.in + ${CMAKE_CURRENT_BINARY_DIR}/Source/Include/swigconfig.h) + +find_package (BISON REQUIRED) + + +# Compiler flags +# -------------- + +include_directories ( + ${SWIG_SOURCE_DIR}/CParse + ${SWIG_SOURCE_DIR}/Include + ${SWIG_SOURCE_DIR}/DOH + ${SWIG_SOURCE_DIR}/Swig + ${SWIG_SOURCE_DIR}/Preprocessor + ${SWIG_SOURCE_DIR}/Modules + ${PROJECT_BINARY_DIR}/Source/Include + ${PROJECT_BINARY_DIR}/Source/CParse + ${PROJECT_SOURCE_DIR}/Source/Doxygen +) + +# generate the parser source code (depends on bison) +file (MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/Source/CParse) + +BISON_TARGET (swig_parser + ${SWIG_SOURCE_DIR}/CParse/parser.y + ${PROJECT_BINARY_DIR}/Source/CParse/parser.c +) + +# generate swigwarn.swg +file (READ ${SWIG_SOURCE_DIR}/Include/swigwarn.h SWIG_WARN_H) +string (REGEX REPLACE "#define WARN([^ \\t]*)[ \\t]*([0-9]+)" "%define SWIGWARN\\1 \\2 %enddef" SWIG_WARN_SWG ${SWIG_WARN_H}) +file (WRITE ${CMAKE_CURRENT_BINARY_DIR}/swigwarn.swg ${SWIG_WARN_SWG}) +set_property (SOURCE ${CMAKE_CURRENT_BINARY_DIR}/swigwarn.swg PROPERTY GENERATED 1) + +# install lib +install (DIRECTORY ${SWIG_ROOT}/Lib/ DESTINATION ${SWIG_LIB}) +install (FILES ${CMAKE_CURRENT_BINARY_DIR}/swigwarn.swg DESTINATION ${SWIG_LIB}) + +# sources +# --------- +file (GLOB DOH_SOURCES ${SWIG_SOURCE_DIR}/DOH/*.c) +file (GLOB CPARSE_SOURCES ${SWIG_SOURCE_DIR}/CParse/*.c) +list (APPEND CPARSE_SOURCES) +file (GLOB PREPROCESSOR_SOURCES ${SWIG_SOURCE_DIR}/Preprocessor/*.c) +file (GLOB CORE_SOURCES ${SWIG_SOURCE_DIR}/Swig/*.c) +file (GLOB DOXYGEN_SOURCES ${SWIG_SOURCE_DIR}/Doxygen/*.cxx) +file (GLOB MODULES_SOURCES ${SWIG_SOURCE_DIR}/Modules/*.cxx) + +add_executable (swig + ${CPARSE_SOURCES} + ${DOH_SOURCES} + ${DOXYGEN_SOURCES} + ${MODULES_SOURCES} + ${CORE_SOURCES} + ${PREPROCESSOR_SOURCES} + ${PROJECT_BINARY_DIR}/Source/Include/swigconfig.h + ${SWIG_SOURCE_DIR}/Include/swigwarn.h + ${PROJECT_BINARY_DIR}/Source/CParse/parser.c + ${PROJECT_BINARY_DIR}/Source/CParse/parser.h +) +if (PCRE2_FOUND) + target_link_libraries (swig ${PCRE2_LIBRARIES}) +endif () +install (TARGETS swig DESTINATION bin) + +# 'make package-source' creates tarballs +set (CPACK_PACKAGE_NAME ${PACKAGE_NAME}) +set (CPACK_SOURCE_GENERATOR "TGZ;TBZ2") +set (CPACK_SOURCE_IGNORE_FILES "/.git;/build;.*~;${CPACK_SOURCE_IGNORE_FILES}") +set (CPACK_SOURCE_PACKAGE_FILE_NAME ${PACKAGE_NAME}-${PACKAGE_VERSION}) +include (CPack) + +# few tests +enable_testing () +add_test (NAME cmd_version COMMAND swig -version) +add_test (NAME cmd_pcreversion COMMAND swig -pcreversion) +add_test (NAME cmd_swiglib COMMAND swig -swiglib) +add_test (NAME cmd_external_runtime COMMAND swig -external-runtime ext_rt.h) +set_tests_properties(cmd_external_runtime PROPERTIES ENVIRONMENT "SWIG_LIB=${PROJECT_SOURCE_DIR}/Lib") + diff --git a/Doc/Devel/internals.html b/Doc/Devel/internals.html index c9082d3f6..0fc6623e8 100644 --- a/Doc/Devel/internals.html +++ b/Doc/Devel/internals.html @@ -441,12 +441,12 @@ Resulting output:

-hash len: 5
-get: hashval2
-hash item: hashval5 [h5]
-hash item: hashval1 [h1]
-hash item: hashval2 [h2]
-hash item: hashval3 [h3]
+list len: 5
+get: listval2
+list item: newlistval1
+list item: listval2
+list item: listval3
+list item: listval5
 
@@ -494,12 +494,12 @@ Resulting output:
-list len: 5
-get: listval2
-list item: newlistval1
-list item: listval2
-list item: listval3
-list item: listval5
+hash len: 5
+get: hashval2
+hash item: hashval5 [h5]
+hash item: hashval1 [h1]
+hash item: hashval2 [h2]
+hash item: hashval3 [h3]
 
diff --git a/Doc/Devel/plan-gsoc-2012.txt b/Doc/Devel/plan-gsoc-2012.txt index ac764fb2a..c217dad8d 100644 --- a/Doc/Devel/plan-gsoc-2012.txt +++ b/Doc/Devel/plan-gsoc-2012.txt @@ -45,7 +45,7 @@ Functionality ----------------- Note: - See 'http://www.stack.nl/~dimitri/doxygen/docblocks.html' for + See 'https://www.doxygen.nl/manual/docblocks.html' for the detailed description of Doxygen syntax and terms used in this section. @@ -72,10 +72,10 @@ Functionality ---- This section contains all doxygen tags taken from - http://www.stack.nl/~dimitri/doxygen/commands.html. If a tag is + https://www.doxygen.nl/manual/commands.html. If a tag is marked as 'ignored', then the tag is ignored, but the text is copied to the destination documentation. 'Not implemented' means that the - tag with it's contents is stripped out of the output. + tag with its contents is stripped out of the output. Doxygen tags: diff --git a/Doc/Manual/Allegrocl.html b/Doc/Manual/Allegrocl.html deleted file mode 100644 index 4069ecd8b..000000000 --- a/Doc/Manual/Allegrocl.html +++ /dev/null @@ -1,2150 +0,0 @@ - - - -SWIG and Allegro Common Lisp - - - - - - -

20 SWIG and Allegro Common Lisp

- - - - - - -

-This chapter describes SWIG's support of Allegro Common Lisp. Allegro -CL is a full-featured implementation of the Common Lisp language -standard that includes many vendor-specific enhancements and add-on -modules for increased usability. -

- -

-One such module included in Allegro CL is the Foreign Functions -Interface (FFI). This module, tailored primarily toward interfacing -with C/C++ and, historically, Fortran, provides a means by which -compiled foreign code can be loaded into a running lisp -environment and executed. The interface supports the calling of -foreign functions and methods, allows for executing lisp routines -from foreign code (callbacks), and the passing of data between foreign -and lisp code. -

- -

-The goal of this module is to make it possible to quickly generate the -necessary foreign function definitions so one can make use of C/C++ -foreign libraries directly from lisp without the tedium of having to -code them by hand. When necessary, it will also generate further C/C++ -code that will need to be linked with the intended library for proper -interfacing from lisp. It has been designed with an eye toward -flexibility. Some foreign function calls may release the heap, while -other should not. Some foreign functions should automatically convert -lisp strings into native strings, while others should not. These -adjustments and many more are possible with the current module. -

- -

-It is significant to note that, while this is a vendor-specific -module, we would like to acknowledge the current and ongoing -work by developers in the open source lisp community that are -working on similar interfaces to implementation-independent -foreign function interfaces (CFFI, for example). Such -work can only benefit the lisp community, and we would not -be unhappy to see some enterprising folk use this work to add -to it. -

- -

20.1 Basics

- - -

20.1.1 Running SWIG

- - -

-If you're reading this, you must have some library you need to -generate an interface for. In order for SWIG to do this work, however, -it needs a bit of information about how it should go about creating -your interface, and what you are interfacing to. -

- -

-SWIG expects a description of what in the foreign interface you wish -to connect to. It must consisting of C/C++ declarations and special -SWIG directives. SWIG can be furnished with a header file, but an -interface can also be generated without library headers by supplying a -simple text file--called the interface file, which is typically named -with a .i extension--containing any foreign declarations of -identifiers you wish to use. The most common approach is to use an -interface file with directives to parse the needed headers. A straight -parse of library headers will result in usable code, but SWIG -directives provides much freedom in how a user might tailor the -generated code to their needs or style of coding. -

- -

-Note that SWIG does not require any function definitions; the -declarations of those functions is all that is necessary. Be careful -when tuning the interface as it is quite possible to generate code -that will not load or compile. -

- -

-An example interface file is shown below. It makes use of two SWIG -directives, one of which requests that the declarations in a header -file be used to generate part of the interface, and also includes an -additional declaration to be added.

- -
example.i -
-%module example
-
-%include "header.h"
-
-int fact(int n);
-
-
- -

The contents of header.h are very simple:

-
header.h -
-int fact(char *statement);   // pass it a fact, and it will rate it.
-
-
- -

The contents of example.cl will look like this:

- -
example.cl -
-(defpackage :example
-  (:use :common-lisp :swig :ff :excl))
-
-  ... helper routines for defining the interface ...
-
-(swig-in-package ())
-
-(swig-defun ("fact")
-  ((PARM0_statement cl:string (* :char) ))
-  (:returning (:int )
-   :strings-convert t)
-  (let ((SWIG_arg0 PARM0_statement))
-  (swig-ff-call SWIG_arg0)))
-
-(swig-defun ("fact")
-  ((PARM0_n cl:integer :int ))
-  (:returning (:int )
-   :strings-convert t)
-  (let ((SWIG_arg0 PARM0_n))
-  (swig-ff-call SWIG_arg0)))
-
-(swig-dispatcher ("fact" :type :function :arities (1)))
-
-
- -

-The generated file contains calls to internal swig helper -functions. In this case there are two calls to swig-defun. -These calls will expand into code that will make the appropriate -definitions using the Allegro FFI. Note also, that this code is -erroneous. Function overloading is not supported in C, and this -code will not compile even though SWIG did not complain. -

- -

-In order to generate a C interface to Allegro CL using this code run -swig using the -allegrocl option, as below: -

- -
-
-% swig -allegrocl example.i
-
-
- -

-When building an interface to C++ code, include the -c++ option: -

- -
-
-% swig -allegrocl -c++ example.i
-
-
- -

-As a result of running one of the above commands, a file named example.cl -will be generated containing the lisp side of the interface. As well, a file -example_wrap.cxx is also generated, containing C/C++ wrapper code to -facilitate access to C++ methods, enumeration values, and constant values. -Wrapper functions are necessary in C++ due to the lack of a standard for mangling -the names of symbols across all C++ compilers. These wrapper functions are -exported from the shared library as appropriate, using the C name mangling -convention. The lisp code that is generated will interface to your foreign -library through these wrappers. -

- -

-It is possible to disable the creation of the .cxx file when generating a C -interface by using the -nocwrap command-line argument. For interfaces that -don't contain complex enum or constant expressions, contain nested struct/union -declarations, or doesn't need to use many of the SWIG customization featuers, -this will result in a more streamlined, direct interface to the -intended module. -

- -

-The generated wrapper file is below. It contains very simple -wrappers by default, that simply pass the arguments to the -actual function. -

- -
example_wrap.i -
-  ... lots of SWIG internals ...
-
-EXPORT int ACL___fact__SWIG_0 (char *larg1) {
-  int lresult = (int)0 ;
-  char *arg1 = (char *) 0 ;
-  int result;
-
-  arg1 = larg1;
-  try {
-    result = (int)fact(arg1);
-
-    lresult = result;
-    return lresult;
-  } catch (...) {
-    return (int)0;
-  }
-}
-
-
-EXPORT int ACL___fact__SWIG_1 (int larg1) {
-  int lresult = (int)0 ;
-  int arg1 ;
-  int result;
-
-  arg1 = larg1;
-  try {
-    result = (int)fact(arg1);
-
-    lresult = result;
-    return lresult;
-  } catch (...) {
-    return (int)0;
-  }
-}
-
-
- -

-And again, the generated lisp code. Note that it differs from -what is generated when parsing C code: -

- -
-
-  ...
-
-(swig-in-package ())
-
-(swig-defmethod ("fact" "ACL___fact__SWIG_0" :type :function :arity 1)
-  ((PARM0_statement cl:string (* :char) ))
-  (:returning (:int )
-   :strings-convert t)
-  (let ((SWIG_arg0 PARM0_statement))
-  (swig-ff-call SWIG_arg0)))
-
-(swig-defmethod ("fact" "ACL___fact__SWIG_1" :type :function :arity 1)
-  ((PARM0_n cl:integer :int ))
-  (:returning (:int )
-   :strings-convert t)
-  (let ((SWIG_arg0 PARM0_n))
-  (swig-ff-call SWIG_arg0)))
-
-(swig-dispatcher ("fact" :type :function :arities (1)))
-
-
- -

In this case, the interface generates two swig-defmethod forms and -a swig-dispatcher form. This provides a single functional interface for -all overloaded routines. A more detailed description of this features -is to be found in the section titled Function overloading/Parameter defaulting. - -

-In order to load a C++ interface, you will need to build a shared library -from example_wrap.cxx. Be sure to link in the actual library you created -the interface for, as well as any other dependent shared libraries. For -example, if you intend to be able to call back into lisp, you will also -need to link in the Allegro shared library. The library you create from -the C++ wrapper will be what you then load into Allegro CL. -

- -

20.1.2 Command Line Options

- - -

-There are three Allegro CL specific command-line option: -

- -
-
-swig -allegrocl [ options ] filename
-
-   -identifier-converter [name] - Binds the variable swig:*swig-identifier-convert* 
-                                  in the generated .cl file to name.
-                                  This function is used to generate symbols
-                                  for the lisp side of the interface.
-
-   -cwrap - [default] Generate a .cxx file containing C wrapper function when
-            wrapping C code. The interface generated is similar to what is
-            done for C++ code.
-   -nocwrap - Explicitly turn off generation of .cxx wrappers for C code. Reasonable
-              for modules with simple interfaces. Can not handle all legal enum
-              and constant constructs, or take advantage of SWIG customization features.
-
-   -isolate - With this command-line argument, all lisp helper functions are defined
-              in a unique package named swig.<module-name> rather than
-              swig. This prevents conflicts when the module is
-              intended to be used with other swig generated interfaces that may,
-              for instance, make use of different identifier converters.
-
-
- -

-See Section 17.5 Identifier converter -functions for more details. -

- -

20.1.3 Inserting user code into generated files

- - -

-It is often necessary to include user-defined code into the -automatically generated interface files. For example, when building -a C++ interface, example_wrap.cxx will likely not compile unless -you add a #include "header.h" directive. This can be done -using the SWIG %insert(section) %{ ...code... %} directive: -

- -
-
-%module example
-
-%{
-#include "header.h"
-%}
-
-%include "header.h"
-
-int fact(int n);
-
-
- -

-Additional sections have been added for inserting into the -generated lisp interface file -

-
    -
  • lisphead - inserts before type declarations
  • -
  • lisp - inserts after type declarations according to - where it appears in the .i file
  • -
-

-Note that the block %{ ... %} is effectively a shortcut for -%insert("header") %{ ... %}. -

- - -

20.2 Wrapping Overview

- - -

-New users to SWIG are encouraged to read -SWIG Basics, and -SWIG and C++, for those -interested in generating an interface to C++. -

- -

20.2.1 Function Wrapping

- - -

- Writing lisp code that directly invokes functions at the foreign - function interface level can be cumbersome. Data must often be - translated between lisp and foreign types, data extracted from - objects, foreign objects allocated and freed upon completion of - the foreign call. Dealing with pointers can be unwieldy when it - comes to keeping them distinct from other valid integer values. -

- -

- We make an attempt to ease some of these burdens by making the - interface to foreign code much more lisp-like, rather than C - like. How this is done is described in later chapters. The - layers themselves, appear as follows: -

- -
-
-        ______________
-       |              |  (foreign side)
-       | Foreign Code |  What we're generating an interface to.
-       |______________|
-               |
-               |
-        _______v______
-       |              |  (foreign side)
-       | Wrapper code |  extern "C" wrappers calling C++ 
-       |______________|  functions and methods.
-               |
-    .  . . - - + - - . .  .
-        _______v______
-       |              |  (lisp side)
-       |  FFI Layer   |  Low level lisp interface. ff:def-foreign-call,
-       |______________|  ff:def-foreign-variable
-               |
-               +----------------------------
-        _______v______              _______v______
-       |              |            |              | (lisp side)    
-       |    Defuns    |            |  Defmethods  | wrapper for overloaded
-       |______________|            |______________| functions or those with
-        (lisp side)                        |        defaulted arguments
-        Wrapper for non-overloaded         |
-        functions and methods       _______v______
-                                   |              | (lisp side)
-                                   |    Defuns    | dispatch function
-                                   |______________| to overloads based
-                                                    on arity
-  
-
- -

20.2.2 Foreign Wrappers

- - -

- These wrappers are as generated by SWIG default. The types of - function parameters can be transformed in place using the CTYPE - typemap. This is use for converting pass-by-value parameters to - pass-by-reference where necessary. All wrapper parameters are then - bound to local variables for possible transformation of values - (see LIN typemap). Return values can be transformed via the OUT - typemap. -

- -

20.2.3 FFI Wrappers

- - -

- These are the generated ff:def-foreign-call forms. No typemaps are - applicable to this layer, but the %ffargs directive is - available for use in .i files, to specify which keyword arguments - should be specified for a given function. -

- -
ffargs.i: -
-%module ffargs
-
-%ffargs(strings_convert="nil", call_direct="t") foo;
-%ffargs(strings_convert="nil", release_heap=":never", optimize_for_space="t") bar;
-
-int foo(float f1, float f2);
-int foo(float f1, char c2);
-
-void bar(void *lisp_fn);
-
-char *xxx();
-  
-
- -

Generates: -

-
ffargs.cl: -
-(swig-in-package ())
-
-(swig-defmethod ("foo" "ACL___foo__SWIG_0" :type :function :arity 2)
-  ((PARM0_f1 cl:single-float :float )
-   (PARM1_f2 cl:single-float :float ))
-  (:returning (:int )
-   :call-direct t
-   :strings-convert nil)
-  (let ((SWIG_arg0 PARM0_f1))
-  (let ((SWIG_arg1 PARM1_f2))
-  (swig-ff-call SWIG_arg0 SWIG_arg1))))
-
-(swig-defmethod ("foo" "ACL___foo__SWIG_1" :type :function :arity 2)
-  ((PARM0_f1 cl:single-float :float )
-   (PARM1_c2 cl:character :char character))
-  (:returning (:int )
-   :call-direct t
-   :strings-convert nil)
-  (let ((SWIG_arg0 PARM0_f1))
-  (let ((SWIG_arg1 PARM1_c2))
-  (swig-ff-call SWIG_arg0 SWIG_arg1))))
-
-(swig-dispatcher ("foo" :type :function :arities (2)))
-(swig-defun ("bar" "ACL___bar__SWIG_0" :type :function)
-  ((PARM0_lisp_fn  (* :void) ))
-  (:returning (:void )
-   :release-heap :never
-   :optimize-for-space t
-   :strings-convert nil)
-  (let ((SWIG_arg0 PARM0_lisp_fn))
-  (swig-ff-call SWIG_arg0)))
-
-
-(swig-defun ("xxx" "ACL___xxx__SWIG_0" :type :function)
-  (:void)
-  (:returning ((* :char) )
-   :strings-convert t)
-  (swig-ff-call))
-  
-
- -
-
%ffargs(strings_convert="t");
-
- -

- Is the only default value specified in allegrocl.swg to force - the muffling of warnings about automatic string conversion when defining - ff:def-foreign-call's. -

- -

20.2.4 Non-overloaded Defuns

- - -

- These are simple defuns. There is no typechecking of arguments. - Parameters are bound to local variables for possible - transformation of values, such as pulling values out of instance - slots or allocating temporary stack allocated structures, via the - lin typemap. These arguments are then passed to the - foreign-call (where typechecking may occur). The return value from - this function can be manipulated via the lout typemap. -

- -

20.2.5 Overloaded Defuns

- - -

- In the case of overloaded functions, multiple layers are - generated. First, all the overloads for a given name are separated - out into groups based on arity, and are wrapped in - defmethods. Each method calls a distinct wrapper function, but are - themselves distinguished by the types of their arguments - (see lispclass typemap). These are further wrapped in a - dispatching function (defun) which will invoke the appropriate - generic-function based on arity. This provides a single functional - interface to all overloads. The return value from this function - can be manipulated via the lout typemap. -

- -

20.2.6 What about constant and variable access?

- - -

- Along with the described functional layering, when creating a .cxx wrapper, - this module will generate getter and--if not immutable--setter, - functions for variables and constants. If the -nocwrap option is used, - defconstant and ff:def-foreign-variable forms will be - generated for accessing constants and global variables. These, along with - the defuns listed above are the intended API for calling - into the foreign module. -

- -

20.2.7 Object Wrapping

- - -

- All non-primitive types (Classes, structs, unions, and typedefs - involving same) have a corresponding foreign-type defined on the - lisp side via ff:def-foreign-type. -

- -

- All non-primitive types are further represented by a CLOS class, - created via defclass. An attempt is made to create the same class - hierarchy, with all classes inheriting directly or indirectly from - ff:foreign-pointer. Further, wherever it is apparent, all pointers - returned from foreign code are wrapped in a CLOS instance of the - appropriate class. For ff:def-foreign-calls that have been defined - to expect a :foreign-address type as argument, these CLOS instances - can legally be passed and the pointer to the C++ object - automatically extracted. This is a natural feature of Allegro's - foreign function interface. -

- -

20.3 Wrapping Details

- - -

- In this section is described how particular C/C++ constructs are - translated into lisp. -

- -

20.3.1 Namespaces

- - -

- C++ namespaces are translated into Lisp packages by SWIG. The - Global namespace is mapped to a package named by the %module - directive or the -module command-line argument. Further - namespaces are generated by the swig-defpackage utility - function and given names based on Allegro CLs nested namespace - convention. For example: -

- -
foo.i: -
-%module foo
-
-%{
-#include "foo.h"
-%}
-
-%include "foo.h"
-
-namespace car {
-  ...
-  namespace tires {
-    int do_something(int n);
-  }
-}
-    
-
-

Generates the following code. -

-
foo.cl -
-(defpackage :foo
-  (:use :common-lisp :swig :ff :excl))
-
-...
-
-(swig-defpackage ("car"))
-(swig-defpackage ("car" "tires"))
-
-...
-
-(swig-in-package ("car" "tires"))
-(swig-defun ("do_something" "ACL_car_tires__do_something__SWIG_0" :type :function)
-  ((PARM0_n  :int ))
-  (:returning (:int )
-   :strings-convert t)
-  (let ((SWIG_arg0 PARM0_n))
-  (swig-ff-call SWIG_arg0)))
-    
-
- -

- The above interface file would cause packages foo, foo.car, and - foo.car.tires to be created. One would find the function wrapper - for do_something defined in the foo.car.tires package(*). -

- -

(*) Except for the package named by the module, all - namespace names are passed to the identifier-converter-function - as strings with a :type of :namespace. It is the - job of this function to generate the desired symbol, accounting for - case preferences, additional naming cues, etc. -

- -

- Note that packages created by swig-defpackage do not - use the COMMON-LISP or EXCL package. This reduces possible - conflicts when defining foreign types via the SWIG interface - in all but the toplevel modules package. This may - lead to confusion if, for example, the current package is - foo.car.tires and you attempt to use a common-lisp - function such as (car '(1 2 3). -

- -

20.3.2 Constants

- - - -

- Constants, as declared by the preprocessor #define macro or SWIG - %constant directive, are included in SWIG's parse tree - when it can be determined that they are, or could be reduced to, - a literal value. Such values are translated into defconstant - forms in the generated lisp wrapper when the -nocwrap command-line - options is used. Else, wrapper functions are generated as in the - case of variable access (see section below). -

-

- Here are examples of simple preprocessor constants when using -nocwrap. -

-
-
-#define A 1                    => (swig-defconstant "A" 1)  
-#define B 'c'                  => (swig-defconstant "B" #\c)
-#define C B                    => (swig-defconstant "C" #\c)
-#define D 1.0e2                => (swig-defconstant "D" 1.0d2)
-#define E 2222                 => (swig-defconstant "E" 2222)
-#define F (unsigned int)2222   => no code generated
-#define G 1.02e2f              => (swig-defconstant "G" 1.02f2)
-#define H foo                  => no code generated
-      
-
- -

- Note that where SWIG is unable to determine if a constant is - a literal, no node is added to the SWIG parse tree, and so - no values can be generated. -

- -

- For preprocessor constants containing expressions which can be - reduced to literal values, nodes are created, but with no simplification - of the constant value. A very very simple infix to prefix converter - has been implemented that tries to do the right thing for simple cases, but - does not for more complex expressions. If the literal parser determines - that something is wrong, a warning will be generated and the literal - expression will be included in the generated code, but commented out. -

- -
-
-#define I A + E                => (swig-defconstant "I" (+ 1 2222))
-#define J 1|2                  => (swig-defconstant "J" (logior 1 2))
-#define Y 1 + 2 * 3 + 4        => (swig-defconstant "Y" (* (+ 1 2) (+ 3 4)))
-#define Y1 (1 + 2) * (3 + 4)   => (swig-defconstant "Y1" (* (+ 1 2) (+ 3 4)))
-#define Y2 1 * 2 + 3 * 4       => (swig-defconstant "Y2" (* 1 (+ 2 3) 4))  ;; WRONG
-#define Y3 (1 * 2) + (3 * 4)   => (swig-defconstant "Y3" (* 1 (+ 2 3) 4))  ;; WRONG
-#define Z 1 + 2 - 3 + 4 * 5    => (swig-defconstant "Z" (* (+ 1 (- 2 3) 4) 5)) ;; WRONG
-      
-
-

- Users are cautioned to get to know their constants before use, or - not use the -nocwrap command-line option. -

- -

20.3.3 Variables

- - -

- For C wrapping, a def-foreign-variable call is generated for access - to global variables. -

-

- When wrapping C++ code, both global and member variables, getter - wrappers are generated for accessing their value, and if not immutable, - setter wrappers as well. In the example below, note the lack of a - setter wrapper for global_var, defined as const. -

- -
vars.h -
-namespace nnn {
-  int const global_var = 2;
-  float glob_float = 2.0;
-}
-    
-
- -

- Generated code: -

-
vars.cl -
-(swig-in-package ("nnn"))
-(swig-defun ("global_var" "ACL_nnn__global_var_get__SWIG_0" :type :getter)
-  (:void)
-  (:returning (:int )
-   :strings-convert t)
-  (swig-ff-call))
-
-
-(swig-defun ("glob_float" "ACL_nnn__glob_float_set__SWIG_0" :type :setter)
-  ((PARM0_glob_float  :float ))
-  (:returning (:void )
-   :strings-convert t)
-  (let ((SWIG_arg0 PARM0_glob_float))
-  (swig-ff-call SWIG_arg0)))
-
-
-(swig-defun ("glob_float" "ACL_nnn__glob_float_get__SWIG_0" :type :getter)
-  (:void)
-  (:returning (:float )
-   :strings-convert t)
-  (swig-ff-call))
-    
-
- -

- Note also, that where applicable, setter wrappers are implemented - as setf methods on the getter function, providing a lispy interface - to the foreign code. -

- -
-
-user> (load "globalvar.dll")
-; Foreign loading globalvar.dll.
-t
-user> (load "globalvar.cl")
-; Loading c:\mikel\src\swig\test\globalvar.cl
-t
-user> 
-globalvar> (globalvar.nnn::global_var)
-2
-globalvar> (globalvar.nnn::glob_float)
-2.0
-globalvar> (setf (globalvar.nnn::glob_float) 3.0)
-3.0
-globalvar> (globalvar.nnn::glob_float)
-3.0
-    
-
- -

20.3.4 Enumerations

- - -

- In C, an enumeration value is an integer value, while in C++ an - enumeration value is implicitly convertible to an integer value, - but can also be distinguished by its enum type. For each enum - declaration a def-foreign-type is generated, assigning the enum - a default type of :int. Users may adjust the foreign type of - enums via SWIG typemaps. -

- -

- Enum values are a bit trickier as they can be initialized using - any valid C/C++ expression. In C with the -nocwrap command-line option, - we handle the typical cases (simple integer initialization) and - generate a defconstant form for each enum value. This has the advantage - of it not being necessary to probe into foreign space to retrieve enum - values. When generating a .cxx wrapper file, a more general solution is - employed. A wrapper variable is created in the module_wrap.cxx file, and - a ff:def-foreign-variable call is generated to retrieve its value into lisp. -

- -

For example, the following header file -

enum.h: -
-enum COL { RED, GREEN, BLUE };
-enum FOO { FOO1 = 10, FOO2, FOO3 };
-      
-
-

- In -nocwrap mode, generates -

-
enum.cl: -
-(swig-def-foreign-type "COL" :int)
-(swig-defconstant "RED" 0)
-(swig-defconstant "GREEN" (+ #.(swig-insert-id "RED" () :type :constant) 1))
-(swig-defconstant "BLUE" (+ #.(swig-insert-id "GREEN" () :type :constant) 1))
-
-(swig-def-foreign-type "FOO" :int)
-(swig-defconstant "FOO1" 10)
-(swig-defconstant "FOO2" (+ #.(swig-insert-id "FOO1" () :type :constant) 1))
-(swig-defconstant "FOO3" (+ #.(swig-insert-id "FOO2" () :type :constant) 1))
-      
-
- -

And when generating a .cxx wrapper -

enum_wrap.cxx: -
-EXPORT const int ACL_ENUM___RED__SWIG_0 = RED;
-EXPORT const int ACL_ENUM___GREEN__SWIG_0 = GREEN;
-EXPORT const int ACL_ENUM___BLUE__SWIG_0 = BLUE;
-EXPORT const int ACL_ENUM___FOO1__SWIG_0 = FOO1;
-EXPORT const int ACL_ENUM___FOO2__SWIG_0 = FOO2;
-EXPORT const int ACL_ENUM___FOO3__SWIG_0 = FOO3;
-      
-
-

- and -

-
enum.cl: -
-(swig-def-foreign-type "COL" :int)
-(swig-defvar "RED" "ACL_ENUM___RED__SWIG_0" :type :constant)
-(swig-defvar "GREEN" "ACL_ENUM___GREEN__SWIG_0" :type :constant)
-(swig-defvar "BLUE" "ACL_ENUM___BLUE__SWIG_0" :type :constant)
-
-(swig-def-foreign-type "FOO" :int)
-(swig-defvar "FOO1" "ACL_ENUM___FOO1__SWIG_0" :type :constant)
-(swig-defvar "FOO2" "ACL_ENUM___FOO2__SWIG_0" :type :constant)
-(swig-defvar "FOO3" "ACL_ENUM___FOO3__SWIG_0" :type :constant)
-
-      
-
- -

20.3.5 Arrays

- - -

- One limitation in the Allegro CL foreign-types module, is that, - without macrology, expressions may not be used to specify the - dimensions of an array declaration. This is not a horrible - drawback unless it is necessary to allocate foreign structures - based on the array declaration using ff:allocate-fobject. When it - can be determined that an array bound is a valid numeric value, - SWIG will include this in the generated array declaration on the - lisp side, otherwise the value will be included, but commented out. -

- -

- Below is a comprehensive example, showing a number of legal - C/C++ array declarations and how they are translated - into foreign-type specifications in the generated lisp code. -

-
array.h -
-#define MAX_BUF_SIZE 1024
-
-namespace FOO {
-  int global_var1[13];
-  float global_var2[MAX_BUF_SIZE];
-
-}
-
-enum COLOR { RED = 10, GREEN = 20, BLUE, PURPLE = 50, CYAN };
-
-namespace BAR {
-  char global_var3[MAX_BUF_SIZE + 1];
-  float global_var4[MAX_BUF_SIZE][13];
-  signed short global_var5[MAX_BUF_SIZE + MAX_BUF_SIZE];
-
-  int enum_var5[GREEN];
-  int enum_var6[CYAN];
-
-  COLOR enum_var7[CYAN][MAX_BUF_SIZE];
-}
-    
-
- -

- Generates: -

- -
array.cl -
-(in-package #.*swig-module-name*)
-
-(swig-defpackage ("FOO"))
-(swig-defpackage ("BAR"))
-
-(swig-in-package ())
-(swig-def-foreign-type "COLOR" :int)
-(swig-defvar "RED" "ACL_ENUM___RED__SWIG_0" :type :constant)
-(swig-defvar "GREEN" "ACL_ENUM___GREEN__SWIG_0" :type :constant)
-(swig-defvar "BLUE" "ACL_ENUM___BLUE__SWIG_0" :type :constant)
-(swig-defvar "PURPLE" "ACL_ENUM___PURPLE__SWIG_0" :type :constant)
-(swig-defvar "CYAN" "ACL_ENUM___CYAN__SWIG_0" :type :constant)
-
-(swig-in-package ())
-
-(swig-defconstant "MAX_BUF_SIZE" 1024)
-(swig-in-package ("FOO"))
-
-(swig-defun ("global_var1" "ACL_FOO__global_var1_get__SWIG_0" :type :getter)
-  (:void)
-  (:returning ((* :int) )
-   :strings-convert t)
-  (make-instance 'ff:foreign-pointer :foreign-address (swig-ff-call)))
-
-
-(swig-defun ("global_var2" "ACL_FOO__global_var2_set__SWIG_0" :type :setter)
-  ((global_var2  (:array :float 1024) ))
-  (:returning (:void )
-   :strings-convert t)
-  (let ((SWIG_arg0 global_var2))
-  (swig-ff-call SWIG_arg0)))
-
-
-(swig-in-package ())
-(swig-in-package ("BAR"))
-(swig-defun ("global_var3" "ACL_BAR__global_var3_set__SWIG_0" :type :setter)
-  ((global_var3  (:array :char #|1024+1|#) ))
-  (:returning (:void )
-   :strings-convert t)
-  (let ((SWIG_arg0 global_var3))
-  (swig-ff-call SWIG_arg0)))
-
-
-(swig-defun ("global_var4" "ACL_BAR__global_var4_set__SWIG_0" :type :setter)
-  ((global_var4  (:array (:array :float 13) 1024) ))
-  (:returning (:void )
-   :strings-convert t)
-  (let ((SWIG_arg0 global_var4))
-  (swig-ff-call SWIG_arg0)))
-
-
-(swig-defun ("global_var4" "ACL_BAR__global_var4_get__SWIG_0" :type :getter)
-  (:void)
-  (:returning ((* (:array :float 13)) )
-   :strings-convert t)
-  (make-instance 'ff:foreign-pointer :foreign-address (swig-ff-call)))
-
-
-(swig-defun ("global_var5" "ACL_BAR__global_var5_set__SWIG_0" :type :setter)
-  ((global_var5  (:array :short #|1024+1024|#) ))
-  (:returning (:void )
-   :strings-convert t)
-  (let ((SWIG_arg0 global_var5))
-  (swig-ff-call SWIG_arg0)))
-
-
-(swig-defun ("enum_var5" "ACL_BAR__enum_var5_set__SWIG_0" :type :setter)
-  ((enum_var5  (:array :int #|GREEN|#) ))
-  (:returning (:void )
-   :strings-convert t)
-  (let ((SWIG_arg0 enum_var5))
-  (swig-ff-call SWIG_arg0)))
-
-
-(swig-defun ("enum_var6" "ACL_BAR__enum_var6_set__SWIG_0" :type :setter)
-  ((enum_var6  (:array :int #|CYAN|#) ))
-  (:returning (:void )
-   :strings-convert t)
-  (let ((SWIG_arg0 enum_var6))
-  (swig-ff-call SWIG_arg0)))
-
-
-(swig-defun ("enum_var7" "ACL_BAR__enum_var7_set__SWIG_0" :type :setter)
-  ((enum_var7  (:array (:array #.(swig-insert-id "COLOR" ()) 1024) #|CYAN|#) ))
-  (:returning (:void )
-   :strings-convert t)
-  (let ((SWIG_arg0 enum_var7))
-  (swig-ff-call SWIG_arg0)))
-
-
-(swig-defun ("enum_var7" "ACL_BAR__enum_var7_get__SWIG_0" :type :getter)
-  (:void)
-  (:returning ((* (:array #.(swig-insert-id "COLOR" ()) 1024)) )
-   :strings-convert t)
-  (make-instance 'ff:foreign-pointer :foreign-address (swig-ff-call)))
-    
-
- -

20.3.6 Classes and Structs and Unions (oh my!)

- - -

20.3.6.1 CLOS wrapping of

- - -

- Classes, unions, and structs are all treated the same way by the - interface generator. For any of these objects, a - def-foreign-type and a defclass form are generated. For every - function that returns an object (or pointer/reference) of C/C++ - type X, the wrapping defun (or defmethod) on the Lisp - side will automatically wrap the pointer returned in an instance - of the appropriate class. This makes it much easier to write and - debug code than if pointers were passed around as a jumble of - integer values. -

- -

20.3.6.2 CLOS Inheritance

- - -

- The CLOS class schema generated by the interface mirrors the - inheritance of the classes in foreign code, with the - ff:foreign-pointer class at its root. ff:foreign-pointer is a thin - wrapper for pointers that is made available by the foreign function - interface. Its key benefit is that it may be passed as an argument - to any ff:def-foreign-call that is expecting a pointer as the - parameter. -

- -

20.3.6.3 Member fields and functions

- - -

- All public fields will have accessor getter/setter functions - generated for them, as appropriate. All public member functions - will have wrapper functions generated. -

- -

- We currently ignore anything that isn't public (i.e. - private or protected), because the C++ compiler - won't allow the wrapper functions to access such fields. Likewise, - the interface does nothing for friend directives, -

- -

20.3.6.4 Why not directly access C++ classes using foreign types?

- - -

- The def-foreign-type generated by the SWIG interface is - currently incomplete. We can reliably generate the object layout - of simple structs and unions; they can be allocated via - ff:allocate-fobject, and their member variables accessed - directly using the various ff:fslot-value-* functions. However, - the layout of C++ classes is more complicated. Different - compilers adjust class layout based on inheritance patterns, and - the presence of virtual member functions. The size of member - function pointers vary across compilers as well. As a result, it - is recommended that users of any generated interface not attempt - to access C++ instances via the foreign type system, but instead - use the more robust wrapper functions. -

- -

20.3.7 Templates

- - - -

20.3.7.1 Generating wrapper code for templates

- - -

-SWIG provides support for dealing with templates, but by -default, it will not generate any member variable or function -wrappers for templated classes. In order to create these -wrappers, you need to explicitly tell SWIG to instantiate -them. This is done via the -%template -directive. -

- -

20.3.7.2 Implicit Template instantiation

- - -

-While no wrapper code is generated for accessing member -variables, or calling member functions, type code is generated -to include these templated classes in the foreign-type and CLOS -class schema. -

- -

20.3.8 Typedef, Templates, and Synonym Types

- - -

- In C/C++ it is possible, via typedef, to have many names refer to - the same type. In general, this is not a problem, though - it can lead to confusion. Assume the below C++ header file: -

- -
synonyms.h -
-class A { 
-  int x;
-  int y;
-};
-
-typedef A Foo;
-
-A *xxx(int i);         /* sets A->x = A->y = i */
-Foo *yyy(int i);       /* sets Foo->x = Foo->y = i */
-
-int zzz(A *inst = 0);  /* return inst->x + inst->y */
-    
-
- -

- The function zzz is an overloaded functions; the - foreign function call to it will be wrapped in a - generic-function whose argument will be checked against a type - of A. Assuming a simple implementation, a call - to xxx(1) will return a pointer to an A object, which - will be wrapped in a CLOS instance of class A, and a - call to yyy(1) will result in a CLOS instance of - type Foo being returned. Without establishing a clear - type relationship between Foo and A, an - attempt to call zzz(yyy(1)) will result in an error. -

- -

- We resolve this issue, by noting synonym relationships between - types while generating the interface. A Primary type is selected - (more on this below) from the candidate list of synonyms. For - all other synonyms, instead of generating a distinct CLOS class - definition, we generate a form that expands to: -

-
- (setf (find-class <synonym>) <primary>) -
-

- The result is that all references to synonym types in foreign - code, are wrapped in the same CLOS wrapper, and, in particular, - method specialization in wrapping generic functions works as - expected. -

- -

- Given the above header file, synonym.h, a Lisp session would - appear as follows: -

-
-
-CL-USER> (load "synonym.dll")
-; Foreign loading synonym.dll.
-t
-CL-USER> (load "synonym.cl")
-; Loading c:\mikel\src\swig\test\synonym.cl
-t
-CL-USER> 
-synonym> (setf a (xxx 3))
-#<A nil #x3261a0 @ #x207299da>
-synonym> (setf foo (yyy 10))
-#<A nil #x3291d0 @ #x2072e982>
-synonym> (zzz a)
-6
-synonym> (zzz foo)
-20
-synonym> 
-    
-
- -

20.3.8.1 Choosing a primary type

- - -

- The choice of a primary type is selected by the following - criteria from a set of synonym types. -

-
    -
  • - If a synonym type has a class definition, it is the primary type. -
  • -
  • - If a synonym type is a class template and has been explicitly - instantiated via %template, it is the primary type. -
  • -
  • - For all other sets of synonymous types, the synonym which is - parsed first becomes the primary type. -
  • -
- -

20.3.9 Function overloading/Parameter defaulting

- - -

- For each possible argument combination, a distinct wrapper - function is created in the .cxx file. On the Lisp side, a - generic functions is defined for each possible arity the - overloaded/defaulted call may have. Each distinct wrapper is - then called from within a defmethod on the appropriate generic - function. These are further wrapped inside a dispatch function - that checks the number of arguments it is called with and passes - them via apply to the appropriate generic-function. This allows - for a single entry point to overloaded functions on the lisp - side. -

- -

Example: -

-
overload.h: -
-
-class A {
- public:
-  int x;
-  int y;
-};
-
-float xxx(int i, int x = 0);   /* return i * x */
-float xxx(A *inst, int x);     /* return x + A->x + A->y */
-    
-
- -

Creates the following three wrappers, for each of the possible argument - combinations -

-
overload_wrap.cxx -
-EXPORT void ACL___delete_A__SWIG_0 (A *larg1) {
-  A *arg1 = (A *) 0 ;
-
-  arg1 = larg1;
-  try {
-    delete arg1;
-
-  } catch (...) {
-
-  }
-}
-
-
-EXPORT float ACL___xxx__SWIG_0 (int larg1, int larg2) {
-  float lresult = (float)0 ;
-  int arg1 ;
-  int arg2 ;
-  float result;
-
-  arg1 = larg1;
-  arg2 = larg2;
-  try {
-    result = (float)xxx(arg1, arg2);
-
-    lresult = result;
-    return lresult;
-  } catch (...) {
-    return (float)0;
-  }
-}
-
-
-EXPORT float ACL___xxx__SWIG_1 (int larg1) {
-  float lresult = (float)0 ;
-  int arg1 ;
-  float result;
-
-  arg1 = larg1;
-  try {
-    result = (float)xxx(arg1);
-
-    lresult = result;
-    return lresult;
-  } catch (...) {
-    return (float)0;
-  }
-}
-
-
-EXPORT float ACL___xxx__SWIG_2 (A *larg1, int larg2) {
-  float lresult = (float)0 ;
-  A *arg1 = (A *) 0 ;
-  int arg2 ;
-  float result;
-
-  arg1 = larg1;
-  arg2 = larg2;
-  try {
-    result = (float)xxx(arg1, arg2);
-
-    lresult = result;
-    return lresult;
-  } catch (...) {
-    return (float)0;
-  }
-}
-    
-
- -

- And the following foreign-function-call and method definitions on the - lisp side: -

-
overload.cl -
-(swig-defmethod ("xxx" "ACL___xxx__SWIG_0" :type :function :arity 2)
-  ((PARM0_i cl:integer :int )
-   (PARM1_x cl:integer :int ))
-  (:returning (:float )
-   :strings-convert t)
-  (let ((SWIG_arg0 PARM0_i))
-  (let ((SWIG_arg1 PARM1_x))
-  (swig-ff-call SWIG_arg0 SWIG_arg1))))
-
-(swig-defmethod ("xxx" "ACL___xxx__SWIG_1" :type :function :arity 1)
-  ((PARM0_i cl:integer :int ))
-  (:returning (:float )
-   :strings-convert t)
-  (let ((SWIG_arg0 PARM0_i))
-  (swig-ff-call SWIG_arg0)))
-
-(swig-defmethod ("xxx" "ACL___xxx__SWIG_2" :type :function :arity 2)
-  ((PARM0_inst #.(swig-insert-id "A" () :type :class) (* #.(swig-insert-id "A" ())) )
-   (PARM1_x cl:integer :int ))
-  (:returning (:float )
-   :strings-convert t)
-  (let ((SWIG_arg0 PARM0_inst))
-  (let ((SWIG_arg1 PARM1_x))
-  (swig-ff-call SWIG_arg0 SWIG_arg1))))
-
-(swig-dispatcher ("xxx" :type :function :arities (1 2)))
-    
-
- -

And their usage in a sample lisp session: -

-
-
-overload> (setf a (new_A))
-#<A nil #x329268 @ #x206cf612>
-overload> (setf (A_x a) 10)
-10
-overload> (setf (A_y a) 20)
-20
-overload> (xxx 1)
-0.0
-overload> (xxx 3 10)
-30.0
-overload> (xxx a 1)
-31.0
-overload> (xxx a 2)
-32.0
-overload> 
-    
-
- -

20.3.10 Operator wrapping and Operator overloading

- - -

- Wrappers to defined C++ Operators are automatically renamed, using - %rename, to the following defaults: -

-
-
-/* name conversion for overloaded operators. */
-#ifdef __cplusplus
-%rename(__add__)             *::operator+;
-%rename(__pos__)             *::operator+();
-%rename(__pos__)             *::operator+() const;
-
-%rename(__sub__)             *::operator-;
-%rename(__neg__)             *::operator-() const;
-%rename(__neg__)             *::operator-();
-
-%rename(__mul__)             *::operator*;
-%rename(__deref__)           *::operator*();
-%rename(__deref__)           *::operator*() const;
-
-%rename(__div__)             *::operator/;
-%rename(__mod__)             *::operator%;
-%rename(__logxor__)          *::operator^;
-%rename(__logand__)          *::operator&;
-%rename(__logior__)          *::operator|;
-%rename(__lognot__)          *::operator~();
-%rename(__lognot__)          *::operator~() const;
-
-%rename(__not__)             *::operator!();
-%rename(__not__)             *::operator!() const;
-
-%rename(__assign__)          *::operator=;
-
-%rename(__add_assign__)      *::operator+=;
-%rename(__sub_assign__)      *::operator-=;
-%rename(__mul_assign__)      *::operator*=;
-%rename(__div_assign__)      *::operator/=;
-%rename(__mod_assign__)      *::operator%=;
-%rename(__logxor_assign__)   *::operator^=;
-%rename(__logand_assign__)   *::operator&=;
-%rename(__logior_assign__)   *::operator|=;
-
-%rename(__lshift__)          *::operator<<;
-%rename(__lshift_assign__)   *::operator<<=;
-%rename(__rshift__)          *::operator>>;
-%rename(__rshift_assign__)   *::operator>>=;
-
-%rename(__eq__)              *::operator==;
-%rename(__ne__)              *::operator!=;
-%rename(__lt__)              *::operator<;
-%rename(__gt__)              *::operator>;
-%rename(__lte__)             *::operator<=;
-%rename(__gte__)             *::operator>=;
-
-%rename(__and__)             *::operator&&;
-%rename(__or__)              *::operator||;
-
-%rename(__preincr__)         *::operator++();
-%rename(__postincr__)        *::operator++(int);
-%rename(__predecr__)         *::operator--();
-%rename(__postdecr__)        *::operator--(int);
-
-%rename(__comma__)           *::operator,();
-%rename(__comma__)           *::operator,() const;
-
-%rename(__member_ref__)      *::operator->;
-%rename(__member_func_ref__) *::operator->*;
-
-%rename(__funcall__)         *::operator();
-%rename(__aref__)            *::operator[];
-    
-
- -

- Name mangling occurs on all such renamed identifiers, so that wrapper name - generated by B::operator= will be B___eq__, i.e. - <class-or-namespace>_ has been added. Users may modify - these default names by adding %rename directives in their own .i files. -

- -

- Operator overloading can be achieved by adding functions based - on the mangled names of the function. In the following example, - a class B is defined with a Operator== method defined. The - swig %extend directive is used to add an overload method - on Operator==. -

- -
opoverload.h -
-class B {
- public:
-  int x;
-  int y;
-  bool operator==(B const& other) const;
-};
-    
-
- -

- and -

-
opoverload.i -
-%module opoverload
-
-%{
-#include <fstream>
-#include "opoverload.h"
-%}
-
-%{
-bool B___eq__(B const *inst, int const x)
-{
-  // insert the function definition into the wrapper code before
-  // the wrapper for it.
-  // ... do stuff ...
-}
-%}
-
-%include "opoverload.h"
-
-%extend B {
- public:
-  bool __eq__(int const x) const;
-};
-    
-
- -

- Either operator can be called via a single call - to the dispatch function: -

-
-
-opoverload> (B___eq__ x1 x2)
-nil
-opoverload> (B___eq__ x1 3)
-nil
-opoverload> 
-    
-
- -

20.3.11 Varargs

- - -

- Variable length argument lists are not supported, by default. If - such a function is encountered, a warning will generated to - stderr. Varargs are supported via the SWIG %varargs - directive. This directive allows you to specify a (finite) - argument list which will be inserted into the wrapper in place - of the variable length argument indicator. As an example, - consider the function printf(). Its declaration would - appear as follows: -

- -

- See the following section - on Variable Length arguments - provides examples on how %varargs can be used, along - with other ways such functions can be wrapped. -

- -

20.3.12 C++ Exceptions

- - -

- Each C++ wrapper includes a handler to catch any exceptions that may - be thrown while in foreign code. This helps prevent simple C++ errors - from killing the entire lisp process. There is currently no mechanism - to have these exceptions forwarded to the lisp condition system, nor - has any explicit support of the exception related SWIG typemaps been - implemented. -

- -

20.3.13 Pass by value, pass by reference

- - -

- Allegro CL does not support the passing of non-primitive foreign - structures by value. As a result, SWIG must automatically detect - and convert function parameters and return values to pointers - whenever necessary. This is done via the use of typemaps, - and should not require any fine tuning by the user, even for - newly defined types. -

- -

20.4 Typemaps

- - -

- SWIG Typemaps provide a powerful tool for automatically generating - code to handle various menial tasks required of writing an interface - to foreign code. The purpose of this section is to describe each of - the typemaps used by the Allegro CL module. Please read the chapter - on Typemaps for more information. -

- -

20.4.1 Code Generation in the C++ Wrapper

- - - -

- Every C++ wrapper generated by SWIG takes the following form: -

- -
-
-return-val wrapper-name(parm0, parm1, ..., parmN)
-{
-  return-val lresult;   /* return value from wrapper */
-  <local-declaration>
-  ... results;          /* return value from function call */
-
-  <binding locals to parameters>
-
-  try {
-    result = function-name(local0, local1, ..., localN);
-
-    <convert and bind result to lresult>
-
-    return lresult;
-  catch (...) {
-    return (int)0;
-  }
-    
-
- -

20.4.1.1 IN Typemap

- - -

- the in typemap is used to generate code to convert parameters - passed to C++ wrapper functions into the arguments desired for the - call being wrapped. That is, it fills in the code for the - <binding locals to parameters> section above. We - use this map to automatically convert parameters passed by - reference to the wrapper function into by-value arguments for - the wrapped call, and also to convert boolean values, which are - passed as integers from lisp (by default), into the appropriate - type for the language of code being wrapped. -

- -

These are the default specifications for the IN typemap. Here, - $input refers to the parameter code is being generated - for, and $1 is the local variable to which it is - being assigned. The default settings of this typemap are as follows: -

- -
-
-%typemap(in) bool                          "$1 = (bool)$input;";
-%typemap(in) char, unsigned char, signed char,
-             short, signed short, unsigned short,
-             int, signed int, unsigned int,
-             long, signed long, unsigned long,
-             float, double, long double, char *, void *, void,
-             enum SWIGTYPE, SWIGTYPE *,
-             SWIGTYPE[ANY], SWIGTYPE &     "$1 = $input;";
-%typemap(in) SWIGTYPE                      "$1 = *$input;";
-    
-
- -

20.4.1.2 OUT Typemap

- - -

- The out typemap is used to generate code to form the - return value of the wrapper from the return value of the wrapped - function. This code is placed in the <convert and bind result to lresult> - section of the above code diagram. Its default mapping is as follows: -

- -
-
-%typemap(out) bool                          "$result = (int)$1;";
-%typemap(out) char, unsigned char, signed char,
-              short, signed short, unsigned short,
-              int, signed int, unsigned int,
-              long, signed long, unsigned long,
-              float, double, long double, char *, void *, void,
-              enum SWIGTYPE, SWIGTYPE *,
-              SWIGTYPE[ANY], SWIGTYPE &    "$result = $1;";
-%typemap(out) SWIGTYPE                     "$result = new $1_type($1);";
-    
-
- -

20.4.1.3 CTYPE Typemap

- - -

- This typemap is not used for code generation, but purely for the - transformation of types in the parameter list of the wrapper function. - Its primary use is to handle by-value to by-reference conversion in the - wrappers parameter list. Its default settings are: -

- -
-
-%typemap(ctype) bool                       "int";
-%typemap(ctype) char, unsigned char, signed char,
-                short, signed short, unsigned short,
-                int, signed int, unsigned int,
-                long, signed long, unsigned long,
-                float, double, long double, char *, void *, void,
-                enum SWIGTYPE, SWIGTYPE *,
-                SWIGTYPE[ANY], SWIGTYPE &  "$1_ltype";
-%typemap(ctype) SWIGTYPE                   "$&1_type";
-    
-
- -

- These three typemaps are specifically employed by the - Allegro CL interface generator. SWIG also implements a number of - other typemaps that can be used for generating code in the C/C++ - wrappers. You can read about - these common typemaps here. -

- -

20.4.2 Code generation in Lisp wrappers

- - -

- A number of custom typemaps have also been added to facilitate - the generation of code in the lisp side of the interface. These - are described below. The basic code generation structure is - applied as a series of nested expressions, one for each - parameter, then one for manipulating the return value, and last, - the foreign function call itself. -

- -

- Note that the typemaps below use fully qualified symbols where - necessary. Users writing their own typemaps should do likewise. - See the explanation in the last paragraph of - 16.3.1 Namespaces for details. -

- -

20.4.2.1 LIN Typemap

- - -

- The LIN typemap allows for the manipulating the lisp objects - passed as arguments to the wrapping defun before passing them to - the foreign function call. For example, when passing lisp - strings to foreign code, it is often necessary to copy the - string into a foreign structure of type (:char *) of appropriate - size, and pass this copy to the foreign call. Using the LIN - typemap, one could arrange for the stack-allocation of a foreign - char array, copy your string into it, and not have to worry - about freeing the copy after the function returns. -

- -

The LIN typemap accepts the following $variable references. -

-
    -
  • $in - expands to the name of the parameter being - applied to this typemap -
  • -
  • $out - expands to the name of the local variable - assigned to this typemap -
  • -
  • $in_fftype - the foreign function type of the C type.
  • -
  • $*in_fftype - the foreign function type of the C type - with one pointer removed. If there is no pointer, then $*in_fftype - is the same as $in_fftype. -
  • -
  • $body - very important. Instructs SWIG where - subsequent code generation steps should be inserted into the - current typemap. Leaving out a $body reference - will result in lisp wrappers that do very little by way of - calling into foreign code. Not recommended. -
  • -
- -
-
-%typemap(lin) SWIGTYPE "(cl:let (($out $in))\n  $body)";
-    
-
- -

20.4.2.2 LOUT Typemap

- - -

- The LOUT typemap is the means by which we effect the wrapping of - foreign pointers in CLOS instances. It is applied after all LIN - typemaps, and immediately before the actual foreign-call. -

- -

The LOUT typemap uses the following $variable -

-
    -
  • $lclass - Expands to the CLOS class that - represents foreign-objects of the return type matching this - typemap. -
  • -
  • $body - Same as for the LIN map. Place this - variable where you want the foreign-function call to occur. -
  • -
  • $ldestructor - Expands to the symbol naming the destructor for this - class ($lclass) of object. Allows you to insert finalization or automatic garbage - collection into the wrapper code (see default mappings below). -
  • -
- -
-
-%typemap(lout) bool, char, unsigned char, signed char,
-               short, signed short, unsigned short,
-               int, signed int, unsigned int,
-               long, signed long, unsigned long,
-               float, double, long double, char *, void *, void,
-               enum SWIGTYPE    "$body";
-%typemap(lout) SWIGTYPE[ANY], SWIGTYPE *,
-               SWIGTYPE &       "(cl:make-instance '$lclass :foreign-address $body)";
-%typemap(lout) SWIGTYPE    "(cl:let* ((address $body)\n
-                            (ACL_result (cl:make-instance '$lclass :foreign-address address)))\n
-                            (cl:unless (cl::zerop address)\n
-                            (excl:schedule-finalization ACL_result #'$ldestructor))\n
-                             ACL_result)";
-    
-
- -

20.4.2.3 FFITYPE Typemap

- - - -

- The FFITYPE typemap works as a helper for a body of code that - converts C/C++ type specifications into Allegro CL foreign-type - specifications. These foreign-type specifications appear in - ff:def-foreing-type declarations, and in the argument list and - return values of ff:def-foreign-calls. You would modify this - typemap if you want to change how the FFI passes through - arguments of a given type. For example, if you know that a - particular compiler represents booleans as a single byte, you - might add an entry for: -

- -
-
-%typemap(ffitype) bool ":unsigned-char";
-    
-
- -

- Note that this typemap is pure type transformation, and is not - used in any code generations step the way the LIN and LOUT - typemaps are. The default mappings for this typemap are: -

- -
-
-%typemap(ffitype) bool ":int";
-%typemap(ffitype) char ":char";
-%typemap(ffitype) unsigned char ":unsigned-char";
-%typemap(ffitype) signed char ":char";
-%typemap(ffitype) short, signed short ":short";
-%typemap(ffitype) unsigned short ":unsigned-short";
-%typemap(ffitype) int, signed int ":int";
-%typemap(ffitype) unsigned int ":unsigned-int";
-%typemap(ffitype) long, signed long ":long";
-%typemap(ffitype) unsigned long ":unsigned-long";
-%typemap(ffitype) float ":float";
-%typemap(ffitype) double ":double";
-%typemap(ffitype) char * "(* :char)";
-%typemap(ffitype) void * "(* :void)";
-%typemap(ffitype) void ":void";
-%typemap(ffitype) enum SWIGTYPE ":int";
-%typemap(ffitype) SWIGTYPE & "(* :void)";
-    
-
- -

20.4.2.4 LISPTYPE Typemap

- - -

- This is another type only transformation map, and is used to - provide the lisp-type, which is the optional third argument in - argument specifier in a ff:def-foreign-call form. Specifying a - lisp-type allows the foreign call to perform type checking on - the arguments passed in. The default entries in this typemap are: -

- -
-
-%typemap(lisptype) bool "cl:boolean";
-%typemap(lisptype) char "cl:character";
-%typemap(lisptype) unsigned char "cl:integer";
-%typemap(lisptype) signed char "cl:integer";
-    
-
- -

20.4.2.5 LISPCLASS Typemap

- - -

- The LISPCLASS typemap is used to generate the method signatures - for the generic-functions which wrap overloaded functions and - functions with defaulted arguments. The default entries are: -

- -
-
-%typemap(lispclass) bool "t";
-%typemap(lispclass) char "cl:character";
-%typemap(lispclass) unsigned char, signed char,
-                    short, signed short, unsigned short,
-                    int, signed int, unsigned int,
-                    long, signed long, unsigned long,
-                    enum SWIGTYPE       "cl:integer";
-%typemap(lispclass) float "cl:single-float";
-%typemap(lispclass) double "cl:double-float";
-%typemap(lispclass) char * "cl:string";
-    
-
- -

20.4.3 Modifying SWIG behavior using typemaps

- - -

- The following example shows how we made use of the above - typemaps to add support for the wchar_t type. -

- -
-
-%typecheck(SWIG_TYPECHECK_UNICHAR) wchar_t { $1 = 1; };
-
-%typemap(in)        wchar_t "$1 = $input;";
-%typemap(lin)       wchar_t "(cl:let (($out (cl:char-code $in)))\n  $body)";
-%typemap(lin)       wchar_t* "(excl:with-native-string
-                                         ($out $in
-                                          :external-format #+little-endian :fat-le 
-                                                           #-little-endian :fat)\n
-                                 $body)"
-
-%typemap(out)       wchar_t "$result = $1;";
-%typemap(lout)      wchar_t "(cl:code-char $body)";
-%typemap(lout)      wchar_t* "(excl:native-to-string $body
-                                          :external-format #+little-endian :fat-le
-                                                           #-little-endian :fat)";
-
-%typemap(ffitype)   wchar_t ":unsigned-short";
-%typemap(lisptype)  wchar_t "";
-%typemap(ctype)     wchar_t "wchar_t";
-%typemap(lispclass) wchar_t "cl:character";
-%typemap(lispclass) wchar_t* "cl:string";
-    
-
- -

20.5 Identifier Converter functions

- - -

20.5.1 Creating symbols in the lisp environment

- - -

- Various symbols must be generated in the lisp environment to which - class definitions, functions, constants, variables, etc. must be - bound. Rather than force a particular convention for naming these - symbols, an identifier (to symbol) conversion function is used. A - user-defined identifier-converter can then implement any symbol - naming, case-modifying, scheme desired. -

- -

- In generated SWIG code, whenever some interface object must be - referenced by its lisp symbol, a macro is inserted that calls the - identifier-converter function to generate the appropriate symbol - reference. It is therefore expected that the identifier-converter - function reliably return the same (eq) symbol given the same set - of arguments. -

- -

20.5.2 Existing identifier-converter functions

- - -

Two basic identifier routines have been defined. -

20.5.2.1 identifier-convert-null

- - -

- No modification of the identifier string is performed. Based on - other arguments, the identifier may be concatenated with other - strings, from which a symbol will be created. -

- -

20.5.2.2 identifier-convert-lispify

- - -

- All underscores in the identifier string are converted to - hyphens. Otherwise, identifier-convert-lispify performs the - same symbol transformations. -

- -

20.5.2.3 Default identifier to symbol conversions

- - -

- Check the definitions of the above two default - identifier-converters in Lib/allegrocl/allegrocl.swg for - default naming conventions. -

- -

20.5.3 Defining your own identifier-converter

- - -

- A user-defined identifier-converter function should conform to the following - specification: -

- -
-
-(defun identifier-convert-fn (id &key type class arity) ...body...)
-result ==> symbol or (setf symbol)
-
-
- -

The ID argument is a string representing an identifier in the -foreign environment. -

- -

-The :type keyword argument provides more information on the type of -identifier. Its value is a symbol. This allows the -identifier-converter to apply different heuristics when mapping -different types of identifiers to symbols. SWIG will generate calls -to your identifier-converter using the following types. -

- -
    -
  • :class - names a CLOS class.
  • -
  • :constant - names a defconstant
  • -
  • :constructor - names a function for creating a foreign object
  • -
  • :destructor - names a function for freeing a foreign object
  • -
  • :function - names a CLOS wrapping defmethod or defun.
  • -
  • :ff-operator - names a foreign call defined via ff:def-foreign-call
  • -
  • :getter - getter function
  • -
  • :namespace - names a C++ namespace
  • -
  • :setter - names a setter function. May return a (setf symbol) reference
  • -
  • :operator - names a C++ operator, such as Operator=, Operator*.
  • -
  • :slot - names a slot in a struct/class/union declaration.
  • -
  • :type - names a foreign-type defined via ff:def-foreign-type.
  • -
  • :variable - names a variable defined via ff:def-foreign-variable.
  • -
- -

-The :class keyword argument is a string naming a foreign -class. When non-nil, it indicates that the current identifier has -scope in the specified class. -

- -

-The :arity keyword argument only appears in swig:swig-defmethod forms -generated for overloaded functions. Its value is an integer -indicating the number of arguments passed to the routine indicated by -this identifier. -

- -

20.5.4 Instructing SWIG to use a particular identifier-converter

- - -

- By default, SWIG will use identifier-converter-null. To specify - another convert function, use the -identifier-converter - command-line argument. The value should be a string naming the - function you wish the interface to use instead, when generating - symbols. ex: -

- -
-
-% swig -allegrocl -c++ -module mymodule -identifier-converter my-identifier-converter
-
-
- - - - diff --git a/Doc/Manual/CPlusPlus11.html b/Doc/Manual/CPlusPlus11.html index 11335a251..86a35bfaa 100644 --- a/Doc/Manual/CPlusPlus11.html +++ b/Doc/Manual/CPlusPlus11.html @@ -144,14 +144,39 @@ When either of these is used from a target language, a runtime call is made to o

7.2.3 Extern template

-

SWIG correctly parses the keywords extern template. +

SWIG correctly parses extern template explicit instantiation declarations. However, this template instantiation suppression in a translation unit has no relevance outside of the C++ compiler and so is not used by SWIG. -SWIG only uses %template for instantiating and wrapping templates.

+SWIG only uses %template for instantiating and wrapping templates. +Consider the class template below: +

-template class std::vector<int>;        // C++03 explicit instantiation in C++
-extern template class std::vector<int>; // C++11 explicit instantiation suppression in C++
-%template(VectorInt) std::vector<int>;  // SWIG instantiation
+// Class template
+template class std::vector<int>;        // C++03 template explicit instantiation definition in C++
+extern template class std::vector<int>; // C++11 template explicit instantiation declaration (extern template)
+%template(VectorInt) std::vector<int>;  // SWIG template instantiation
+
+ +

+The above result in warnings: +

+ +
+
+example.i:2: Warning 320: Explicit template instantiation ignored.
+example.i:3: Warning 327: Extern template ignored.
+
+
+ +

+Similarly for the function template below: +

+ +
+// Function template
+template void Func<int>();              // C++03 template explicit instantiation definition in C++
+extern template void Func<int>();       // C++11 template explicit instantiation declaration (extern template)
+%template(FuncInt) Func<int>;           // SWIG template instantiation
 

7.2.4 Initializer lists

@@ -336,6 +361,10 @@ int i; int j; decltype(i+j) k; // syntax error +

SWIG does not support auto as a type specifier for variables, only +for specifying the return type of lambdas +and functions.

+

7.2.7 Range-based for-loop

diff --git a/Doc/Manual/CSharp.html b/Doc/Manual/CSharp.html index ef4c0104d..fe8f7c4bd 100644 --- a/Doc/Manual/CSharp.html +++ b/Doc/Manual/CSharp.html @@ -240,6 +240,7 @@ javabody -> csbody javafinalize -> csfinalize javadestruct -> csdisposing and csdispose javadestruct_derived -> csdisposing_derived and csdispose_derived +javainterfacemodifiers -> csinterfacemodifiers javainterfacecode -> csinterfacecode diff --git a/Doc/Manual/Chicken.html b/Doc/Manual/Chicken.html deleted file mode 100644 index 3a80811bd..000000000 --- a/Doc/Manual/Chicken.html +++ /dev/null @@ -1,597 +0,0 @@ - - - -SWIG and Chicken - - - - - - -

23 SWIG and Chicken

- - - - - - -

- This chapter describes SWIG's support of CHICKEN. CHICKEN is a - Scheme-to-C compiler supporting most of the language features as - defined in the Revised^5 Report on Scheme. Its main - attributes are that it -

- -
    -
  1. generates portable C code
  2. -
  3. includes a customizable interpreter
  4. -
  5. links to C libraries with a simple Foreign Function Interface
  6. -
  7. supports full tail-recursion and first-class continuations
  8. -
- -

- When confronted with a large C library, CHICKEN users can use - SWIG to generate CHICKEN wrappers for the C library. However, - the real advantages of using SWIG with CHICKEN are its - support for C++ -- object-oriented code is - difficult to wrap by hand in CHICKEN -- and its typed - pointer representation, essential for C and C++ - libraries involving structures or classes. - -

- -

23.1 Preliminaries

- - -

- CHICKEN support was introduced to SWIG in version 1.3.18. SWIG - relies on some recent additions to CHICKEN, which are only - present in releases of CHICKEN with version number - greater than or equal to 1.89. - To use a chicken version between 1.40 and 1.89, see the Garbage collection - section below. -

- -

- You may want to look at any of the examples in Examples/chicken/ - directory for the basic steps to run SWIG CHICKEN. -

- -

23.1.1 Running SWIG in C mode

- - -

- To run SWIG CHICKEN in C mode, use - the -chicken option. -

- -
-
% swig -chicken example.i
-
- -

- To allow the wrapper to take advantage of future CHICKEN code - generation improvements, part of the wrapper is direct CHICKEN - function calls (example_wrap.c) and part is CHICKEN - Scheme (example.scm). The basic Scheme code must - be compiled to C using your system's CHICKEN compiler or - both files can be compiled directly using the much simpler csc. -

- -
-
-% chicken example.scm -output-file oexample.c
-
-
- -

- So for the C mode of SWIG CHICKEN, example_wrap.c and - oexample.c are the files that must be compiled to - object files and linked into your project. -

- -

23.1.2 Running SWIG in C++ mode

- - -

- To run SWIG CHICKEN in C++ mode, use - the -chicken -c++ option. -

- -
-
% swig -chicken -c++ example.i
-
- -

- This will generate example_wrap.cxx and - example.scm. The basic Scheme code must be - compiled to C using your system's CHICKEN compiler or - both files can be compiled directly using the much simpler csc. -

- -
-
% chicken example.scm -output-file oexample.c
-
- -

- So for the C++ mode of SWIG CHICKEN, example_wrap.cxx - and oexample.c are the files that must be compiled to - object files and linked into your project. -

- -

23.2 Code Generation

- - -

23.2.1 Naming Conventions

- - -

- Given a C variable, function or constant declaration named - Foo_Bar, the declaration will be available - in CHICKEN as an identifier ending with - Foo-Bar. That is, an underscore is converted - to a dash. -

- -

- You may control what the CHICKEN identifier will be by using the - %rename SWIG directive in the SWIG interface file. -

- -

23.2.2 Modules

- - -

- The name of the module must be declared one of two ways: -

    -
  • Placing %module example in the SWIG interface - file.
  • -
  • Using -module example on the SWIG command - line.
  • -
- -

- The generated example.scm file then exports (declare (unit modulename)). - If you do not want SWIG to export the (declare (unit modulename)), pass - the -nounit option to SWIG. - -

- CHICKEN will be able to access the module using the (declare - (uses modulename)) CHICKEN Scheme form. -

- -

23.2.3 Constants and Variables

- - -

- Constants may be created using any of the four constructs in - the interface file: -

-
    -
  1. #define MYCONSTANT1 ...
  2. -
  3. %constant int MYCONSTANT2 = ...
  4. -
  5. const int MYCONSTANT3 = ...
  6. -
  7. enum { MYCONSTANT4 = ... };
  8. -
- -

- In all cases, the constants may be accessed from within CHICKEN - using the form (MYCONSTANT1); that is, the constants - may be accessed using the read-only parameter form. -

- -

- Variables are accessed using the full parameter form. - For example, to set the C variable "int my_variable;", use the - Scheme form (my-variable 2345). To get the C variable, - use (my-variable). -

- -

- The %feature("constasvar") can be applied to any constant - or immutable variable. Instead of exporting the constant as - a function that must be called, the constant will appear as a - scheme variable. This causes the generated .scm file to just contain the code - (set! MYCONSTANT1 (MYCONSTANT1)). See - Features and the %feature directive - for info on how to apply the %feature. -

- -

23.2.4 Functions

- - -

- C functions declared in the SWIG interface file will have - corresponding CHICKEN Scheme procedures. For example, the C - function "int sqrt(double x);" will be available using the - Scheme form (sqrt 2345.0). A void return - value will give C_SCHEME_UNDEFINED as a result. -

-

- A function may return more than one value by using the - OUTPUT specifier (see Lib/chicken/typemaps.i). - They will be returned as multiple values using (values) if there is more than one - result (that is, a non-void return value and at least one argout - parameter, or a void return value and at least two argout - parameters). The return values can then be accessed with (call-with-values). -

- -

23.2.5 Exceptions

- - -

The SWIG chicken module has support for exceptions thrown from - C or C++ code to be caught in scheme. - See Exception handling with %exception - for more information about declaring exceptions in the interface file. -

- -

Chicken supports both the SWIG_exception(int code, const char *msg) interface - as well as a SWIG_ThrowException(C_word val) function for throwing exceptions from - inside the %exception blocks. SWIG_exception will throw a list consisting of the code - (as an integer) and the message. Both of these will throw an exception using (abort), - which can be handled by (handle-exceptions). See - the Chicken manual on Exceptions - and SFRI-12. Since the exception values are thrown - directly, if (condition-case) is used to catch an exception the exception will come through in the val () case. -

- -

The following simple module

- -
-%module exception_test
-
-%inline %{
-  void test_throw(int i) throws (int) { 
-    if (i == 1) throw 15; 
-  }
-%}
-
- -

could be run with

- -
-(handle-exceptions exvar 
-  (if (= exvar 15)
-    (print "Correct!") 
-    (print "Threw something else " exvar))
-  (test-throw 1))
-
- - -

23.3 TinyCLOS

- - -

- The author of TinyCLOS, Gregor Kiczales, describes TinyCLOS as: - "Tiny CLOS is a Scheme implementation of a 'kernelized' CLOS, with a - metaobject protocol. The implementation is even simpler than - the simple CLOS found in 'The Art of the Metaobject Protocol', - weighing in at around 850 lines of code, including (some) - comments and documentation." -

- -

- Almost all good Scheme books describe how to use metaobjects and - generic procedures to implement an object-oriented Scheme - system. Please consult a Scheme book if you are unfamiliar - with the concept. -

- -

- - CHICKEN has a modified version of TinyCLOS, which SWIG CHICKEN - uses if the -proxy argument is given. If -proxy is passed, then - the generated example.scm file will contain TinyCLOS class definitions. - A class named Foo is declared as <Foo>, and each member variable - is allocated a slot. Member functions are exported as generic functions. - -

- - Primitive symbols and functions (the interface that would be presented if - -proxy was not passed) are hidden and no longer accessible. If the -unhideprimitive - command line argument is passed to SWIG, then the primitive symbols will be - available, but each will be prefixed by the string "primitive:" - -

- - The exported symbol names can be controlled with the -closprefix and -useclassprefix arguments. - If -useclassprefix is passed to SWIG, every member function will be generated with the class name - as a prefix. If the -closprefix mymod: argument is passed to SWIG, then the exported functions will - be prefixed by the string "mymod:". If -useclassprefix is passed, -closprefix is ignored. - -

- -

23.4 Linkage

- - -

- Please refer to CHICKEN - A practical and portable Scheme - system - User's manual for detailed help on how to link - object files to create a CHICKEN Scheme program. Briefly, to - link object files, be sure to add `chicken-config - -extra-libs -libs` or `chicken-config -shared - -extra-libs -libs`to your linker options. Use the - -shared option if you want to create a dynamically - loadable module. You might also want to use the much simpler - csc or csc.bat. -

- -

Each scheme file that is generated - by SWIG contains (declare (uses modname)). This means that to load the - module from scheme code, the code must include (declare (uses modname)). -

- - -

23.4.1 Static binary or shared library linked at compile time

- - -

We can easily use csc to build a static binary.

- -
-
-$ swig -chicken example.i
-$ csc -v example.scm example_impl.c example_wrap.c test_script.scm -o example
-$ ./example
-
-
- -

Similar to the above, any number of module.scm files could be compiled -into a shared library, and then that shared library linked when compiling the -main application.

- -
-
-$ swig -chicken example.i
-$ csc -sv example.scm example_wrap.c example_impl.c -o example.so
-
-
- -

The example.so file can then linked with test_script.scm when it -is compiled, in which case test_script.scm must have (declare (uses example)). -Multiple SWIG modules could have been linked into example.so and each -one accessed with a (declare (uses ... )). -

- -
-
-$ csc -v test_script.scm -lexample
-
-
- -

An alternative is that the test_script.scm can have the code (load-library 'example "example.so"), -in which case the test script does not need to be linked with example.so. The test_script.scm file can then -be run with csi. -

- -

23.4.2 Building chicken extension libraries

- - -

Building a shared library like in the above section only works if the library -is linked at compile time with a script containing (declare (uses ...)) or is -loaded explicitly with (load-library 'example "example.so"). It is -not the format that CHICKEN expects for extension libraries and eggs. The problem is the -(declare (unit modname)) inside the modname.scm file. There are -two possible solutions to this.

- -

First, SWIG accepts a -nounit argument, in which case the (declare (unit modname)) -is not generated. Then, the modname.scm and modname_wrap.c files must be compiled into -their own shared library.

- -
-
-$ csc -sv modname.scm modname_wrap.c modname_impl.c -o modname.so
-
-
- -

This library can then be loaded by scheme code with the (require 'modname) function. -See the -Loading-extension-libraries in the eval unit inside the CHICKEN manual for more information.

- -

Another alternative is to run SWIG normally and create a scheme file that contains (declare (uses modname)) -and then compile that file into the shared library as well. For example, inside the mod_load.scm file,

- -
-
-(declare (uses mod1))
-(declare (uses mod2))
-
-
- -

Which would then be compiled with

- -
-
-$ swig -chicken mod1.i
-$ swig -chicken mod2.i
-$ csc -sv mod_load.scm mod1.scm mod2.scm mod1_wrap.c mod2_wrap.c mod1_impl.c mod2_impl.c -o mod.so
-
-
- -

Then the extension library can be loaded with (require 'mod). As we can see here, -mod_load.scm contains the code that gets executed when the module is loaded. All this code -does is load both mod1 and mod2. As we can see, this technique is more useful when you want to -combine a few SWIG modules into one chicken extension library, especially if modules are related by -%import

- -

In either method, the files that are compiled into the shared library could also be -packaged into an egg. The mod1_wrap.c and mod2_wrap.c files that are created by SWIG -are stand alone and do not need SWIG to be installed to be compiled. Thus the egg could be -distributed and used by anyone, even if SWIG is not installed.

- -

See the Examples/chicken/egg directory in the SWIG source for an example that builds -two eggs, one using the first method and one using the second method.

- -

23.4.3 Linking multiple SWIG modules with TinyCLOS

- - -

Linking together multiple modules that share type information using the %import -directive while also using -proxy is more complicated. For example, if mod2.i imports mod1.i, then the -mod2.scm file contains references to symbols declared in mod1.scm, -and thus a (declare (uses mod1)) or (require 'mod1) must be exported -to the top of mod2.scm. By default, when SWIG encounters an %import "modname.i" directive, -it exports (declare (uses modname)) into the scm file. This works fine unless mod1 was compiled with -the -nounit argument or was compiled into an extension library with other modules under a different name.

- -

One option is to override the automatic generation of (declare (uses mod1)) -by passing the -noclosuses option to SWIG when compiling mod2.i. -SWIG then provides the %insert(closprefix) %{ %} directive. Any scheme code inside that directive is inserted into the -generated .scm file, and if mod1 was compiled with -nounit, the directive should contain (require 'mod1). -This option allows for mixed loading as well, where some modules are imported with (declare (uses modname)) -(which means they were compiled without -nounit) and some are imported with (require 'modname).

- -

The other option is to use the second idea in the above section. Compile all the modules normally, without any -%insert(closprefix), -nounit, or -noclosuses. Then the modules will import each other correctly -with (declare (uses ...)). -To create an extension library or an egg, just create a module_load.scm file that (declare (uses ...)) -all the modules.

- -

23.5 Typemaps

- - -

- The Chicken module handles all types via typemaps. This information is - read from Lib/chicken/typemaps.i and - Lib/chicken/chicken.swg. -

- -

23.6 Pointers

- - -

- For pointer types, SWIG uses CHICKEN tagged pointers. - - A tagged pointer is an ordinary CHICKEN pointer with an - extra slot for a void *. With SWIG - CHICKEN, this void * is a pointer to a type-info - structure. So each pointer used as input or output from - the SWIG-generated CHICKEN wrappers will have type - information attached to it. This will let the wrappers - correctly determine which method should be called - according to the object type hierarchy exposed in the SWIG - interface files. -

-

- To construct a Scheme object from a C pointer, the wrapper code - calls the function - SWIG_NewPointerObj(void *ptr, swig_type_info *type, int owner), - The function that calls SWIG_NewPointerObj must have a variable declared - C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER); - It is ok to call SWIG_NewPointerObj more than once, - just make sure known_space has enough space for all the created pointers. -

-

- To get the pointer represented by a CHICKEN tagged pointer, the - wrapper code calls the function - SWIG_ConvertPtr(C_word s, void **result, swig_type_info *type, int flags), - passing a pointer to a struct representing the expected pointer - type. flags is either zero or SWIG_POINTER_DISOWN (see below). -

- -

23.6.1 Garbage collection

- - -

If the owner flag passed to SWIG_NewPointerObj is 1, NewPointerObj will add a - finalizer to the type which will call the destructor or delete method of - that type. The destructor and delete functions are no longer exported for - use in scheme code, instead SWIG and chicken manage pointers. - In situations where SWIG knows that a function is returning a type that should - be garbage collected, SWIG will automatically set the owner flag to 1. For other functions, - the %newobject directive must be specified for functions whose return values - should be garbage collected. See - Object ownership and %newobject for more information. -

- -

In situations where a C or C++ function will assume ownership of a pointer, and thus - chicken should no longer garbage collect it, SWIG provides the DISOWN input typemap. - After applying this typemap (see the Typemaps chapter for more information on how to apply typemaps), - any pointer that gets passed in will no longer be garbage collected. - An object is disowned by passing the SWIG_POINTER_DISOWN flag to SWIG_ConvertPtr. - Warning: Since the lifetime of the object is now controlled by the underlying code, the object might - get deleted while the scheme code still holds a pointer to it. Further use of this pointer - can lead to a crash. -

- -

Adding a finalizer function from C code was added to chicken in the 1.89 release, so garbage collection - does not work for chicken versions below 1.89. If you would like the SWIG generated code to work with - chicken 1.40 to 1.89, pass the -nocollection argument to SWIG. This will not export code - inside the _wrap.c file to register finalizers, and will then export destructor functions which - must be called manually. -

- -

23.7 Unsupported features and known problems

- - -
    -
  • No director support.
  • -
  • No support for c++ standard types like std::vector.
  • -
  • The TinyCLOS wrappers for overloaded functions will not work correctly when using - %feature(compactdefaultargs).
  • -
- -

23.7.1 TinyCLOS problems with Chicken version <= 1.92

- - -

In Chicken versions equal to or below 1.92, TinyCLOS has a limitation such that generic methods do not properly work on methods - with different number of specializers: TinyCLOS assumes that every method added to a generic function - will have the same number of specializers. SWIG generates functions with different lengths of specializers - when C/C++ functions are overloaded. For example, the code

- -
-
-class Foo {};
-int foo(int a, Foo *b);
-int foo(int a);
-
- -

will produce scheme code

- -
-
-(define-method (foo (arg0 <top>) (arg1 <Foo>)) (call primitive function))
-(define-method (foo (arg0 <top>)) (call primitive function))
-
- -

Using unpatched TinyCLOS, the second (define-method) will replace the first one, -so calling (foo 3 f) will produce an error.

- -

There are three solutions to this. The easist is to upgrade to the latest Chicken version. Otherwise, the -file Lib/chicken/tinyclos-multi-generic.patch in the SWIG source contains a patch against -tinyclos.scm inside the 1.92 chicken source to add support into TinyCLOS for multi-argument generics. (This patch was accepted into Chicken) -This requires chicken to be rebuilt and custom install of chicken. An alternative is the Lib/chicken/multi-generic.scm -file in the SWIG source. This file can be loaded after TinyCLOS is loaded, and it will override some functions -inside TinyCLOS to correctly support multi-argument generics. Please see the comments at the top of both files for more information.

- - - diff --git a/Doc/Manual/Contents.html b/Doc/Manual/Contents.html index 79ffdd50e..433ae5f9e 100644 --- a/Doc/Manual/Contents.html +++ b/Doc/Manual/Contents.html @@ -91,16 +91,16 @@
  • Instructions for using the Examples with other compilers -
  • SWIG on Cygwin and MinGW -
  • Microsoft extensions and other Windows quirks @@ -171,6 +171,7 @@
  • Renaming and ignoring declarations
  • Overloaded operators
  • Class extension +
  • Templates @@ -1473,7 +1478,10 @@
  • Python 3 Support
      -
    • Function annotation +
    • Function annotations +
    • Buffer interface
    • Abstract base classes
    • Byte string output conversion diff --git a/Doc/Manual/Doxygen.html b/Doc/Manual/Doxygen.html index 53238c24d..5b2f7cac6 100644 --- a/Doc/Manual/Doxygen.html +++ b/Doc/Manual/Doxygen.html @@ -181,7 +181,7 @@ or enum element comments:
       enum E_NUMBERS
       {
      -    EN_ZERO, ///< The first enum item, gets zero as it's value
      +    EN_ZERO, ///< The first enum item, gets zero as its value
           EN_ONE, ///< The second, EN_ONE=1
           EN_THREE
       };
      @@ -1354,7 +1354,7 @@ Here is the list of all Doxygen tags and the description of how they are transla
       
       
       \throws
      -replaced wih ':raises:'
      +replaced with ':raises:'
       
       
       \todo
      diff --git a/Doc/Manual/Extending.html b/Doc/Manual/Extending.html
      index 7c2a6c66c..fd607f1d7 100644
      --- a/Doc/Manual/Extending.html
      +++ b/Doc/Manual/Extending.html
      @@ -1132,6 +1132,11 @@ DOH_REPLACE_FIRST     - Replace first occurrence only.
       Returns the number of replacements made (if any).
       

      +

      +At most one of DOH_REPLACE_ANY and DOH_REPLACE_FIRST should be specified. +DOH_REPLACE_ANY is the default if neither is specified. +

      +

      40.5.2 Hashes

      @@ -2986,7 +2991,7 @@ virtual int functionWrapper(Node *n) { /* create the wrapper object */ Wrapper *wrapper = NewWrapper(); - /* create the functions wrappered name */ + /* create the wrapper function's name */ String *wname = Swig_name_wrapper(iname); /* deal with overloading */ @@ -2995,7 +3000,7 @@ virtual int functionWrapper(Node *n) { /* write the wrapper function definition */ Printv(wrapper->def, "RETURN_TYPE ", wname, "(ARGS) {", NIL); - /* if any additional local variable needed, add them now */ + /* if any additional local variables are needed, add them now */ ... /* write the list of locals/arguments required */ @@ -3613,7 +3618,7 @@ A target language is given the 'Supported' status when Examples must be available and run successfully.
    • - The examples and test-suite must be fully functioning on the Travis Continuous Integration platform. + The examples and test-suite must be fully functioning on the Github Actions Continuous Integration platform.
    @@ -3660,9 +3665,9 @@ Some minimum requirements and notes about languages with the 'Experimental' stat The number of tests in these lists should be no greater than half of the number of tests in the full test-suite.
  • - The examples and test-suite must also be fully functioning on the Travis Continuous Integration platform. - However, experimental languages will be set as 'allow_failures'. - This means that pull requests and normal development commits will not break the entire Travis build should an experimental language fail. + The examples and test-suite must also be fully functioning on the Github Actions Continuous Integration platform. + However, experimental languages will be flagged as 'continue-on-error'. + This means that pull requests and normal development commits will not break the entire Github Actions build should an experimental language fail.
  • Any new failed tests will be fixed on a 'best effort' basis by core developers with no promises made. diff --git a/Doc/Manual/Go.html b/Doc/Manual/Go.html index 1a5bb08c7..4e230c78b 100644 --- a/Doc/Manual/Go.html +++ b/Doc/Manual/Go.html @@ -71,6 +71,7 @@ code. SWIG fills this gap. There are (at least) two different Go compilers. The first is the gc compiler of the Go distribution, normally invoked via the go tool. +SWIG supports the gc compiler version 1.2 or later. The second Go compiler is the gccgo compiler, which is a frontend to the GCC compiler suite. The interface to C/C++ code is completely different for the two Go compilers. @@ -142,44 +143,6 @@ You will now have a Go package that you can import from other Go packages as usual.

    -

    -SWIG can be used without cgo, via the -no-cgo option, but -more steps are required. 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 Go compiler of the Go -distribution would look like this: -

    - -
    -% swig -go -no-cgo example.i
    -% gcc -c code.c    # The C library being wrapped.
    -% gcc -c example_wrap.c
    -% go tool 6g example.go
    -% go tool 6c example_gc.c
    -% go tool pack grc example.a example.6 example_gc.6 code.o example_wrap.o
    -% go tool 6g main.go
    -% go tool 6l main.6
    -
    - -

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

    - -
    -% swig -go -no-cgo -use-shlib example.i
    -% gcc -c -fpic example.c
    -% gcc -c -fpic example_wrap.c
    -% gcc -shared example.o example_wrap.o -o example.so
    -% go tool 6g example.go
    -% go tool 6c example_gc.c
    -% go tool pack grc example.a example.6 example_gc.6
    -% go tool 6g main.go  # your code, not generated by SWIG
    -% go tool 6l main.6
    -
    -

    25.3.1 Go-specific Commandline Options

    @@ -206,9 +169,7 @@ swig -go -help -no-cgo -Generate files that can be used directly, rather than via the Go - cgo tool. This option does not work with Go 1.5 or later. It is - required for versions of Go before 1.2. +This option is no longer supported. @@ -279,13 +240,10 @@ swig -go -help

    25.3.2 Generated Wrapper Files

    -

    There are two different approaches to generating wrapper files, - controlled by SWIG's -no-cgo option. The -no-cgo - option only works with version of Go before 1.5. It is required - when using versions of Go before 1.2.

    - -

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

    +

    +SWIG will generate the following files when generating wrapper +code: +

    • @@ -308,17 +266,6 @@ or C++ compiler.
    -

    When the -no-cgo option is used, and the -gccgo - option is not used, SWIG will also generate an additional file:

    - -
      -
    • -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. -
    • -
    -

    25.4 A tour of basic C/C++ wrapping

    diff --git a/Doc/Manual/Guile.html b/Doc/Manual/Guile.html index 9d55b632b..26679dc4b 100644 --- a/Doc/Manual/Guile.html +++ b/Doc/Manual/Guile.html @@ -183,7 +183,7 @@ information by including a directive like this in the interface file:

    -(The %scheme directive allows to insert arbitrary Scheme +(The %scheme directive allows inserting arbitrary Scheme code into the generated file module.scm; it is placed between the define-module form and the export form.) diff --git a/Doc/Manual/Java.html b/Doc/Manual/Java.html index b9234b24f..9b4213ae9 100644 --- a/Doc/Manual/Java.html +++ b/Doc/Manual/Java.html @@ -644,7 +644,7 @@ java::

    To build the DLL and compile the java code, run NMAKE (you may need to run vcvars32 first). -This is a pretty simplistic Makefile, but hopefully its enough to get you started. +This is a pretty simplistic Makefile, but hopefully it's enough to get you started. Of course you may want to make changes for it to work for C++ by adding in the -c++ command line option for swig and replacing .c with .cxx.

    @@ -4030,7 +4030,7 @@ repetitive duplication of the director:except feature code for each director method. To mitigate this, a second approach is provided via typemaps in a fashion analogous to -the "throws" typemap. +the "throws" typemap. The "throws" typemap provides a way to map all the C++ exceptions listed in a method's defined exceptions (either from a C++ exception specification or a %catches @@ -4081,7 +4081,7 @@ has the $directorthrowshandlers special variable replaced with the the relevant "directorthrows" typemaps, for each and every exception defined for the method. The relevant exceptions can be defined either with a C++ exception specification or %catches as described for the -"throws" typemap. +"throws" typemap.

    @@ -6610,6 +6610,15 @@ Below shows an example modifying the finalizer, assuming the delete met +

    %typemap(javainterfacemodifiers)

    +
    +Interface modifiers for the Java interface generated when using the interface feature, see Java interfaces section. The default is "public interface". +

    +Compatibility note: This typemap was added in SWIG-4.1.0. +

    + +
    +

    %typemap(javainterfacecode, declaration="...", cptrmethod="...")

    @@ -6709,7 +6718,7 @@ The "javaimports" typemap is ignored if the enum class is wrapped by an inner Ja

     [ javaimports typemap ]
    -public interface [ javainterfacename ] {
    +[ javainterfacemodifiers typemap ] [ javainterfacename ] {
     [ javainterfacecode:cptrmethod typemap attribute ]
     ... interface declarations ...
     }
    @@ -9053,6 +9062,11 @@ You may have to add in some "jtype", "jstype", "javain" and "javaout" typemaps w
     Here the default typemaps work for int and char *.
     

    +

    +Note that if you're wanting to effectively replace the JNI code generated for a C/C++ function then you'll need to use %ignore as well +to tell SWIG not to automatically generate a JNI wrapper for it. +

    +

    In summary the %native directive is telling SWIG to generate the Java code to access the JNI C code, but not the JNI C function itself. This directive is only really useful if you want to mix your own hand crafted JNI code and the SWIG generated code into one Java class or package. @@ -9086,7 +9100,7 @@ This method normally calls the C++ destructor or free() for C code.

    The generated code can be debugged using both a Java debugger and a C++ debugger using the usual debugging techniques. Breakpoints can be set in either Java or C++ code and so both can be debugged simultaneously. -Most debuggers do not understand both Java and C++, with one noteable exception of Sun Studio, +Most debuggers do not understand both Java and C++, with one notable exception of Sun Studio, where it is possible to step from Java code into a JNI method within one environment.

    diff --git a/Doc/Manual/Javascript.html b/Doc/Manual/Javascript.html index cce5b5e2e..ab8657510 100644 --- a/Doc/Manual/Javascript.html +++ b/Doc/Manual/Javascript.html @@ -89,19 +89,10 @@ $ swig -javascript -jsc example.i
     $ swig -c++ -javascript -jsc example.i
    -

    The V8 code that SWIG generates should work with most versions from 3.11.10 up to 3.29.14 and later.

    -

    The API headers for V8 >= 4.3.0 define constants which SWIG can use to -determine the V8 version it is compiling for. For versions < 4.3.0, you -need to specify the V8 version when running SWIG. This is specified as a hex -constant, but the constant is read as pairs of decimal digits, so for V8 -3.25.30 use constant 0x032530. This scheme can't represent components > 99, -but this constant is only useful for V8 < 4.3.0, and no V8 versions from -that era had a component > 99. For example:

    -
    -
    -$ swig -c++ -javascript -v8 -DV8_VERSION=0x032530 example.i
    -
    -

    If you're targeting V8 >= 4.3.0, you would just run swig like so:

    +

    The V8 code that SWIG generates requires at least V8 5.0. Keep in mind +that this is theV8 version, not Node.js. To give some perspective, Node.js v6.0 +uses V8 5.0, v12.0 - 7.4, v14.0 - 8.1...

    +

    To generate code for V8, you would run swig like so:

     $ swig -c++ -javascript -v8 example.i
    @@ -401,7 +392,7 @@ the main window.

    As known from node.js one can use require to load javascript modules. -Additionally, node-webkit provides an API that allows to manipulate the window's menu, +Additionally, node-webkit provides an API that allows manipulating the window's menu, open new windows, and many more things.

    diff --git a/Doc/Manual/Library.html b/Doc/Manual/Library.html index 5f72b557d..896cb217b 100644 --- a/Doc/Manual/Library.html +++ b/Doc/Manual/Library.html @@ -44,6 +44,7 @@
  • Utility Libraries @@ -2108,5 +2109,224 @@ For example: +

    12.5.2 attribute.i

    + + +

    +The attribute library contains a set of macros to convert a pair of set/get methods +into a "native" attribute/property. +

    + +

    +Use %attribute when you have a pair of get/set methods to a +primitive type like: +

    + +
    +
    +%include "attribute.i"
    +%attribute(A, int, a, get_a, set_a);
    +
    +struct A {
    +  int get_a() const;
    +  void set_a(int aa);
    +};
    +
    +
    + +

    +and you want to provide that variable as an attribute in the target +language. This example only works for primitive types, not derived +types. +Now you can use the attributes like so (in Python): +

    + +
    +
    +x = A()
    +x.a = 3        # calls A::set_a(3)
    +print(x.a)     # calls A::get_a() const
    +
    +
    + +

    +If you don't provide a 'set' method, a 'read-only' attribute +is generated, ie, like: +

    + +
    +
    +%attribute(A, int, c, get_c);
    +
    +
    + +

    +Use %attributeref when you have const/non-const reference +access methods for primitive types or class/structs, like: +

    + +
    +
    +%attributeref(A, int, b);
    +
    +struct A {
    +  const int & b() const;
    +  int & b();
    +};
    +
    +%attributeref(B, int, c);
    +
    +struct B {
    +  int & c();
    +};
    +
    +
    + +

    +Use the attributes like so (in Python): +

    + +
    +
    +x = A()
    +x.b = 3        # calls A::b()
    +print(x.b)     # calls A::b() const
    +
    +
    + +

    +You can also use +

    + +
    +
    +%attributeref(Class, AttributeType, AttributeName, AccessorMethod)
    +
    +
    + +

    +if the internal C++ reference methods have a different name from the +attribute you want, so +

    + +
    +
    +%attributeref(B, int, d, c);
    +
    +
    + +

    +is the same as the last example, but instead of the attribute 'c' being +called 'c', it is called 'd'. +

    + +

    +Use %attribute2 instead of %attribute to indicate +that reference-pointer translation is required. +Use %attribute2 instead of %attribute in cases like +this: +

    + +
    +
    +%attribute2(MyClass, MyFoo, Foo, GetFoo, SetFoo);
    +%inline %{
    +  struct MyFoo {
    +    int x;
    +  };
    +  class MyClass {
    +    MyFoo foo;
    +  public:
    +    MyFoo & GetFoo() { return foo; }
    +    void SetFoo(const MyFoo &other) { foo = other; }
    +  };
    +%}
    +
    +
    + +

    +Here, the data type of the property is a wrapped type MyFoo and on +the C++ side it is passed by reference. The problem is that the SWIG +wrapper will pass around a pointer (MyFoo *) which is not compatible +with the reference type of the accessors (MyFoo &). Therefore, if you +use %attribute, you'll get an error from your C/C++ +compiler. %attribute2 translates between a pointer and a +reference to eliminate the error. In case you're confused, let's make +it simple: just use %attribute at first, but if the C/C++ +compiler gives an error while compiling the wrapper, +try %attribute2 instead. +

    + +

    +NOTE: remember that if the type contains commas, such as +std::pair<int, int>, you need to use the macro like: +

    + +
    +
    +%attributeref(A, %arg(std::pair<int, int>), pval);
    +
    +
    + +

    +where %arg() 'normalizes' the type to be understood as a single +argument, otherwise the macro will get confused by the comma. +

    + +

    +The %attributeval is the same as %attribute, but +should be used when the type is a class/struct (ie a non-primitive +type) and when the get and set methods return/pass by value. The +following is very similar to the above example, but note that the +access is by value rather than reference. +

    + +
    +
    +%attributeval(MyClassVal, MyFoo, ReadWriteFoo, GetFoo, SetFoo);
    +%attributeval(MyClassVal, MyFoo, ReadOnlyFoo, GetFoo);
    +%inline %{
    +  class MyClassVal {
    +    MyFoo foo;
    +  public:
    +    MyFoo GetFoo() { return foo; }
    +    void SetFoo(MyFoo other) { foo = other; }
    +  };
    +%}
    +
    +
    + +

    +The %attributestring is the same as %attributeval, +but should be used for string class types, which are unusual as they +are a class on the C++ side, but normally an immutable/primitive type +in the target language. Example usage for std::string: +

    + +
    +
    +%include <std_string.i>
    +%attributestring(MyStringyClass, std::string, ReadWriteString, GetString, SetString);
    +%attributestring(MyStringyClass, std::string, ReadOnlyString, GetString);
    +%inline %{
    +  class MyStringyClass {
    +    std::string str;
    +  public:
    +    MyStringyClass(const std::string &val) : str(val) {}
    +    std::string GetString() { return str; }
    +    void SetString(std::string other) { str = other; }
    +  };
    +%}
    +
    +
    + +

    +The %attributestring also works for class types that +have %naturalvar turned on and so is also useful for +shared_ptr which has %naturalvar turned on in +%shared_ptr. +

    + + diff --git a/Doc/Manual/Lua.html b/Doc/Manual/Lua.html index 80807baf4..682126dc9 100644 --- a/Doc/Manual/Lua.html +++ b/Doc/Manual/Lua.html @@ -1520,7 +1520,7 @@ function nil > -

    This behaviour was changed. Now unless -squash-bases option is provided, Derived store a list of it's bases and if some symbol is not found in it's own service tables +

    This behaviour was changed. Now unless -squash-bases option is provided, Derived stores a list of its bases and if some symbol is not found in its own service tables then its bases are searched for it. Option -squash-bases will effectively return old behaviour.

    @@ -1638,7 +1638,7 @@ More details can be found in the carrays.
    // using the C-array
     %include <carrays.i>
    -// this declares a batch of function for manipulating C integer arrays
    +// this declares a batch of functions for manipulating C integer arrays
     %array_functions(int, int)
     
     extern void sort_int(int* arr, int len); // the function to wrap
    @@ -1997,10 +1997,10 @@ So when 'p:Print()' is called, the __index looks on the object metatable for a '
     In theory, you can play with this usertable & add new features, but remember that it is a shared table between all instances of one class, and you could very easily corrupt the functions in all the instances.
     

    -Note: Both the opaque structures (like the FILE*) and normal wrapped classes/structs use the same 'swig_lua_userdata' structure. Though the opaque structures has do not have a metatable attached, or any information on how to dispose of them when the interpreter has finished with them. +Note: Both the opaque structures (like the FILE*) and normal wrapped classes/structs use the same 'swig_lua_userdata' structure. Though the opaque structures do not have a metatable attached, or any information on how to dispose of them when the interpreter has finished with them.

    -Note: Operator overloads are basically done in the same way, by adding functions such as '__add' & '__call' to the class' metatable. The current implementation is a bit rough as it will add any member function beginning with '__' into the metatable too, assuming its an operator overload. +Note: Operator overloads are basically done in the same way, by adding functions such as '__add' & '__call' to the class' metatable. The current implementation is a bit rough as it will add any member function beginning with '__' into the metatable too, assuming it's an operator overload.

    29.7.3 Memory management

    diff --git a/Doc/Manual/Modula3.html b/Doc/Manual/Modula3.html deleted file mode 100644 index fc4ffa03c..000000000 --- a/Doc/Manual/Modula3.html +++ /dev/null @@ -1,942 +0,0 @@ - - - -SWIG and Modula-3 - - - - -

    31 SWIG and Modula-3

    - - - - - - -

    -This chapter describes SWIG's support for -Modula-3. -You should be familiar with the -basics -of SWIG, -especially -typemaps. -

    - -

    31.1 Overview

    - - -

    -Modula-3 is a compiled language in the tradition of Niklaus Wirth's Modula 2, -which is in turn a successor to Pascal. -

    - -

    -SWIG's Modula-3 support is currently very basic and highly experimental! -Many features are still not designed satisfyingly -and I need more discussion about the odds and ends. -Don't rely on any feature, incompatible changes are likely in the future! -However, the Modula-3 generator was already useful for interfacing -to the libraries: -

    - -
      -
    1. - -PLPlot - -
    2. -
    3. - -FFTW - -
    4. -
    - -

    31.1.1 Motivation

    - - -

    -Although it is possible to write Modula-3 code that performs as well as C/C++ -most existing libraries are not written in Modula-3 but in C or C++, and -even libraries in other languages may provide C header files. -

    - -

    -Fortunately Modula-3 can call C functions, but you have to write Modula-3 -interfaces to them, and to make things comfortable you will also need -wrappers that convert between high-level features of Modula-3 (garbage -collecting, exceptions) and the explicit tracking of allocated memory and -exception codes used by C APIs. -

    - -

    -SWIG converts C headers to Modula-3 interfaces for you, and using typemaps -you can pass TEXTs or open arrays, and convert error return codes -into exceptions. -

    - -

    -If the library API is ill designed -writing appropriate typemaps can still be time-consuming. -E.g. C programmers are very creative to work-around -missing data types like (real) enumerations and sets. -You should turn such work-arounds back to the Modula-3 way -otherwise you lose static safety and consistency. -

    - -

    -Without SWIG you would probably never consider trying to call C++ libraries -from Modula-3, but with SWIG this is becomes feasible. -SWIG can generate C wrappers to C++ functions and object methods -that may throw exceptions, and then wrap these C wrappers for Modula-3. -To make it complete you can then hide the C interface with Modula-3 classes and -exceptions. -

    - -

    -SWIG allows you to call C and C++ libraries from Modula-3 (even with call back -functions), but it doesn't allow you to easily integrate a Modula-3 module into -a C/C++ project. -

    - -

    31.2 Conception

    - - -

    31.2.1 Interfaces to C libraries

    - - -

    -Modula-3 has integrated support for calling C functions. -This is also extensively used by the standard Modula-3 libraries -to call OS functions. -The Modula-3 part of SWIG and the corresponding SWIG library -modula3.swg -contain code that uses these features. -Because of the built-in support there is no need -for calling the SWIG kernel to generate wrappers written in C. -All conversion and argument checking can be done in Modula-3 -and the interfacing is quite efficient. -All you have to do is to write pieces of Modula-3 code -that SWIG puts together. -

    - - - - - - - - - - - - - - - - - - - -
    C library support integrated in Modula-3
    Pragma <* EXTERNAL *>Precedes a declaration of a PROCEDURE that is implemented -in an external library instead of a Modula-3 module.
    Pragma <* CALLBACK *>Precedes a declaration of a PROCEDURE that should be called -by external library code.
    Module CtypesContains Modula-3 types that match some basic C types.
    Module M3toCContains routines that convert between Modula-3's TEXT type -and C's char * type.
    - -

    -In each run of SWIG the Modula-3 part -generates several files: -

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Module name schemeIdentifier for %insertDescription
    ModuleRaw.i3m3rawintfDeclaration of types that are equivalent to those of the C library, - EXTERNAL procedures as interface to the C library functions
    ModuleRaw.m3m3rawimplAlmost empty.
    Module.i3m3wrapintfDeclaration of comfortable wrappers to the C library functions.
    Module.m3m3wrapimplImplementation of the wrappers that - convert between Modula-3 and C types, - check for validity of values, - hand-over resource management to the garbage collector using WeakRefs - and raises exceptions.
    m3makefilem3makefileAdd the modules above to the Modula-3 project and - specify the name of the Modula-3 wrapper library - to be generated. - - Today I'm not sure if it is a good idea - to create a m3makefile in each run, - because SWIG must be started for each Modula-3 module it creates. - Thus the m3makefile is overwritten each time. :-( -
    - -

    -Here's a scheme of how the function calls to Modula-3 wrappers -are redirected to C library functions: -

    - - - - - - - - - - - - - - - - - -
    - Modula-3 wrapper
    - Module.i3
    - generated by Modula-3 part of SWIG -
    - - |
    - v -
    - Modula-3 interface to C
    - ModuleRaw.i3
    - generated by Modula-3 part of SWIG -
    --> - C library -
    - - -

    -I have still no good conception how one can split C library interfaces -into type oriented interfaces. -A Module in Modula-3 represents an Abstract DataType -(or call it a static classes, i.e. a class without virtual methods). -E.g. if you have a principal type, say Database, -it is good Modula-3 style to set up one Module with the name Database -where the database type is declared with the name T -and where all functions are declared that operates on it. -

    - -

    -The normal operation of SWIG is to generate a fixed set of files per call. -To generate multiple modules one has to write one SWIG interface -(different SWIG interfaces can share common data) per module. -Identifiers belonging to a different module may ignored (%ignore) -and the principal type must be renamed (%typemap). -

    - - -

    31.2.2 Interfaces to C++ libraries

    - - -

    -Interfaces to C++ files are much more complicated and -there are some more design decisions that are not made, yet. -Modula-3 has no support for C++ functions -but C++ compilers should support generating C++ functions -with a C interface. -

    - -

    -Here's a scheme of how the function calls to Modula-3 wrappers -are redirected to C library functions: -

    - - - - - - - - - - - - - - - - - -
    - Modula-3 wrapper
    - Module.i3
    - generated by Modula-3 part of SWIG -
    C++ library
    - - |
    - v -
    - ^
    - | -
    - Modula-3 interface to C
    - ModuleRaw.i3
    - generated by Modula-3 part of SWIG -
    --> - C interface to C++
    - module_wrap.cxx
    - generated by the SWIG core -
    - -

    -Wrapping C++ libraries arises additional problems: -

    -
      -
    • -Is it sensible to wrap C++ classes with Modula-3 classes? -
    • -
    • -How to find the wrapping Modula-3 class -for a class pointer that is returned by a C++ routine? -
    • -
    • -How to deal with multiple inheritance -which was neglected for Modula-3 for good reasons? -
    • -
    • -Is it possible to sub-class C++ classes with Modula-3 code? -This issue is addressed by directors, -a feature that was experimentally added to some Language modules -like -Java and -Python. -
    • -
    • -How to manage storage with the garbage collector of Modula-3? -Support for - -%newobject and %typemap(newfree) -isn't implemented, yet. -What's about resources that are managed by the garbage collector -but shall be passed back to the storage management of the C++ library? -This is a general issue which is not solved in a satisfying fashion -as far as I know. -
    • -
    • -How to turn C++ exceptions into Modula-3 exceptions? -There's also no support for - -%exception, yet. -
    • -
    - -

    -Be warned: -There is no C++ library I wrote a SWIG interface for, -so I'm not sure if this is possible or sensible, yet. -

    - -

    31.3 Preliminaries

    - - -

    31.3.1 Compilers

    - - -

    -There are different Modula-3 compilers around: -cm3, pm3, ezm3, Klagenfurth Modula-3, Cambridge Modula-3. -SWIG itself does not contain compiler specific code -but the modula3.swg library file -may do so. -For testing examples I use Critical Mass cm3. -

    - - -

    31.3.2 Additional Commandline Options

    - - -

    -There are some experimental command line options -that prevent SWIG from generating interface files. -Instead files are emitted that may assist you -when writing SWIG interface files. -

    - - - - - - - - - - - - - - - - - - - - - -
    Modula-3 specific optionsDescription
    -generateconst <file> -Disable generation of interfaces and wrappers. -Instead write code for computing numeric values of constants -to the specified file. -
    -C code may contain several constant definitions -written as preprocessor macros. -Other language modules of SWIG use -compute-once-use-readonly variables or -functions to wrap such definitions. -All of them can invoke C code dynamically -for computing the macro values. -But if one wants to turn them into Modula-3 -integer constants, enumerations or set types, -the values of these expressions has to be known statically. -Although definitions like (1 << FLAG_MAXIMIZEWINDOW) -must be considered as good C style -they are hard to convert to Modula-3 -since the value computation can use every feature of C. -
    -Thus I implemented these switch -to extract all constant definitions -and write a C program that output the values of them. -It works for numeric constants only -and treats all of them as double. -Future versions may generate a C++ program -that can detect the type of the macros -by overloaded output functions. -Then strings can also be processed. -
    -generaterename <file> -Disable generation of interfaces and wrappers. -Instead generate suggestions for %rename. -
    -C libraries use a naming style -that is neither homogeneous nor similar to that of Modula-3. -C function names often contain a prefix denoting the library -and some name components separated by underscores -or capitalization changes. -To get library interfaces that are really Modula-3 like -you should rename the function names with the %rename directive. -This switch outputs a list of such directives -with a name suggestion generated by a simple heuristic. -
    -generatetypemap <file> -Disable generation of interfaces and wrappers. -Instead generate templates for some basic typemaps. -
    - -

    31.4 Modula-3 typemaps

    - - -

    31.4.1 Inputs and outputs

    - - -

    -Each C procedure has a bunch of inputs and outputs. -Inputs are passed as function arguments, -outputs are updated referential arguments and -the function value. -

    - -

    -Each C type can have several typemaps -that apply only in case if a type is used -for an input argument, for an output argument, -or for a return value. -A further typemap may specify -the direction that is used for certain parameters. -I have chosen this separation -in order to be able to write general typemaps for the modula3.swg typemap library. -In the library code the final usage of the type is not known. -Using separate typemaps for each possible use -allows appropriate definitions for each case. -If these pre-definitions are fine -then the direction of the function parameter -is the only hint the user must give. -

    - -

    -The typemaps specific to Modula-3 have a common name scheme: -A typemap name starts with "m3", -followed by "raw" or "wrap" -depending on whether it controls the generation -of the ModuleRaw.i3 or the Module.i3, respectively. -It follows an "in" for typemaps applied to input argument, -"out" for output arguments, "arg" for all kind of arguments, -"ret" for returned values. -

    - -

    -The main task of SWIG is to build wrapper function, -i.e. functions that convert values between C and Modula-3 -and call the corresponding C function. -Modula-3 wrapper functions generated by SWIG -consist of the following parts: -

    -
      -
    • Generate PROCEDURE signature.
    • -
    • Declare local variables.
    • -
    • Convert input values from Modula-3 to C.
    • -
    • Check for input value integrity.
    • -
    • Call the C function.
    • -
    • Check returned values, e.g. error codes.
    • -
    • Convert and write back values into Modula-3 records.
    • -
    • Free temporary storage.
    • -
    • Return values.
    • -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    TypemapExampleDescription
    m3wrapargvar$1: INTEGER := $1_name; - Declaration of some variables needed for temporary results. -
    m3wrapargconst$1 = "$1_name"; - Declaration of some constant, maybe for debug purposes. -
    m3wrapargrawORD($1_name) - The expression that should be passed as argument to the raw Modula-3 interface function. -
    m3wrapargdirout - Referential arguments can be used for input, output, update. - ??? -
    m3wrapinmodeREADONLY - One of Modula-3 parameter modes - VALUE (or empty), - VAR, - READONLY -
    m3wrapinname - New name of the input argument. -
    m3wrapintype - Modula-3 type of the input argument. -
    m3wrapindefault - Default value of the input argument -
    m3wrapinconv$1 := M3toC.SharedTtoS($1_name); - Statement for converting the Modula-3 input value to C compliant value. -
    m3wrapincheckIF Text.Length($1_name) > 10 THEN RAISE E("str too long"); END; - Check the integrity of the input value. -
    m3wrapoutname - Name of the RECORD field to be used for returning multiple values. - This applies to referential output arguments that shall be turned - into return values. -
    m3wrapouttype - Type of the value that is returned instead of a referential output argument. -
    m3wrapoutconv -
    m3wrapoutcheck -
    m3wrapretraw -
    m3wrapretname -
    m3wraprettype -
    m3wrapretvar -
    m3wrapretconv -
    m3wrapretcheck -
    m3wrapfreeargM3toC.FreeSharedS(str, arg1); - Free resources that were temporarily used in the wrapper. - Since this step should never be skipped, - SWIG will put it in the FINALLY branch - of a TRY .. FINALLY structure. -
    - - -

    31.4.2 Subranges, Enumerations, Sets

    - - -

    -Subranges, enumerations, and sets are machine oriented types -that make Modula very strong and expressive compared -with the type systems of many other languages. -

    - -
      -
    • -Subranges are used for statically restricted choices of integers. -
    • -
    • -Enumerations are used for named choices. -
    • -
    • -Sets are commonly used for flag (option) sets. -
    • -
    - -

    -Using them extensively makes Modula code very safe and readable. -

    - -

    -C supports enumerations, too, but they are not as safe as the ones of Modula. -Thus they are abused for many things: -For named choices, for integer constant definitions, for sets. -To make it complete every way of defining a value in C -(#define, const int, enum) -is somewhere used for defining something -that must be handled completely different in Modula-3 -(INTEGER, enumeration, SET). -

    - -

    -I played around with several %features and %pragmas -that split the task up into converting -the C bit patterns (integer or bit set) -into Modula-3 bit patterns (integer or bit set) -and change the type as requested. -See the corresponding example in the -Examples/modula3/enum/example.i file. -This is quite messy and not satisfying. -So the best what you can currently do is -to rewrite constant definitions manually. -Though this is a tedious work -that I'd like to automate. -

    - - -

    31.4.3 Objects

    - - -

    -Declarations of C++ classes are mapped to OBJECT types -while it is tried to retain the access hierarchy -"public - protected - private" using partial revelation. -Though the example in -Examples/modula3/class/example.i -is not really useful, yet. -

    - - -

    31.4.4 Imports

    - - -

    -Pieces of Modula-3 code provided by typemaps -may contain identifiers from foreign modules. -If the typemap m3wrapinconv for blah * -contains code using the function M3toC.SharedTtoS -you may declare %typemap("m3wrapinconv:import") blah * %{M3toC%}. -Then the module M3toC is imported -if the m3wrapinconv typemap for blah * -is used at least once. -Use %typemap("m3wrapinconv:import") blah * %{MyConversions AS M3toC%} -if you need module renaming. -Unqualified import is not supported. -

    - -

    -It is cumbersome to add this typemap to each piece of Modula-3 code. -It is especially useful when writing general typemaps -for the modula3.swg typemap library. -For a monolithic module you might be better off -if you add the imports directly: -

    - -
    -
    -%insert(m3rawintf) %{
    -IMPORT M3toC;
    -%}
    -
    - - -

    31.4.5 Exceptions

    - - -

    -Modula-3 provides another possibility -of an output of a function: exceptions. -

    - -

    -Any piece of Modula-3 code that SWIG inserts -due to a typemap can raise an exception. -This way you can also convert an error code -from a C function into a Modula-3 exception. -

    - -

    -The RAISES clause is controlled -by typemaps with the throws extension. -If the typemap m3wrapinconv for blah * -contains code that may raise the exceptions OSError.E -you should declare -%typemap("m3wrapinconv:throws") blah * %{OSError.E%}. -

    - -

    31.4.6 Example

    - - -

    -The generation of wrappers in Modula-3 needs very fine control -to take advantage of the language features. -Here is an example of a generated wrapper -where almost everything is generated by a typemap: -

    - -
    -         (* %relabel  m3wrapinmode m3wrapinname m3wrapintype  m3wrapindefault *)
    -  PROCEDURE Name     (READONLY       str       :    TEXT    :=      ""       )
    -              (* m3wrapoutcheck:throws *)
    -     : NameResult RAISES {E} =
    -    CONST
    -      arg1name = "str";                  (* m3wrapargconst *)
    -    VAR
    -      arg0   : C.char_star;              (* m3wrapretvar *)
    -      arg1   : C.char_star;              (* m3wrapargvar *)
    -      arg2   : C.int;
    -      result : RECORD
    -           (*m3wrapretname  m3wraprettype*)
    -                 unixPath : TEXT;
    -           (*m3wrapoutname  m3wrapouttype*)
    -                 checksum : CARDINAL;
    -               END;
    -    BEGIN
    -      TRY
    -        arg1 := M3toC.SharedTtoS(str);   (* m3wrapinconv *)
    -        IF Text.Length(arg1) > 10 THEN   (* m3wrapincheck *)
    -          RAISE E("str too long");
    -        END;
    - (* m3wrapretraw           m3wrapargraw *)
    -        arg0 := MessyToUnix  (arg1,   arg2);
    -        result.unixPath := M3toC.CopyStoT(arg0);  (* m3wrapretconv *)
    -        result.checksum := arg2;         (* m3wrapoutconv *)
    -        IF result.checksum = 0 THEN      (* m3wrapoutcheck *)
    -          RAISE E("invalid checksum");
    -        END;
    -      FINALLY
    -        M3toC.FreeSharedS(str, arg1);     (* m3wrapfreearg *)
    -      END;
    -    END Name;
    -
    - - -

    31.5 More hints to the generator

    - - -

    31.5.1 Features

    - - - - - - - - - - - - - - - - - - -
    FeatureExampleDescription
    multiretval%m3multiretval get_box; or - %feature("modula3:multiretval") get_box;Let the denoted function return a RECORD - rather than a plain value. - This RECORD contains all arguments with "out" direction - including the return value of the C function (if there is one). - If more than one argument is "out" - then the function must have the multiretval feature activated, - but it is explicitly requested from the user to prevent mistakes.
    constnumeric%constnumeric(12) twelve; or - %feature("constnumeric", "12") twelve;This feature can be used to tell Modula-3's back-end of SWIG - the value of an identifier. - This is necessary in the cases - where it was defined by a non-trivial C expression. - This feature is used by the - -generateconst option. - In future it may be generalized to other kind of values - such as strings. -
    - -

    31.5.2 Pragmas

    - - - - - - - - - - - - - - - - - - -
    PragmaExampleDescription
    unsafe%pragma(modula3) unsafe="true";Mark the raw interface modules as UNSAFE. - This will be necessary in many cases.
    library%pragma(modula3) library="m3fftw";Specifies the library name for the wrapper library to be created. - It should be distinct from the name of the library to be wrapped.
    - -

    31.6 Remarks

    - - -
      -
    • -The Modula-3 part of SWIG doesn't try to generate nicely formatted code. -If you need to read the generated code, use m3pp to postprocess the -Modula files. -
    • -
    - - - diff --git a/Doc/Manual/Ocaml.html b/Doc/Manual/Ocaml.html index 4ae07e969..9b59eec61 100644 --- a/Doc/Manual/Ocaml.html +++ b/Doc/Manual/Ocaml.html @@ -720,7 +720,6 @@ Here's a simple example using Trolltech's Qt Library: class QApplication { public: QApplication( int argc, char **argv ); - void setMainWidget( QWidget *widget ); void exec(); }; @@ -736,16 +735,15 @@ public:
    -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$ 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 qt.mli
    -bash-2.05a$ ocamlc -c qt.ml
    -bash-2.05a$ ocamlmktop -custom swig.cmo -I `camlp4 -where` \
    +$ QTPATH=/your/qt/path
    +$ for file in swig.mli swig.ml swigp4.ml ; do swig -ocaml -co $file ; done
    +$ ocamlc -c swig.mli ; ocamlc -c swig.ml
    +$ ocamlc -I `camlp4 -where` -pp "camlp4o pa_extend.cmo q_MLast.cmo" -c swigp4.ml
    +$ swig -ocaml -c++ -o qt_wrap.c qt.i
    +$ ocamlc -c -ccopt -xc++ -ccopt -g -g -ccopt -I$QTPATH/include qt_wrap.c
    +$ ocamlc -c qt.mli
    +$ ocamlc -c qt.ml
    +$ ocamlmktop -custom swig.cmo -I `camlp4 -where` \
       camlp4o.cma swigp4.cmo qt_wrap.o qt.cmo -o qt_top -cclib \
       -L$QTPATH/lib -cclib -lqt
     
    diff --git a/Doc/Manual/Octave.html b/Doc/Manual/Octave.html index bdef5db7c..151957cff 100644 --- a/Doc/Manual/Octave.html +++ b/Doc/Manual/Octave.html @@ -570,13 +570,13 @@ __mul__ a * b __div__ a / b __pow__ a ^ b __ldiv__ a \ b -__lshift__ a << b -__rshift__ a >> b -__lt__ a < b -__le__ a <= b +__lshift__ a << b +__rshift__ a >> b +__lt__ a < b +__le__ a <= b __eq__ a == b -__ge__ a >= b -__gt__ a > b +__ge__ a >= b +__gt__ a > b __ne__ a != b __el_mul__ a .* b __el_div__ a ./ b @@ -598,16 +598,16 @@ On the C++ side, the default mappings are as follows: %rename(__mul__) *::operator*; %rename(__div__) *::operator/; %rename(__mod__) *::operator%; -%rename(__lshift__) *::operator<<; -%rename(__rshift__) *::operator>>; +%rename(__lshift__) *::operator<<; +%rename(__rshift__) *::operator>>; %rename(__el_and__) *::operator&&; %rename(__el_or__) *::operator||; %rename(__xor__) *::operator^; %rename(__invert__) *::operator~; -%rename(__lt__) *::operator<; -%rename(__le__) *::operator<=; -%rename(__gt__) *::operator>; -%rename(__ge__) *::operator>=; +%rename(__lt__) *::operator<; +%rename(__le__) *::operator<=; +%rename(__gt__) *::operator>; +%rename(__ge__) *::operator>=; %rename(__eq__) *::operator==; %rename(__ne__) *::operator!=; %rename(__not__) *::operator!; @@ -634,7 +634,7 @@ You can use it to define special behavior, like for example defining Octave oper %extend A { string __str__() { stringstream sout; - sout<<$self->value; + sout<<$self->value; return sout.str(); } } diff --git a/Doc/Manual/Perl5.html b/Doc/Manual/Perl5.html index 1e7bd9f86..d1b5d6746 100644 --- a/Doc/Manual/Perl5.html +++ b/Doc/Manual/Perl5.html @@ -91,10 +91,10 @@

    This chapter describes SWIG's support of Perl5. Although the Perl5 module is one of the earliest SWIG modules, it has continued to evolve -and has been improved greatly with the help of SWIG users. For the -best results, it is recommended that SWIG be used with Perl 5.8 or -later. We're no longer testing regularly with older versions, but -Perl 5.6 seems to mostly work, while older versions don't. +and has been improved greatly with the help of SWIG users. As of SWIG +4.1.0, the minimum version of Perl we aim to support is Perl 5.8.0. +We can no longer easily test with older versions, and they no longer +seem to be in active use.

    31.1 Overview

    @@ -680,7 +680,6 @@ files(s) field". installation under "Additional include directories".
  • Define the symbols WIN32 and MSWIN32 under preprocessor options. -If using the ActiveWare port, also define the symbol PERL_OBJECT. Note that all extensions to the ActiveWare port must be compiled with the C++ compiler since Perl has been encapsulated in a C++ class. @@ -1065,7 +1064,7 @@ int *Foo_x_get(Foo *self) {

    If you want to set an array member, you will need to supply a "memberin" typemap described later in this chapter. As a special case, SWIG does generate -code to set array members of type char (allowing you to store a Python +code to set array members of type char (allowing you to store a Perl string in the structure).

    @@ -1736,7 +1735,7 @@ See the chapter on "Customization fea
    -%except(python) {
    +%except(perl5) {
       try {
         $function
       }
    @@ -2243,7 +2242,7 @@ can be done using the EXTEND() macro as in:
         EXTEND(sp, 1);              /* Extend the stack by 1 object */
       }
       $result = sv_newmortal();
    -  sv_setiv($target, (IV) *($1));
    +  sv_setiv($result, (IV) *($1));
       argvi++;
     }
     
    @@ -2320,7 +2319,7 @@ typedef struct {

    By default, SWIG doesn't know how to the handle the values structure -member it's an array, not a pointer. In this case, SWIG makes the array member +member because it's an array, not a pointer. In this case, SWIG makes the array member read-only. Reading will simply return a pointer to the first item in the array. To make the member writable, a "memberin" typemap can be used.

    @@ -2651,8 +2650,8 @@ constructors and destructors for the package and are always named "new" and "DESTROY". The constructor always returns a tied hash table. This hash table is used to access the member variables of a structure in addition to being able to invoke member functions. The -%OWNER and %BLESSEDMEMBERS hash tables are used -internally and described shortly. +%OWNER and %BLESSEDMEMBERS hash tables are +implementation details used internally and described shortly.

    @@ -2740,8 +2739,15 @@ to a C function that remembers the object, and then destroy the corresponding Perl object (this situation turns out to come up frequently when constructing objects like linked lists and trees). When C takes possession of an object, you can change Perl's ownership -by simply deleting the object from the %OWNER hash. This is -done using the DISOWN method. +by calling the DISOWN method (which will delete the object +from the internal %OWNER hash). +

    + +

    +The %OWNER hash is an implementation detail, discussed here +only to help clarify the operation of ACQUIRE and DISOWN. +You should not access %OWNER directly - the details of how it +works (and possibly even its existence) may change in future SWIG versions.

    diff --git a/Doc/Manual/Php.html b/Doc/Manual/Php.html
    index 09c514e94..419e87b50 100644
    --- a/Doc/Manual/Php.html
    +++ b/Doc/Manual/Php.html
    @@ -50,18 +50,19 @@
     
     
     

    -In this chapter, we discuss SWIG's support of PHP. SWIG currently supports -generating wrappers for PHP7. Support for PHP5 was removed in SWIG 4.0.0 -and support for PHP4 was removed in SWIG 1.3.37. +In this chapter, we discuss SWIG's support of PHP. Currently any PHP7 or PHP8 +release should work.

    -Currently any PHP7 release should work. +Support for PHP7 was added in SWIG 3.0.11 and for PHP8 in 4.1.0. +Support for PHP5 was removed in SWIG 4.0.0 and support for PHP4 was removed in +SWIG 1.3.37. There never was a PHP6 release.

    In order to use this module, you will need to have a copy of the PHP -include files to compile the SWIG generated files. If you installed +include files to compile the SWIG generated C/C++ sources. If you installed PHP from a binary package, you may need to install a "php-dev" or "php-devel" package for these to be installed. You can find out where these files are by running php-config --includes. To use the built PHP module you @@ -84,16 +85,21 @@ swig -php7 example.i

    -This will produce 3 files example_wrap.c, php_example.h and -example.php. The first file, example_wrap.c contains all of +This will produce 2 files: example_wrap.c and php_example.h. +The first file, example_wrap.c contains all of the C code needed to build a PHP extension. The second file, php_example.h contains the header information needed if you wish to statically link the extension into the php interpreter. -The third file, -example.php can be included by PHP scripts. It attempts to -dynamically load the extension and contains extra php code specified -in the interface file. If wrapping C++ code with PHP classes, it will -also contain PHP class wrappers. +

    + +

    +If the interface file uses %pragma(php) include=... or +%pragma(php) code=... then SWIG will also generate a third file, +example.php to contain what these specify. In SWIG < 4.1.0, +this third file was always generated as it defined the PHP classes, etc +(but this is now done via C code in example_wrap.c) and also +contained code to dynamically load the extension (but this used the +PHP dl() function, which isn't recommended nowadays).

    @@ -139,8 +145,20 @@ least work for Linux though):

    To test the extension from a PHP script, you first need to tell PHP to -load it. To do this, add a line like this to the [PHP] section of -php.ini: +load it. Assuming you're using PHP 7.2 or higher, the recommended (and +simplest!) way to do this is to copy it to PHP's default extension directory +and add a line like this to the [PHP] section of php.ini: +

    + +
    +        extension=modulename
    +
    + +

    +PHP < 7.2 doesn't support loading by just the module name, so you need +to specify the filename of the module to be specified, which varies +between platforms. And for any PHP version, if the module is not in PHP's +default extension directory, you also need to specify the path, for example:

    @@ -148,13 +166,9 @@ load it.  To do this, add a line like this to the [PHP] section of
     

    -If the module is in PHP's default extension directory, you can omit the path. -

    - -

    -For some SAPIs (for example, the CLI SAPI) you can instead use the -dl() function to load -an extension at run time, by adding a line like this to the start of each +If you're using the PHP CLI SAPI it's possible (but not recommended) to use the +dl() function to +load an extension at run time, by adding a line like this to the start of each PHP script which uses your extension:

    @@ -163,23 +177,11 @@ PHP script which uses your extension:
  • -But note that dl() isn't supported when running PHP through a -webserver - you'll need to use extension in php.ini as -described above. -

    - -

    -The PHP module which SWIG generates will also attempt to do the dl() -call for you if the extension isn't already loaded: -

    - -
    -        include("example.php");
    -
    - -

    -This PHP module also defines the PHP classes for the wrapped API, so you'll -almost certainly want to include it anyway. +But to do this portably you need to take into account that pathnames and the +filename extension vary by platform, and for security reasons PHP no longer +supports dl() when running PHP through a webserver. Overall it's +better to instead use extension in php.ini as described +above.

    32.2 Basic PHP interface

    @@ -219,24 +221,19 @@ you can access the constants in your PHP script like this,

    -include("example.php");
    -
     echo "PI = " . PI . "\n";
    -
     echo "E = " . E . "\n";
    -
     

    -There's one peculiarity of how constants work in PHP which it is useful -to note (this is not specific to SWIG though) - if you try to use an undeclared -constant, PHP will emit a warning (or a notice in PHP 7.1 and earlier) and then -expand the constant to a string version of the constant's name. Unfortunately -it is easy to miss the warning message if you're using PHP in a webserver as -it will probably end up in error.log or similar. Apparently this will throw -an Error in a future version of PHP, but until then it's something to be -aware of. +There's one peculiarity of how constants work in PHP prior to PHP 8 +which it is useful to note (this is not specific to SWIG though) - if you try +to use an undeclared constant, PHP will emit a warning (or a notice in PHP 7.1 +and earlier) and then expand the constant to a string version of the constant's +name. Unfortunately it is easy to miss the warning message if you're using PHP +in a webserver as it will probably end up in error.log or similar. PHP 8.0 +made this an error.

    @@ -256,8 +253,6 @@ accessed incorrectly in PHP,

    -include("example.php");
    -
     if(EASY_TO_MISPEL) {
       ...
     } else {
    @@ -298,7 +293,6 @@ is accessed as follows:
     

    -include("example.php");
     print seki_get();
     seki_set( seki_get() * 2); # The C variable is now 4.
     print seki_get();
    @@ -306,8 +300,10 @@ print seki_get();
     
     

    SWIG supports global variables of all C datatypes including pointers -and complex objects. Additional types can be supported by using the -varinit typemap. +and complex objects. To support additional types, you just need to +supply the standard in and out typemaps, which get +used because of the wrapping as _get() and _set() +functions.

    @@ -342,13 +338,86 @@ Will be accessed in PHP like this :

    -include("example.php");
     $a = foo(2);
     $b = bar(3.5, -1.5);
     $c = bar(3.5);  # Use default argument for 2nd parameter
     
     
    +

    +SWIG generates PHP type declarations for function parameters and return +types for PHP 8 and later (we don't try to support PHP 7's more limited type +declarations and the generated wrappers compiled for PHP 7 will not have any +type declarations). +

    + +

    +You can control the generation of PHP type declarations using +the "php:type" %feature. This has three settings: +

    + +
      +
    • If unset or set to "0" then no type declarations are generated, e.g.: %feature("php:type", "0"); +

      +
    • +
    • If set to "1" then type declarations are generated for both parameters and return types, e.g.: %feature("php:type", "1"); +

    • +
    • The default setting is "compat", which is the same as "1" except no + return type declarations are generated for virtual methods for which + directors are enabled. This provides better compatibility for PHP + subclasses of wrapped virtual methods in existing SWIG-generated bindings, e.g.: %feature("php:type", "compat"); +

    • +
    + +

    +If you have an existing PHP interface and are upgrading to SWIG >= 4.1.0 +then the default "compat" setting should work well. +

    + +

    +If you're writing a new set of bindings and only targeting PHP8 or newer +then enabling type declarations everywhere probably makes sense. It will +only actually make a difference if you enable directors and are wrapping C++ +classes with virtual methods, but doing it anyway means you won't forget to if +the code you are wrapping later evolves to have such classes and methods. +

    + +

    +The type declaration information will make the generated source code and +compiler extension module larger, so you might want to turn off type +declarations if keeping these small is important to you. If you find you +need to turn off type declarations to fix a problem, please let us know +via our github issue tracker. +

    + +

    +Note that being a SWIG feature this can be specified globally (like above) or +per class, per method, etc. See the %feature directives +section for full details of how to control at a fine-grained level. +

    + +

    +The PHP type information is specified via a "phptype" attribute on "in" and +"out" typemaps, and these have been added for all the typemaps we supply for +PHP. We don't currently support this for "argout" templates, but probably +will in a future version. +

    + +

    +If you have written custom SWIG typemaps for PHP and want to add PHP type +declarations, then the syntax is very like how you'd specify the type in +PHP code, e.g. %typemap(in, phptype="int|string|Foo") means the +typemap accepts a PHP int or string or an object of class Foo, +%typemap(in, phptype="?int") means a PHP int or NULL, etc. +As well as the standard PHP type declaration types, SWIG also understands the +special type "SWIGTYPE" as an entry in phptype, which means the PHP type +corresponding to the type that this typemap matched on - for a object this +will give you the PHP class for the object, and for a pointer to a non-class +type it will give you the name of the PHP class SWIG created for that +pointer type. +

    + - - - - - -

    -This chapter describes SWIG support for Pike. As of this writing, the -SWIG Pike module is still under development and is not considered -ready for prime time. The Pike module is being developed against the -Pike 7.4.10 release and may not be compatible with previous versions -of Pike. -

    - -

    -This chapter covers most SWIG features, but certain low-level details -are covered in less depth than in earlier chapters. At the very -least, make sure you read the "SWIG Basics" -chapter.
    -

    - -

    37.1 Preliminaries

    - - -

    37.1.1 Running SWIG

    - - -

    -Suppose that you defined a SWIG module such as the following: -

    - -
    -
    %module example

    %{
    #include "example.h"
    %}

    int fact(int n);
    -
    - -

    -To build a C extension module for Pike, run SWIG using the -pike option : -

    - -
    -
    $ swig -pike example.i
    -
    - -

    -If you're building a C++ extension, be sure to add the -c++ option: -

    - -
    -
    $ swig -c++ -pike example.i
    -
    - -

    -This creates a single source file named example_wrap.c (or example_wrap.cxx, if you -ran SWIG with the -c++ option). -The SWIG-generated source file contains the low-level wrappers that need -to be compiled and linked with the rest of your C/C++ application to -create an extension module. -

    - -

    -The name of the wrapper file is derived from the name of the input -file. For example, if the input file is example.i, the name -of the wrapper file is example_wrap.c. To change this, you -can use the -o option: -

    - -
    -
    $ swig -pike -o pseudonym.c example.i
    -
    -

    37.1.2 Getting the right header files

    - - -

    -In order to compile the C/C++ wrappers, the compiler needs to know the -path to the Pike header files. These files are usually contained in a -directory such as -

    - -
    -
    /usr/local/pike/7.4.10/include/pike
    -
    - -

    -There doesn't seem to be any way to get Pike itself to reveal the -location of these files, so you may need to hunt around for them. -You're looking for files with the names global.h, program.h -and so on. -

    - -

    37.1.3 Using your module

    - - -

    -To use your module, simply use Pike's import statement: -

    - -
    -$ pike
    -Pike v7.4 release 10 running Hilfe v3.5 (Incremental Pike Frontend)
    -> import example;
    -> fact(4);
    -(1) Result: 24
    -
    - -

    37.2 Basic C/C++ Mapping

    - - -

    37.2.1 Modules

    - - -

    -All of the code for a given SWIG module is wrapped into a single Pike -module. Since the name of the shared library that implements your -module ultimately determines the module's name (as far as Pike is -concerned), SWIG's %module directive doesn't really have any -significance. -

    - -

    37.2.2 Functions

    - - -

    -Global functions are wrapped as new Pike built-in functions. For -example, -

    - -
    -%module example
    -
    -int fact(int n);
    -
    - -

    -creates a new built-in function example.fact(n) that works -exactly as you'd expect it to: -

    - -
    -> import example;
    -> fact(4);
    -(1) Result: 24
    -
    - -

    37.2.3 Global variables

    - - -

    -Global variables are currently wrapped as a pair of functions, one to get -the current value of the variable and another to set it. For example, the -declaration -

    - -
    -%module example
    -
    -double Foo;
    -
    - -

    -will result in two functions, Foo_get() and Foo_set(): -

    - -
    -> import example;
    -> Foo_get();
    -(1) Result: 3.000000
    -> Foo_set(3.14159);
    -(2) Result: 0
    -> Foo_get();
    -(3) Result: 3.141590
    -
    - -

    37.2.4 Constants and enumerated types

    - - -

    -Enumerated types in C/C++ declarations are wrapped as Pike constants, -not as Pike enums. -

    - -

    37.2.5 Constructors and Destructors

    - - -

    -Constructors are wrapped as create() methods, and destructors are -wrapped as destroy() methods, for Pike classes. -

    - -

    37.2.6 Static Members

    - - -

    -Since Pike doesn't support static methods or data for Pike classes, static -member functions in your C++ classes are wrapped as regular functions and -static member variables are wrapped as pairs of functions (one to get the -value of the static member variable, and another to set it). The names of -these functions are prepended with the name of the class. -For example, given this C++ class declaration: -

    - -
    -class Shape
    -{
    -public:
    -  static void print();
    -  static int nshapes;
    -};
    -
    - -

    -SWIG will generate a Shape_print() method that invokes the static -Shape::print() member function, as well as a pair of methods, -Shape_nshapes_get() and Shape_nshapes_set(), to get and set -the value of Shape::nshapes. -

    - - - diff --git a/Doc/Manual/Preface.html b/Doc/Manual/Preface.html index 36a99bd1f..41f21d48d 100644 --- a/Doc/Manual/Preface.html +++ b/Doc/Manual/Preface.html @@ -281,12 +281,12 @@ You must use GNU make to build a

    -PCRE +PCRE2 needs to be installed on your system to build SWIG, in particular -pcre-config must be available. If you have PCRE headers and libraries but not -pcre-config itself or, alternatively, wish to override the compiler or linker -flags returned by pcre-config, you may set PCRE_LIBS and PCRE_CFLAGS variables -to be used instead. And if you don't have PCRE at all, the configure script +pcre2-config must be available. If you have PCRE2 headers and libraries but not +pcre2-config itself or, alternatively, wish to override the compiler or linker +flags returned by pcre2-config, you may set PCRE2_LIBS and PCRE2_CFLAGS variables +to be used instead. And if you don't have PCRE2 at all, the configure script will provide instructions for obtaining it.

    diff --git a/Doc/Manual/Preprocessor.html b/Doc/Manual/Preprocessor.html index 51cc06378..1170bc50d 100644 --- a/Doc/Manual/Preprocessor.html +++ b/Doc/Manual/Preprocessor.html @@ -99,8 +99,23 @@ header files without generating any wrappers.

    SWIG fully supports the use of #if, #ifdef, #ifndef, #else, #endif to conditionally -include parts of an interface. The following symbols are predefined -by SWIG when it is parsing the interface: +include parts of an interface. +

    + +

    +SWIG's preprocessor conditionals support the standard C/C++ preprocessor +integer expressions. As a SWIG-specific extension, string equality and +inequality tests are also supported, for example: +

    + +
    +
    +#if defined __cplusplus && (#__VA_ARGS__ != "" || #TYPE == "void")
    +
    +
    + +

    +The following symbols are predefined by SWIG when it is parsing the interface:

    @@ -123,7 +138,7 @@ SWIGOCAML                       Defined when using OCaml
     SWIGOCTAVE                      Defined when using Octave
     SWIGPERL                        Defined when using Perl
     SWIGPHP                         Defined when using PHP (any version)
    -SWIGPHP7                        Defined when using PHP7
    +SWIGPHP7                        Defined when using PHP 7 or later (with a compatible C API)
     SWIGPYTHON                      Defined when using Python
     SWIGR                           Defined when using R
     SWIGRUBY                        Defined when using Ruby
    diff --git a/Doc/Manual/Python.html b/Doc/Manual/Python.html
    index fd07301d4..00439765d 100644
    --- a/Doc/Manual/Python.html
    +++ b/Doc/Manual/Python.html
    @@ -133,7 +133,10 @@
     
     
  • Python 3 Support
  • -In Python, the static member can be access in three different ways: +In Python, the static member can be accessed in three different ways:

    @@ -1616,7 +1619,7 @@ In Python, the static member can be access in three different ways: >>> example.Spam_foo() # Spam::foo() >>> s = example.Spam() >>> s.foo() # Spam::foo() via an instance ->>> example.Spam.foo() # Spam::foo(). Python-2.2 only +>>> example.Spam.foo() # Spam::foo() using Python-2.2 and later
    @@ -1627,16 +1630,31 @@ last technique is only available in Python-2.2 and later versions.

    Static member variables are currently accessed as global variables. This means, -they are accessed through cvar like this: +they are accessed through cvar or via an instance property:

    ->>> print example.cvar.Spam_bar
    +>>> example.cvar.Spam_bar # Spam::bar
    +7
    +>>> s = example.Spam()
    +>>> s.bar                 # Spam::bar via an instance property
     7
     
    +

    +The -builtin option uses a metaclass to additionally provide access as follows: +

    + +
    +
    +>>> example.Spam.bar      # Spam::bar using -builtin option only
    +7
    +
    +
    + +

    33.3.8 C++ inheritance

    @@ -2516,6 +2534,12 @@ import A assert(issubclass(B.Derived, A.Base))
  • + + +
  • Python function annotations are not supported. +

    +
  • +

    33.4.2.2 Operator overloads and slots -- use them!

    @@ -2568,7 +2592,7 @@ but the line that uses the '+' operator is much faster. (operator==, operator<, etc.) are also converted to Python slot operators. For a complete list of C++ operators that are automatically converted to Python slot operators, refer to the file -python/pyopers.swig in the SWIG library. +python/pyopers.swg in the SWIG library.

    @@ -2674,7 +2698,7 @@ the chosen closure function.

    There is further information on %feature("python:slot") -in the file python/pyopers.swig in the SWIG library. +in the file python/pyopers.swg in the SWIG library.

    @@ -4939,7 +4963,6 @@ object to be used as a char ** object. if (PyString_Check(o)) { $1[i] = PyString_AsString(PyList_GetItem($input, i)); } else { - free($1); PyErr_SetString(PyExc_TypeError, "list must contain strings"); SWIG_fail; } @@ -5038,7 +5061,6 @@ previous example: if (PyString_Check(o)) { $2[i] = PyString_AsString(PyList_GetItem($input, i)); } else { - free($2); PyErr_SetString(PyExc_TypeError, "list must contain strings"); SWIG_fail; } @@ -6740,37 +6762,66 @@ The following are Python 3 new features that are currently supported by SWIG.

    -

    33.12.1 Function annotation

    +

    33.12.1 Function annotations

    -The -py3 option will enable function annotation support. When used -SWIG is able to generate proxy method definitions like this: -

    - -
    -  def foo(self, bar : "int"=0) -> "void" : ...
    -
    - -

    -Also, even if without passing SWIG the -py3 option, the parameter list -still could be generated: -

    - -
    -  def foo(self, bar=0): ...
    -
    - -

    -But for overloaded function or method, the parameter list would fallback to -*args or self, *args, and **kwargs may be append -depend on whether you enabled the keyword argument. This fallback is due to -all overloaded functions share the same function in SWIG generated proxy class. -

    - -

    -For detailed usage of function annotation, see +Python 3 supports function annotations as defined in PEP 3107. +Note that there is currently no annotations support for the -builtin nor +the -fastproxy option. +Annotations are added via the python:annotations +%feature directives. +SWIG currently supports one type of function annotation. +

    + +

    33.12.1.1 C/C++ annotation types

    + + +

    +The %feature("python:annotations", "c") directive generates function annotations +containing C/C++ types. For example: +

    + +
    +%feature("python:annotations", "c") global_ints;
    +int *global_ints(int &ri);
    +
    + +

    +The generated code then contains function annotations containing the C types: +

    + +
    +def global_ints(ri: "int &") -> "int *":
    +    return _python_annotations_c.global_ints(ri)
    +
    + +

    +There are some limitations with annotations support, for example, overloaded functions use +*args or **kwargs when keyword arguments are enabled. +The parameter names and types are then not shown. For example, with input: +

    + +
    +int *global_overloaded(int &ri);
    +int *global_overloaded();
    +
    + +

    +The generated Python function including annotations is shown below. +Only the return type is annotated. +

    + +
    +def global_overloaded(*args) -> "int *":
    +    return _python_annotations_c.global_overloaded(*args)
    +
    + +

    +Compatibility Note: SWIG-4.1.0 changed the way that function annotations are generated. +Prior versions required the -py3 option which enabled function annotation support +containing C/C++ types instead of supporting %feature("python:annotations", "c").

    33.12.2 Buffer interface

    diff --git a/Doc/Manual/R.html b/Doc/Manual/R.html index e44fe432c..9b05922fd 100644 --- a/Doc/Manual/R.html +++ b/Doc/Manual/R.html @@ -196,7 +196,7 @@ slices)

    Wrapping of C++ classes for R works quite well. R has a special type, known as an external reference, that can be used as a pointer -to arbitary things, including C++ classes. The proxy layers generated +to arbitrary things, including C++ classes. The proxy layers generated for other classes are not required.

    @@ -265,7 +265,7 @@ v2$Axles [1] 4 v1$Available [1] FALSE -# Set availabilty +# Set availability v1$Available <- TRUE v1$Available [1] TRUE diff --git a/Doc/Manual/SWIG.html b/Doc/Manual/SWIG.html index c54d117e0..ea2e625ef 100644 --- a/Doc/Manual/SWIG.html +++ b/Doc/Manual/SWIG.html @@ -47,6 +47,7 @@
  • Renaming and ignoring declarations
    • Simple renaming of specific identifiers +
    • Ignoring identifiers
    • Advanced renaming support
    • Limiting global renaming rules
    • Ignoring everything then wrapping a few selected symbols @@ -127,7 +128,7 @@ Supported Target Language Options -lua - Generate Lua wrappers -octave - Generate Octave wrappers -perl5 - Generate Perl 5 wrappers - -php7 - Generate PHP 7 wrappers + -php7 - Generate PHP 7 or later wrappers -python - Generate Python wrappers -r - Generate R (aka GNU S) wrappers -ruby - Generate Ruby wrappers @@ -208,7 +209,7 @@ General Options -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 to <dir> - -pcreversion - Display PCRE version information + -pcreversion - Display PCRE2 version information -small - Compile in virtual elimination and compact mode -swiglib - Report location of SWIG library and exit -templatereduce - Reduce all the typedefs in templates @@ -1469,14 +1470,14 @@ SWIG generates the following code:
       /* C mode */
       void foo_set(char *value) {
      -  if (foo) free(foo);
      +  free(foo);
         foo = (char *) malloc(strlen(value)+1);
         strcpy(foo, value);
       }
       
       /* C++ mode.  When -c++ option is used */
       void foo_set(char *value) {
      -  if (foo) delete [] foo;
      +  delete [] foo;
         foo = new char[strlen(value)+1];
         strcpy(foo, value);
       }
      @@ -1841,6 +1842,25 @@ all to `output' by specifying :

      %rename(output) print; // Rename all `print' functions to `output'
      +

      +A new %rename for the same name will replace the current +%rename for all uses after it in the file, and setting the +new name to "" will remove the rename. So, for instance, if you +wanted to rename some things in one file and not in another, you could +do: +

      + +
      +
      +  %rename(print1) print;
      +  %include "header1.h" //Anything "print" in here will become "print1"
      +  %rename(print2) print;
      +  %include "header2.h" //Anything "print" in here will become "print2"
      +  %rename("") print;
      +  %include "header3.h" //Anything "print" in here will remain "print"
      +
      +
      +

      SWIG does not normally perform any checks to see if the functions it wraps are already defined in the target scripting language. However, if you are @@ -1857,6 +1877,9 @@ If you are using the %rename directive and C++, make sure you read the for method overloading and default arguments.

      +

      5.4.7.2 Ignoring identifiers

      + +

      Closely related to %rename is the %ignore directive. %ignore instructs SWIG to ignore declarations that match a given identifier. For example: @@ -1896,7 +1919,7 @@ This directive is still supported, but it is deprecated and should probably be a directive is more powerful and better supports wrapping of raw header file information.

      -

      5.4.7.2 Advanced renaming support

      +

      5.4.7.3 Advanced renaming support

      @@ -2020,10 +2043,10 @@ and a more descriptive one, but the two functions are otherwise equivalent: regex:/pattern/subst/ String after (Perl-like) regex substitution operation. This function - allows to apply arbitrary regular expressions to the identifier names. The + allows applying arbitrary regular expressions to the identifier names. The pattern part is a regular expression in Perl syntax (as supported - by the Perl Compatible Regular Expressions (PCRE)) - library and the subst string + by the Perl Compatible Regular Expressions) + (PCRE2 library) and the subst string can contain back-references of the form \N where N is a digit from 0 to 9, or one of the following escape sequences: \l, \L, \u, \U or \E. The back-references are replaced with the @@ -2041,23 +2064,10 @@ and a more descriptive one, but the two functions are otherwise equivalent: %rename("regex:/(\\w+)_(.*)/\\u\\2/") prefix_printPrint - - command:cmd - Output of an external command cmd with the string passed to - it as input. Notice that this function is extremely slow compared to all - the other ones as it involves spawning a separate process and using it for - many declarations is not recommended. The cmd is not enclosed in - square brackets but must be terminated with a triple '<' sign, - e.g. %rename("command:tr -d aeiou <<<") - (nonsensical example removing all vowels) - PrintPrnt -

      -The most general function of all of the above ones (not counting -command which is even more powerful in principle but which should -generally be avoided because of performance considerations) is the +The most general function of all of the above ones is the regex one. Here are some more examples of its use:

      @@ -2105,7 +2115,7 @@ are exactly equivalent and %rename can be used to selectively ignore multiple declarations using the previously described matching possibilities.

      -

      5.4.7.3 Limiting global renaming rules

      +

      5.4.7.4 Limiting global renaming rules

      @@ -2137,11 +2147,15 @@ the match to class declarations only (in C++) and match="enumitem" restricts it to the enum elements. SWIG also provides convenience macros for such match expressions, for example

      +
       %rename("%(title)s", %$isenumitem) "";
      +// same as:
      +%rename("%(title)s", match="enumitem") "";
       
      +

      will capitalize the names of all the enum elements but not change the case of the other declarations. Similarly, %$isclass, %$isfunction, @@ -2151,6 +2165,55 @@ documentation is not exhaustive, see the "%rename predicates" section in swig.swg for the full list of supported match expressions.

      +

      +A logical not is also possible by using notmatch. +For example, notmatch="enumitem" will restrict the +match to all items that are not enum elements. +There is also a %$not macro which simply expands to "not". +Be careful using this as some of the other macros in swig.swg +are complex expressions and so it will only "notmatch" the first part +of the expression. +

      + +
      +
      +%rename("%(title)s", %$not %$isenumitem) "";
      +// same as:
      +%rename("%(title)s", notmatch="enumitem") "";
      +
      +
      + +

      +For a comprehensive understanding of how the matching works, the internal +parse tree needs to be examined using the +command line option: -debug-module 1. +A snippet of the resulting output might be: +

      + +
      +
      +            +++ destructor - 0x7fc10ea05af0 ----------------------------------------
      +            | name         - "~Shape"
      +            | ismember     - "1"
      +            | sym:name     - "~Shape"
      +            | access       - "public"
      +            | storage      - "virtual"
      +
      +
      + +

      +Here the node type is a "destructor" and in order to match all destructor nodes, use +match="destructor". To match one of the listed attributes in the node, +such as when the storage is virtual, use match$storage="virtual". +This will match all nodes that have a storage attribute set to "virtual". +To match only virtual destructors, combine them and use match="destructor", match$storage="virtual". +

      + +

      +While the vast majority of these internal parse tree nodes are unlikely to change from one version of +SWIG to the next, use these matching rules at your own risk as there are no guarantees that they will not change. +

      +

      In addition to literally matching some string with match you can also use regexmatch or notregexmatch to match a string @@ -2203,7 +2266,7 @@ wrap C++ overloaded functions and methods or C++ methods which use default argum

      -

      5.4.7.4 Ignoring everything then wrapping a few selected symbols

      +

      5.4.7.5 Ignoring everything then wrapping a few selected symbols

      @@ -2227,6 +2290,23 @@ the following approach could be taken: %rename("%s") Star::shine; // named method %include "myheader.h" + +%rename("%s") ""; // Undo the %ignore + + + +

      +If Star was in the Galaxy namespace, you would need +to unignore the namespace, too, and add the namespace to all the +renames: +

      + +
      +
      +%rename("%s") Galaxy;
      +%rename("%s") Galaxy::Star;
      +%rename("%s") Galaxy::Star::Star;
      +...
       
      @@ -2241,6 +2321,7 @@ members of the class, so when the chosen class is unignored, all of its methods %rename($ignore, %$isclass) ""; // Only ignore all classes %rename("%s") Star; // Unignore 'Star' %include "myheader.h" +%rename("%s", %$isclass) ""; // Stop ignoring all classes @@ -2594,8 +2675,7 @@ char *Foo_name_get(Foo *obj) { } char *Foo_name_set(Foo *obj, char *c) { - if (obj->name) - free(obj->name); + free(obj->name); obj->name = (char *) malloc(strlen(c)+1); strcpy(obj->name, c); return obj->name; @@ -2733,6 +2813,11 @@ void Foo_w_set(FOO *f, WORD value) { +

      +If you have accessor methods that you want to use as attributes in the +target language, you can make them appear as data members using +attributes.i. +

      Compatibility Note: SWIG-1.3.11 and earlier releases transformed all non-primitive member datatypes @@ -2976,6 +3061,11 @@ typedef struct Vector { +

      +You'll also need to use these names if you want to directly call methods added +using %extend from other C/C++ code. +

      +

      The name used for %extend should be the name of the struct and not the name of any typedef to the struct. For example: diff --git a/Doc/Manual/SWIGPlus.html b/Doc/Manual/SWIGPlus.html index 0c259e393..9820a1800 100644 --- a/Doc/Manual/SWIGPlus.html +++ b/Doc/Manual/SWIGPlus.html @@ -48,6 +48,9 @@

  • Overloaded operators
  • Class extension +
  • Templates
    • The %template directive @@ -1122,7 +1125,7 @@ customization features.

      SWIG wraps class members that are public following the C++ conventions, i.e., by explicit public declaration or by the use of - the using directive. In general, anything specified in a + using declarations. In general, anything specified in a private or protected section will be ignored, although the internal code generator sometimes looks at the contents of the private and protected sections so that it can properly generate code for default @@ -2080,7 +2083,6 @@ or for statically typed languages like Java:

       example.i:4: Warning 516: Overloaded method foo(long) ignored,
       example.i:3: Warning 516: using foo(int) instead.
      -at example.i:3 used.
       
      @@ -2327,8 +2329,8 @@ also apply to %ignore. For example:
       %ignore foo(double);          // Ignore all foo(double)
      -%ignore Spam::foo;            // Ignore foo in class Spam
      -%ignore Spam::foo(double);    // Ignore foo(double) in class Spam
      +%ignore Spam::foo;            // Ignore foo in class Spam (and foo in any derived classes)
      +%ignore Spam::foo(double);    // Ignore foo(double) in class Spam (and foo in any derived classes)
       %ignore *::foo(double);       // Ignore foo(double) in all classes
       
      @@ -2383,6 +2385,53 @@ global scope (e.g., a renaming of Spam::foo takes precedence over a renaming of foo(int)).

    • +
    • +Renaming a class member, using an unparameterized but qualified name, such as Spam::foo, also applies to members in all derived classes +that have members with the same name. +This can be used to simply rename a method, across an entire class hierarchy for all overloaded and non-overloaded methods. +This also applies to methods introduced via using declarations, see +Using declarations and inheritance. +For example: + +

      +
      +%rename(foo_new) Spam::foo;
      +
      +class Spam {
      +public:
      +  virtual void foo(int);      // Renamed to foo_new
      +};
      +
      +class Bar : public Spam {
      +public:
      +  virtual void foo(int);      // Renamed to foo_new
      +  void foo(bool, short, int); // Renamed to foo_new
      +};
      +
      +class Grok : public Bar {
      +public:
      +  virtual void foo(int);      // Renamed to foo_new
      +  void foo(bool, int);        // Renamed to foo_new
      +  void foo(const char *);     // Renamed to foo_new
      +  void foo(Bar *);            // Renamed to foo_new
      +};
      +
      +class Spok : public Grok {
      +public:
      +  void foo();                 // Renamed to foo_new
      +};
      +
      +class Knock : public Spok {
      +public:
      +  using Grok::foo;            // Introduced methods renamed to foo_new
      +};
      +
      +
      + +

      +
    • + +
    • The order in which %rename directives are defined does not matter as long as they appear before the declarations to be renamed. Thus, there is no difference @@ -2944,6 +2993,59 @@ be used to extend a structure with more than just methods, a more suitable directive name has been chosen.

      +

      6.17.1 Replacing class methods

      + + +

      +Suppose there is a method in a class that you need to replace and keep the method name the same. +This can be achieved combining the %extend and %ignore directives covered earlier. +Here is an example to replace the MyClass::mymethod(): + +

      +
      +%extend MyClass {
      +  void mymethod() {
      +    std::cout << "swig mymethod" << std::endl;
      +  }
      +}
      +
      +%ignore MyClass::mymethod;
      +
      +%inline %{
      +class MyClass {
      +public:
      +  void mymethod() {
      +    std::cout << "class mymethod" << std::endl;
      +  }
      +};
      +%}
      +
      +
      + +

      +Or if your code organization makes more sense to put +the %extend after the class definition, you would need the following: +

      + +
      +
      +%rename("") MyClass::mymethod; // unignores the method
      +
      +
      + +

      +before the %extend or SWIG will continue to ignore +mymethod(), even in an %extend. +

      + +

      +Note that you can call the class method from the method +in %extend, just use self->mymethod() and it will call +the class method, not the one in %extend. +

      + + +

      6.18 Templates

      @@ -3632,7 +3734,7 @@ Alternatively, you could expand the constructor template in selected instantiati // Create default and conversion constructors %extend pair<double, double> { - %template(paird) pair<double, dobule>; // Default constructor + %template(paird) pair<double, double>; // Default constructor %template(pairc) pair<int, int>; // Conversion constructor }; @@ -3647,7 +3749,7 @@ instead:
       // Create default and conversion constructors 
       %extend pair<double, double> {
      -  %template(pair) pair<double, dobule>;   // Default constructor
      +  %template(pair) pair<double, double>;   // Default constructor
         %template(pair) pair<int, int>;         // Conversion constructor
       };
       
      @@ -4017,23 +4119,23 @@ math::Complex c;

      At this level, namespaces are relatively easy to manage. However, things start to get very ugly when you throw in the other ways a namespace can be used. For example, -selective symbols can be exported from a namespace with using. +selective symbols can be exported from a namespace with a using declaration:

      -using math::Complex;
      +using math::Complex;                // Using declaration
       double magnitude(Complex *c);       // Namespace prefix stripped
       

      -Similarly, the contents of an entire namespace can be made available like this: +Similarly, the contents of an entire namespace can be made available via a using directive:

      -using namespace math;
      +using namespace math;               // Using directive
       double x = sin(1.0);
       double magnitude(Complex *c);
       
      @@ -4190,9 +4292,11 @@ Similarly, %ignore can be used to ignore declarations.

      -using declarations do not have any effect on the generated wrapper -code. They are ignored by SWIG language modules and they do not result in any -code. However, these declarations are used by the internal type +C++ using directives and using declarations +do not add any code to the generated wrapper code. +However, there is an exception in one context, see Using declarations and inheritance +for introducing members of a base class into a derived class definition. +C++ using declarations and directives are used by the internal type system to track type-names. Therefore, if you have code like this:

      @@ -5116,7 +5220,7 @@ exit # 'a' is released, SWIG unref 'a' called in the destructor wra

      -using declarations are sometimes used to adjust access to members of +C++ using declarations are sometimes used to introduce members of base classes. For example:

      @@ -5124,7 +5228,7 @@ base classes. For example:
       class Foo {
       public:
      -  int  blah(int x);
      +  int blah(int x);
       };
       
       class Bar {
      @@ -5172,7 +5276,8 @@ you wrap this code in Python, the module works just like you would expect:
       

      -using declarations can also be used to change access when applicable. For example: +C++ using declarations can also be used to change access when applicable. +For example, protected methods in a base class can be made public in a derived class:

      @@ -5205,15 +5310,15 @@ ignored in a base class, it will also be ignored by a using declaration

      Because a using declaration does not provide fine-grained -control over the declarations that get imported, it may be difficult +control over the declarations that get imported, because a single using declaration +may introduce multiple methods, it may be difficult to manage such declarations in applications that make heavy use of SWIG customization features. If you can't get using to work -correctly, you can always change the interface to the following: +correctly, you can always modify the C++ code to handle SWIG differently such as:

      -
       class FooBar : public Foo, public Bar {
       public:
       #ifndef SWIG
      @@ -5229,13 +5334,36 @@ public:
       
      +

      +If the C++ code being wrapped cannot be changed, make judicious usage of %extend and %rename +to ignore and unignore declarations. The example below is effectively the same as above: +

      + +
      +
      +%extend FooBar {
      +  int blah(int x) { return $self->Foo::blah(x); }
      +  double blah(double x) { return $self->Bar::blah(x); }
      +}
      +%ignore FooBar::blah; // ignore all FooBar::blah below
      +%rename("") FooBar::blah(const char *x); // parameterized unignore
      +
      +class FooBar : public Foo, public Bar {
      +public:
      +  using Foo::blah;
      +  using Bar::blah;
      +  char *blah(const char *x);
      +};
      +
      +
      +

      Notes:

        -
      • If a derived class redefines a method defined in a base class, then a using declaration -won't cause a conflict. For example:

        +
      • If a derived class introduces a method defined in a base class via a using declaration, +there won't be a conflict due to incorrect additional methods. For example:

        @@ -5247,14 +5375,14 @@ public:
         
         class Bar : public Foo {
         public:
        -  using Foo::blah;    // Only imports blah(double);
        +  using Foo::blah;    // Only introduces blah(double);
           int blah(int);
         };
         
        -
      • Resolving ambiguity in overloading may prevent declarations from being -imported by using. For example: +

      • Renaming methods may prevent methods from being +introduced into the derived class via using declarations. For example:

        @@ -5268,11 +5396,38 @@ public: class Bar : public Foo { public: - using Foo::blah; // Only imports blah(int) + using Foo::blah; // Only introduces blah(int) double blah(double x); };
        + +

        +The problem here is Foo::blah is renamed to blah_long in the target language, but +the using declaration in Bar is not renamed in the target language and thinks all introduced methods should simply +be called blah. +It is not clear what target language names should be used in Bar and so the conflicting names are effectively ignored +as they are not introduced into the derived class for the target language wrappers. +In such situations SWIG will emit a warning: +

        + +
        +
        +example.i:15: Warning 526: Using declaration Foo::blah, with name 'blah', is not actually using
        +example.i:10: Warning 526: the method from Foo::blah(long), with name 'blah_long', as the names are different.
        +
        +
        + +

        +Compatibility Note: +This warning message was introduced in SWIG-4.1.0. +Prior versions also effectively ignored the using declaration for the same reasons, but were silent about it. +

        + +

        +If methods really need different names, please use of combinations of %rename, %ignore and %extend to achieve the desired outcome. +

        +

      6.27 Nested classes

      diff --git a/Doc/Manual/Scilab.html b/Doc/Manual/Scilab.html index 5c4ef6269..a8d34c592 100644 --- a/Doc/Manual/Scilab.html +++ b/Doc/Manual/Scilab.html @@ -304,11 +304,6 @@ The following table lists the Scilab specific command line options in addition t Generate the gateway XML with the given <gateway_id> - --targetversion -Generate for Scilab target (major) version - -

      @@ -343,10 +338,6 @@ In Scilab 5.x, identifier names are composed of 24 characters maximum (this limi In these cases, the %rename directive can be used to choose a different Scilab name.

      -

      -Note: truncations can be disabled by specifying the target version 6 of Scilab in the targetversion argument (i.e. -targetversion 6). -

      -

      36.3.3 Functions

      @@ -768,7 +759,7 @@ Pointers are supported by SWIG. A pointer can be returned from a wrapped C/C++ f Also, thanks to the SWIG runtime which stores information about types, pointer types are tracked between exchanges Scilab and the native code. Indeed pointer types are stored alongside the pointer address. A pointer is mapped to a Scilab structure (tlist), which contains as fields the pointer address and the pointer type (in fact a pointer to the type information structure in the SWIG runtime).
      -Why a native pointer is not mapped to a Scilab pointer (type name: "pointer", type ID: 128) ? The big advantage of mapping to a tlist is that it exposes a new type for the pointer in Scilab, type which can be acessed in Scilab with the typeof function, and manipulated using the overloading mechanism. +Why a native pointer is not mapped to a Scilab pointer (type name: "pointer", type ID: 128) ? The big advantage of mapping to a tlist is that it exposes a new type for the pointer in Scilab, type which can be accessed in Scilab with the typeof function, and manipulated using the overloading mechanism.

      @@ -776,7 +767,7 @@ Notes:

      • type tracking needs the SWIG runtime to be first initialized with the appropriate function (see the Module initialization section).
      • -
      • for any reason, if a wrapped pointer type is unknown (or if the SWIG runtime is not initialized), SWIG maps it to a Scilab pointer. Also, a Scilab pointer is always accepted as a pointer argument of a wrapped function. The drawaback is that pointer type is lost.
      • +
      • for any reason, if a wrapped pointer type is unknown (or if the SWIG runtime is not initialized), SWIG maps it to a Scilab pointer. Also, a Scilab pointer is always accepted as a pointer argument of a wrapped function. The drawback is that pointer type is lost.

      diff --git a/Doc/Manual/Tcl.html b/Doc/Manual/Tcl.html index 0a22afb18..50f736d93 100644 --- a/Doc/Manual/Tcl.html +++ b/Doc/Manual/Tcl.html @@ -636,7 +636,7 @@ tcl:

      To build the extension, run NMAKE (you may need to run vcvars32 -first). This is a pretty minimal Makefile, but hopefully its enough +first). This is a pretty minimal Makefile, but hopefully it's enough to get you started. With a little practice, you'll be making lots of Tcl extensions.

      @@ -1227,7 +1227,15 @@ _108fea88_p_Bar

      Finally, to destroy objects created from Tcl, you can either let the object -name go out of scope or you can explicitly delete the object. For example: +name go out of scope or you can explicitly delete the object as shown below. +Objects won't get automatically destroyed when the Tcl program exits, so if +it's important that the C++ destructor is called for a class you'll need to +make sure that you explicitly do this for objects of that class before program +exit. +

      + +

      +For example:

      @@ -2811,9 +2819,7 @@ used as a char ** object. // This gives SWIG some cleanup code that will get called after the function call %typemap(freearg) char ** { - if ($1) { - free($1); - } + free($1); } // Now a test functions diff --git a/Doc/Manual/Typemaps.html b/Doc/Manual/Typemaps.html index a12ede553..4842641dd 100644 --- a/Doc/Manual/Typemaps.html +++ b/Doc/Manual/Typemaps.html @@ -3103,7 +3103,7 @@ as shown. To work with heap allocated data, the following technique can be use } } %typemap(freearg) float value[ANY] { - if ($1) free($1); + free($1); }
      @@ -3556,7 +3556,7 @@ maps perform the conversion described for the above example: } %typemap(freearg) (int argc, char *argv[]) { - if ($2) free($2); + free($2); } /* Required for C++ method overloading */ @@ -3835,7 +3835,7 @@ To eliminate this, define a fragment that includes the common marshalling code:

      When the "in" or "varin" typemaps for MyClass are required, the -contents of the fragment called "AsMyClass" is added to the "header" section within the generated code, and then the +contents of the fragment called "AsMyClass" are added to the "header" section within the generated code, and then the typemap code is emitted. Hence, the method AsMyClass will be generated into the wrapper code before any typemap code that calls it.

      @@ -3983,19 +3983,34 @@ inclusion of the other fragments.
    • -A typemap can also use more than one fragment, but since the -syntax is different, you need to specify the dependent fragments in a comma separated -list. Consider: +A typemap can also use more than one fragment:

      -
      -%typemap(in, fragment="frag1, frag2, frag3") {...}
      +%typemap("in", fragment="frag1", fragment="frag2", fragment="frag3") {...}
       

      -which is equivalent to: +Compatibility note: The ability to use multiple +fragment keys as shown above was introduced in SWIG-4.1.0. +

      + +

      +Multiple fragments can alternatively be specified as a comma +separated list value in a single fragment key. +Note that no whitespace is allowed within this comma separated list. +The following is the equivalent to the above: +

      + +
      +
      +%typemap(in, fragment="frag1,frag2,frag3") {...}
      +
      +
      + +

      +which in turn is functionally equivalent to:

      diff --git a/Doc/Manual/Warnings.html b/Doc/Manual/Warnings.html index 0cf2a1066..bb20db38b 100644 --- a/Doc/Manual/Warnings.html +++ b/Doc/Manual/Warnings.html @@ -428,6 +428,7 @@ example.i(4) : Syntax error in input(1).
    • 324. Named nested template instantiations not supported. Processing as if no name was given to %template().
    • 325. Nested kind not currently supported (name ignored).
    • 326. Deprecated %extend name used - the kind name 'name' should be used instead of the typedef name 'name'. +
    • 327. Extern template ignored.
    • 350. operator new ignored.
    • 351. operator delete ignored.
    • 352. operator+ ignored. @@ -483,7 +484,7 @@ example.i(4) : Syntax error in input(1).
    • 401. Nothing known about class 'name'. Ignored.
    • 402. Base class 'name' is incomplete.
    • 403. Class 'name' might be abstract. -
    • 450. Deprecated typemap feature ($source/$target). +
    • 450. Reserved
    • 451. Setting const char * variable may leak memory.
    • 452. Reserved
    • 453. Can't apply (pattern). No typemaps are defined. @@ -536,6 +537,7 @@ example.i(4) : Syntax error in input(1).
    • 523. Use of an illegal destructor name 'name' in %extend is deprecated, the destructor name should be 'name'.
    • 524. Experimental target language. Target language language specified by lang is an experimental language. Please read about SWIG experimental languages, htmllink.
    • 525. Destructor declaration is final, name cannot be a director class. +
    • 526. Using declaration declaration, with name 'name', is not actually using the method from declaration, with name 'name', as the names are different.

    19.9.6 Doxygen comments (560-599)

    diff --git a/Doc/Manual/Windows.html b/Doc/Manual/Windows.html index 800e2e420..7a39e88f3 100644 --- a/Doc/Manual/Windows.html +++ b/Doc/Manual/Windows.html @@ -29,16 +29,16 @@
  • Instructions for using the Examples with other compilers -
  • SWIG on Cygwin and MinGW -
  • Microsoft extensions and other Windows quirks @@ -77,10 +77,10 @@ If you want to build your own swig.exe have a look at examples using Cygwin. @@ -95,9 +95,11 @@ More information on each of the examples is available with the examples distribu Ensure the SWIG executable is as supplied in the SWIG root directory in order for the examples to work. Most languages require some environment variables to be set before running Visual C++. Note that Visual C++ must be re-started to pick up any changes in environment variables. -Open up an example .dsp file, Visual C++ will create a workspace for you (.dsw file). -Ensure the Release build is selected then do a Rebuild All from the Build menu. -The required environment variables are displayed with their current values. +Open up an example .dsp file, Visual C++ will prompt you to upgrade the project and convert +it into an MSBuild project (.vcxproj file) and Solution (.sln file). +Note that older versions of Visual C++ will simply create a workspace for you (.dsw file). +Ensure the Release build is selected then do a Rebuild Solution from the Build menu. +The required environment variables are displayed with their current values during the build.

    The list of required environment variables for each module language is also listed below. @@ -111,7 +113,7 @@ If you are interested in how the project files are set up there is explanatory i

    The C# examples do not require any environment variables to be set as a C# project file is included. -Just open up the .sln solution file in Visual Studio .NET 2003 or later, select Release Build, and do a Rebuild All from the Build menu. +Just open up the .sln solution file in Visual Studio 2005 or later, select Release Build, and do a Rebuild Solution from the Build menu. The accompanying C# and C++ project files are automatically used by the solution file.

    @@ -207,24 +209,149 @@ RUBY_LIB: D:\ruby\lib\mswin32-ruby16.lib
    If you do not have access to Visual C++ you will have to set up project files / Makefiles for your chosen compiler. There is a section in each of the language modules detailing what needs setting up using Visual C++ which may be of some guidance. Alternatively you may want to use Cygwin as described in the following section.

    -

    3.3 SWIG on Cygwin and MinGW

    +

    3.3 Building swig.exe on Windows

    -SWIG can also be compiled and run using Cygwin or MinGW which provides a Unix like front end to Windows and comes free with gcc, an ISO C/C++ compiler. However, this is not a recommended approach as the prebuilt executable is supplied. +The SWIG distribution provides a pre-built swig.exe and so it is not necessary for users to build the SWIG executable. +However, this section is provided for those that want to modify the SWIG source code in a Windows environment. +Normally this is not needed, so most people will want to ignore this section.

    -

    3.3.1 Building swig.exe on Windows

    +

    +There are various ways to build the SWIG executable including CMake which is able to generate project files for building with Visual Studio. +SWIG can also be compiled and run using MSYS2, Cygwin or MinGW, all of which provide a Unix like front end to Windows and comes free with the gcc C/C++ compiler. +

    + + +

    3.3.1 Building swig.exe using CMake

    -If you want to replicate the build of swig.exe that comes with the download, follow the MinGW instructions below. -This is not necessary to use the supplied swig.exe. -This information is provided for those that want to modify the SWIG source code in a Windows environment. -Normally this is not needed, so most people will want to ignore this section. +SWIG can be built using CMake and Visual Studio rather than autotools. As with the other approaches to +building SWIG the dependencies need to be installed. The steps below are one of a number of ways of installing the dependencies without requiring Cygwin or MinGW. +For fully working build steps always check the Continuous Integration (CI) setups currently detailed in the Appveyor YAML file.

    -

    3.3.1.1 Building swig.exe using MinGW and MSYS

    +
      +
    1. + Install Nuget from https://www.nuget.org/downloads (v6.0.0 is used in this example, and installed to C:\Tools). Nuget is the package manager + for .NET, but allows us to easily install CMake and other dependencies required by SWIG. +
    2. +
    3. + Install CMake-win64 Nuget package using the following command:
      C:\Tools\nuget install CMake-win64 -Version 3.15.5 -OutputDirectory C:\Tools\CMake
      + Alternatively you can download CMake from https://cmake.org/download/. +
    4. +
    5. + Install the Bison Nuget package using the following command:
      C:\Tools\nuget install Bison -Version 3.7.4 -OutputDirectory C:\Tools\bison
      + Alternatively download Bison from https://sourceforge.net/projects/winflexbison/files/ (Bison 3.7.4 is used in this example) + and save to a folder e.g. C:\Tools\Bison +
    6. +
    7. + Unfortunately, PCRE2 is not yet available on Nuget. Instead we will use CMake to build and install PCRE2 to C:\Tools\pcre2 using the following commands: +
      +cd C:\
      +SET PATH=C:\Tools\CMake\CMake-win64.3.15.5\bin;%PATH%
      +git clone https://github.com/PhilipHazel/pcre2.git
      +cd pcre2
      +cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_INSTALL_PREFIX=C:/Tools/pcre2 -S . -B build
      +cmake --build build --config Release --target install
      +        
      + Alternatively, set WITH_PCRE=OFF to disable PCRE2 support if you are sure you do not require it. +
    8. +
    9. + We will also need the SWIG source code. Either download a zipped archive from GitHub, or if git is installed clone the latest codebase + using
      git clone https://github.com/swig/swig.git
      + In this example we are assuming the source code is available at C:\swig +
    10. +
    11. +

      + Now we have all the required dependencies we can build SWIG using the commands below. We are assuming Visual Studio 2019 is installed. For other versions of Visual Studio change "Visual Studio 16 2019 -A x64" to the relevant + Visual Studio Generator and + architecture. We add the required build tools to the system PATH, and then + build a Release version of SWIG. If all runs successfully a new swig.exe should be generated in the C:/swig/install2/bin folder. +

      +
      +cd C:\swig
      +SET PATH=C:\Tools\CMake\CMake-win64.3.15.5\bin;C:\Tools\bison\Bison.3.7.4\bin;%PATH%
      +SET PCRE_ROOT=C:/Tools/pcre2
      +SET PCRE_PLATFORM=x64
      +cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_INSTALL_PREFIX="%CD:\=/%/install2" -DCMAKE_C_FLAGS="/DPCRE2_STATIC" ^
      +-DCMAKE_CXX_FLAGS="/DPCRE2_STATIC" -DPCRE2_INCLUDE_DIR=%PCRE_ROOT%/include -DPCRE2_LIBRARY=%PCRE_ROOT%/lib/pcre2-8-static.lib -S . -B build
      +cmake --build build --config Release --target install
      +
      +REM to test the exe
      +cd install2/bin
      +swig.exe -help
      +    
      +
    12. +
    +

    + In addition to Release builds you can create a Debug build using: +

    +
    +
    cmake --build build --config Debug
    +
    +

    + A Visual Studio solution file should be generated named swig.sln. This can be opened and debugged by running the swig project and setting Properties > Debugging > Command Arguments. For example to debug one of the test-suite .i files included with the SWIG source use the following: +

    +
    +
    -python -c++ -o C:\Temp\doxygen_parsing.cpp C:\swig\Examples\test-suite\doxygen_parsing.i
    +
    + +

    3.3.2 Building swig.exe using MSYS2

    + + +

    +Download and install MSYS2 from www.msys2.org (tested with version msys2-x86_64-20201109). +Launch the MSYS2 shell. +

    +

    +Install the packages needed to build swig:
    +

    + +
    +
    +pacman -S git autoconf automake bison gcc make pcre2-devel
    +
    +
    + +

    +Clone the repository to /usr/src/: +

    + +
    +
    +mkdir /usr/src/
    +cd /usr/src/
    +git clone https://github.com/swig/swig.git
    +
    +
    + +

    +Configure and build: +

    + +
    +
    +cd /usr/src/swig
    +./autogen.sh
    +./configure
    +make
    +
    +
    + +

    +Finally you may also want to install SWIG: +

    + +
    +
    +make install
    +
    +
    + +

    3.3.3 Building swig.exe using MinGW and MSYS

    @@ -319,10 +446,10 @@ the autotools will fail miserably on those.

  • -The PCRE third party library needs to be built next. -Download the latest PCRE source tarball, such as pcre-8.10.tar.bz2, from -PCRE and place in the /usr/src/swig directory. -Build PCRE as a static library using the Tools/pcre-build.sh script as follows: +The PCRE2 third party library needs to be built next. +Download the latest PCRE2 source tarball, such as pcre2-10.39.tar.bz2, from +www.pcre.org and place in the /usr/src/swig directory. +Build PCRE2 as a static library using the Tools/pcre-build.sh script as follows:
     cd /usr/src/swig
    @@ -342,7 +469,7 @@ make
     
     
     
    -

    3.3.1.2 Building swig.exe using Cygwin

    +

    3.3.4 Building swig.exe using Cygwin

    @@ -353,17 +480,8 @@ Note that the Cygwin environment will also allow one to regenerate the autotool These files are generated using the autogen.sh script and will only need regenerating in circumstances such as changing the build system.

    -

    3.3.1.3 Building swig.exe alternatives

    - -

    -If you don't want to install Cygwin or MinGW, use a different compiler to build -SWIG. For example, all the source code files can be added to a Visual C++ project -file in order to build swig.exe from the Visual C++ IDE. -

    - - -

    3.3.2 Running the examples on Windows using Cygwin

    +

    3.3.4.1 Running the examples on Windows using Cygwin

    diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 87386f7eb..67db611b7 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -165,6 +165,7 @@ TCL_SO = @TCL_SO@ TCLLDSHARED = @TCLLDSHARED@ TCLCXXSHARED = @TCLCXXSHARED@ TCL_SCRIPT = $(SRCDIR)$(RUNME).tcl +TCL_LINK = @TCLLINK@ # ----------------------------------------------------------- # Build a new version of the tclsh shell @@ -187,7 +188,7 @@ tclsh_cpp: $(SRCDIR_SRCS) tcl: $(SRCDIR_SRCS) $(SWIG) -tcl8 $(SWIGOPT) $(TCL_SWIGOPTS) -o $(ISRCS) $(INTERFACEPATH) $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(TCL_INCLUDE) - $(TCLLDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(TCL_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(TCL_SO) + $(TCLLDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(TCL_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(TCL_SO) $(TCL_LINK) # ----------------------------------------------------------- # Build a Tcl7.5 dynamic loadable module for C++ @@ -196,7 +197,7 @@ tcl: $(SRCDIR_SRCS) tcl_cpp: $(SRCDIR_SRCS) $(SWIG) -tcl8 -c++ $(SWIGOPT) $(TCL_SWIGOPTS) -o $(ICXXSRCS) $(INTERFACEPATH) $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) - $(TCLCXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(TCL_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(TCL_SO) + $(TCLCXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(TCL_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(TCL_SO) $(TCL_LINK) # ----------------------------------------------------------------- # Run Tcl example @@ -381,13 +382,7 @@ python_static_cpp: $(SRCDIR_SRCS) # Running a Python example # ----------------------------------------------------------------- -ifeq (,$(PY3)) - PYSCRIPT = $(RUNME).py -else - PYSCRIPT = $(RUNME)3.py -endif - -PY2TO3 = @PY2TO3@ `@PY2TO3@ -l | grep -v -E "Available|import$$" | awk '{print "-f "$$0}'` +PYSCRIPT = $(RUNME).py python_run: $(PYSCRIPT) ifneq (,$(PYCODESTYLE)) @@ -400,10 +395,6 @@ $(RUNME).py: $(SRCDIR)$(RUNME).py cp $< $@ endif -$(RUNME)3.py: $(SRCDIR)$(RUNME).py - cp $< $@ - $(PY2TO3) -w $@ >/dev/null 2>&1 - # ----------------------------------------------------------------- # Version display # ----------------------------------------------------------------- @@ -421,7 +412,6 @@ python_clean: rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *@SO@ *$(PYTHON_SO) rm -f $(TARGET).py - if test -f $(SRCDIR)$(RUNME).py; then rm -f $(RUNME)3.py $(RUNME)3.py.bak; fi case "x$(SRCDIR)" in x|x./);; *) rm -f $(RUNME).py;; esac @@ -1056,20 +1046,21 @@ ruby_clean: rm -f *.@OBJEXT@ *$(RUBY_SO) ################################################################## -##### PHP7 ###### +##### PHP ###### ################################################################## PHP = @PHP@ PHP_INCLUDE = @PHPINC@ PHP_SO = @PHP_SO@ PHP_SCRIPT = $(SRCDIR)$(RUNME).php +PHP_EXTENSION = example$(PHP_SO) # ------------------------------------------------------------------- # Build a PHP dynamically loadable module (C) # ------------------------------------------------------------------- php: $(SRCDIR_SRCS) - $(SWIG) -php7 $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(SWIG) -php $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(PHP_INCLUDE) $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(PHP_SO) @@ -1078,7 +1069,7 @@ php: $(SRCDIR_SRCS) # -------------------------------------------------------------------- php_cpp: $(SRCDIR_SRCS) - $(SWIG) -php7 -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(SWIG) -php -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(PHP_INCLUDE) $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(PHP_SO) @@ -1087,7 +1078,7 @@ php_cpp: $(SRCDIR_SRCS) # ----------------------------------------------------------------- php_run: - $(RUNTOOL) $(PHP) -n -q -d extension_dir=. -d safe_mode=Off -d display_errors=stderr $(PHP_SCRIPT) $(RUNPIPE) + $(RUNTOOL) $(PHP) -n -d extension_dir=. -d extension=$(PHP_EXTENSION) -d display_errors=stderr -r 'set_error_handler(function($$n,$$s,$$f,$$l){if($$f!==Null){print$$f;if($$l!==Null)print":$$l";print": ";}print"$$s\n";exit(1);});include($$argv[1]);' $(PHP_SCRIPT) $(RUNPIPE) # ----------------------------------------------------------------- # Version display @@ -1259,46 +1250,6 @@ lua_clean: rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *$(LUA_SO) -################################################################## -##### ALLEGRO CL ###### -################################################################## - -ALLEGROCL = @ALLEGROCLBIN@ -ALLEGROCL_SCRIPT=$(RUNME).lisp - -allegrocl: $(SRCDIR_SRCS) - $(SWIG) -allegrocl -cwrap $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCDIR_SRCS) - $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) - -allegrocl_cpp: $(SRCDIR_SRCS) - $(SWIG) -c++ -allegrocl $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) - $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) - -# ----------------------------------------------------------------- -# Run ALLEGRO CL example -# ----------------------------------------------------------------- - -allegrocl_run: - $(RUNTOOL) $(ALLEGROCL) -batch -s $(ALLEGROCL_SCRIPT) $(RUNPIPE) - -# ----------------------------------------------------------------- -# Version display -# ----------------------------------------------------------------- - -allegrocl_version: - $(ALLEGROCL) --version - -# ----------------------------------------------------------------- -# Cleaning the ALLEGRO CL examples -# ----------------------------------------------------------------- - -allegrocl_clean: - rm -f *_wrap* *~ .~* - rm -f core @EXTRA_CLEAN@ - rm -f *.@OBJEXT@ *@SO@ - ################################################################## ##### CFFI ###### ################################################################## @@ -1406,6 +1357,7 @@ r_clean: SCILAB = @SCILAB@ SCILAB_INC= @SCILABINCLUDE@ SCILAB_OPT = @SCILABOPT@ +SCILAB_VERSION = @SCILAB_VERSION@ SCILAB_LIBPREFIX = lib # ---------------------------------------------------------------- @@ -1438,7 +1390,7 @@ scilab_run: # ----------------------------------------------------------------- scilab_version: - echo `$(SCILAB) -version | head -1` + echo `$(SCILAB) -nwni -version | head -1` # ----------------------------------------------------------------- # Cleaning the scilab examples diff --git a/Examples/chicken/README b/Examples/chicken/README deleted file mode 100644 index d4f91baf6..000000000 --- a/Examples/chicken/README +++ /dev/null @@ -1,12 +0,0 @@ -This directory contains examples for CHICKEN. - -class -- illustrates the proxy class C++ interface -constants -- handling #define and %constant literals -egg -- examples of building chicken extension libraries -multimap -- typemaps with multiple sub-types -overload -- C++ function overloading -simple -- the simple example from the user manual -zlib -- a wrapping of the zlib compression library - -You should be able to run make in each of the examples. By default, a shared -library will be built. Run make check to execute the test. diff --git a/Examples/chicken/check.list b/Examples/chicken/check.list deleted file mode 100644 index 9ea022bfb..000000000 --- a/Examples/chicken/check.list +++ /dev/null @@ -1,6 +0,0 @@ -# see top-level Makefile.in -class -constants -multimap -overload -simple diff --git a/Examples/chicken/class/Makefile b/Examples/chicken/class/Makefile deleted file mode 100644 index ea2d8b62e..000000000 --- a/Examples/chicken/class/Makefile +++ /dev/null @@ -1,40 +0,0 @@ -TOP = ../.. -SWIGEXE = $(TOP)/../swig -SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib -INTERFACE = example.i -SRCS = -CXXSRCS = example.cxx -TARGET = class -INCLUDE = -SWIGOPT = -VARIANT = - -# uncomment the following lines to build a static exe (only pick one of the CHICKEN_MAIN lines) -#CHICKEN_MAIN = runme-lowlevel.scm -#CHICKEN_MAIN = runme-tinyclos.scm -#VARIANT = _static - -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CHICKEN_SCRIPT='runme-lowlevel.scm' chicken_run - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CHICKEN_SCRIPT='runme-tinyclos.scm' chicken_run - -build: $(TARGET) $(TARGET)_proxy - -$(TARGET): $(INTERFACE) $(SRCS) - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ - SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' \ - INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT)_cpp - -$(TARGET)_proxy: $(INTERFACE) $(SRCS) - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ - SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT) -proxy' TARGET='$(TARGET)_proxy' \ - INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT)_cpp - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_clean - rm -f example.scm - rm -f $(TARGET) diff --git a/Examples/chicken/class/example.cxx b/Examples/chicken/class/example.cxx deleted file mode 100644 index 046304519..000000000 --- a/Examples/chicken/class/example.cxx +++ /dev/null @@ -1,28 +0,0 @@ -/* File : example.cxx */ - -#include "example.h" -#define M_PI 3.14159265358979323846 - -/* Move the shape to a new location */ -void Shape::move(double dx, double dy) { - x += dx; - y += dy; -} - -int Shape::nshapes = 0; - -double Circle::area() { - return M_PI*radius*radius; -} - -double Circle::perimeter() { - return 2*M_PI*radius; -} - -double Square::area() { - return width*width; -} - -double Square::perimeter() { - return 4*width; -} diff --git a/Examples/chicken/class/example.h b/Examples/chicken/class/example.h deleted file mode 100644 index 5bad31693..000000000 --- a/Examples/chicken/class/example.h +++ /dev/null @@ -1,41 +0,0 @@ -/* File : example.h */ - -class Shape { -public: - Shape() { - nshapes++; - } - virtual ~Shape() { - nshapes--; - } - double x, y; - void move(double dx, double dy); - virtual double area() = 0; - virtual double perimeter() = 0; - static int nshapes; - - enum SomeEnum { - First = 0, - Second, - Third, - Last = 1000 - }; -}; - -class Circle : public Shape { -private: - double radius; -public: - Circle(double r) : radius(r) { } - virtual double area(); - virtual double perimeter(); -}; - -class Square : public Shape { -private: - double width; -public: - Square(double w) : width(w) { } - virtual double area(); - virtual double perimeter(); -}; diff --git a/Examples/chicken/class/example.i b/Examples/chicken/class/example.i deleted file mode 100644 index fbdf7249f..000000000 --- a/Examples/chicken/class/example.i +++ /dev/null @@ -1,9 +0,0 @@ -/* File : example.i */ -%module example - -%{ -#include "example.h" -%} - -/* Let's just grab the original header file here */ -%include "example.h" diff --git a/Examples/chicken/class/runme-lowlevel.scm b/Examples/chicken/class/runme-lowlevel.scm deleted file mode 100644 index 7c59c0aaa..000000000 --- a/Examples/chicken/class/runme-lowlevel.scm +++ /dev/null @@ -1,76 +0,0 @@ -;; This file illustrates the low-level C++ interface generated -;; by SWIG. - -(load-library 'example "class.so") -(declare (uses example)) - -;; ----- Object creation ----- - -(display "Creating some objects:\n") -(define c (new-Circle 10.0)) -(display " Created circle ") -(display c) -(display "\n") -(define s (new-Square 10.0)) -(display " Created square ") -(display s) -(display "\n") - -;; ----- Access a static member ----- - -(display "\nA total of ") -(display (Shape-nshapes)) -(display " shapes were created\n") - -;; ----- Member data access ----- - -;; Set the location of the object - -(Shape-x-set c 20.0) -(Shape-y-set c 30.0) - -(Shape-x-set s -10.0) -(Shape-y-set s 5.0) - -(display "\nHere is their current position:\n") -(display " Circle = (") -(display (Shape-x-get c)) -(display ", ") -(display (Shape-y-get c)) -(display ")\n") -(display " Square = (") -(display (Shape-x-get s)) -(display ", ") -(display (Shape-y-get s)) -(display ")\n") - -;; ----- Call some methods ----- - -(display "\nHere are some properties of the shapes:\n") -(let - ((disp (lambda (o) - (display " ") - (display o) - (display "\n") - (display " area = ") - (display (Shape-area o)) - (display "\n") - (display " perimeter = ") - (display (Shape-perimeter o)) - (display "\n")))) - (disp c) - (disp s)) - -(display "\nGuess I'll clean up now\n") - -;; Note: this invokes the virtual destructor -(set! c #f) -(set! s #f) -(gc #t) - -(set! s 3) -(display (Shape-nshapes)) -(display " shapes remain\n") -(display "Goodbye\n") - -(exit) diff --git a/Examples/chicken/class/runme-tinyclos.scm b/Examples/chicken/class/runme-tinyclos.scm deleted file mode 100644 index 5ba1d6adb..000000000 --- a/Examples/chicken/class/runme-tinyclos.scm +++ /dev/null @@ -1,76 +0,0 @@ -;; This file illustrates the proxy C++ interface generated -;; by SWIG. - -(load-library 'example "class_proxy.so") -(declare (uses example)) -(declare (uses tinyclos)) - -;; ----- Object creation ----- - -(display "Creating some objects:\n") -(define c (make 10.0)) -(display " Created circle ") -(display c) -(display "\n") -(define s (make 10.0)) -(display " Created square ") -(display s) -(display "\n") - -;; ----- Access a static member ----- - -(display "\nA total of ") -(display (Shape-nshapes)) -(display " shapes were created\n") - -;; ----- Member data access ----- - -;; Set the location of the object - -(slot-set! c 'x 20.0) -(slot-set! c 'y 30.0) - -(slot-set! s 'x -10.0) -(slot-set! s 'y 5.0) - -(display "\nHere is their current position:\n") -(display " Circle = (") -(display (slot-ref c 'x)) -(display ", ") -(display (slot-ref c 'y)) -(display ")\n") -(display " Square = (") -(display (slot-ref s 'x)) -(display ", ") -(display (slot-ref s 'y)) -(display ")\n") - -;; ----- Call some methods ----- - -(display "\nHere are some properties of the shapes:\n") -(let - ((disp (lambda (o) - (display " ") - (display o) - (display "\n") - (display " area = ") - (display (area o)) - (display "\n") - (display " perimeter = ") - (display (perimeter o)) - (display "\n")))) - (disp c) - (disp s)) - -(display "\nGuess I'll clean up now\n") - -;; Note: Invoke the virtual destructors by forcing garbage collection -(set! c 77) -(set! s 88) -(gc #t) - -(display (Shape-nshapes)) -(display " shapes remain\n") -(display "Goodbye\n") - -(exit) diff --git a/Examples/chicken/constants/Makefile b/Examples/chicken/constants/Makefile deleted file mode 100644 index 2fdde0a58..000000000 --- a/Examples/chicken/constants/Makefile +++ /dev/null @@ -1,31 +0,0 @@ -TOP = ../.. -SWIGEXE = $(TOP)/../swig -SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib -INTERFACE = example.i -SRCS = -CXXSRCS = -TARGET = constants -INCLUDE = -SWIGOPT = -VARIANT = - -# uncomment the following two lines to build a static exe -#CHICKEN_MAIN = runme.scm -#VARIANT = _static - -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_run - -build: $(TARGET) - -$(TARGET): $(INTERFACE) $(SRCS) - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ - SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' \ - INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT) - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_clean - rm -f example.scm - rm -f $(TARGET) diff --git a/Examples/chicken/constants/example.i b/Examples/chicken/constants/example.i deleted file mode 100644 index 0995c19b9..000000000 --- a/Examples/chicken/constants/example.i +++ /dev/null @@ -1,27 +0,0 @@ -/* File : example.i */ -%module example - -/* A few preprocessor macros */ - -#define ICONST 42 -#define FCONST 2.1828 -#define CCONST 'x' -#define CCONST2 '\n' -#define SCONST "Hello World" -#define SCONST2 "\"Hello World\"" - -/* This should work just fine */ -#define EXPR ICONST + 3*(FCONST) - -/* This shouldn't do anything */ -#define EXTERN extern - -/* Neither should this (BAR isn't defined) */ -#define FOO (ICONST + BAR) - -/* The following directives also produce constants. Remember that - CHICKEN is normally case-insensitive, so don't rely on differing - case to differentiate variable names */ - -%constant int iconstX = 37; -%constant double fconstX = 3.14; diff --git a/Examples/chicken/constants/runme.scm b/Examples/chicken/constants/runme.scm deleted file mode 100644 index 1b10b2605..000000000 --- a/Examples/chicken/constants/runme.scm +++ /dev/null @@ -1,16 +0,0 @@ -;; feel free to uncomment and comment sections - -(load-library 'example "./constants.so") - -(display "starting test ... you will see 'finished' if successful.\n") -(or (= (ICONST) 42) (exit 1)) -(or (< (abs (- (FCONST) 2.1828)) 0.00001) (exit 1)) -(or (char=? (CCONST) #\x) (exit 1)) -(or (char=? (CCONST2) #\newline) (exit 1)) -(or (string=? (SCONST) "Hello World") (exit 1)) -(or (string=? (SCONST2) "\"Hello World\"") (exit 1)) -(or (< (abs (- (EXPR) (+ (ICONST) (* 3 (FCONST))))) 0.00001) (exit 1)) -(or (= (iconstX) 37) (exit 1)) -(or (< (abs (- (fconstX) 3.14)) 0.00001) (exit 1)) -(display "finished test.\n") -(exit 0) diff --git a/Examples/chicken/egg/Makefile b/Examples/chicken/egg/Makefile deleted file mode 100644 index 0137dc0a7..000000000 --- a/Examples/chicken/egg/Makefile +++ /dev/null @@ -1,41 +0,0 @@ -TOP = ../.. -SWIGEXE = $(TOP)/../swig -SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib - -check: build - cd eggs/install && csi ../../test.scm - -build: single multi - -# This creates an egg which contains only the single module. Any additional implementation files -# that implement the interface being wrapped should also be added to this egg -single: single_wrap.cxx - mkdir -p eggs - tar czf eggs/single.egg single.setup single.scm single_wrap.cxx - rm -f single.scm single_wrap.cxx - -# compile the single module with -nounit -single_wrap.cxx: single.i - $(SWIGEXE) -chicken -c++ -proxy -nounit single.i - -# Now build both mod1 and mod2 into a single egg -multi: mod1_wrap.cxx mod2_wrap.cxx - mkdir -p eggs - tar czf eggs/multi.egg multi.setup multi_init.scm mod1.scm mod1_wrap.cxx mod2.scm mod2_wrap.cxx - rm -f mod1.scm mod1_wrap.cxx mod2.scm mod2_wrap.cxx - -mod1_wrap.cxx: mod1.i - $(SWIGEXE) -chicken -c++ -proxy mod1.i - -mod2_wrap.cxx: mod2.i - $(SWIGEXE) -chicken -c++ -proxy mod2.i - -clean: - rm -rf eggs - -# this part is for testing... -setup: - cd eggs && \ - mkdir -p install && \ - chicken-setup -repository `pwd`/install single.egg && \ - chicken-setup -repository `pwd`/install multi.egg diff --git a/Examples/chicken/egg/README b/Examples/chicken/egg/README deleted file mode 100644 index b5df0e631..000000000 --- a/Examples/chicken/egg/README +++ /dev/null @@ -1,19 +0,0 @@ -These examples show how to build a chicken extension module in the form of an -egg. There are two eggs that get built, single.egg which contains a single -module which is built with -nounit and multi.egg, which contains two modules -mod1 and mod2. These are built normally, and multi_init.scm loads them both. -Read section "17.4.2 Building chicken extension libraries" in the manual -for a description of these two techniques. - -To build: - -$ make -$ make setup -$ make run - -$ make clean - -The eggs are built into an eggs subdirectory, because chicken-setup has -problems installing eggs when there are other files named similar in -the same directory. The make setup step runs chicken-setup to install -the eggs into the eggs/install directory. diff --git a/Examples/chicken/egg/mod1.i b/Examples/chicken/egg/mod1.i deleted file mode 100644 index 6a2940b89..000000000 --- a/Examples/chicken/egg/mod1.i +++ /dev/null @@ -1,8 +0,0 @@ -%module mod1 - -%inline %{ -class Bar { - public: - int b; -}; -%} diff --git a/Examples/chicken/egg/mod2.i b/Examples/chicken/egg/mod2.i deleted file mode 100644 index e9ae4a6a8..000000000 --- a/Examples/chicken/egg/mod2.i +++ /dev/null @@ -1,17 +0,0 @@ -%module mod2 - -%import "mod1.i" - -%{ -class Bar { - public: - int b; -}; -%} - -%inline %{ - class Bar2 : public Bar { - public: - int c; - }; -%} diff --git a/Examples/chicken/egg/multi.setup b/Examples/chicken/egg/multi.setup deleted file mode 100644 index 95aeb001c..000000000 --- a/Examples/chicken/egg/multi.setup +++ /dev/null @@ -1,2 +0,0 @@ -(run (csc -s -o multi.so multi_init.scm mod1.scm mod1_wrap.cxx mod2.scm mod2_wrap.cxx)) -(install-extension 'multi '("multi.so")) diff --git a/Examples/chicken/egg/multi_init.scm b/Examples/chicken/egg/multi_init.scm deleted file mode 100644 index 600491d5b..000000000 --- a/Examples/chicken/egg/multi_init.scm +++ /dev/null @@ -1,2 +0,0 @@ -(declare (uses mod1)) -(declare (uses mod2)) diff --git a/Examples/chicken/egg/single.i b/Examples/chicken/egg/single.i deleted file mode 100644 index 46266b4bf..000000000 --- a/Examples/chicken/egg/single.i +++ /dev/null @@ -1,8 +0,0 @@ -%module single - -%inline %{ -class Foo { - public: - int a; -}; -%} diff --git a/Examples/chicken/egg/single.setup b/Examples/chicken/egg/single.setup deleted file mode 100644 index 4b503ec21..000000000 --- a/Examples/chicken/egg/single.setup +++ /dev/null @@ -1,2 +0,0 @@ -(run (csc -s -o single.so single.scm single_wrap.cxx)) -(install-extension 'single '("single.so")) diff --git a/Examples/chicken/egg/test.scm b/Examples/chicken/egg/test.scm deleted file mode 100644 index 4ec94ed18..000000000 --- a/Examples/chicken/egg/test.scm +++ /dev/null @@ -1,18 +0,0 @@ -(require-extension single) -(require-extension multi) - -(define f (make )) -(slot-set! f 'a 3) -(print (slot-ref f 'a)) - -(define b (make )) -(slot-set! b 'b 2) -(print (slot-ref b 'b)) - -(define b2 (make )) -(slot-set! b2 'b 4) -(slot-set! b2 'c 6) -(print (slot-ref b2 'b)) -(print (slot-ref b2 'c)) - -(exit 0) diff --git a/Examples/chicken/multimap/Makefile b/Examples/chicken/multimap/Makefile deleted file mode 100644 index 551d1c74d..000000000 --- a/Examples/chicken/multimap/Makefile +++ /dev/null @@ -1,31 +0,0 @@ -TOP = ../.. -SWIGEXE = $(TOP)/../swig -SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib -INTERFACE = example.i -SRCS = example.c -CXXSRCS = -TARGET = multimap -INCLUDE = -SWIGOPT = -VARIANT = - -# uncomment the following two lines to build a static exe -#CHICKEN_MAIN = runme.scm -#VARIANT = _static - -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_run - -build: $(TARGET) - -$(TARGET): $(INTERFACE) $(SRCS) - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ - SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' \ - INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT) - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_clean - rm -f example.scm - rm -f $(TARGET) diff --git a/Examples/chicken/multimap/example.c b/Examples/chicken/multimap/example.c deleted file mode 100644 index b8360fa8a..000000000 --- a/Examples/chicken/multimap/example.c +++ /dev/null @@ -1,53 +0,0 @@ -/* File : example.c */ -#include -#include -#include - -/* Compute the greatest common divisor of positive integers */ -int gcd(int x, int y) { - int g; - g = y; - while (x > 0) { - g = x; - x = y % x; - y = g; - } - return g; -} - -int gcdmain(int argc, char *argv[]) { - int x,y; - if (argc != 3) { - printf("usage: gcd x y\n"); - return -1; - } - x = atoi(argv[1]); - y = atoi(argv[2]); - printf("gcd(%d,%d) = %d\n", x,y,gcd(x,y)); - return 0; -} - -int count(char *bytes, int len, char c) { - int i; - int count = 0; - for (i = 0; i < len; i++) { - if (bytes[i] == c) count++; - } - return count; -} - -void capitalize(char *str, int len) { - int i; - for (i = 0; i < len; i++) { - str[i] = (char)toupper(str[i]); - } -} - -void circle(double x, double y) { - double a = x*x + y*y; - if (a > 1.0) { - printf("Bad points %g, %g\n", x,y); - } else { - printf("Good points %g, %g\n", x,y); - } -} diff --git a/Examples/chicken/multimap/example.i b/Examples/chicken/multimap/example.i deleted file mode 100644 index 02567f48f..000000000 --- a/Examples/chicken/multimap/example.i +++ /dev/null @@ -1,96 +0,0 @@ -/* File : example.i */ -%module example - -%{ -extern int gcd(int x, int y); -extern int gcdmain(int argc, char *argv[]); -extern int count(char *bytes, int len, char c); -extern void capitalize (char *str, int len); -extern void circle (double cx, double cy); -extern int squareCubed (int n, int *OUTPUT); -%} - -%include exception.i -%include typemaps.i - -extern int gcd(int x, int y); - -%typemap(in) (int argc, char *argv[]) { - int i; - if (!C_swig_is_vector ($input)) { - swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument $input is not a vector"); - } - $1 = C_header_size ($input); - $2 = (char **) malloc(($1+1)*sizeof(char *)); - for (i = 0; i < $1; i++) { - C_word o = C_block_item ($input, i); - if (!C_swig_is_string (o)) { - char err[50]; - free($2); - sprintf (err, "$input[%d] is not a string", i); - swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, err); - } - $2[i] = C_c_string (o); - } - $2[i] = 0; -} - -%typemap(freearg) (int argc, char *argv[]) { - free($2); -} -extern int gcdmain(int argc, char *argv[]); - -%typemap(in) (char *bytes, int len) { - if (!C_swig_is_string ($input)) { - swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument $input is not a string"); - } - $1 = C_c_string ($input); - $2 = C_header_size ($input); -} - -extern int count(char *bytes, int len, char c); - - -/* This example shows how to wrap a function that mutates a string */ - -%typemap(in) (char *str, int len) -%{ if (!C_swig_is_string ($input)) { - swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument $input is not a string"); - } - $2 = C_header_size ($input); - $1 = (char *) malloc ($2+1); - memmove ($1, C_c_string ($input), $2); -%} - -/* Return the mutated string as a new object. Notice the if MANY construct ... they must be at column 0. */ - -%typemap(argout) (char *str, int len) (C_word *scmstr) -%{ scmstr = C_alloc (C_SIZEOF_STRING ($2)); - SWIG_APPEND_VALUE(C_string (&scmstr, $2, $1)); - free ($1); -%} - -extern void capitalize (char *str, int len); - -/* A multi-valued constraint. Force two arguments to lie - inside the unit circle */ - -%typemap(check) (double cx, double cy) { - double a = $1*$1 + $2*$2; - if (a > 1.0) { - SWIG_exception (SWIG_ValueError, "cx and cy must be in unit circle"); - } -} - -extern void circle (double cx, double cy); - -/* Test out multiple return values */ - -extern int squareCubed (int n, int *OUTPUT); -%{ -/* Returns n^3 and set n2 to n^2 */ -int squareCubed (int n, int *n2) { - *n2 = n * n; - return (*n2) * n; -}; -%} diff --git a/Examples/chicken/multimap/runme.scm b/Examples/chicken/multimap/runme.scm deleted file mode 100644 index ebe644004..000000000 --- a/Examples/chicken/multimap/runme.scm +++ /dev/null @@ -1,58 +0,0 @@ -;; feel free to uncomment and comment sections - -(load-library 'example "multimap.so") - -(display "(gcd 90 12): ") -(display (gcd 90 12)) -(display "\n") - -(display "(circle 0.5 0.5): ") -(display (circle 0.5 0.5)) -(display "\n") - -(display "(circle 1.0 1.0): ") -(handle-exceptions exvar - (if (= (car exvar) 9) - (display "success: exception thrown") - (display "an incorrect exception was thrown")) - (begin - (circle 1.0 1.0) - (display "an exception was not thrown when it should have been"))) -(display "\n") - -(display "(circle 1 1): ") -(handle-exceptions exvar - (if (= (car exvar) 9) - (display "success: exception thrown") - (display "an incorrect exception was thrown")) - (begin - (circle 1 1) - (display "an exception was not thrown when it should have been"))) -(display "\n") - -(display "(capitalize \"will this be all capital letters?\"): ") -(display (capitalize "will this be all capital letters?")) -(display "\n") - -(display "(count \"jumpity little spider\" #\\t): ") -(display (count "jumpity little spider" #\t)) -(display "\n") - -(display "(gcdmain '#(\"hi\" \"there\")): ") -(display (gcdmain '#("hi" "there"))) -(display "\n") - -(display "(gcdmain '#(\"gcd\" \"9\" \"28\")): ") -(gcdmain '#("gcd" "9" "28")) -(display "\n") - -(display "(gcdmain '#(\"gcd\" \"12\" \"90\")): ") -(gcdmain '#("gcd" "12" "90")) -(display "\n") - -(display "squarecubed 3: ") -(call-with-values (lambda() (squareCubed 3)) - (lambda (a b) (printf "~A ~A" a b))) -(display "\n") - -(exit) diff --git a/Examples/chicken/overload/Makefile b/Examples/chicken/overload/Makefile deleted file mode 100644 index 019390192..000000000 --- a/Examples/chicken/overload/Makefile +++ /dev/null @@ -1,31 +0,0 @@ -TOP = ../.. -SWIGEXE = $(TOP)/../swig -SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib -INTERFACE = example.i -SRCS = -CXXSRCS = example.cxx -TARGET = overload -INCLUDE = -SWIGOPT = -proxy -unhideprimitive -VARIANT = - -# uncomment the following lines to build a static exe -#CHICKEN_MAIN = runme.scm -#VARIANT = _static - -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_run - -build: $(TARGET) - -$(TARGET): $(INTERFACE) $(SRCS) - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ - SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' \ - INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT)_cpp - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_clean - rm -f example.scm - rm -f $(TARGET) diff --git a/Examples/chicken/overload/README b/Examples/chicken/overload/README deleted file mode 100644 index 9487c3f3e..000000000 --- a/Examples/chicken/overload/README +++ /dev/null @@ -1,2 +0,0 @@ -Overloading example from Chapter 5.14 of SWIG Core Documentation for -version 1.3. diff --git a/Examples/chicken/overload/example.cxx b/Examples/chicken/overload/example.cxx deleted file mode 100644 index 65e743941..000000000 --- a/Examples/chicken/overload/example.cxx +++ /dev/null @@ -1,33 +0,0 @@ -/* File : example.c */ - -#include "example.h" -#include - -void foo(int x) { - printf("x is %d\n", x); -} - -void foo(char *x) { - printf("x is '%s'\n", x); -} - -Foo::Foo () { - myvar = 55; - printf ("Foo constructor called\n"); -} - -Foo::Foo (const Foo &) { - myvar = 66; - printf ("Foo copy constructor called\n"); -} - -void Foo::bar (int x) { - printf ("Foo::bar(x) method ... \n"); - printf("x is %d\n", x); -} - -void Foo::bar (char *s, int y) { - printf ("Foo::bar(s,y) method ... \n"); - printf ("s is '%s'\n", s); - printf ("y is %d\n", y); -} diff --git a/Examples/chicken/overload/example.h b/Examples/chicken/overload/example.h deleted file mode 100644 index 1c135d509..000000000 --- a/Examples/chicken/overload/example.h +++ /dev/null @@ -1,14 +0,0 @@ -/* File : example.h */ - -extern void foo (int x); -extern void foo (char *x); - -class Foo { - private: - int myvar; - public: - Foo(); - Foo(const Foo &); // Copy constructor - void bar(int x); - void bar(char *s, int y); -}; diff --git a/Examples/chicken/overload/example.i b/Examples/chicken/overload/example.i deleted file mode 100644 index 23a29986e..000000000 --- a/Examples/chicken/overload/example.i +++ /dev/null @@ -1,16 +0,0 @@ -/* File : example.i */ -%module example - -%{ -#include "example.h" -%} - -/* Let "Foo" objects be converted back and forth from TinyCLOS into - low-level CHICKEN SWIG procedures */ - -%typemap(clos_in) Foo * = SIMPLE_CLOS_OBJECT *; -%typemap(clos_out) Foo * = SIMPLE_CLOS_OBJECT *; - -/* Let's just grab the original header file here */ -%include "example.h" - diff --git a/Examples/chicken/overload/runme.scm b/Examples/chicken/overload/runme.scm deleted file mode 100644 index 168490f76..000000000 --- a/Examples/chicken/overload/runme.scm +++ /dev/null @@ -1,45 +0,0 @@ -;; This file demonstrates the overloading capabilities of SWIG - -(load-library 'example "overload.so") - -;; Low level -;; --------- - -(display " -Trying low level code ... - (foo 1) - (foo \"some string\") - (define A-FOO (new-Foo)) - (define ANOTHER-FOO (new-Foo A-FOO)) ;; copy constructor - (Foo-bar A-FOO 2) - (Foo-bar ANOTHER-FOO \"another string\" 3) -") - -(primitive:foo 1) -(primitive:foo "some string") -(define A-FOO (slot-ref (primitive:new-Foo) 'swig-this)) -(define ANOTHER-FOO (slot-ref (primitive:new-Foo A-FOO) 'swig-this)) ;; copy constructor -(primitive:Foo-bar A-FOO 2) -(primitive:Foo-bar ANOTHER-FOO "another string" 3) - -;; TinyCLOS -;; -------- - -(display " -Trying TinyCLOS code ... - (+foo+ 1) - (+foo+ \"some string\") - (define A-FOO (make )) - (define ANOTHER-FOO (make A-FOO)) ;; copy constructor - (-bar- A-FOO 2) - (-bar- ANOTHER-FOO \"another string\" 3) -") - -(foo 1) -(foo "some string") -(define A-FOO (make )) -(define ANOTHER-FOO (make A-FOO)) ;; copy constructor -(bar A-FOO 2) -(bar ANOTHER-FOO "another string" 3) - -(exit) diff --git a/Examples/chicken/simple/Makefile b/Examples/chicken/simple/Makefile deleted file mode 100644 index f5dd1a966..000000000 --- a/Examples/chicken/simple/Makefile +++ /dev/null @@ -1,31 +0,0 @@ -TOP = ../.. -SWIGEXE = $(TOP)/../swig -SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib -INTERFACE = example.i -SRCS = example.c -CXXSRCS = -TARGET = simple -INCLUDE = -SWIGOPT = -VARIANT = - -# uncomment the following two lines to build a static exe -#CHICKEN_MAIN = runme.scm -#VARIANT = _static - -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_run - -build: $(TARGET) - -$(TARGET): $(INTERFACE) $(SRCS) - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ - SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' \ - INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT) - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_clean - rm -f example.scm example-generic.scm example-clos.scm - rm -f $(TARGET) diff --git a/Examples/chicken/simple/README b/Examples/chicken/simple/README deleted file mode 100644 index 07e8da069..000000000 --- a/Examples/chicken/simple/README +++ /dev/null @@ -1 +0,0 @@ -Simple example from users manual. diff --git a/Examples/chicken/simple/example.c b/Examples/chicken/simple/example.c deleted file mode 100644 index f2b074781..000000000 --- a/Examples/chicken/simple/example.c +++ /dev/null @@ -1,24 +0,0 @@ -/* Simple example from documentation */ -/* File : example.c */ - -#include - -double My_variable = 3.0; - -/* Compute factorial of n */ -int fact(int n) { - if (n <= 1) return 1; - else return n*fact(n-1); -} - -/* Compute n mod m */ -int my_mod(int n, int m) { - return (n % m); -} - - -char *get_time() { - long ltime; - time(<ime); - return ctime(<ime); -} diff --git a/Examples/chicken/simple/example.i b/Examples/chicken/simple/example.i deleted file mode 100644 index 5b3e95580..000000000 --- a/Examples/chicken/simple/example.i +++ /dev/null @@ -1,16 +0,0 @@ -/* File : example.i */ -%module example -%{ -/* Put headers and other declarations here */ -%} - -%include typemaps.i - -%rename(mod) my_mod; - -%inline %{ -extern double My_variable; -extern int fact(int); -extern int my_mod(int n, int m); -extern char *get_time(); -%} diff --git a/Examples/chicken/simple/runme.scm b/Examples/chicken/simple/runme.scm deleted file mode 100644 index 05aa87081..000000000 --- a/Examples/chicken/simple/runme.scm +++ /dev/null @@ -1,28 +0,0 @@ -;; feel free to uncomment and comment sections -(load-library 'example "simple.so") - -(display "(My-variable): ") -(display (My-variable)) -(display "\n") - -(display "(My-variable 3.141259): ") -(display (My-variable 3.141259)) -(display "\n") - -(display "(My-variable): ") -(display (My-variable)) -(display "\n") - -(display "(fact 5): ") -(display (fact 5)) -(display "\n") - -(display "(mod 75 7): ") -(display (mod 75 7)) -(display "\n") - -(display "(get-time): ") -(display (get-time)) -(display "\n") - -(exit) diff --git a/Examples/contract/simple_c/example.c b/Examples/contract/simple_c/example.c deleted file mode 100644 index 85a3e1417..000000000 --- a/Examples/contract/simple_c/example.c +++ /dev/null @@ -1,11 +0,0 @@ -#include - -int Circle (int x, int y, int radius) { - /* Draw Circle */ - printf("Drawing the circle...\n"); - /* Return -1 to test contract post assertion */ - if (radius == 2) - return -1; - else - return 1; -} diff --git a/Examples/contract/simple_c/example.i b/Examples/contract/simple_c/example.i deleted file mode 100644 index 49df09af6..000000000 --- a/Examples/contract/simple_c/example.i +++ /dev/null @@ -1,19 +0,0 @@ -/* File : example.i */ - -/* Basic C example for swig contract */ -/* Tiger, University of Chicago, 2003 */ - -%module example - -%contract Circle (int x, int y, int radius) { -require: - x >= 0; - y >= 0; - radius > x; -ensure: - Circle >= 0; -} - -%inline %{ -extern int Circle (int x, int y, int radius); -%} diff --git a/Examples/contract/simple_c/runme1.py b/Examples/contract/simple_c/runme1.py deleted file mode 100644 index abd8df62f..000000000 --- a/Examples/contract/simple_c/runme1.py +++ /dev/null @@ -1,17 +0,0 @@ -import example -# Call the Circle() function correctly - -x = 1; -y = 1; -r = 3; - -c = example.Circle(x, y, r) - -# test post-assertion -x = 1; -y = 1; -r = 2; - -c = example.Circle(x, y, r) - -print "The return value of Circle(%d, %d, %d) is %d" % (x,y,r,c) diff --git a/Examples/contract/simple_c/runme2.py b/Examples/contract/simple_c/runme2.py deleted file mode 100644 index 48d4a3f10..000000000 --- a/Examples/contract/simple_c/runme2.py +++ /dev/null @@ -1,20 +0,0 @@ -import example - -# Call the Circle() function correctly - -x = 1; -y = 1; -r = 3; - -c = example.Circle(x, y, r) - -print "The return value of Circle(%d, %d, %d) is %d" % (x,y,r,c) - -# test pre-assertion -x = 1; -y = -1; -r = 3; - -c = example.Circle(x, y, r) - -print "The return value of Circle(%d, %d, %d) is %d" % (x,y,r,c) diff --git a/Examples/contract/simple_cxx/example.cxx b/Examples/contract/simple_cxx/example.cxx deleted file mode 100644 index e3dd2ca7a..000000000 --- a/Examples/contract/simple_cxx/example.cxx +++ /dev/null @@ -1,30 +0,0 @@ -#include "example.h" - -#define M_PI 3.14159265358979323846 - -/* Move the shape to a new location */ -void Shape::move(double dx, double dy) { - x += dx; - y += dy; -} - -int Shape::nshapes = 0; - -double Circle::area(void) { - /* return -1 is to test post-assertion */ - if (radius == 1) - return -1; - return M_PI*radius*radius; -} - -double Circle::perimeter(void) { - return 2*M_PI*radius; -} - -double Square::area(void) { - return width*width; -} - -double Square::perimeter(void) { - return 4*width; -} diff --git a/Examples/contract/simple_cxx/example.h b/Examples/contract/simple_cxx/example.h deleted file mode 100644 index de708bb7b..000000000 --- a/Examples/contract/simple_cxx/example.h +++ /dev/null @@ -1,34 +0,0 @@ -/* File : example.h */ - -class Shape { -public: - Shape() { - nshapes++; - } - virtual ~Shape() { - nshapes--; - } - double x, y; - void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; - static int nshapes; -}; - -class Circle : public Shape { -private: - double radius; -public: - Circle(double r) : radius(r) { } - virtual double area(void); - virtual double perimeter(void); -}; - -class Square : public Shape { -private: - double width; -public: - Square(double w) : width(w) { } - virtual double area(void); - virtual double perimeter(void); -}; diff --git a/Examples/contract/simple_cxx/example.i b/Examples/contract/simple_cxx/example.i deleted file mode 100644 index 9b47409d0..000000000 --- a/Examples/contract/simple_cxx/example.i +++ /dev/null @@ -1,28 +0,0 @@ -%module example - -%contract Circle::Circle(double radius) { -require: - radius > 0; -} - -%contract Circle::area(void) { -ensure: - area > 0; -} - -%contract Shape::move(double dx, double dy) { -require: - dx > 0; -} - -/* should be no effect, since there is no move() for class Circle */ -%contract Circle::move(double dx, double dy) { -require: - dy > 1; -} - -# include must be after contracts -%{ -#include "example.h" -%} -%include "example.h" diff --git a/Examples/contract/simple_cxx/runme1.py b/Examples/contract/simple_cxx/runme1.py deleted file mode 100644 index 9028d02d9..000000000 --- a/Examples/contract/simple_cxx/runme1.py +++ /dev/null @@ -1,33 +0,0 @@ -import example - -# Create the Circle object - -r = 2; -print " Creating circle (radium: %d) :" % r -c = example.Circle(r) - -# Set the location of the object - -c.x = 20 -c.y = 30 -print " Here is its current position:" -print " Circle = (%f, %f)" % (c.x,c.y) - -# ----- Call some methods ----- - -print "\n Here are some properties of the Circle:" -print " area = ", c.area() -print " perimeter = ", c.perimeter() -dx = 1; -dy = 1; -print " Moving with (%d, %d)..." % (dx, dy) -c.move(dx, dy) - -del c - -print "===================================" - -# test construction */ -r = -1; -print " Creating circle (radium: %d) :" % r -c = example.Circle(r) diff --git a/Examples/contract/simple_cxx/runme2.py b/Examples/contract/simple_cxx/runme2.py deleted file mode 100644 index 5f9c0df5b..000000000 --- a/Examples/contract/simple_cxx/runme2.py +++ /dev/null @@ -1,44 +0,0 @@ -import example - -# Create the Circle object - -r = 2; -print " Creating circle (radium: %d) :" % r -c = example.Circle(r) - -# Set the location of the object - -c.x = 20 -c.y = 30 -print " Here is its current position:" -print " Circle = (%f, %f)" % (c.x,c.y) - -# ----- Call some methods ----- - -print "\n Here are some properties of the Circle:" -print " area = ", c.area() -print " perimeter = ", c.perimeter() -dx = 1; -dy = 1; -print " Moving with (%d, %d)..." % (dx, dy) -c.move(dx, dy) - -del c - -print "===================================" - -# test area function */ -r = 1; -print " Creating circle (radium: %d) :" % r -c = example.Circle(r) -# Set the location of the object - -c.x = 20 -c.y = 30 -print " Here is its current position:" -print " Circle = (%f, %f)" % (c.x,c.y) - -# ----- Call some methods ----- - -print "\n Here are some properties of the Circle:" -print " area = ", c.area() diff --git a/Examples/contract/simple_cxx/runme3.py b/Examples/contract/simple_cxx/runme3.py deleted file mode 100644 index a663732b1..000000000 --- a/Examples/contract/simple_cxx/runme3.py +++ /dev/null @@ -1,57 +0,0 @@ -import example - -# Create the Circle object - -r = 2; -print " Creating circle (radium: %d) :" % r -c = example.Circle(r) - -# Set the location of the object - -c.x = 20 -c.y = 30 -print " Here is its current position:" -print " Circle = (%f, %f)" % (c.x,c.y) - -# ----- Call some methods ----- - -print "\n Here are some properties of the Circle:" -print " area = ", c.area() -print " perimeter = ", c.perimeter() -dx = 1; -dy = 1; -print " Moving with (%d, %d)..." % (dx, dy) -c.move(dx, dy) - -del c - -print "===================================" - -# test move function */ -r = 2; -print " Creating circle (radium: %d) :" % r -c = example.Circle(r) -# Set the location of the object - -c.x = 20 -c.y = 30 -print " Here is its current position:" -print " Circle = (%f, %f)" % (c.x,c.y) - -# ----- Call some methods ----- - -print "\n Here are some properties of the Circle:" -print " area = ", c.area() -print " perimeter = ", c.perimeter() - -# no error for Circle's pre-assertion -dx = 1; -dy = -1; -print " Moving with (%d, %d)..." % (dx, dy) -c.move(dx, dy) - -# error with Shape's pre-assertion -dx = -1; -dy = 1; -print " Moving with (%d, %d)..." % (dx, dy) -c.move(dx, dy) diff --git a/Examples/guile/check.list b/Examples/guile/check.list index 726e6ab75..1f22adf78 100644 --- a/Examples/guile/check.list +++ b/Examples/guile/check.list @@ -1,9 +1,9 @@ # see top-level Makefile.in -constants class -port -simple -std_vector +constants matrix multimap multivalue +port +simple +std_vector diff --git a/Examples/guile/matrix/example.i b/Examples/guile/matrix/example.i index 3f801dcdf..6f8fa8859 100644 --- a/Examples/guile/matrix/example.i +++ b/Examples/guile/matrix/example.i @@ -14,4 +14,8 @@ %include math.i -extern double drand48(); +%{ +/* Add drand48 declaration as it is posix only and is not in stdlib.h when using strict c99 and later */ +extern double drand48(void); +%} +extern double drand48(void); diff --git a/Examples/guile/multimap/example.i b/Examples/guile/multimap/example.i index c24d45ddc..776eb30c4 100644 --- a/Examples/guile/multimap/example.i +++ b/Examples/guile/multimap/example.i @@ -78,7 +78,7 @@ extern int count(char *bytes, int len, char c); %typemap(argout) (char *str, int len) { SWIG_APPEND_VALUE(scm_from_locale_stringn($1,$2)); - if ($1) SWIG_free($1); + SWIG_free($1); } extern void capitalize(char *str, int len); diff --git a/Examples/javascript/exception/example.h b/Examples/javascript/exception/example.h index bc744cda7..c76c46a5d 100644 --- a/Examples/javascript/exception/example.h +++ b/Examples/javascript/exception/example.h @@ -10,7 +10,7 @@ class Exc { public: Exc(int c, const char *m) { code = c; - strncpy(msg,m,256); + strncpy(msg,m,255); } int code; char msg[256]; diff --git a/Examples/javascript/native/example.i b/Examples/javascript/native/example.i index 8c6160060..a9ca094a7 100644 --- a/Examples/javascript/native/example.i +++ b/Examples/javascript/native/example.i @@ -15,7 +15,7 @@ int placeholder() { return 0; } static SwigV8ReturnValue JavaScript_do_work(const SwigV8Arguments &args) { SWIGV8_HANDLESCOPE(); const int MY_MAGIC_NUMBER = 5; - v8::Handle jsresult = + SWIGV8_VALUE jsresult = SWIG_From_int(static_cast< int >(MY_MAGIC_NUMBER)); if (args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments."); diff --git a/Examples/lua/arrays/example.i b/Examples/lua/arrays/example.i index eafd8ff55..54bc31bde 100644 --- a/Examples/lua/arrays/example.i +++ b/Examples/lua/arrays/example.i @@ -9,12 +9,12 @@ See the lua code for how they are called %include // array helpers -// this declares a batch of function for manipulating C integer arrays +// this declares a batch of functions for manipulating C integer arrays %array_functions(int,int) // this adds some lua code directly into the module // warning: you need the example. prefix if you want it added into the module -// admittedly this code is a bit tedious, but its a one off effort +// admittedly this code is a bit tedious, but it's a one off effort %luacode { function example.sort_int2(t) -- local len=table.maxn(t) -- the len - maxn deprecated in 5.3 diff --git a/Examples/lua/constants/runme.lua b/Examples/lua/constants/runme.lua index ad6bd45d2..bc7ca2450 100644 --- a/Examples/lua/constants/runme.lua +++ b/Examples/lua/constants/runme.lua @@ -30,6 +30,6 @@ function checkfail(fn) end -- these should fail --- example.EXTERN is a nil value, so concatentatin will make it fail +-- example.EXTERN is a nil value, so concatenation will make it fail checkfail(function() print("EXTERN = "..example.EXTERN) end) checkfail(function() print("FOO = "..example.FOO) end) diff --git a/Examples/lua/embed/embed.c b/Examples/lua/embed/embed.c index 1f10cc8e8..2cb4728fb 100644 --- a/Examples/lua/embed/embed.c +++ b/Examples/lua/embed/embed.c @@ -23,7 +23,7 @@ We will be using the luaL_dostring()/lua_dostring() function to call into lua #define lua_open luaL_newstate #endif -/* the SWIG wrappered library */ +/* the SWIG wrapped library */ extern int luaopen_example(lua_State*L); /* a really simple way of calling lua from C diff --git a/Examples/lua/embed2/embed2.c b/Examples/lua/embed2/embed2.c index 0ce9f8f7f..5507877e5 100644 --- a/Examples/lua/embed2/embed2.c +++ b/Examples/lua/embed2/embed2.c @@ -41,7 +41,7 @@ extern int luaopen_example(lua_State*L); /* This is an example of how to call the Lua function int add(int,int) - its very tedious, but gives you an idea of the issues involved. + it's very tedious, but gives you an idea of the issues involved. (look below for a better idea) */ int call_add(lua_State *L,int a,int b,int* res) { @@ -75,7 +75,7 @@ int call_add(lua_State *L,int a,int b,int* res) { return 1; } -/* This is a variargs call function for calling from C into Lua. +/* This is a varargs call function for calling from C into Lua. Original Code from Programming in Lua (PIL) by Roberto Ierusalimschy ISBN 85-903798-1-7 http://www.lua.org/pil/25.3.html @@ -186,7 +186,7 @@ int main(int argc,char* argv[]) { luaopen_base(L); luaopen_string(L); luaopen_math(L); - printf("[C] now loading the SWIG wrappered library\n"); + printf("[C] now loading the SWIG wrapped library\n"); luaopen_example(L); printf("[C] all looks ok\n"); printf("\n"); @@ -226,8 +226,8 @@ int main(int argc,char* argv[]) { printf("\n"); printf("[C] Note: no protection if you mess up the va-args, this is C\n"); printf("\n"); - printf("[C] Finally we will call the wrappered gcd function gdc(6,9):\n"); - printf("[C] This will pass the values to Lua, then call the wrappered function\n"); + printf("[C] Finally we will call the wrapped gcd function gdc(6,9):\n"); + printf("[C] This will pass the values to Lua, then call the wrapped function\n"); printf(" Which will get the values from Lua, call the C code \n"); printf(" and return the value to Lua and eventually back to C\n"); printf("[C] Certainly not the best way to do it :-)\n"); diff --git a/Examples/lua/embed3/embed3.cpp b/Examples/lua/embed3/embed3.cpp index 9be49add3..c3c5d380c 100644 --- a/Examples/lua/embed3/embed3.cpp +++ b/Examples/lua/embed3/embed3.cpp @@ -61,7 +61,7 @@ bool push_pointer(lua_State*L, void* ptr, const char* type_name, int owned = 0) /* This is an example of how to call the Lua function void onEvent(Event e) - its very tedious, but gives you an idea of the issues involed. + it's very tedious, but gives you an idea of the issues involved. */ int call_onEvent(lua_State *L, Event e) { int top; @@ -105,7 +105,7 @@ int main(int argc, char* argv[]) { /* this code will pass a pointer into lua, but C++ still owns the object this is a little tedious, to do, but let's do it we need to pass the pointer (obviously), the type name - and a flag which states if Lua should delete the pointer once its finished with it + and a flag which states if Lua should delete the pointer once it's finished with it The type name is a class name string which is registered with SWIG (normally, just look in the wrapper file to get this) in this case we don't want Lua to delete the pointer so the ownership flag is 0 diff --git a/Examples/lua/exception/example.h b/Examples/lua/exception/example.h index bc744cda7..c76c46a5d 100644 --- a/Examples/lua/exception/example.h +++ b/Examples/lua/exception/example.h @@ -10,7 +10,7 @@ class Exc { public: Exc(int c, const char *m) { code = c; - strncpy(msg,m,256); + strncpy(msg,m,255); } int code; char msg[256]; diff --git a/Examples/lua/owner/example.cxx b/Examples/lua/owner/example.cxx index c2c073d79..a4dcc68a1 100644 --- a/Examples/lua/owner/example.cxx +++ b/Examples/lua/owner/example.cxx @@ -3,7 +3,9 @@ #include "example.h" #include +#ifndef M_PI #define M_PI 3.14159265358979323846 +#endif /* Move the shape to a new location */ void Shape::move(double dx, double dy) { diff --git a/Examples/modula3/check.list b/Examples/modula3/check.list deleted file mode 100644 index 37ac8c105..000000000 --- a/Examples/modula3/check.list +++ /dev/null @@ -1,7 +0,0 @@ -# see top-level Makefile.in -class -enum -exception -reference -simple -typemap diff --git a/Examples/modula3/class/Makefile b/Examples/modula3/class/Makefile deleted file mode 100644 index b25f636c3..000000000 --- a/Examples/modula3/class/Makefile +++ /dev/null @@ -1,26 +0,0 @@ -TOP = ../.. -SWIGEXE = $(TOP)/../swig -SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib -SRCS = -TARGET = example -PLATFORM = LINUXLIBC6 -INTERFACE = example.i -SWIGOPT = -c++ -MODULA3SRCS = *.[im]3 - -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' modula3 - m3ppinplace $(MODULA3SRCS) -# compilation of example_wrap.cxx is started by cm3 -# $(CXX) -c $(TARGET)_wrap.cxx - mv example_wrap.cxx m3makefile $(MODULA3SRCS) src/ - ln -sf ../example.h src/example.h - cm3 - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_clean diff --git a/Examples/modula3/class/example.cxx b/Examples/modula3/class/example.cxx deleted file mode 100644 index 046304519..000000000 --- a/Examples/modula3/class/example.cxx +++ /dev/null @@ -1,28 +0,0 @@ -/* File : example.cxx */ - -#include "example.h" -#define M_PI 3.14159265358979323846 - -/* Move the shape to a new location */ -void Shape::move(double dx, double dy) { - x += dx; - y += dy; -} - -int Shape::nshapes = 0; - -double Circle::area() { - return M_PI*radius*radius; -} - -double Circle::perimeter() { - return 2*M_PI*radius; -} - -double Square::area() { - return width*width; -} - -double Square::perimeter() { - return 4*width; -} diff --git a/Examples/modula3/class/example.h b/Examples/modula3/class/example.h deleted file mode 100644 index 0dff185b2..000000000 --- a/Examples/modula3/class/example.h +++ /dev/null @@ -1,34 +0,0 @@ -/* File : example.h */ - -class Shape { -public: - Shape() { - nshapes++; - } - virtual ~Shape() { - nshapes--; - } - double x, y; - void move(double dx, double dy); - virtual double area() = 0; - virtual double perimeter() = 0; - static int nshapes; -}; - -class Circle : public Shape { -private: - double radius; -public: - Circle(double r) : radius(r) { } - virtual double area(); - virtual double perimeter(); -}; - -class Square : public Shape { -private: - double width; -public: - Square(double w) : width(w) { } - virtual double area(); - virtual double perimeter(); -}; diff --git a/Examples/modula3/class/example.i b/Examples/modula3/class/example.i deleted file mode 100644 index 2fafadbd6..000000000 --- a/Examples/modula3/class/example.i +++ /dev/null @@ -1,32 +0,0 @@ -/* File : example.i */ -%module Example - -%{ -#include "example.h" -%} - -%insert(m3makefile) %{template("../swig") -cxx_source("example_wrap")%} - -%typemap(m3rawinmode) Shape *, Circle *, Square * "" -%typemap(m3rawrettype) Shape *, Circle *, Square * "$1_basetype" - -%typemap(m3wrapinmode) Shape *, Circle *, Square * "" -%typemap(m3wrapargraw) Shape *, Circle *, Square * "self.cxxObj" - -%typemap(m3wrapretvar) Circle *, Square * "cxxObj : ExampleRaw.$1_basetype;" -%typemap(m3wrapretraw) Circle *, Square * "cxxObj" -%typemap(m3wrapretconv) Circle *, Square * "NEW($1_basetype,cxxObj:=cxxObj)" -%typemap(m3wraprettype) Circle *, Square * "$1_basetype" - -/* Should work with and without renaming -%rename(M3Shape) Shape; -%rename(M3Circle) Circle; -%rename(M3Square) Square; -%typemap(m3wrapintype) Shape *, Circle *, Square * "M3$1_basetype" -%typemap(m3wraprettype) Shape *, Circle *, Square * "M3$1_basetype" -%typemap(m3wrapretconv) Circle *, Square * "NEW(M3$1_basetype,cxxObj:=cxxObj)" -*/ - -/* Let's just grab the original header file here */ -%include "example.h" diff --git a/Examples/modula3/class/swig.tmpl b/Examples/modula3/class/swig.tmpl deleted file mode 100644 index e3e9bf178..000000000 --- a/Examples/modula3/class/swig.tmpl +++ /dev/null @@ -1,11 +0,0 @@ - -readonly proc cxx_source (X) is - local cxxfile = X&".cxx" - local objfile = X&".o" - %exec("echo $PWD") - if stale(objfile,cxxfile) - exec("cd",path(),"; g++ -I.. -c -o",objfile,cxxfile) - end - import_obj(X) - %unlink_file(path()&SL&objfile) -end diff --git a/Examples/modula3/enum/Makefile b/Examples/modula3/enum/Makefile deleted file mode 100644 index 2c5c9b0a5..000000000 --- a/Examples/modula3/enum/Makefile +++ /dev/null @@ -1,27 +0,0 @@ -TOP = ../.. -SWIGEXE = $(TOP)/../swig -SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib -SRCS = -TARGET = example -INTERFACE = example.i -CONSTNUMERIC = example_const -SWIGOPT = -c++ -MODULA3SRCS = *.[im]3 - -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_run - -build: - $(SWIGEXE) -modula3 $(SWIGOPT) -module Example -generateconst $(CONSTNUMERIC) $(TARGET).h - $(CXX) -Wall $(CONSTNUMERIC).c -o $(CONSTNUMERIC) - $(CONSTNUMERIC) >$(CONSTNUMERIC).i - - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' modula3 - m3ppinplace $(MODULA3SRCS) - mv m3makefile $(MODULA3SRCS) src/ - cm3 - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_clean diff --git a/Examples/modula3/enum/example.cxx b/Examples/modula3/enum/example.cxx deleted file mode 100644 index bd808ff7c..000000000 --- a/Examples/modula3/enum/example.cxx +++ /dev/null @@ -1,32 +0,0 @@ -/* File : example.cxx */ - -#include "example.h" -#include - -void Foo::enum_test(speed s) { - if (s == IMPULSE) { - printf("IMPULSE speed\n"); - } else if (s == WARP) { - printf("WARP speed\n"); - } else if (s == LUDICROUS) { - printf("LUDICROUS speed\n"); - } else if (s == HYPER) { - printf("HYPER speed\n"); - } else { - printf("Unknown speed\n"); - } -} - -void enum_test(color c, Foo::speed s) { - if (c == RED) { - printf("color = RED, "); - } else if (c == BLUE) { - printf("color = BLUE, "); - } else if (c == GREEN) { - printf("color = GREEN, "); - } else { - printf("color = Unknown color!, "); - } - Foo obj; - obj.enum_test(s); -} diff --git a/Examples/modula3/enum/example.h b/Examples/modula3/enum/example.h deleted file mode 100644 index 2f44a6ccf..000000000 --- a/Examples/modula3/enum/example.h +++ /dev/null @@ -1,83 +0,0 @@ -/* File : example.h */ - -#define PI 3.141 - -#define DAY_MONDAY 0 -#define DAY_TUESDAY 1 -#define DAY_WEDNESDAY 2 -#define DAY_THURSDAY 3 -#define DAY_FRIDAY 4 -#define DAY_SATURDAY 5 -#define DAY_SUNDAY 6 - -enum color { BLUE, RED, GREEN }; - -#define CLB_BLACK 0 -#define CLB_BLUE 1 -#define CLB_RED 2 -#define CLB_MAGENTA 3 -#define CLB_GREEN 4 -#define CLB_CYAN 5 -#define CLB_YELLOW 6 -#define CLB_WHITE 7 - -/* Using this would be good style - which cannot be expected for general C header files. - Instead I want to demonstrate how to live without it. -enum month { - MTHF_JANUARY, - MTHF_FEBRUARY, - MTHF_MARCH, - MTHF_APRIL, - MTHF_MAY, - MTHF_JUNE, - MTHF_JULY, - MTHF_AUGUST, - MTHF_SEPTEMBER, - MTHF_OCTOBER, - MTHF_NOVEMBER, - MTHF_DECEMBER, -} -*/ - -/* Since there are no compile time constants in C / C++ - it is a common abuse - to declare bit set (flag) constants - as enumerations. */ -enum calendar { - MTHB_JANUARY = 1 << 0, /* 1 << MTHF_JANUARY, */ - MTHB_FEBRUARY = 1 << 1, /* 1 << MTHF_FEBRUARY, */ - MTHB_MARCH = 1 << 2, /* 1 << MTHF_MARCH, */ - MTHB_APRIL = 1 << 3, /* 1 << MTHF_APRIL, */ - MTHB_MAY = 1 << 4, /* 1 << MTHF_MAY, */ - MTHB_JUNE = 1 << 5, /* 1 << MTHF_JUNE, */ - MTHB_JULY = 1 << 6, /* 1 << MTHF_JULY, */ - MTHB_AUGUST = 1 << 7, /* 1 << MTHF_AUGUST, */ - MTHB_SEPTEMBER = 1 << 8, /* 1 << MTHF_SEPTEMBER, */ - MTHB_OCTOBER = 1 << 9, /* 1 << MTHF_OCTOBER, */ - MTHB_NOVEMBER = 1 << 10, /* 1 << MTHF_NOVEMBER, */ - MTHB_DECEMBER = 1 << 11, /* 1 << MTHF_DECEMBER, */ - - MTHB_SPRING = MTHB_MARCH | MTHB_APRIL | MTHB_MAY, - MTHB_SUMMER = MTHB_JUNE | MTHB_JULY | MTHB_AUGUST, - MTHB_AUTUMN = MTHB_SEPTEMBER | MTHB_OCTOBER | MTHB_NOVEMBER, - MTHB_WINTER = MTHB_DECEMBER | MTHB_JANUARY | MTHB_FEBRUARY, -}; - - -namespace Answer { - enum { - UNIVERSE_AND_EVERYTHING = 42, - SEVENTEEN_AND_FOUR = 21, - TWOHUNDRED_PERCENT_OF_NOTHING = 0, - }; - - class Foo { - public: - Foo() { } - enum speed { IMPULSE = -2, WARP = 0, HYPER, LUDICROUS = 3}; - void enum_test(speed s); - }; -}; - -void enum_test(color c, Answer::Foo::speed s); diff --git a/Examples/modula3/enum/example.i b/Examples/modula3/enum/example.i deleted file mode 100644 index f5947b3bc..000000000 --- a/Examples/modula3/enum/example.i +++ /dev/null @@ -1,72 +0,0 @@ -/* File : example.i */ -%module Example - -%{ -#include "example.h" -%} - -%include "example_const.i" - -// such features are generated by the following pragmas -#if 0 -%feature("modula3:enumitem:enum","Days") DAY_MONDAY; -%feature("modula3:enumitem:name","monday") DAY_MONDAY; -%feature("modula3:enumitem:conv","int:int") DAY_MONDAY; - -%feature("modula3:enumitem:enum","Month") MTHB_JANUARY; -%feature("modula3:enumitem:name","january") MTHB_JANUARY; -%feature("modula3:enumitem:conv","set:int") MTHB_JANUARY; -//%feature("modula3:constset:type","MonthSet") MTHB_JANUARY; /*type in the constant definition*/ -%feature("modula3:constset:set", "MonthSet") MTHB_JANUARY; /*remarks that the 'type' is a set type*/ -%feature("modula3:constset:base","Month") MTHB_JANUARY; -%feature("modula3:constset:name","monthsJanuary") MTHB_JANUARY; -%feature("modula3:constset:conv","set:set") MTHB_JANUARY; /*conversion of the bit pattern: no change*/ - -%feature("modula3:enumitem:enum","Color") BLUE; -%feature("modula3:enumitem:name","blue") BLUE; -%feature("modula3:enumitem:conv","int:int") BLUE; - -%feature("modula3:constint:type","INTEGER") Foo::IMPULSE; -%feature("modula3:constint:name","impulse") Foo::IMPULSE; -%feature("modula3:constint:conv","int:int") Foo::IMPULSE; -#endif - -%rename(pi) PI; - -%pragma(modula3) enumitem="prefix=DAY_;int;srcstyle=underscore;Day"; - -%pragma(modula3) enumitem="enum=color;int;srcstyle=underscore;Color"; -%pragma(modula3) makesetofenum="Color"; -%pragma(modula3) constset="prefix=CLB_;set;srcstyle=underscore,prefix=clb;ColorSet,Color"; - -%pragma(modula3) enumitem="prefix=MTHB_,enum=calendar;set;srcstyle=underscore;Month"; -%pragma(modula3) makesetofenum="Month"; -%pragma(modula3) constset="prefix=MTHB_,enum=calendar;set;srcstyle=underscore,prefix=monthset;MonthSet,Month"; - -%pragma(modula3) constint="prefix=Answer::Foo::,enum=Answer::Foo::speed;int;srcstyle=underscore,prefix=speed;INTEGER"; - -%pragma(modula3) constint="prefix=Answer::,enum=Answer::;int;srcstyle=underscore,prefix=answer;CARDINAL"; - -%rename(AnswerFoo) Answer::Foo; -%typemap("m3rawrettype") Answer::Foo * %{AnswerFoo%} -%typemap("m3rawintype") Answer::Foo * %{AnswerFoo%} -%typemap("m3rawinmode") Answer::Foo * %{%} -%typemap("m3wraprettype") Answer::Foo * %{AnswerFoo%} -%typemap("m3wrapintype") Answer::Foo * %{AnswerFoo%} -%typemap("m3wrapinmode") Answer::Foo * %{%} -%typemap("m3wrapargraw") Answer::Foo * %{self.cxxObj%} - -%typemap("m3wrapretvar") Answer::Foo * %{cxxObj : ExampleRaw.AnswerFoo;%} -%typemap("m3wrapretraw") Answer::Foo * %{cxxObj%} -%typemap("m3wrapretconv") Answer::Foo * %{NEW(AnswerFoo,cxxObj:=cxxObj)%} - - -%typemap("m3rawintype") Answer::Foo::speed %{C.int%}; -%typemap("m3rawintype:import") Answer::Foo::speed %{Ctypes AS C%}; -%typemap("m3wrapintype") Answer::Foo::speed %{[-2..3]%}; - -%typemap("m3wrapintype") color %{Color%}; -%typemap("m3wrapargraw") color %{ORD($1_name)%}; - -/* Let's just grab the original header file here */ -%include "example.h" diff --git a/Examples/modula3/exception/Makefile b/Examples/modula3/exception/Makefile deleted file mode 100644 index 8d12ef19e..000000000 --- a/Examples/modula3/exception/Makefile +++ /dev/null @@ -1,24 +0,0 @@ -TOP = ../.. -SWIGEXE = $(TOP)/../swig -SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib -CXXSRCS = example.cxx -TARGET = example -INTERFACE = example.i -SWIGOPT = -MODULA3SRCS = *.[im]3 -MODULA3FLAGS= -o runme - -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' modula3_cpp -# $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' MODULA3SRCS='$(MODULA3SRCS)' MODULA3FLAGS='$(MODULA3FLAGS)' modula3_compile - m3ppinplace $(MODULA3SRCS) - mv m3makefile $(MODULA3SRCS) src/ - cm3 - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_clean diff --git a/Examples/modula3/exception/example.h b/Examples/modula3/exception/example.h deleted file mode 100644 index 0e9e0e81d..000000000 --- a/Examples/modula3/exception/example.h +++ /dev/null @@ -1,18 +0,0 @@ -/* File : example.h */ - -enum error {OK, OVERFLOW, DIVISION_BY_ZERO, NEGATIVE_RADICAND, NEGATIVE_BASE}; -typedef error errorstate; /* just to separate the typemaps */ - -error acc_add (double &x, double y); -error acc_sub (double &x, double y); -error acc_mul (double &x, double y); -error acc_div (double &x, double y); - -double op_add (double x, double y, errorstate &err); -double op_sub (double x, double y, errorstate &err); -double op_mul (double x, double y, errorstate &err); -double op_div (double x, double y, errorstate &err); -double op_sqrt (double x, errorstate &err); -double op_pow (double x, double y, errorstate &err); - -double op_noexc (double x, double y); diff --git a/Examples/modula3/exception/example.i b/Examples/modula3/exception/example.i deleted file mode 100644 index 92a716fae..000000000 --- a/Examples/modula3/exception/example.i +++ /dev/null @@ -1,43 +0,0 @@ -/* File : example.i */ -%module Example - -%{ -#include "example.h" -%} - -%insert(m3wrapintf) %{ -EXCEPTION E(Error); -%} -%insert(m3wrapimpl) %{ -IMPORT Ctypes AS C; -%} - -%pragma(modula3) enumitem="enum=error;int;srcstyle=underscore;Error"; - -%typemap("m3rawintype") double & %{C.double%}; -%typemap("m3wrapintype") double & %{LONGREAL%}; - -%typemap("m3wraprettype") error "" -%typemap("m3wrapretvar") error "rawerr: C.int;" -%typemap("m3wrapretraw") error "rawerr" -%typemap("m3wrapretcheck:throws") error "E" -%typemap("m3wrapretcheck") error -%{VAR err := VAL(rawerr, Error); -BEGIN -IF err # Error.ok THEN -RAISE E(err); -END; -END;%} - -%typemap("m3rawintype") errorstate & %{C.int%}; -%typemap("m3wrapintype",numinputs=0) errorstate & %{%}; -%typemap("m3wrapargvar") errorstate & %{err:C.int:=ORD(Error.ok);%}; -%typemap("m3wrapoutcheck:throws") errorstate & "E"; -%typemap("m3wrapoutcheck") errorstate & -%{IF VAL(err,Error) # Error.ok THEN -RAISE E(VAL(err,Error)); -END;%} - -/* Let's just grab the original header file here */ - -%include "example.h" diff --git a/Examples/modula3/reference/Makefile b/Examples/modula3/reference/Makefile deleted file mode 100644 index eaceceb1f..000000000 --- a/Examples/modula3/reference/Makefile +++ /dev/null @@ -1,22 +0,0 @@ -TOP = ../.. -SWIGEXE = $(TOP)/../swig -SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib -SRCS = -TARGET = example -INTERFACE = example.i -SWIGOPT = -c++ -MODULA3SRCS = *.[im]3 - -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' modula3 - m3ppinplace $(MODULA3SRCS) - mv m3makefile $(MODULA3SRCS) src/ - cm3 - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_clean diff --git a/Examples/modula3/reference/example.cxx b/Examples/modula3/reference/example.cxx deleted file mode 100644 index 9dbaed2ee..000000000 --- a/Examples/modula3/reference/example.cxx +++ /dev/null @@ -1,46 +0,0 @@ -/* File : example.cxx */ - -/* Deal with Microsoft's attempt at deprecating C standard runtime functions */ -#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) -# define _CRT_SECURE_NO_DEPRECATE -#endif - -#include "example.h" -#include -#include - -Vector operator+(const Vector &a, const Vector &b) { - Vector r; - r.x = a.x + b.x; - r.y = a.y + b.y; - r.z = a.z + b.z; - return r; -} - -char *Vector::print() { - static char temp[512]; - sprintf(temp,"Vector %p (%g,%g,%g)", (void *)this, x,y,z); - return temp; -} - -VectorArray::VectorArray(int size) { - items = new Vector[size]; - maxsize = size; -} - -VectorArray::~VectorArray() { - delete [] items; -} - -Vector &VectorArray::operator[](int index) { - if ((index < 0) || (index >= maxsize)) { - printf("Panic! Array index out of bounds.\n"); - exit(1); - } - return items[index]; -} - -int VectorArray::size() { - return maxsize; -} - diff --git a/Examples/modula3/reference/example.h b/Examples/modula3/reference/example.h deleted file mode 100644 index 7b4ba8fb8..000000000 --- a/Examples/modula3/reference/example.h +++ /dev/null @@ -1,22 +0,0 @@ -/* File : example.h */ - -struct Vector { -private: - double x,y,z; -public: - Vector() : x(0), y(0), z(0) { } - Vector(double x, double y, double z) : x(x), y(y), z(z) { } - Vector operator+(const Vector &b) const; - char *print(); -}; - -struct VectorArray { -private: - Vector *items; - int maxsize; -public: - VectorArray(int maxsize); - ~VectorArray(); - Vector &operator[](int); - int size(); -}; diff --git a/Examples/modula3/reference/example.i b/Examples/modula3/reference/example.i deleted file mode 100644 index 002090918..000000000 --- a/Examples/modula3/reference/example.i +++ /dev/null @@ -1,32 +0,0 @@ -/* File : example.i */ - -/* This file has a few "typical" uses of C++ references. */ - -%module Example - -%{ -#include "example.h" -%} - -%pragma(modula3) unsafe="1"; - -%insert(m3wrapintf) %{FROM ExampleRaw IMPORT Vector, VectorArray;%} -%insert(m3wrapimpl) %{FROM ExampleRaw IMPORT Vector, VectorArray;%} - -%typemap(m3wrapretvar) Vector %{vec: UNTRACED REF Vector;%} -%typemap(m3wrapretraw) Vector %{vec%} -%typemap(m3wrapretconv) Vector %{vec^%} - - -/* This helper function calls an overloaded operator */ -%inline %{ -Vector addv(const Vector &a, const Vector &b) { - return a+b; -} -%} - -%rename(Vector_Clear) Vector::Vector(); -%rename(Add) Vector::operator+; -%rename(GetItem) VectorArray::operator[]; - -%include "example.h" diff --git a/Examples/modula3/simple/Makefile b/Examples/modula3/simple/Makefile deleted file mode 100644 index 3ba35d18b..000000000 --- a/Examples/modula3/simple/Makefile +++ /dev/null @@ -1,22 +0,0 @@ -TOP = ../.. -SWIGEXE = $(TOP)/../swig -SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib -SRCS = -TARGET = example -INTERFACE = example.i -SWIGOPT = -MODULA3SRCS = *.[im]3 - -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' modula3 - m3ppinplace $(MODULA3SRCS) - mv m3makefile $(MODULA3SRCS) src/ - cm3 - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_clean diff --git a/Examples/modula3/simple/example.c b/Examples/modula3/simple/example.c deleted file mode 100644 index 1c2af789c..000000000 --- a/Examples/modula3/simple/example.c +++ /dev/null @@ -1,18 +0,0 @@ -/* File : example.c */ - -/* A global variable */ -double Foo = 3.0; - -/* Compute the greatest common divisor of positive integers */ -int gcd(int x, int y) { - int g; - g = y; - while (x > 0) { - g = x; - x = y % x; - y = g; - } - return g; -} - - diff --git a/Examples/modula3/simple/example.i b/Examples/modula3/simple/example.i deleted file mode 100644 index 1694e6dbe..000000000 --- a/Examples/modula3/simple/example.i +++ /dev/null @@ -1,7 +0,0 @@ -/* File : example.i */ -%module Example - -%inline %{ -extern int gcd(int x, int y); -extern double Foo; -%} diff --git a/Examples/modula3/typemap/Makefile b/Examples/modula3/typemap/Makefile deleted file mode 100644 index 3ba35d18b..000000000 --- a/Examples/modula3/typemap/Makefile +++ /dev/null @@ -1,22 +0,0 @@ -TOP = ../.. -SWIGEXE = $(TOP)/../swig -SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib -SRCS = -TARGET = example -INTERFACE = example.i -SWIGOPT = -MODULA3SRCS = *.[im]3 - -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' modula3 - m3ppinplace $(MODULA3SRCS) - mv m3makefile $(MODULA3SRCS) src/ - cm3 - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_clean diff --git a/Examples/modula3/typemap/example.i b/Examples/modula3/typemap/example.i deleted file mode 100644 index 2f454eff3..000000000 --- a/Examples/modula3/typemap/example.i +++ /dev/null @@ -1,90 +0,0 @@ -/* File : example.i */ -%module Example - -%pragma(modula3) unsafe="true"; - -%insert(m3wrapintf) %{FROM ExampleRaw IMPORT Window, Point; -%} -%insert(m3wrapimpl) %{FROM ExampleRaw IMPORT Window, Point; -IMPORT M3toC; -IMPORT Ctypes AS C; -%} - -/* Typemap applied to patterns of multiple arguments */ - -%typemap(m3rawinmode) (char *outstr) %{VAR%} -%typemap(m3rawintype) (char *outstr) %{CHAR%} -%typemap(m3wrapinmode) (char *outstr, int size) %{VAR%} -%typemap(m3wrapintype) (char *outstr, int size) %{ARRAY OF CHAR%} -%typemap(m3wrapargraw) (char *outstr, int size) %{$1_name[0], NUMBER($1_name)%} - - -%typemap(m3rawinmode) (const struct Window *) %{READONLY%} -%typemap(m3wrapinmode) (const struct Window *) %{READONLY%} -%typemap(m3rawintype) ( struct Window *) %{Window%} -%typemap(m3wrapintype) ( struct Window *) %{Window%} - -%typemap(m3rawinmode) (const char *str []) %{READONLY%} -%typemap(m3wrapinmode) (const char *str []) %{READONLY%} -%typemap(m3rawintype) (const char *str []) %{(*ARRAY OF*) C.char_star%} -%typemap(m3wrapintype) (const char *str []) %{ARRAY OF TEXT%} -%typemap(m3wrapargvar) (const char *str []) %{$1: REF ARRAY OF C.char_star;%} -%typemap(m3wrapargraw) (const char *str []) %{$1[0]%} -%typemap(m3wrapinconv) (const char *str []) %{$1:= NEW(REF ARRAY OF C.char_star,NUMBER($1_name)); -FOR i:=FIRST($1_name) TO LAST($1_name) DO -$1[i]:=M3toC.SharedTtoS($1_name[i]); -END;%} -%typemap(m3wrapfreearg) (const char *str []) -%{FOR i:=FIRST($1_name) TO LAST($1_name) DO -M3toC.FreeSharedS($1_name[i],$1[i]); -END;%} - -%typemap(m3wraprettype) char * %{TEXT%} -%typemap(m3wrapretvar) char * %{result_string: C.char_star;%} -%typemap(m3wrapretraw) char * %{result_string%} -%typemap(m3wrapretconv) char * %{M3toC.CopyStoT(result_string)%} - -struct Window { - char *label; - int left,top,width,height; -}; - - -%typemap(m3wrapinname) (int x, int y) %{p%} -%typemap(m3wrapinmode) (int x, int y) %{READONLY%} -%typemap(m3wrapintype) (int x, int y) %{Point%} -%typemap(m3wrapargraw) (int x, int y) %{p.$1_name, p.$2_name%} - -%typemap(m3wrapargraw) (int &x, int &y) %{p.$1_name, p.$2_name%} -%typemap(m3wrapintype) (int &x, int &y) %{Point%} -%typemap(m3wrapoutname) (int &x, int &y) %{p%} -%typemap(m3wrapouttype) (int &x, int &y) %{Point%} -%typemap(m3wrapargdir) (int &x, int &y) "out" - - -%typemap(m3wrapargvar) int &left, int &top, int &width, int &height "$1:C.int;" -%typemap(m3wrapargraw) int &left, int &top, int &width, int &height "$1" -%typemap(m3wrapoutconv) int &left, int &top, int &width, int &height "$1" - -%typemap(m3wrapargdir) int &left, int &top "out" - -%typemap(m3wrapouttype) int &width, int &height "CARDINAL" -%typemap(m3wrapargdir) int &width, int &height "out" - -struct Point { - int x,y; -}; - -%m3multiretval get_box; - -void set_label ( struct Window *win, const char *str, bool activate); -void set_multi_label ( struct Window *win, const char *str []); -void write_label (const struct Window *win, char *outstr, int size); -int get_label (const struct Window *win, char *outstr, int size); -char *get_label_ptr (const struct Window *win); -void move(struct Window *win, int x, int y); -int get_area(const struct Window *win); -void get_box(const struct Window *win, int &left, int &top, int &width, int &height); -void get_left(const struct Window *win, int &left); -void get_mouse(const struct Window *win, int &x, int &y); -int get_attached_data(const struct Window *win, const char *id); diff --git a/Examples/ocaml/shapes/example.i b/Examples/ocaml/shapes/example.i index ac0fa4a56..a261b92e7 100644 --- a/Examples/ocaml/shapes/example.i +++ b/Examples/ocaml/shapes/example.i @@ -1,10 +1,8 @@ /* File : example.i */ %module(directors="1") example -#ifndef SWIGSEXP %{ #include "example.h" %} -#endif %feature("director"); %include "example.h" diff --git a/Examples/octave/check.list b/Examples/octave/check.list index e9c719231..54a591042 100644 --- a/Examples/octave/check.list +++ b/Examples/octave/check.list @@ -8,8 +8,8 @@ extend funcptr funcptr2 functor -operator module_load +operator pointer reference simple diff --git a/Examples/octave/module_load/runme.m b/Examples/octave/module_load/runme.m index beab1213b..4e52c6ee0 100644 --- a/Examples/octave/module_load/runme.m +++ b/Examples/octave/module_load/runme.m @@ -19,7 +19,8 @@ clear all # load module in a function globally before base context clear all; function testme_1 - assert(exist("swigexample") == 3); + % exist("swigexample") returns 1 (variable) in octave >= 4.4 < 6 but 3 (.oct file) in octave >= 6 + assert(exist("swigexample")); swigexample; assert(isglobal("swigexample")); assert(cvar.ivar == ifunc); @@ -32,7 +33,8 @@ assert(isglobal("swigexample")); assert(cvar.ivar == ifunc); clear all function testme_2 - assert(exist("swigexample") == 3); + % exist("swigexample") returns 1 (variable) in octave >= 4.4 < 6 but 3 (.oct file) in octave >= 6 + assert(exist("swigexample")); swigexample; assert(isglobal("swigexample")); assert(cvar.ivar == ifunc); @@ -52,7 +54,8 @@ swigexample; assert(isglobal("swigexample")); assert(cvar.ivar == ifunc); function testme_3 - assert(exist("swigexample") == 3); + % exist("swigexample") returns 1 (variable) in octave >= 4.4 < 6 but 3 (.oct file) in octave >= 6 + assert(exist("swigexample")); swigexample; assert(isglobal("swigexample")); assert(cvar.ivar == ifunc); @@ -65,7 +68,8 @@ swigexample; assert(isglobal("swigexample")); assert(cvar.ivar == ifunc); function testme_4 - assert(exist("swigexample") == 3); + % exist("swigexample") returns 1 (variable) in octave >= 4.4 < 6 but 3 (.oct file) in octave >= 6 + assert(exist("swigexample")); swigexample; assert(isglobal("swigexample")); assert(cvar.ivar == ifunc); diff --git a/Examples/octave/operator/@swig_ref/horzcat.m b/Examples/octave/operator/@swig_ref/horzcat.m new file mode 100644 index 000000000..00fdfd5ce --- /dev/null +++ b/Examples/octave/operator/@swig_ref/horzcat.m @@ -0,0 +1,6 @@ +% test octaves concatenation operator +function ret=horzcat(a, b) + % return the concatenation of two ComplexVal values as a cell array. + % (not really useful but it tests the concatenation of swig_ref objects) + ret={a, b}; +end diff --git a/Examples/octave/operator/runme.m b/Examples/octave/operator/runme.m index e17494a84..d88dcff0b 100644 --- a/Examples/octave/operator/runme.m +++ b/Examples/octave/operator/runme.m @@ -3,6 +3,9 @@ if exist("crash_dumps_octave_core", "builtin") crash_dumps_octave_core(0); endif +scriptDir = fileparts(mfilename('fullpath')); +addpath(scriptDir); + # Operator overloading example swigexample @@ -42,3 +45,7 @@ if swig_octave_prereq(3,8,0) printf("conj(a) = %s\n", disp(conj(a))); printf("exp(a) = %s\n", disp(exp(a))); endif + +# concatenation operator +g = [a, b, c]; +printf("g = %s\n",disp(g)); diff --git a/Examples/php/callback/runme.php b/Examples/php/callback/runme.php index 2be71994f..e7093209c 100644 --- a/Examples/php/callback/runme.php +++ b/Examples/php/callback/runme.php @@ -2,8 +2,6 @@ # This file illustrates the cross language polymorphism using directors. -require("example.php"); - # Class, which overwrites Callback::run(). class PhpCallback extends Callback { @@ -43,5 +41,3 @@ $caller->delCallback(); # All done. print "php exit\n"; - -?> diff --git a/Examples/php/class/runme.php b/Examples/php/class/runme.php index 99c253b46..0f667695b 100644 --- a/Examples/php/class/runme.php +++ b/Examples/php/class/runme.php @@ -2,8 +2,6 @@ # This example illustrates how member variables are wrapped. -require("example.php"); - # ----- Object creation ----- print "Creating some objects:\n"; @@ -56,5 +54,3 @@ $o = NULL; print Shape::nshapes() . " shapes remain\n"; print "Goodbye\n"; - -?> diff --git a/Examples/php/constants/runme.php b/Examples/php/constants/runme.php index 91c597a40..e561626d8 100644 --- a/Examples/php/constants/runme.php +++ b/Examples/php/constants/runme.php @@ -1,7 +1,5 @@ diff --git a/Examples/php/cpointer/runme.php b/Examples/php/cpointer/runme.php index 22e8a681a..f552ed78a 100644 --- a/Examples/php/cpointer/runme.php +++ b/Examples/php/cpointer/runme.php @@ -1,7 +1,5 @@ diff --git a/Examples/php/disown/example.cxx b/Examples/php/disown/example.cxx index 6393735e9..247eb6a27 100644 --- a/Examples/php/disown/example.cxx +++ b/Examples/php/disown/example.cxx @@ -39,7 +39,6 @@ double Square::perimeter(void) { } ShapeContainer::~ShapeContainer() { - iterator i=shapes.begin(); for( iterator i = shapes.begin(); i != shapes.end(); ++i ) { delete *i; } diff --git a/Examples/php/disown/runme.php b/Examples/php/disown/runme.php index a70d7b061..e847dc71d 100644 --- a/Examples/php/disown/runme.php +++ b/Examples/php/disown/runme.php @@ -4,8 +4,6 @@ # created by SWIG. In this case, all of our C++ classes # get converted into function calls. -require("example.php"); - # ----- Object creation ----- print "Creating some objects:\n"; @@ -45,5 +43,3 @@ $container = NULL; print "\nA total of " . Shape::nshapes() . " shapes remain\n"; print "Goodbye\n"; - -?> diff --git a/Examples/php/enum/runme.php b/Examples/php/enum/runme.php index 813476645..bf5ba881f 100644 --- a/Examples/php/enum/runme.php +++ b/Examples/php/enum/runme.php @@ -1,7 +1,5 @@ enum_test(Foo::IMPULSE); $f->enum_test(Foo::WARP); $f->enum_test(Foo::LUDICROUS); - -?> diff --git a/Examples/php/extend/runme.php b/Examples/php/extend/runme.php index 158683142..93eedee99 100644 --- a/Examples/php/extend/runme.php +++ b/Examples/php/extend/runme.php @@ -2,8 +2,6 @@ # This file illustrates the cross language polymorphism using directors. -require("example.php"); - # CEO class, which overrides Employee::getPosition(). class CEO extends Manager { @@ -72,5 +70,3 @@ print "----------------------\n"; # All done. print "php exit\n"; - -?> diff --git a/Examples/php/funcptr/runme.php b/Examples/php/funcptr/runme.php index 712d4147c..d76a19bc7 100644 --- a/Examples/php/funcptr/runme.php +++ b/Examples/php/funcptr/runme.php @@ -1,7 +1,5 @@ - +print " ADD = " . example::ADD . "\n"; +print " SUB = " . example::SUB . "\n"; +print " MUL = " . example::MUL . "\n"; diff --git a/Examples/php/overloading/runme.php b/Examples/php/overloading/runme.php index 56d515138..d4df899f0 100644 --- a/Examples/php/overloading/runme.php +++ b/Examples/php/overloading/runme.php @@ -4,8 +4,6 @@ # created by SWIG. In this case, all of our C++ classes # get converted into function calls. -include("example.php"); - # ----- Object creation ----- print "Creating some objects:\n"; @@ -54,5 +52,3 @@ $s = 42; print Shape::nshapes() . " shapes remain\n"; print "Goodbye\n"; - -?> diff --git a/Examples/php/pointer/example.i b/Examples/php/pointer/example.i index 1f0059406..31d2a03e0 100644 --- a/Examples/php/pointer/example.i +++ b/Examples/php/pointer/example.i @@ -21,10 +21,5 @@ extern void sub(int *INPUT, int *INPUT, int *OUTPUT); /* Next we'll use typemaps and the %apply directive */ -//%apply int *OUTPUT { int *r }; -//extern int divide(int n, int d, int *r); - - - - - +%apply int *OUTPUT { int *r }; +extern int divide(int n, int d, int *r); diff --git a/Examples/php/pointer/runme.php b/Examples/php/pointer/runme.php index e79b23810..8dc3ab887 100644 --- a/Examples/php/pointer/runme.php +++ b/Examples/php/pointer/runme.php @@ -1,7 +1,5 @@ + print "Testing multiple return values\n"; + $a = divide(42,37); + $q = $a[0]; + $r = $a[1]; + print " 42/37 = $q remainder $r\n"; diff --git a/Examples/php/pragmas/include.php b/Examples/php/pragmas/include.php index 11d985d66..442f8e2e0 100644 --- a/Examples/php/pragmas/include.php +++ b/Examples/php/pragmas/include.php @@ -2,6 +2,3 @@ # This code is inserted into example.php echo "This is include.php\n"; - - -?> diff --git a/Examples/php/pragmas/runme.php b/Examples/php/pragmas/runme.php index 7b2c179cb..e2b276313 100644 --- a/Examples/php/pragmas/runme.php +++ b/Examples/php/pragmas/runme.php @@ -6,4 +6,3 @@ set_include_path(realpath(dirname(__FILE__)) . PATH_SEPARATOR . get_include_path require "example.php"; echo "Version - " . ((new ReflectionExtension('example'))->getVersion()) . "\n"; -?> diff --git a/Examples/php/proxy/runme.php b/Examples/php/proxy/runme.php index e70ab229f..0f156b6ad 100644 --- a/Examples/php/proxy/runme.php +++ b/Examples/php/proxy/runme.php @@ -4,8 +4,6 @@ # created by SWIG. In this case, all of our C++ classes # get converted into function calls. -include("example.php"); - # ----- Object creation ----- print "Creating some objects:\n"; @@ -64,5 +62,3 @@ Shape::nshapes(42); print Shape::get_nshapes() ." == 42\n"; print "Goodbye\n"; - -?> diff --git a/Examples/php/reference/runme.php b/Examples/php/reference/runme.php index 5d264ee43..5c7fc9a88 100644 --- a/Examples/php/reference/runme.php +++ b/Examples/php/reference/runme.php @@ -2,8 +2,6 @@ # This file illustrates the manipulation of C++ references in PHP. -require "example.php"; - # ----- Object creation ----- print "Creating some objects:\n"; @@ -45,5 +43,3 @@ print "Getting some array values\n"; for ($i = 0; $i < 5; $i++) { print " va[$i] = {$va->get($i)->as_string()}\n"; } - -?> diff --git a/Examples/php/simple/runme.php b/Examples/php/simple/runme.php index 0e96fe800..2795f32a0 100644 --- a/Examples/php/simple/runme.php +++ b/Examples/php/simple/runme.php @@ -1,7 +1,5 @@ diff --git a/Examples/php/sync/example.cxx b/Examples/php/sync/example.cxx index 0942279b2..2001a5b4e 100644 --- a/Examples/php/sync/example.cxx +++ b/Examples/php/sync/example.cxx @@ -1,13 +1,19 @@ #include "example.h" -#include +#include int x = 42; -char *s = (char *)"Test"; +std::string s = "Test"; -void Sync::printer(void) { - - printf("The value of global s is %s\n", s); - printf("The value of global x is %d\n", x); - printf("The value of class s is %s\n", s); - printf("The value of class x is %d\n", x); +void Sync::printer() { + std::cout << "The value of global s is " << ::s << '\n'; + std::cout << "The value of global x is " << ::x << '\n'; + std::cout << "The value of class s is " << this->s << '\n'; + std::cout << "The value of class x is " << this->x << '\n'; +} + +void Sync::all_change() { + ::s = "global change"; + ++::x; + this->s = "local change"; + ++this->x; } diff --git a/Examples/php/sync/example.h b/Examples/php/sync/example.h index d67ec21dc..381473f2e 100644 --- a/Examples/php/sync/example.h +++ b/Examples/php/sync/example.h @@ -1,9 +1,14 @@ -extern char *s; +#include + +extern std::string s; extern int x; class Sync { - public: - int x; - char *s; - void printer(void); + public: + int x; + std::string s; + void printer(); + void all_change(); + + Sync() : x(0) { } }; diff --git a/Examples/php/sync/example.i b/Examples/php/sync/example.i index 17ff87cf3..bc10e0fb7 100644 --- a/Examples/php/sync/example.i +++ b/Examples/php/sync/example.i @@ -1,5 +1,7 @@ %module example +%include + %{ #include "example.h" %} diff --git a/Examples/php/sync/runme.php b/Examples/php/sync/runme.php index a7c43474f..f01a9b3f6 100644 --- a/Examples/php/sync/runme.php +++ b/Examples/php/sync/runme.php @@ -1,15 +1,29 @@ printer(); +echo "PHP reading object: string is '", $o->s, "' and value is ", $o->x, "\n"; -?> +$o->printer(); +example::s_set("global string"); +example::x_set(42); + +$o->s = "object string"; +$o->x = 1234; + +echo "PHP reading globals: string is '", example::s_get(), "' and int is ", example::x_get(), "\n"; +echo "PHP reading object: string is '", $o->s, "' and int is ", $o->x, "\n"; + +$o->printer(); + +echo "Calling all_change() method\n"; +$o->all_change(); + +echo "PHP reading globals: string is '", example::s_get(), "' and int is ", example::x_get(), "\n"; +echo "PHP reading object: string is '", $o->s, "' and int is ", $o->x, "\n"; + +$o->printer(); diff --git a/Examples/php/value/runme.php b/Examples/php/value/runme.php index 569c87cf5..754f94233 100644 --- a/Examples/php/value/runme.php +++ b/Examples/php/value/runme.php @@ -1,8 +1,5 @@ x = 1.0; $v->y = 2.0; @@ -34,10 +31,6 @@ echo "\nNow I'm going to clean up the return result\n"; -# free($r); + unset($r); echo "Good\n"; - -?> - - diff --git a/Examples/php/variables/runme.php b/Examples/php/variables/runme.php index 14f27f389..a14fede72 100644 --- a/Examples/php/variables/runme.php +++ b/Examples/php/variables/runme.php @@ -1,6 +1,5 @@ - diff --git a/Examples/pike/check.list b/Examples/pike/check.list deleted file mode 100644 index d6c8e2e7b..000000000 --- a/Examples/pike/check.list +++ /dev/null @@ -1,7 +0,0 @@ -# see top-level Makefile.in -class -constants -enum -overload -simple -template diff --git a/Examples/pike/class/Makefile b/Examples/pike/class/Makefile deleted file mode 100644 index e5319dbe2..000000000 --- a/Examples/pike/class/Makefile +++ /dev/null @@ -1,23 +0,0 @@ -TOP = ../.. -SWIGEXE = $(TOP)/../swig -SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib -CXXSRCS = example.cxx -TARGET = example -INTERFACE = example.i -LIBS = -lm - -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike_cpp - -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - TARGET='mypike' INTERFACE='$(INTERFACE)' pike_cpp_static - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_clean diff --git a/Examples/pike/class/example.cxx b/Examples/pike/class/example.cxx deleted file mode 100644 index 046304519..000000000 --- a/Examples/pike/class/example.cxx +++ /dev/null @@ -1,28 +0,0 @@ -/* File : example.cxx */ - -#include "example.h" -#define M_PI 3.14159265358979323846 - -/* Move the shape to a new location */ -void Shape::move(double dx, double dy) { - x += dx; - y += dy; -} - -int Shape::nshapes = 0; - -double Circle::area() { - return M_PI*radius*radius; -} - -double Circle::perimeter() { - return 2*M_PI*radius; -} - -double Square::area() { - return width*width; -} - -double Square::perimeter() { - return 4*width; -} diff --git a/Examples/pike/class/example.h b/Examples/pike/class/example.h deleted file mode 100644 index 0dff185b2..000000000 --- a/Examples/pike/class/example.h +++ /dev/null @@ -1,34 +0,0 @@ -/* File : example.h */ - -class Shape { -public: - Shape() { - nshapes++; - } - virtual ~Shape() { - nshapes--; - } - double x, y; - void move(double dx, double dy); - virtual double area() = 0; - virtual double perimeter() = 0; - static int nshapes; -}; - -class Circle : public Shape { -private: - double radius; -public: - Circle(double r) : radius(r) { } - virtual double area(); - virtual double perimeter(); -}; - -class Square : public Shape { -private: - double width; -public: - Square(double w) : width(w) { } - virtual double area(); - virtual double perimeter(); -}; diff --git a/Examples/pike/class/example.i b/Examples/pike/class/example.i deleted file mode 100644 index fbdf7249f..000000000 --- a/Examples/pike/class/example.i +++ /dev/null @@ -1,9 +0,0 @@ -/* File : example.i */ -%module example - -%{ -#include "example.h" -%} - -/* Let's just grab the original header file here */ -%include "example.h" diff --git a/Examples/pike/class/runme.pike b/Examples/pike/class/runme.pike deleted file mode 100644 index a6377600e..000000000 --- a/Examples/pike/class/runme.pike +++ /dev/null @@ -1,53 +0,0 @@ -import .example; - -int main() -{ - // ----- Object creation ----- - - write("Creating some objects:\n"); - Circle c = Circle(10.0); - write(" Created circle.\n"); - Square s = Square(10.0); - write(" Created square.\n"); - - // ----- Access a static member ----- - - write("\nA total of " + Shape_nshapes_get() + " shapes were created\n"); - - // ----- Member data access ----- - - // Set the location of the object - - c->x_set(20.0); - c->y_set(30.0); - - s->x_set(-10.0); - s->y_set(5.0); - - write("\nHere is their current position:\n"); - write(" Circle = (%f, %f)\n", c->x_get(), c->y_get()); - write(" Square = (%f, %f)\n", s->x_get(), s->y_get()); - - // ----- Call some methods ----- - - write("\nHere are some properties of the shapes:\n"); - write(" The circle:\n"); - write(" area = %f.\n", c->area()); - write(" perimeter = %f.\n", c->perimeter()); - write(" The square:\n"); - write(" area = %f.\n", s->area()); - write(" perimeter = %f.\n", s->perimeter()); - - write("\nGuess I'll clean up now\n"); - - /* See if we can force 's' to be garbage-collected */ - s = 0; - - /* Now we should be down to only 1 shape */ - write("%d shapes remain\n", Shape_nshapes_get()); - - /* Done */ - write("Goodbye\n"); - - return 0; -} diff --git a/Examples/pike/constants/Makefile b/Examples/pike/constants/Makefile deleted file mode 100644 index 45da7d269..000000000 --- a/Examples/pike/constants/Makefile +++ /dev/null @@ -1,22 +0,0 @@ -TOP = ../.. -SWIGEXE = $(TOP)/../swig -SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib -SRCS = -TARGET = example -INTERFACE = example.i - -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike - -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - TARGET='mypike' INTERFACE='$(INTERFACE)' pike_static - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_clean diff --git a/Examples/pike/constants/example.i b/Examples/pike/constants/example.i deleted file mode 100644 index 4f7b1a4d7..000000000 --- a/Examples/pike/constants/example.i +++ /dev/null @@ -1,27 +0,0 @@ -/* File : example.i */ -%module example - -/* A few preprocessor macros */ - -#define ICONST 42 -#define FCONST 2.1828 -#define CCONST 'x' -#define CCONST2 '\n' -#define SCONST "Hello World" -#define SCONST2 "\"Hello World\"" - -/* This should work just fine */ -#define EXPR ICONST + 3*(FCONST) - -/* This shouldn't do anything */ -#define EXTERN extern - -/* Neither should this (BAR isn't defined) */ -#define FOO (ICONST + BAR) - -/* The following directives also produce constants */ - -%constant int iconst = 37; -%constant double fconst = 3.14; - - diff --git a/Examples/pike/constants/runme.pike b/Examples/pike/constants/runme.pike deleted file mode 100644 index a8d9f944f..000000000 --- a/Examples/pike/constants/runme.pike +++ /dev/null @@ -1,24 +0,0 @@ -int main() -{ - write("ICONST = %d (should be 42)\n", .example.ICONST); - write("FCONST = %f (should be 2.1828)\n", .example.FCONST); - write("CCONST = %c (should be 'x')\n", .example.CCONST); - write("CCONST2 = %c (this should be on a new line)\n", .example.CCONST2); - write("SCONST = %s (should be 'Hello World')\n", .example.SCONST); - write("SCONST2 = %s (should be '\"Hello World\"')\n", .example.SCONST2); - write("EXPR = %f (should be 48.5484)\n", .example.EXPR); - write("iconst = %d (should be 37)\n", .example.iconst); - write("fconst = %f (should be 3.14)\n", .example.fconst); - - if (search(indices(.example), "EXTERN") == -1) - write("EXTERN isn't defined (good)\n"); - else - write("EXTERN is defined (bad)\n"); - - if (search(indices(.example), "FOO") == -1) - write("FOO isn't defined (good)\n"); - else - write("FOO is defined (bad)\n"); - - return 0; -} diff --git a/Examples/pike/enum/Makefile b/Examples/pike/enum/Makefile deleted file mode 100644 index e5319dbe2..000000000 --- a/Examples/pike/enum/Makefile +++ /dev/null @@ -1,23 +0,0 @@ -TOP = ../.. -SWIGEXE = $(TOP)/../swig -SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib -CXXSRCS = example.cxx -TARGET = example -INTERFACE = example.i -LIBS = -lm - -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike_cpp - -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - TARGET='mypike' INTERFACE='$(INTERFACE)' pike_cpp_static - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_clean diff --git a/Examples/pike/enum/README b/Examples/pike/enum/README deleted file mode 100644 index 055aa9fce..000000000 --- a/Examples/pike/enum/README +++ /dev/null @@ -1,13 +0,0 @@ -This example will not compile with Pike versions 7.4.20 unless you first -patch the Pike sources. The problem is for line 91 of Pike's "stralloc.h" -(usually installed as /usr/local/pike/7.4.10/include/pike/stralloc.h). That -line reads: - - tmp.ptr=ptr; - -but should be patched to read: - - tmp.ptr=(p_wchar0 *) ptr; - -This bug has been reported to the Pike developers. - diff --git a/Examples/pike/enum/example.cxx b/Examples/pike/enum/example.cxx deleted file mode 100644 index 6785e57ac..000000000 --- a/Examples/pike/enum/example.cxx +++ /dev/null @@ -1,37 +0,0 @@ -/* File : example.c */ - -#include "example.h" -#include - -void Foo::enum_test(speed s) { - if (s == IMPULSE) { - printf("IMPULSE speed\n"); - } else if (s == WARP) { - printf("WARP speed\n"); - } else if (s == LUDICROUS) { - printf("LUDICROUS speed\n"); - } else { - printf("Unknown speed\n"); - } -} - -void enum_test(color c, Foo::speed s) { - if (c == RED) { - printf("color = RED, "); - } else if (c == BLUE) { - printf("color = BLUE, "); - } else if (c == GREEN) { - printf("color = GREEN, "); - } else { - printf("color = Unknown color!, "); - } - if (s == Foo::IMPULSE) { - printf("speed = IMPULSE speed\n"); - } else if (s == Foo::WARP) { - printf("speed = WARP speed\n"); - } else if (s == Foo::LUDICROUS) { - printf("speed = LUDICROUS speed\n"); - } else { - printf("speed = Unknown speed!\n"); - } -} diff --git a/Examples/pike/enum/example.h b/Examples/pike/enum/example.h deleted file mode 100644 index 525d62afc..000000000 --- a/Examples/pike/enum/example.h +++ /dev/null @@ -1,13 +0,0 @@ -/* File : example.h */ - -enum color { RED, BLUE, GREEN }; - -class Foo { - public: - Foo() { } - enum speed { IMPULSE, WARP, LUDICROUS }; - void enum_test(speed s); -}; - -void enum_test(color c, Foo::speed s); - diff --git a/Examples/pike/enum/example.i b/Examples/pike/enum/example.i deleted file mode 100644 index 23ee8a822..000000000 --- a/Examples/pike/enum/example.i +++ /dev/null @@ -1,11 +0,0 @@ -/* File : example.i */ -%module example - -%{ -#include "example.h" -%} - -/* Let's just grab the original header file here */ - -%include "example.h" - diff --git a/Examples/pike/enum/runme.pike b/Examples/pike/enum/runme.pike deleted file mode 100644 index 4846356b3..000000000 --- a/Examples/pike/enum/runme.pike +++ /dev/null @@ -1,28 +0,0 @@ -int main() -{ - write("*** color ***\n"); - write(" RED = " + .example.RED + "\n"); - write(" BLUE = " + .example.BLUE + "\n"); - write(" GREEN = " + .example.GREEN + "\n"); - - write("\n*** Foo::speed ***\n"); - write(" Foo_IMPULSE = " + .example.Foo.IMPULSE + "\n"); - write(" Foo_WARP = " + .example.Foo.WARP + "\n"); - write(" Foo_LUDICROUS = " + .example.Foo.LUDICROUS + "\n"); - - write("\nTesting use of enums with functions\n\n"); - - .example.enum_test(.example.RED, .example.Foo.IMPULSE); - .example.enum_test(.example.BLUE, .example.Foo.WARP); - .example.enum_test(.example.GREEN, .example.Foo.LUDICROUS); - .example.enum_test(1234, 5678); - - write("\nTesting use of enum with class method\n"); - .example.Foo f = .example.Foo(); - - f->enum_test(.example.Foo.IMPULSE); - f->enum_test(.example.Foo.WARP); - f->enum_test(.example.Foo.LUDICROUS); - - return 0; -} diff --git a/Examples/pike/overload/Makefile b/Examples/pike/overload/Makefile deleted file mode 100644 index 5e5fe669b..000000000 --- a/Examples/pike/overload/Makefile +++ /dev/null @@ -1,23 +0,0 @@ -TOP = ../.. -SWIGEXE = $(TOP)/../swig -SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib -CXXSRCS = example.cxx -TARGET = example -INTERFACE = example.i -LIBS = -lstdc++ -lm - -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike_cpp - -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - TARGET='mypike' INTERFACE='$(INTERFACE)' pike_cpp_static - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_clean diff --git a/Examples/pike/overload/example.cxx b/Examples/pike/overload/example.cxx deleted file mode 100644 index 3760fdd49..000000000 --- a/Examples/pike/overload/example.cxx +++ /dev/null @@ -1,115 +0,0 @@ -#include - -#include "example.h" - -// Overloaded constructors for class Bar -Bar::Bar() { - std::cout << "Called Bar::Bar()" << std::endl; -} - -Bar::Bar(const Bar&) { - std::cout << "Called Bar::Bar(const Bar&)" << std::endl; -} - -Bar::Bar(double x) { - std::cout << "Called Bar::Bar(double) with x = " << x << std::endl; -} - -Bar::Bar(double x, char *y) { - std::cout << "Called Bar::Bar(double, char *) with x, y = " << x << ", \"" << y << "\"" << std::endl; -} - -Bar::Bar(int x, int y) { - std::cout << "Called Bar::Bar(int, int) with x, y = " << x << ", " << y << std::endl; -} - -Bar::Bar(char *x) { - std::cout << "Called Bar::Bar(char *) with x = \"" << x << "\"" << std::endl; -} - -Bar::Bar(int x) { - std::cout << "Called Bar::Bar(int) with x = " << x << std::endl; -} - -Bar::Bar(long x) { - std::cout << "Called Bar::Bar(long) with x = " << x << std::endl; -} - -Bar::Bar(Bar *x) { - std::cout << "Called Bar::Bar(Bar *) with x = " << x << std::endl; -} - -// Overloaded member functions -void Bar::foo(const Bar& x) { - std::cout << "Called Bar::foo(const Bar&) with &x = " << &x << std::endl; -} - -void Bar::foo(double x) { - std::cout << "Called Bar::foo(double) with x = " << x << std::endl; -} - -void Bar::foo(double x, char *y) { - std::cout << "Called Bar::foo(double, char *) with x, y = " << x << ", \"" << y << "\"" << std::endl; -} - -void Bar::foo(int x, int y) { - std::cout << "Called Bar::foo(int, int) with x, y = " << x << ", " << y << std::endl; -} - -void Bar::foo(char *x) { - std::cout << "Called Bar::foo(char *) with x = \"" << x << "\"" << std::endl; -} - -void Bar::foo(int x) { - std::cout << "Called Bar::foo(int) with x = " << x << std::endl; -} - -void Bar::foo(long x) { - std::cout << "Called Bar::foo(long) with x = " << x << std::endl; -} - -void Bar::foo(Bar *x) { - std::cout << "Called Bar::foo(Bar *) with x = " << x << std::endl; -} - -void Bar::spam(int x, int y, int z) { - std::cout << "Called Bar::spam(int, int, int) with x, y, z = " << x << ", " << y << ", " << z << std::endl; -} - -void Bar::spam(double x, int y, int z) { - std::cout << "Called Bar::spam(double, int, int) with x, y, z = " << x << ", " << y << ", " << z << std::endl; -} - -// Overloaded global methods -void foo(const Bar& x) { - std::cout << "Called foo(const Bar& x) with &x = " << &x << std::endl; -} - -void foo(double x) { - std::cout << "Called foo(double) with x = " << x << std::endl; -} - -void foo(double x, char *y) { - std::cout << "Called foo(double, char *) with x, y = " << x << ", \"" << y << "\"" << std::endl; -} - -void foo(int x, int y) { - std::cout << "Called foo(int, int) with x, y = " << x << ", " << y << std::endl; -} - -void foo(char *x) { - std::cout << "Called foo(char *) with x = \"" << x << "\"" << std::endl; -} - -void foo(int x) { - std::cout << "Called foo(int) with x = " << x << std::endl; -} - -void foo(long x) { - std::cout << "Called foo(long) with x = " << x << std::endl; -} - -void foo(Bar *x) { - std::cout << "Called foo(Bar *) with x = " << x << std::endl; -} - diff --git a/Examples/pike/overload/example.h b/Examples/pike/overload/example.h deleted file mode 100644 index e47a122ee..000000000 --- a/Examples/pike/overload/example.h +++ /dev/null @@ -1,41 +0,0 @@ -#ifndef EXAMPLE_H -#define EXAMPLE_H - -class Bar { -public: - Bar(); - Bar(const Bar&); - Bar(double); - Bar(double, char *); - Bar(int, int); - Bar(char *); - Bar(long); - Bar(int); - Bar(Bar *); - - void foo(const Bar&); - void foo(double); - void foo(double, char *); - void foo(int, int); - void foo(char *); - void foo(long); - void foo(int); - void foo(Bar *); - - void spam(int x, int y=2, int z=3); - void spam(double x, int y=2, int z=3); -}; - -void foo(const Bar&); -void foo(double); -void foo(double, char *); -void foo(int, int); -void foo(char *); -void foo(int); -void foo(long); -void foo(Bar *); - -void spam(int x, int y=2, int z=3); -void spam(double x, int y=2, int z=3); - -#endif diff --git a/Examples/pike/overload/example.i b/Examples/pike/overload/example.i deleted file mode 100644 index ddcd006be..000000000 --- a/Examples/pike/overload/example.i +++ /dev/null @@ -1,28 +0,0 @@ -/* File : example.i */ -%module example - -%{ -#include "example.h" -%} - -/** - * These overloaded declarations conflict with other overloads (as far as - * SWIG's Ruby module's implementation for overloaded methods is concerned). - * One option is use the %rename directive to rename the conflicting methods; - * here, we're just using %ignore to avoid wrapping some of the overloaded - * functions altogether. - */ - -%ignore Bar; - -%ignore Bar::Bar(Bar *); -%ignore Bar::Bar(long); - -%ignore Bar::foo(const Bar&); -%ignore Bar::foo(long); - -%ignore ::foo(const Bar&); -%ignore ::foo(int); - -/* Let's just grab the original header file here */ -%include "example.h" diff --git a/Examples/pike/overload/runme.pike b/Examples/pike/overload/runme.pike deleted file mode 100644 index d30e947b3..000000000 --- a/Examples/pike/overload/runme.pike +++ /dev/null @@ -1,83 +0,0 @@ -// import .example; - -int main() -{ - // This should invoke foo(double) - .example.foo(3.14159); - - // This should invoke foo(double, char *) - .example.foo(3.14159, "Pi"); - - // This should invoke foo(int, int) - .example.foo(3, 4); - - // This should invoke foo(char *) - .example.foo("This is a test"); - - // This should invoke foo(long) - .example.foo(42); - - /* - // This should invoke Bar::Bar() followed by foo(Bar *) - foo(Bar.new); - - // Skip a line - write("\n"); - - // This should invoke Bar::Bar(double) - Bar.new(3.14159); - - // This should invoke Bar::Bar(double, char *) - Bar.new(3.14159, "Pi"); - - // This should invoke Bar::Bar(int, int) - Bar.new(3, 4); - - // This should invoke Bar::Bar(char *) - Bar.new("This is a test"); - - // This should invoke Bar::Bar(int) - Bar.new(42); - - // This should invoke Bar::Bar() for the input argument, - // followed by Bar::Bar(const Bar&). - Bar.new(Bar.new); - - // Skip a line - write("\n"); - */ - - // Construct a new Bar instance (invokes Bar::Bar()) - /* - bar = Bar.new; - - // This should invoke Bar::foo(double) - bar.foo(3.14159); - - // This should invoke Bar::foo(double, char *) - bar.foo(3.14159, "Pi"); - - // This should invoke Bar::foo(int, int) - bar.foo(3, 4); - - // This should invoke Bar::foo(char *) - bar.foo("This is a test"); - - // This should invoke Bar::foo(int) - bar.foo(42); - - // This should invoke Bar::Bar() to construct the input - // argument, followed by Bar::foo(Bar *). - bar.foo(Example::Bar.new); - - // This should invoke Bar::spam(int x, int y, int z) - bar.spam(1); - - // This should invoke Bar::spam(double x, int y, int z) - bar.spam(3.14159); - */ - - write("Goodbye\n"); - - return 0; -} diff --git a/Examples/pike/simple/Makefile b/Examples/pike/simple/Makefile deleted file mode 100644 index 8b49b4ea5..000000000 --- a/Examples/pike/simple/Makefile +++ /dev/null @@ -1,22 +0,0 @@ -TOP = ../.. -SWIGEXE = $(TOP)/../swig -SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib -SRCS = example.c -TARGET = example -INTERFACE = example.i - -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike - -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - TARGET='mypike' INTERFACE='$(INTERFACE)' pike_static - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_clean diff --git a/Examples/pike/simple/example.c b/Examples/pike/simple/example.c deleted file mode 100644 index 1c2af789c..000000000 --- a/Examples/pike/simple/example.c +++ /dev/null @@ -1,18 +0,0 @@ -/* File : example.c */ - -/* A global variable */ -double Foo = 3.0; - -/* Compute the greatest common divisor of positive integers */ -int gcd(int x, int y) { - int g; - g = y; - while (x > 0) { - g = x; - x = y % x; - y = g; - } - return g; -} - - diff --git a/Examples/pike/simple/example.i b/Examples/pike/simple/example.i deleted file mode 100644 index 24093b9bf..000000000 --- a/Examples/pike/simple/example.i +++ /dev/null @@ -1,7 +0,0 @@ -/* File : example.i */ -%module example - -%inline %{ -extern int gcd(int x, int y); -extern double Foo; -%} diff --git a/Examples/pike/simple/runme.pike b/Examples/pike/simple/runme.pike deleted file mode 100644 index a6a78e9e7..000000000 --- a/Examples/pike/simple/runme.pike +++ /dev/null @@ -1,20 +0,0 @@ -int main() -{ - /* Call our gcd() function */ - int x = 42; - int y = 105; - int g = .example.gcd(x, y); - write("The gcd of %d and %d is %d\n", x, y, g); - - /* Manipulate the Foo global variable */ - /* Output its current value */ - write("Foo = %f\n", .example->Foo_get()); - - /* Change its value */ - .example->Foo_set(3.1415926); - - /* See if the change took effect */ - write("Foo = %f\n", .example->Foo_get()); - - return 0; -} diff --git a/Examples/pike/template/Makefile b/Examples/pike/template/Makefile deleted file mode 100644 index 513dc3b4b..000000000 --- a/Examples/pike/template/Makefile +++ /dev/null @@ -1,24 +0,0 @@ -TOP = ../.. -SWIGEXE = $(TOP)/../swig -SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib -CXXSRCS = -TARGET = example -INTERFACE = example.i -LIBS = -lm -SWIGOPT = - -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike_cpp - -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - SWIGOPT='$(SWIGOPT)' TARGET='mypike' INTERFACE='$(INTERFACE)' pike_cpp_static - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_clean diff --git a/Examples/pike/template/example.h b/Examples/pike/template/example.h deleted file mode 100644 index 7401df650..000000000 --- a/Examples/pike/template/example.h +++ /dev/null @@ -1,32 +0,0 @@ -/* File : example.h */ - -// Some template definitions - -template T max(T a, T b) { return a>b ? a : b; } - -template class vector { - T *v; - int sz; - public: - vector(int _sz) { - v = new T[_sz]; - sz = _sz; - } - T &get(int index) { - return v[index]; - } - void set(int index, T &val) { - v[index] = val; - } -#ifdef SWIG - %extend { - T getitem(int index) { - return $self->get(index); - } - void setitem(int index, T val) { - $self->set(index,val); - } - } -#endif -}; - diff --git a/Examples/pike/template/example.i b/Examples/pike/template/example.i deleted file mode 100644 index 8f94c4da1..000000000 --- a/Examples/pike/template/example.i +++ /dev/null @@ -1,17 +0,0 @@ -/* File : example.i */ -%module example - -%{ -#include "example.h" -%} - -/* Let's just grab the original header file here */ -%include "example.h" - -/* Now instantiate some specific template declarations */ - -%template(maxint) max; -%template(maxdouble) max; -%template(vecint) vector; -%template(vecdouble) vector; - diff --git a/Examples/pike/template/runme.pike b/Examples/pike/template/runme.pike deleted file mode 100644 index 36825c3e3..000000000 --- a/Examples/pike/template/runme.pike +++ /dev/null @@ -1,33 +0,0 @@ -int main() -{ - // Call some templated functions - write(sprintf("%d\n", .example.maxint(3, 7))); - write(sprintf("%f\n", .example.maxdouble(3.14, 2.18))); - - // Create some objects - .example.vecint iv = .example.vecint(100); - .example.vecdouble dv = .example.vecdouble(1000); - - for (int i = 0; i < 100; i++) { - iv->setitem(i, 2*i); - } - - for (int i = 0; i < 1000; i++) { - dv->setitem(i, 1.0/(i+1)); - } - - int isum = 0; - for (int i = 0; i < 100; i++) { - isum += iv->getitem(i); - } - - write(sprintf("%d\n", isum)); - - float fsum = 0.0; - for (int i = 0; i < 1000; i++) { - fsum += dv->getitem(i); - } - write(sprintf("%f\n", fsum)); - - return 0; -} diff --git a/Examples/python/callback/runme.py b/Examples/python/callback/runme.py index 345a3eb6e..41deb8386 100644 --- a/Examples/python/callback/runme.py +++ b/Examples/python/callback/runme.py @@ -11,7 +11,7 @@ class PyCallback(example.Callback): example.Callback.__init__(self) def run(self): - print "PyCallback.run()" + print("PyCallback.run()") # Create an Caller instance @@ -20,8 +20,8 @@ caller = example.Caller() # Add a simple C++ callback (caller owns the callback, so # we disown it first by clearing the .thisown flag). -print "Adding and calling a normal C++ callback" -print "----------------------------------------" +print("Adding and calling a normal C++ callback") +print("----------------------------------------") callback = example.Callback() callback.thisown = 0 @@ -29,9 +29,9 @@ caller.setCallback(callback) caller.call() caller.delCallback() -print -print "Adding and calling a Python callback" -print "------------------------------------" +print("") +print("Adding and calling a Python callback") +print("------------------------------------") # Add a Python callback (caller owns the callback, so we # disown it first by calling __disown__). @@ -40,9 +40,9 @@ caller.setCallback(PyCallback().__disown__()) caller.call() caller.delCallback() -print -print "Adding and calling another Python callback" -print "------------------------------------------" +print("") +print("Adding and calling another Python callback") +print("------------------------------------------") # Let's do the same but use the weak reference this time. @@ -53,5 +53,5 @@ caller.delCallback() # All done. -print -print "python exit" +print("") +print("python exit") diff --git a/Examples/python/check.list b/Examples/python/check.list index 0798b5f7e..025278f89 100644 --- a/Examples/python/check.list +++ b/Examples/python/check.list @@ -13,8 +13,8 @@ funcptr funcptr2 functor import -import_template import_packages +import_template #libffi multimap operator @@ -22,8 +22,8 @@ pointer reference simple smartptr -std_vector std_map +std_vector template varargs variables diff --git a/Examples/python/class/runme.py b/Examples/python/class/runme.py index 34d21505c..adade7468 100644 --- a/Examples/python/class/runme.py +++ b/Examples/python/class/runme.py @@ -7,15 +7,15 @@ import example # ----- Object creation ----- -print "Creating some objects:" +print("Creating some objects:") c = example.Circle(10) -print " Created circle", c +print(" Created circle %s" % c) s = example.Square(10) -print " Created square", s +print(" Created square %s" % s) # ----- Access a static member ----- -print "\nA total of", example.cvar.Shape_nshapes, "shapes were created" +print("\nA total of %d shapes were created" % example.cvar.Shape_nshapes) # ----- Member data access ----- @@ -27,25 +27,25 @@ c.y = 30 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("\nHere is their current position:") +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:" +print("\nHere are some properties of the shapes:") for o in [c, s]: - print " ", o - print " area = ", o.area() - print " perimeter = ", o.perimeter() + print(" %s" % o) + print(" area = %s" % o.area()) + print(" perimeter = %s" % o.perimeter()) # prevent o from holding a reference to the last object looked at o = None -print "\nGuess I'll clean up now" +print("\nGuess I'll clean up now") # Note: this invokes the virtual destructor del c del s -print example.cvar.Shape_nshapes, "shapes remain" -print "Goodbye" +print("%d shapes remain" % example.cvar.Shape_nshapes) +print("Goodbye") diff --git a/Examples/python/constants/runme.py b/Examples/python/constants/runme.py index 415d1adc4..808bf1fe6 100644 --- a/Examples/python/constants/runme.py +++ b/Examples/python/constants/runme.py @@ -2,22 +2,24 @@ import example -print "ICONST =", example.ICONST, "(should be 42)" -print "FCONST =", example.FCONST, "(should be 2.1828)" -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 "iconst =", example.iconst, "(should be 37)" -print "fconst =", example.fconst, "(should be 3.14)" +print("ICONST = %s (should be 42)" % example.ICONST) +print("FCONST = %s (should be 2.1828)" % example.FCONST) +print("CCONST = %s (should be 'x')" % example.CCONST) +print("CCONST2 = %s (this should be on a new line)" % example.CCONST2) +print("SCONST = %s (should be 'Hello World')" % example.SCONST) +print("SCONST2 = %s (should be '\"Hello World\"')" % example.SCONST2) +print("EXPR = %s (should be 48.5484)" % example.EXPR) +print("iconst = %s (should be 37)" % example.iconst) +print("fconst = %s (should be 3.14)" % example.fconst) try: - print "EXTERN = ", example.EXTERN, "(Arg! This shouldn't print anything)" + x = example.EXTERN + print("%s (Arg! This shouldn't print anything)" % x) except AttributeError: - print "EXTERN isn't defined (good)" + print("EXTERN isn't defined (good)") try: - print "FOO = ", example.FOO, "(Arg! This shouldn't print anything)" + x = example.FOO + print("%s (Arg! This shouldn't print anything)" % x) except AttributeError: - print "FOO isn't defined (good)" + print("FOO isn't defined (good)") diff --git a/Examples/python/contract/runme.py b/Examples/python/contract/runme.py index ce01e5a1d..ec0aceb45 100644 --- a/Examples/python/contract/runme.py +++ b/Examples/python/contract/runme.py @@ -7,15 +7,15 @@ import example x = 42 y = 105 g = example.gcd(x, y) -print "The gcd of %d and %d is %d" % (x, y, g) +print("The gcd of %d and %d is %d" % (x, y, g)) # Manipulate the Foo global variable # Output its current value -print "Foo = ", example.cvar.Foo +print("Foo = %s" % example.cvar.Foo) # Change its value example.cvar.Foo = 3.1415926 # See if the change took effect -print "Foo = ", example.cvar.Foo +print("Foo = %s" % example.cvar.Foo) diff --git a/Examples/python/docstrings/runme.py b/Examples/python/docstrings/runme.py index c25d291b6..76386d214 100644 --- a/Examples/python/docstrings/runme.py +++ b/Examples/python/docstrings/runme.py @@ -2,4 +2,4 @@ import example -print "example.Foo.bar.__doc__ =", repr(example.Foo.bar.__doc__), "(Should be 'No comment')" +print("example.Foo.bar.__doc__ = %s (Should be 'No comment')" % repr(example.Foo.bar.__doc__)) diff --git a/Examples/python/doxygen/runme.py b/Examples/python/doxygen/runme.py index e23528874..657535cc2 100644 --- a/Examples/python/doxygen/runme.py +++ b/Examples/python/doxygen/runme.py @@ -5,24 +5,24 @@ import example -print "Creating some objects:" +print("Creating some objects:") c = example.MakeCircle(10) -print " Created circle", c +print(" Created circle %s" % c) s = example.MakeSquare(10) -print " Created square", s +print(" Created square %s" % s) r = example.MakeRectangleInt(10, 20) -print " Created rectangle", r +print(" Created rectangle %s" % r) -print "\nHere are some properties of the shapes:" +print("\nHere are some properties of the shapes:") for o in [c, s, r]: - print " ", o - print " area = ", o.area() - print " perimeter = ", o.perimeter() + print(" %s" % o) + print(" area = %s" % o.area()) + print(" perimeter = %s" % o.perimeter()) -print "\nRunning pydoc, this is the equivalent to executing: pydoc -w ./example.py" +print("\nRunning pydoc, this is the equivalent to executing: pydoc -w ./example.py") import pydoc pydoc.writedoc("example") -print "Open example.html in your browser to view the generated python docs" +print("Open example.html in your browser to view the generated python docs") diff --git a/Examples/python/enum/runme.py b/Examples/python/enum/runme.py index def01b147..4920c1dcf 100644 --- a/Examples/python/enum/runme.py +++ b/Examples/python/enum/runme.py @@ -5,24 +5,24 @@ import example # ----- Object creation ----- # Print out the value of some enums -print "*** color ***" -print " RED =", example.RED -print " BLUE =", example.BLUE -print " GREEN =", example.GREEN +print("*** color ***") +print(" RED = %s" % example.RED) +print(" BLUE = %s" % example.BLUE) +print(" GREEN = %s" % example.GREEN) -print "\n*** Foo::speed ***" -print " Foo_IMPULSE =", example.Foo.IMPULSE -print " Foo_WARP =", example.Foo.WARP -print " Foo_LUDICROUS =", example.Foo.LUDICROUS +print("\n*** Foo::speed ***") +print(" Foo_IMPULSE = %s" % example.Foo.IMPULSE) +print(" Foo_WARP = %s" % example.Foo.WARP) +print(" Foo_LUDICROUS = %s" % example.Foo.LUDICROUS) -print "\nTesting use of enums with functions\n" +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.GREEN, example.Foo.LUDICROUS) example.enum_test(1234, 5678) -print "\nTesting use of enum with class method" +print("\nTesting use of enum with class method") f = example.Foo() f.enum_test(example.Foo.IMPULSE) diff --git a/Examples/python/exception/example.h b/Examples/python/exception/example.h index bc744cda7..c76c46a5d 100644 --- a/Examples/python/exception/example.h +++ b/Examples/python/exception/example.h @@ -10,7 +10,7 @@ class Exc { public: Exc(int c, const char *m) { code = c; - strncpy(msg,m,256); + strncpy(msg,m,255); } int code; char msg[256]; diff --git a/Examples/python/exception/runme.py b/Examples/python/exception/runme.py index 7fae49030..7b5c10d19 100644 --- a/Examples/python/exception/runme.py +++ b/Examples/python/exception/runme.py @@ -7,36 +7,36 @@ import example t = example.Test() try: t.unknown() -except RuntimeError, e: - print "incomplete type", e.args[0] +except RuntimeError as e: + print("incomplete type %s" % e.args[0]) try: t.simple() -except RuntimeError, e: - print e.args[0] +except RuntimeError as e: + print(e.args[0]) try: t.message() -except RuntimeError, e: - print e.args[0] +except RuntimeError as e: + print(e.args[0]) if not example.is_python_builtin(): try: t.hosed() - except example.Exc, e: - print e.code, e.msg + except example.Exc as e: + print("%s %s" % (e.code, e.msg)) else: try: t.hosed() - except BaseException, e: + except BaseException as e: # Throwing builtin classes as exceptions not supported (-builtin # option) - print e + 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 + except RuntimeError as e: + print(e.args[0]) + except example.Exc as e: + print("%s %s" % (e.code, e.msg)) diff --git a/Examples/python/exceptproxy/runme.py b/Examples/python/exceptproxy/runme.py index 970d6201d..d25fb6de6 100644 --- a/Examples/python/exceptproxy/runme.py +++ b/Examples/python/exceptproxy/runme.py @@ -2,44 +2,44 @@ import example if example.is_python_builtin(): - print "Skipping example: -builtin option does not support %exceptionclass" + print("Skipping example: -builtin option does not support %exceptionclass") exit(0) q = example.intQueue(10) -print "Inserting items into intQueue" +print("Inserting items into intQueue") -print type(example.FullError) +print(type(example.FullError)) try: for i in range(0, 100): q.enqueue(i) -except example.FullError, e: - print "Maxsize is", e.maxsize +except example.FullError as e: + print("Maxsize is %s" % e.maxsize) -print "Removing items" +print("Removing items") try: - while 1: + while True: q.dequeue() -except example.EmptyError, e: +except example.EmptyError as e: pass q = example.doubleQueue(1000) -print "Inserting items into doubleQueue" +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 +except example.FullError as e: + print("Maxsize is %s" % e.maxsize) -print "Removing items" +print("Removing items") try: - while 1: + while True: q.dequeue() -except example.EmptyError, e: +except example.EmptyError as e: pass diff --git a/Examples/python/extend/runme.py b/Examples/python/extend/runme.py index e97358b99..d7e626ec2 100644 --- a/Examples/python/extend/runme.py +++ b/Examples/python/extend/runme.py @@ -21,9 +21,9 @@ class CEO(example.Manager): # the director wrappers to call CEO.getPosition. e = CEO("Alice") -print e.getName(), "is a", e.getPosition() -print "Just call her \"%s\"" % e.getTitle() -print "----------------------" +print("%s is a %s" % (e.getName(), e.getPosition())) +print("Just call her \"%s\"" % e.getTitle()) +print("----------------------") # Create a new EmployeeList instance. This class does not have a C++ @@ -40,7 +40,7 @@ list = example.EmployeeList() e = e.__disown__() list.addEmployee(e) -print "----------------------" +print("----------------------") # Now we access the first four items in list (three are C++ objects that # EmployeeList's constructor adds, the last is our CEO). The virtual @@ -59,13 +59,13 @@ print "----------------------" # passes down through the C++ director class to the Python implementation # in CEO. All this routing takes place transparently. -print "(position, title) for items 0-3:" +print("(position, title) for items 0-3:") -print " %s, \"%s\"" % (list.get_item(0).getPosition(), list.get_item(0).getTitle()) -print " %s, \"%s\"" % (list.get_item(1).getPosition(), list.get_item(1).getTitle()) -print " %s, \"%s\"" % (list.get_item(2).getPosition(), list.get_item(2).getTitle()) -print " %s, \"%s\"" % (list.get_item(3).getPosition(), list.get_item(3).getTitle()) -print "----------------------" +print(" %s, \"%s\"" % (list.get_item(0).getPosition(), list.get_item(0).getTitle())) +print(" %s, \"%s\"" % (list.get_item(1).getPosition(), list.get_item(1).getTitle())) +print(" %s, \"%s\"" % (list.get_item(2).getPosition(), list.get_item(2).getTitle())) +print(" %s, \"%s\"" % (list.get_item(3).getPosition(), list.get_item(3).getTitle())) +print("----------------------") # Time to delete the EmployeeList, which will delete all the Employee* # items it contains. The last item is our CEO, which gets destroyed as its @@ -75,8 +75,8 @@ print "----------------------" # usual to destroy the object. del list -print "----------------------" +print("----------------------") # All done. -print "python exit" +print("python exit") diff --git a/Examples/python/funcptr/runme.py b/Examples/python/funcptr/runme.py index bf0c6e1ac..4248f928d 100644 --- a/Examples/python/funcptr/runme.py +++ b/Examples/python/funcptr/runme.py @@ -7,14 +7,14 @@ b = 42 # Now call our C function with a bunch of callbacks -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("Trying some C callback functions") +print(" a = %s" % a) +print(" b = %s" % b) +print(" ADD(a,b) = %s" % example.do_op(a, b, example.ADD)) +print(" SUB(a,b) = %s" % example.do_op(a, b, example.SUB)) +print(" MUL(a,b) = %s" % example.do_op(a, b, example.MUL)) -print "Here is what the C callback function objects look like in Python" -print " ADD =", example.ADD -print " SUB =", example.SUB -print " MUL =", example.MUL +print("Here is what the C callback function objects look like in Python") +print(" ADD = %s" % example.ADD) +print(" SUB = %s" % example.SUB) +print(" MUL = %s" % example.MUL) diff --git a/Examples/python/funcptr2/runme.py b/Examples/python/funcptr2/runme.py index a4405d9d9..afa2e2db6 100644 --- a/Examples/python/funcptr2/runme.py +++ b/Examples/python/funcptr2/runme.py @@ -7,18 +7,18 @@ b = 42 # Now call our C function with a bunch of callbacks -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("Trying some C callback functions") +print(" a = %s" % a) +print(" b = %s" % b) +print(" ADD(a,b) = %s" % example.do_op(a, b, example.ADD)) +print(" SUB(a,b) = %s" % example.do_op(a, b, example.SUB)) +print(" MUL(a,b) = %s" % example.do_op(a, b, example.MUL)) -print "Here is what the C callback function objects look like in Python" -print " ADD =", example.ADD -print " SUB =", example.SUB -print " MUL =", example.MUL +print("Here is what the C callback function objects look like in Python") +print(" ADD = %s" % example.ADD) +print(" SUB = %s" % example.SUB) +print(" MUL = %s" % example.MUL) -print "Call the functions directly..." -print " add(a,b) =", example.add(a, b) -print " sub(a,b) =", example.sub(a, b) +print("Call the functions directly...") +print(" add(a,b) = %s" % example.add(a, b)) +print(" sub(a,b) = %s" % example.sub(a, b)) diff --git a/Examples/python/functor/runme.py b/Examples/python/functor/runme.py index 7f6f2b649..69289a78b 100644 --- a/Examples/python/functor/runme.py +++ b/Examples/python/functor/runme.py @@ -12,5 +12,5 @@ for i in range(0, 100): a(i) # Note: function call b(math.sqrt(i)) # Note: function call -print a.result() -print b.result() +print(a.result()) +print(b.result()) diff --git a/Examples/python/import/runme.py b/Examples/python/import/runme.py index 0e83acad0..7970dec26 100644 --- a/Examples/python/import/runme.py +++ b/Examples/python/import/runme.py @@ -1,15 +1,22 @@ # file: runme.py # Test various properties of classes defined in separate modules +import sys + +print("Testing the %import directive") -print "Testing the %import directive" import base import foo import bar import spam +def write_flush(s): + # Python 2/3 compatible write and flush + sys.stdout.write(s) + sys.stdout.flush() + # Create some objects -print "Creating some objects" +print("Creating some objects") a = base.Base() b = foo.Foo() @@ -17,91 +24,74 @@ c = bar.Bar() d = spam.Spam() # Try calling some methods -print "Testing some methods" -print "", -print "Should see 'Base::A' ---> ", +print("Testing some methods") + +write_flush(" Should see 'Base::A' ---> ") a.A() -print "Should see 'Base::B' ---> ", +write_flush(" Should see 'Base::B' ---> ") a.B() -print "Should see 'Foo::A' ---> ", +write_flush(" Should see 'Foo::A' ---> ") b.A() -print "Should see 'Foo::B' ---> ", +write_flush(" Should see 'Foo::B' ---> ") b.B() -print "Should see 'Bar::A' ---> ", +write_flush(" Should see 'Bar::A' ---> ") c.A() -print "Should see 'Bar::B' ---> ", +write_flush(" Should see 'Bar::B' ---> ") c.B() -print "Should see 'Spam::A' ---> ", +write_flush(" Should see 'Spam::A' ---> ") d.A() -print "Should see 'Spam::B' ---> ", +write_flush(" Should see 'Spam::B' ---> ") d.B() # Try some casts -print "\nTesting some casts\n" -print "", +print("\nTesting some casts\n") x = a.toBase() -print "Should see 'Base::A' ---> ", +write_flush(" Should see 'Base::A' ---> ") x.A() -print "Should see 'Base::B' ---> ", +write_flush(" Should see 'Base::B' ---> ") x.B() x = b.toBase() -print "Should see 'Foo::A' ---> ", +write_flush(" Should see 'Foo::A' ---> ") x.A() -print "Should see 'Base::B' ---> ", +write_flush(" Should see 'Base::B' ---> ") x.B() x = c.toBase() -print "Should see 'Bar::A' ---> ", +write_flush(" Should see 'Bar::A' ---> ") x.A() -print "Should see 'Base::B' ---> ", +write_flush(" Should see 'Base::B' ---> ") x.B() x = d.toBase() -print "Should see 'Spam::A' ---> ", +write_flush(" Should see 'Spam::A' ---> ") x.A() -print "Should see 'Base::B' ---> ", +write_flush(" Should see 'Base::B' ---> ") x.B() x = d.toBar() -print "Should see 'Bar::B' ---> ", +write_flush(" Should see 'Bar::B' ---> ") x.B() -print "\nTesting some dynamic casts\n" +print("\nTesting some dynamic casts\n") x = d.toBase() -print " Spam -> Base -> Foo : ", -y = foo.Foo_fromBase(x) -if y: - print "bad swig" -else: - print "good swig" +y = foo.Foo.fromBase(x) +print(" Spam -> Base -> Foo : {} swig".format("bad" if y else "good")) -print " Spam -> Base -> Bar : ", -y = bar.Bar_fromBase(x) -if y: - print "good swig" -else: - print "bad swig" +y = bar.Bar.fromBase(x) +print(" Spam -> Base -> Bar : {} swig".format("good" if y else "bad")) -print " Spam -> Base -> Spam : ", -y = spam.Spam_fromBase(x) -if y: - print "good swig" -else: - print "bad swig" +y = spam.Spam.fromBase(x) +print(" Spam -> Base -> Spam : {} swig".format("good" if y else "bad")) -print " Foo -> Spam : ", -y = spam.Spam_fromBase(b) -if y: - print "bad swig" -else: - print "good swig" +y = spam.Spam.fromBase(b) +print(" Foo -> Spam : {} swig".format("bad" if y else "good")) diff --git a/Examples/python/import_packages/from_init1/runme.py b/Examples/python/import_packages/from_init1/runme.py index a663a136b..c76716f16 100644 --- a/Examples/python/import_packages/from_init1/runme.py +++ b/Examples/python/import_packages/from_init1/runme.py @@ -6,26 +6,26 @@ def run_except_on_windows(commandline, env=None): if os.name != "nt" and sys.platform != "cygwin": # Strange failures on windows/cygin/mingw subprocess.check_call(commandline, env=env, shell=True) - print(" Finished running: " + commandline) + print((" Finished running: " + commandline)) # Test import of modules content from within __init__.py testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) -print "Testing " + testname + " - %module(package=...) + python 'import' in __init__.py" +print("Testing " + testname + " - %module(package=...) + python 'import' in __init__.py") if sys.version_info < (2, 5): - print " Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'" + print(" Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'") sys.exit(0) if sys.version_info < (3, 0): import py2.pkg2 - print " Finished importing py2.pkg2" + print(" Finished importing py2.pkg2") commandline = sys.executable + " -m py2.pkg2.bar" run_except_on_windows(commandline) commandline = sys.executable + " -m py2.pkg2.foo" run_except_on_windows(commandline) else: import py3.pkg2 - print " Finished importing py3.pkg2" + print(" Finished importing py3.pkg2") # commandline = sys.executable + " -m py3.pkg2.bar" # run_except_on_windows(commandline) # commandline = sys.executable + " -m py3.pkg2.foo" diff --git a/Examples/python/import_packages/from_init2/runme.py b/Examples/python/import_packages/from_init2/runme.py index 3c7b12693..c9c46a4da 100644 --- a/Examples/python/import_packages/from_init2/runme.py +++ b/Examples/python/import_packages/from_init2/runme.py @@ -6,24 +6,24 @@ def run_except_on_windows(commandline, env=None): if os.name != "nt" and sys.platform != "cygwin": # Strange failures on windows/cygin/mingw subprocess.check_call(commandline, env=env, shell=True) - print(" Finished running: " + commandline) + print((" Finished running: " + commandline)) # Test import of modules content from within __init__.py testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) -print "Testing " + testname + " - %module(package=...) + python 'import' in __init__.py" +print("Testing " + testname + " - %module(package=...) + python 'import' in __init__.py") if sys.version_info < (2, 5): - print " Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'" + print(" Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'") sys.exit(0) if sys.version_info < (3, 0): import py2.pkg2 - print " Finished importing py2.pkg2" + print(" Finished importing py2.pkg2") commandline = sys.executable + " -m py2.pkg2.bar" run_except_on_windows(commandline) else: import py3.pkg2 - print " Finished importing py3.pkg2" + print(" Finished importing py3.pkg2") # commandline = sys.executable + " -m py3.pkg2.bar" # run_except_on_windows(commandline) diff --git a/Examples/python/import_packages/from_init3/runme.py b/Examples/python/import_packages/from_init3/runme.py index 3c7b12693..c9c46a4da 100644 --- a/Examples/python/import_packages/from_init3/runme.py +++ b/Examples/python/import_packages/from_init3/runme.py @@ -6,24 +6,24 @@ def run_except_on_windows(commandline, env=None): if os.name != "nt" and sys.platform != "cygwin": # Strange failures on windows/cygin/mingw subprocess.check_call(commandline, env=env, shell=True) - print(" Finished running: " + commandline) + print((" Finished running: " + commandline)) # Test import of modules content from within __init__.py testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) -print "Testing " + testname + " - %module(package=...) + python 'import' in __init__.py" +print("Testing " + testname + " - %module(package=...) + python 'import' in __init__.py") if sys.version_info < (2, 5): - print " Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'" + print(" Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'") sys.exit(0) if sys.version_info < (3, 0): import py2.pkg2 - print " Finished importing py2.pkg2" + print(" Finished importing py2.pkg2") commandline = sys.executable + " -m py2.pkg2.bar" run_except_on_windows(commandline) else: import py3.pkg2 - print " Finished importing py3.pkg2" + print(" Finished importing py3.pkg2") # commandline = sys.executable + " -m py3.pkg2.bar" # run_except_on_windows(commandline) diff --git a/Examples/python/import_packages/module_is_init/runme.py b/Examples/python/import_packages/module_is_init/runme.py index b5e646e85..c4806cdf8 100644 --- a/Examples/python/import_packages/module_is_init/runme.py +++ b/Examples/python/import_packages/module_is_init/runme.py @@ -3,10 +3,10 @@ import sys # Test import of a SWIG generated module renamed as the package's __init__.py testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) -print "Testing " + testname + " - module renamed as __init__.py" +print("Testing " + testname + " - module renamed as __init__.py") if sys.version_info >= (3, 0, 0) and sys.version_info < (3, 3, 0): - print " Not importing as Python version is >= 3.0 and < 3.3" + print(" Not importing as Python version is >= 3.0 and < 3.3") # Package detection does not work in these versions. # Can be fixed by using this in the interface file: # %module(moduleimport="from . import $module") foo # without -builtin @@ -14,7 +14,7 @@ if sys.version_info >= (3, 0, 0) and sys.version_info < (3, 3, 0): sys.exit(0) import pkg1 -print " Finished importing pkg1" +print(" Finished importing pkg1") if pkg1.foofunction(123) != 1230: raise RuntimeError("foofunction failed") @@ -23,4 +23,4 @@ fc = pkg1.FooClass() if fc.foomethod(1) != 6: raise RuntimeError("foomethod failed") -print " Finished testing pkg1" +print(" Finished testing pkg1") diff --git a/Examples/python/import_packages/namespace_pkg/runme.py b/Examples/python/import_packages/namespace_pkg/runme.py index d2af05619..54a8e4ee6 100644 --- a/Examples/python/import_packages/namespace_pkg/runme.py +++ b/Examples/python/import_packages/namespace_pkg/runme.py @@ -5,14 +5,14 @@ import subprocess import sys testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) -print "Testing " + testname + " - namespace packages" +print("Testing " + testname + " - namespace packages") if sys.version_info < (3, 3, 0): - print " Not importing nstest as Python version is < 3.3" + print(" Not importing nstest as Python version is < 3.3") sys.exit(0) import nstest -print " Finished importing nstest" +print(" Finished importing nstest") nstest.main() diff --git a/Examples/python/import_packages/relativeimport1/runme.py b/Examples/python/import_packages/relativeimport1/runme.py index 87101ea46..3073cb5a7 100644 --- a/Examples/python/import_packages/relativeimport1/runme.py +++ b/Examples/python/import_packages/relativeimport1/runme.py @@ -6,26 +6,26 @@ def run_except_on_windows(commandline, env=None): if os.name != "nt" and sys.platform != "cygwin": # Strange failures on windows/cygin/mingw subprocess.check_call(commandline, env=env, shell=True) - print(" Finished running: " + commandline) + print((" Finished running: " + commandline)) # Test import of modules content from within __init__.py testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) -print "Testing " + testname + " - %module(package=...) with -relativeimport" +print("Testing " + testname + " - %module(package=...) with -relativeimport") if sys.version_info < (2, 5): - print " Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'" + print(" Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'") sys.exit(0) if sys.version_info < (3, 0): import py2.pkg2.bar - print " Finished importing py2.pkg2.bar" + print(" Finished importing py2.pkg2.bar") commandline = sys.executable + " -m py2.pkg2.bar" run_except_on_windows(commandline) commandline = sys.executable + " -m py2.pkg2.pkg3.foo" run_except_on_windows(commandline) else: import py3.pkg2.bar - print " Finished importing py3.pkg2.bar" + print(" Finished importing py3.pkg2.bar") commandline = sys.executable + " -m py3.pkg2.bar" run_except_on_windows(commandline) commandline = sys.executable + " -m py3.pkg2.pkg3.foo" diff --git a/Examples/python/import_packages/relativeimport2/runme.py b/Examples/python/import_packages/relativeimport2/runme.py index f5b55782f..9ab8d9471 100644 --- a/Examples/python/import_packages/relativeimport2/runme.py +++ b/Examples/python/import_packages/relativeimport2/runme.py @@ -6,26 +6,26 @@ def run_except_on_windows(commandline, env=None): if os.name != "nt" and sys.platform != "cygwin": # Strange failures on windows/cygin/mingw subprocess.check_call(commandline, env=env, shell=True) - print(" Finished running: " + commandline) + print((" Finished running: " + commandline)) # Test import of modules content from within __init__.py testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) -print "Testing " + testname + " - %module(package=...) + python 'import' in __init__.py" +print("Testing " + testname + " - %module(package=...) + python 'import' in __init__.py") if sys.version_info < (2, 5): - print " Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'" + print(" Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'") sys.exit(0) if sys.version_info < (3, 0): import py2.pkg2.bar - print " Finished importing py2.pkg2.bar" + print(" Finished importing py2.pkg2.bar") commandline = sys.executable + " -m py2.pkg2.bar" run_except_on_windows(commandline) commandline = sys.executable + " -m py2.pkg2.pkg3.pkg4.foo" run_except_on_windows(commandline) else: import py3.pkg2.bar - print " Finished importing py3.pkg2.bar" + print(" Finished importing py3.pkg2.bar") commandline = sys.executable + " -m py3.pkg2.bar" run_except_on_windows(commandline) commandline = sys.executable + " -m py3.pkg2.pkg3.pkg4.foo" diff --git a/Examples/python/import_packages/relativeimport3/runme.py b/Examples/python/import_packages/relativeimport3/runme.py index 87101ea46..3073cb5a7 100644 --- a/Examples/python/import_packages/relativeimport3/runme.py +++ b/Examples/python/import_packages/relativeimport3/runme.py @@ -6,26 +6,26 @@ def run_except_on_windows(commandline, env=None): if os.name != "nt" and sys.platform != "cygwin": # Strange failures on windows/cygin/mingw subprocess.check_call(commandline, env=env, shell=True) - print(" Finished running: " + commandline) + print((" Finished running: " + commandline)) # Test import of modules content from within __init__.py testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) -print "Testing " + testname + " - %module(package=...) with -relativeimport" +print("Testing " + testname + " - %module(package=...) with -relativeimport") if sys.version_info < (2, 5): - print " Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'" + print(" Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'") sys.exit(0) if sys.version_info < (3, 0): import py2.pkg2.bar - print " Finished importing py2.pkg2.bar" + print(" Finished importing py2.pkg2.bar") commandline = sys.executable + " -m py2.pkg2.bar" run_except_on_windows(commandline) commandline = sys.executable + " -m py2.pkg2.pkg3.foo" run_except_on_windows(commandline) else: import py3.pkg2.bar - print " Finished importing py3.pkg2.bar" + print(" Finished importing py3.pkg2.bar") commandline = sys.executable + " -m py3.pkg2.bar" run_except_on_windows(commandline) commandline = sys.executable + " -m py3.pkg2.pkg3.foo" diff --git a/Examples/python/import_packages/same_modnames1/runme.py b/Examples/python/import_packages/same_modnames1/runme.py index a64551bfd..05846ed9d 100644 --- a/Examples/python/import_packages/same_modnames1/runme.py +++ b/Examples/python/import_packages/same_modnames1/runme.py @@ -6,21 +6,21 @@ def run_except_on_windows(commandline, env=None): if os.name != "nt" and sys.platform != "cygwin": # Strange failures on windows/cygin/mingw subprocess.check_call(commandline, env=env, shell=True) - print(" Finished running: " + commandline) + print((" Finished running: " + commandline)) # Test import of same modules from different packages testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) -print "Testing " + testname + " - %module(package=...) + python 'import' in __init__.py" +print("Testing " + testname + " - %module(package=...) + python 'import' in __init__.py") import pkg2.foo -print " Finished importing pkg2.foo" +print(" Finished importing pkg2.foo") var2 = pkg2.foo.Pkg2_Foo() classname = str(type(var2)) if classname.find("pkg2.foo.Pkg2_Foo") == -1: raise RuntimeError("failed type checking: " + classname) -print " Successfully created object pkg2.foo.Pkg2_Foo" +print(" Successfully created object pkg2.foo.Pkg2_Foo") commandline = sys.executable + " -m pkg2.foo" run_except_on_windows(commandline) diff --git a/Examples/python/import_packages/same_modnames2/runme.py b/Examples/python/import_packages/same_modnames2/runme.py index c2cf2744c..190dadc77 100644 --- a/Examples/python/import_packages/same_modnames2/runme.py +++ b/Examples/python/import_packages/same_modnames2/runme.py @@ -6,20 +6,20 @@ def run_except_on_windows(commandline, env=None): if os.name != "nt" and sys.platform != "cygwin": # Strange failures on windows/cygin/mingw subprocess.check_call(commandline, env=env, shell=True) - print(" Finished running: " + commandline) + print((" Finished running: " + commandline)) testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) -print "Testing " + testname + " - %module(package=...) + python 'import' in __init__.py" +print("Testing " + testname + " - %module(package=...) + python 'import' in __init__.py") import pkg1.pkg2.foo -print " Finished importing pkg1.pkg2.foo" +print(" Finished importing pkg1.pkg2.foo") var2 = pkg1.pkg2.foo.Pkg2_Foo() classname = str(type(var2)) if classname.find("pkg1.pkg2.foo.Pkg2_Foo") == -1: raise RuntimeError("failed type checking: " + classname) -print " Successfully created object pkg1.pkg2.foo.Pkg2_Foo" +print(" Successfully created object pkg1.pkg2.foo.Pkg2_Foo") commandline = sys.executable + " -m pkg1.pkg2.foo" run_except_on_windows(commandline) diff --git a/Examples/python/import_packages/split_modules/vanilla/runme.py b/Examples/python/import_packages/split_modules/vanilla/runme.py index 79d79b4c3..0f7b8806b 100644 --- a/Examples/python/import_packages/split_modules/vanilla/runme.py +++ b/Examples/python/import_packages/split_modules/vanilla/runme.py @@ -6,14 +6,14 @@ def run_except_on_windows(commandline, env=None): if os.name != "nt" and sys.platform != "cygwin": # Strange failures on windows/cygin/mingw subprocess.check_call(commandline, env=env, shell=True) - print(" Finished running: " + commandline) + print((" Finished running: " + commandline)) testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) -print "Testing " + testname + " - split modules" +print("Testing " + testname + " - split modules") import pkg1.foo -print " Finished importing pkg1.foo" +print(" Finished importing pkg1.foo") if not(pkg1.foo.count() == 3): raise RuntimeError("test failed") diff --git a/Examples/python/import_packages/split_modules/vanilla_split/runme.py b/Examples/python/import_packages/split_modules/vanilla_split/runme.py index 79d79b4c3..0f7b8806b 100644 --- a/Examples/python/import_packages/split_modules/vanilla_split/runme.py +++ b/Examples/python/import_packages/split_modules/vanilla_split/runme.py @@ -6,14 +6,14 @@ def run_except_on_windows(commandline, env=None): if os.name != "nt" and sys.platform != "cygwin": # Strange failures on windows/cygin/mingw subprocess.check_call(commandline, env=env, shell=True) - print(" Finished running: " + commandline) + print((" Finished running: " + commandline)) testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) -print "Testing " + testname + " - split modules" +print("Testing " + testname + " - split modules") import pkg1.foo -print " Finished importing pkg1.foo" +print(" Finished importing pkg1.foo") if not(pkg1.foo.count() == 3): raise RuntimeError("test failed") diff --git a/Examples/python/import_template/runme.py b/Examples/python/import_template/runme.py index 35f8924c1..74a918426 100644 --- a/Examples/python/import_template/runme.py +++ b/Examples/python/import_template/runme.py @@ -1,15 +1,22 @@ # file: runme.py # Test various properties of classes defined in separate modules +import sys + +print("Testing the %import directive with templates") -print "Testing the %import directive with templates" import base import foo import bar import spam +def write_flush(s): + # Python 2/3 compatible write and flush + sys.stdout.write(s) + sys.stdout.flush() + # Create some objects -print "Creating some objects" +print("Creating some objects") a = base.intBase() b = foo.intFoo() @@ -17,91 +24,74 @@ c = bar.intBar() d = spam.intSpam() # Try calling some methods -print "Testing some methods" -print "", -print "Should see 'Base::A' ---> ", +print("Testing some methods") + +write_flush(" Should see 'Base::A' ---> ") a.A() -print "Should see 'Base::B' ---> ", +write_flush(" Should see 'Base::B' ---> ") a.B() -print "Should see 'Foo::A' ---> ", +write_flush(" Should see 'Foo::A' ---> ") b.A() -print "Should see 'Foo::B' ---> ", +write_flush(" Should see 'Foo::B' ---> ") b.B() -print "Should see 'Bar::A' ---> ", +write_flush(" Should see 'Bar::A' ---> ") c.A() -print "Should see 'Bar::B' ---> ", +write_flush(" Should see 'Bar::B' ---> ") c.B() -print "Should see 'Spam::A' ---> ", +write_flush(" Should see 'Spam::A' ---> ") d.A() -print "Should see 'Spam::B' ---> ", +write_flush(" Should see 'Spam::B' ---> ") d.B() # Try some casts -print "\nTesting some casts\n" -print "", +print("\nTesting some casts\n") x = a.toBase() -print "Should see 'Base::A' ---> ", +write_flush(" Should see 'Base::A' ---> ") x.A() -print "Should see 'Base::B' ---> ", +write_flush(" Should see 'Base::B' ---> ") x.B() x = b.toBase() -print "Should see 'Foo::A' ---> ", +write_flush(" Should see 'Foo::A' ---> ") x.A() -print "Should see 'Base::B' ---> ", +write_flush(" Should see 'Base::B' ---> ") x.B() x = c.toBase() -print "Should see 'Bar::A' ---> ", +write_flush(" Should see 'Bar::A' ---> ") x.A() -print "Should see 'Base::B' ---> ", +write_flush(" Should see 'Base::B' ---> ") x.B() x = d.toBase() -print "Should see 'Spam::A' ---> ", +write_flush(" Should see 'Spam::A' ---> ") x.A() -print "Should see 'Base::B' ---> ", +write_flush(" Should see 'Base::B' ---> ") x.B() x = d.toBar() -print "Should see 'Bar::B' ---> ", +write_flush(" Should see 'Bar::B' ---> ") x.B() -print "\nTesting some dynamic casts\n" +print("\nTesting some dynamic casts\n") x = d.toBase() -print " Spam -> Base -> Foo : ", -y = foo.intFoo_fromBase(x) -if y: - print "bad swig" -else: - print "good swig" +y = foo.intFoo.fromBase(x) +print(" Spam -> Base -> Foo : {} swig".format("bad" if y else "good")) -print " Spam -> Base -> Bar : ", -y = bar.intBar_fromBase(x) -if y: - print "good swig" -else: - print "bad swig" +y = bar.intBar.fromBase(x) +print(" Spam -> Base -> Bar : {} swig".format("good" if y else "bad")) -print " Spam -> Base -> Spam : ", -y = spam.intSpam_fromBase(x) -if y: - print "good swig" -else: - print "bad swig" +y = spam.intSpam.fromBase(x) +print(" Spam -> Base -> Spam : {} swig".format("good" if y else "bad")) -print " Foo -> Spam : ", -y = spam.intSpam_fromBase(b) -if y: - print "bad swig" -else: - print "good swig" +y = spam.intSpam.fromBase(b) +print(" Foo -> Spam : {} swig".format("bad" if y else "good")) diff --git a/Examples/python/index.html b/Examples/python/index.html index 3bbdd66e8..750c0f04a 100644 --- a/Examples/python/index.html +++ b/Examples/python/index.html @@ -89,7 +89,6 @@ to look at the distutils

    Compatibility

    For Python 3, set the environment variable PY3=1. -This will ensure the 2to3 program is run prior to running any example.

    Your mileage may vary. If you experience a problem, please let us know by diff --git a/Examples/python/multimap/runme.py b/Examples/python/multimap/runme.py index ad693b73a..e24f54ee1 100644 --- a/Examples/python/multimap/runme.py +++ b/Examples/python/multimap/runme.py @@ -7,14 +7,14 @@ import example x = 42 y = 105 g = example.gcd(x, y) -print "The gcd of %d and %d is %d" % (x, y, g) +print("The gcd of %d and %d is %d" % (x, y, g)) # Call the gcdmain() function example.gcdmain(["gcdmain", "42", "105"]) # Call the count function -print example.count("Hello World", "l") +print(example.count("Hello World", "l")) # Call the capitalize function -print example.capitalize("hello world") +print(example.capitalize("hello world")) diff --git a/Examples/python/operator/runme.py b/Examples/python/operator/runme.py index ac48f2676..ee479f0b5 100644 --- a/Examples/python/operator/runme.py +++ b/Examples/python/operator/runme.py @@ -4,17 +4,17 @@ import example a = example.Complex(2, 3) b = example.Complex(-5, 10) -print "a =", a -print "b =", b +print("a = %s" % a) +print("b = %s" % b) c = a + b -print "c =", c -print "a*b =", a * b -print "a-c =", a - c +print("c = %s" % c) +print("a*b = %s" % (a * b)) +print("a-c = %s" % (a - c)) e = example.ComplexCopy(a - c) -print "e =", e +print("e = %s" % e) # Big expression f = ((a + b) * (c + b * e)) + (-a) -print "f =", f +print("f = %s" % f) diff --git a/Examples/python/pointer/runme.py b/Examples/python/pointer/runme.py index 5b5f16bc2..46371b89a 100644 --- a/Examples/python/pointer/runme.py +++ b/Examples/python/pointer/runme.py @@ -3,23 +3,23 @@ import example # First create some objects using the pointer library. -print "Testing 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 " a =", a -print " b =", b -print " c =", c +print(" a = %s" % a) +print(" b = %s" % b) +print(" c = %s" % c) # Call the add() function with some pointers example.add(a, b, c) # Now get the result r = example.intp_value(c) -print " 37 + 42 =", r +print(" 37 + 42 = %s" % r) # Clean up the pointers example.delete_intp(a) @@ -30,12 +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" +print("Trying the typemap library") r = example.sub(37, 42) -print " 37 - 42 =", r +print(" 37 - 42 = %s" % r) # Now try the version with multiple return values -print "Testing multiple return values" +print("Testing multiple return values") q, r = example.divide(42, 37) -print " 42/37 = %d remainder %d" % (q, r) +print(" 42/37 = %d remainder %d" % (q, r)) diff --git a/Examples/python/reference/runme.py b/Examples/python/reference/runme.py index 0ff217b02..8a96e03a7 100644 --- a/Examples/python/reference/runme.py +++ b/Examples/python/reference/runme.py @@ -6,12 +6,12 @@ import example # ----- Object creation ----- -print "Creating some objects:" +print("Creating some objects:") a = example.Vector(3, 4, 5) b = example.Vector(10, 11, 12) -print " Created", a.cprint() -print " Created", b.cprint() +print(" Created %s" % a.cprint()) +print(" Created %s" % b.cprint()) # ----- Call an overloaded operator ----- @@ -21,9 +21,9 @@ print " Created", b.cprint() # # It returns a new allocated object. -print "Adding a+b" +print("Adding a+b") c = example.addv(a, b) -print " a+b =", c.cprint() +print(" a+b = %s" % c.cprint()) # Note: Unless we free the result, a memory leak will occur del c @@ -31,9 +31,9 @@ del c # ----- Create a vector array ----- # Note: Using the high-level interface here -print "Creating an array of vectors" +print("Creating an array of vectors") va = example.VectorArray(10) -print " va = ", va +print(" va = %s" % va) # ----- Set some values in the array ----- @@ -45,17 +45,17 @@ va.set(2, example.addv(a, b)) # Get some values from the array -print "Getting some array values" +print("Getting some array values") for i in range(0, 5): - print " va(%d) = %s" % (i, va.get(i).cprint()) + 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): +print("Making sure we don't leak memory.") +for i in range(0, 1000000): c = va.get(i % 10) # ----- Clean up ----- -print "Cleaning up" +print("Cleaning up") del va del a diff --git a/Examples/python/simple/runme.py b/Examples/python/simple/runme.py index ce01e5a1d..ec0aceb45 100644 --- a/Examples/python/simple/runme.py +++ b/Examples/python/simple/runme.py @@ -7,15 +7,15 @@ import example x = 42 y = 105 g = example.gcd(x, y) -print "The gcd of %d and %d is %d" % (x, y, g) +print("The gcd of %d and %d is %d" % (x, y, g)) # Manipulate the Foo global variable # Output its current value -print "Foo = ", example.cvar.Foo +print("Foo = %s" % example.cvar.Foo) # Change its value example.cvar.Foo = 3.1415926 # See if the change took effect -print "Foo = ", example.cvar.Foo +print("Foo = %s" % example.cvar.Foo) diff --git a/Examples/python/smartptr/runme.py b/Examples/python/smartptr/runme.py index 5f8b73476..f01636ad6 100644 --- a/Examples/python/smartptr/runme.py +++ b/Examples/python/smartptr/runme.py @@ -7,17 +7,17 @@ import example # ----- Object creation ----- -print "Creating some objects:" +print("Creating some objects:") cc = example.Circle(10) c = example.ShapePtr(cc) -print " Created circle", c +print(" Created circle %s" % c) ss = example.Square(10) s = example.ShapePtr(ss) -print " Created square", s +print(" Created square %s" % s) # ----- Access a static member ----- -print "\nA total of", example.cvar.Shape_nshapes, "shapes were created" +print("\nA total of %s shapes were created" % example.cvar.Shape_nshapes) # ----- Member data access ----- @@ -29,19 +29,19 @@ c.y = 30 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("\nHere is their current position:") +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:" +print("\nHere are some properties of the shapes:") for o in [c, s]: - print " ", o - print " area = ", o.area() - print " perimeter = ", o.perimeter() + print(" %s" % o) + print(" area = %s" % o.area()) + print(" perimeter = %s" % o.perimeter()) -print "\nGuess I'll clean up now" +print("\nGuess I'll clean up now") # Note: this invokes the virtual destructor del c @@ -50,5 +50,5 @@ del cc del ss s = 3 -print example.cvar.Shape_nshapes, "shapes remain" -print "Goodbye" +print("%d shapes remain" % example.cvar.Shape_nshapes) +print("Goodbye") diff --git a/Examples/python/std_map/runme.py b/Examples/python/std_map/runme.py index 26031f3f4..e86f613fa 100644 --- a/Examples/python/std_map/runme.py +++ b/Examples/python/std_map/runme.py @@ -11,45 +11,45 @@ dmap = {} dmap["hello"] = 1.0 dmap["hi"] = 2.0 -print dmap.items() -print dmap.keys() -print dmap.values() +print(list(dmap.items())) +print(list(dmap.keys())) +print(list(dmap.values())) -print dmap +print(dmap) hmap = example.halfd(dmap) dmap = hmap -print dmap -for i in dmap.iterkeys(): - print "key", i +print(dmap) +for i in dmap.keys(): + print("key %s" % i) -for i in dmap.itervalues(): - print "val", i +for i in dmap.values(): + print("val %s" % i) -for k, v in dmap.iteritems(): - print "item", k, v +for k, v in dmap.items(): + print("item %s %s" % (k, v)) dmap = example.DoubleMap() dmap["hello"] = 1.0 dmap["hi"] = 2.0 -for i in dmap.iterkeys(): - print "key", i +for i in dmap.keys(): + print("key %s" % i) -for i in dmap.itervalues(): - print "val", i +for i in dmap.values(): + print("val %s" % i) -for k, v in dmap.iteritems(): - print "item", k, v +for k, v in dmap.items(): + print("item %s %s" % (k, v)) -print dmap.items() -print dmap.keys() -print dmap.values() +print(list(dmap.items())) +print(list(dmap.keys())) +print(list(dmap.values())) hmap = example.halfd(dmap) -print hmap.keys() -print hmap.values() +print(list(hmap.keys())) +print(list(hmap.values())) dmap = {} @@ -57,23 +57,23 @@ dmap["hello"] = 2 dmap["hi"] = 4 hmap = example.halfi(dmap) -print hmap -print hmap.keys() -print hmap.values() +print(hmap) +print(list(hmap.keys())) +print(list(hmap.values())) dmap = hmap -for i in dmap.iterkeys(): - print "key", i +for i in dmap.keys(): + print("key %s" % i) -for i in dmap.itervalues(): - print "val", i +for i in dmap.values(): + print("val %s" % i) -for i in dmap.iteritems(): - print "item", i +for i in dmap.items(): + print("item %s" % str(i)) -for k, v in dmap.iteritems(): - print "item", k, v +for k, v in dmap.items(): + print("item %s %s" % (k, v)) -print dmap +print(dmap) diff --git a/Examples/python/std_vector/runme.py b/Examples/python/std_vector/runme.py index d7d3c2ea4..3f1106d59 100644 --- a/Examples/python/std_vector/runme.py +++ b/Examples/python/std_vector/runme.py @@ -4,32 +4,30 @@ 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 -print example.average(v) +print(example.average(v)) # half will return a Python list. # Call it with a Python tuple... -print example.half((1.0, 1.5, 2.0, 2.5, 3.0)) +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) -print example.half(v) +print(example.half(v)) # now halve a wrapped std::vector in place example.halve_in_place(v) -for i in range(len(v)): - print v[i], "; ", -print +print([i for i in v]) diff --git a/Examples/python/template/runme.py b/Examples/python/template/runme.py index e408e15f9..85b1ba937 100644 --- a/Examples/python/template/runme.py +++ b/Examples/python/template/runme.py @@ -3,8 +3,8 @@ 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 @@ -21,12 +21,12 @@ sum = 0 for i in range(0, 100): sum = sum + iv.getitem(i) -print sum +print(sum) sum = 0.0 for i in range(0, 1000): sum = sum + dv.getitem(i) -print sum +print(sum) del iv del dv diff --git a/Examples/python/variables/runme.py b/Examples/python/variables/runme.py index 4d34e92dd..d59e0aa3e 100644 --- a/Examples/python/variables/runme.py +++ b/Examples/python/variables/runme.py @@ -22,51 +22,51 @@ example.cvar.name = "Bill" # Now print out the values of the variables -print "Variables (values printed from Python)" +print("Variables (values printed from Python)") -print "ivar =", example.cvar.ivar -print "svar =", example.cvar.svar -print "lvar =", example.cvar.lvar -print "uivar =", example.cvar.uivar -print "usvar =", example.cvar.usvar -print "ulvar =", example.cvar.ulvar -print "scvar =", example.cvar.scvar -print "ucvar =", example.cvar.ucvar -print "fvar =", example.cvar.fvar -print "dvar =", example.cvar.dvar -print "cvar =", example.cvar.cvar -print "strvar =", example.cvar.strvar -print "cstrvar =", example.cvar.cstrvar -print "iptrvar =", example.cvar.iptrvar -print "name =", example.cvar.name -print "ptptr =", example.cvar.ptptr, example.Point_print(example.cvar.ptptr) -print "pt =", example.cvar.pt, example.Point_print(example.cvar.pt) +print("ivar = %s" % example.cvar.ivar) +print("svar = %s" % example.cvar.svar) +print("lvar = %s" % example.cvar.lvar) +print("uivar = %s" % example.cvar.uivar) +print("usvar = %s" % example.cvar.usvar) +print("ulvar = %s" % example.cvar.ulvar) +print("scvar = %s" % example.cvar.scvar) +print("ucvar = %s" % example.cvar.ucvar) +print("fvar = %s" % example.cvar.fvar) +print("dvar = %s" % example.cvar.dvar) +print("cvar = %s" % example.cvar.cvar) +print("strvar = %s" % example.cvar.strvar) +print("cstrvar = %s" % example.cvar.cstrvar) +print("iptrvar = %s" % example.cvar.iptrvar) +print("name = %s" % example.cvar.name) +print("ptptr = %s %s" % (example.cvar.ptptr, example.Point_print(example.cvar.ptptr))) +print("pt = %s %s" % (example.cvar.pt, example.Point_print(example.cvar.pt))) -print "\nVariables (values printed from C)" +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 " Trying to set 'path'" +print(" Trying to set 'path'") try: example.cvar.path = "Whoa!" - print "Hey, what's going on?!?! This shouldn't work" + print("Hey, what's going on?!?! This shouldn't work") except Exception: - print "Good." + 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" + print("Hey, what's going on?!?! This shouldn't work") except Exception: - print "Good." + print("Good.") -print "\nI'm going to try and update a structure variable.\n" +print("\nI'm going to try and update a structure variable.\n") example.cvar.pt = example.cvar.ptptr -print "The new value is" +print("The new value is") example.pt_print() -print "You should see the value", example.Point_print(example.cvar.ptptr) +print("You should see the value %s" % example.Point_print(example.cvar.ptptr)) diff --git a/Examples/s-exp/uffi.lisp b/Examples/s-exp/uffi.lisp deleted file mode 100644 index aea9a1405..000000000 --- a/Examples/s-exp/uffi.lisp +++ /dev/null @@ -1,389 +0,0 @@ -;;; This is experimental code that uses the s-expression -;;; representation of a C/C++ library interface to generate Foreign -;;; Function Interface definitions for use with Kevin Rosenberg's -;;; UFFI. -;;; -;;; Written by Matthias Koeppe - -(eval-when (:compile-toplevel :load-toplevel :execute) - (require 'port) ; from CLOCC - (require 'uffi)) - -(in-package :cl-user) - -;; Interaction with the SWIG binary - -(defvar *swig-source-directory* #p"/home/mkoeppe/s/swig1.3/") - -(defvar *swig-program* (merge-pathnames "swig" *swig-source-directory*)) - -(defun run-swig (swig-interface-file-name &key directory-search-list module - ignore-errors c++) - (let ((temp-file-name "/tmp/swig.lsp")) - (let ((process - (port:run-prog (namestring *swig-program*) - :output t - :args `(,@(and c++ '("-c++")) - "-sexp" - ,@(mapcar (lambda (dir) - (concatenate 'string - "-I" (namestring dir))) - directory-search-list) - ,@(and module - `("-module" ,module)) - "-o" ,temp-file-name - ,(namestring swig-interface-file-name))))) - #+cmu (unless (or (zerop (ext:process-exit-code process)) - ignore-errors) - (error "Process swig exited abnormally")) - (with-open-file (s temp-file-name) - (read s))))) - -;; Type system - -(defun parse-swigtype (type-string &key start end junk-ok) - "Parse TYPE-STRING as SWIG's internal representation of C/C++ -types. Return two values: The type description (an improper list) and -the terminating index into TYPE-STRING." - ;; SWIG's internal representation is described in Source/Swig/stype.c - (unless start - (setq start 0)) - (unless end - (setq end (length type-string))) - (flet ((prefix-match (prefix) - (let ((position (mismatch prefix type-string :start2 start :end2 end))) - (or (not position) - (= position (length prefix))))) - (bad-type-error (reason) - (error "Bad SWIG type (~A): ~A" reason - (subseq type-string start end))) - (type-char (index) - (and (< index (length type-string)) - (char type-string index))) - (cons-and-recurse (prefix start end) - (multiple-value-bind (type-description index) - (parse-swigtype type-string :start start :end end - :junk-ok junk-ok) - (values (cons prefix type-description) - index)))) - (cond - ((prefix-match "p.") ; pointer - (cons-and-recurse '* (+ start 2) end)) - ((prefix-match "r.") ; C++ reference - (cons-and-recurse '& (+ start 2) end)) - ((prefix-match "a(") ; array - (let ((closing-paren (position #\) type-string - :start (+ start 2) - :end end))) - (unless closing-paren - (bad-type-error "missing right paren")) - (unless (eql (type-char (+ closing-paren 1)) #\.) - (bad-type-error "missing dot")) - (cons-and-recurse (list 'ARRAY (subseq type-string (+ start 2) closing-paren)) - (+ closing-paren 2) end))) - ((prefix-match "q(") ; qualifier (const, volatile) - (let ((closing-paren (position #\) type-string - :start (+ start 2) - :end end))) - (unless closing-paren - (bad-type-error "missing right paren")) - (unless (eql (type-char (+ closing-paren 1)) #\.) - (bad-type-error "missing dot")) - (cons-and-recurse (list 'QUALIFIER (subseq type-string (+ start 2) closing-paren)) - (+ closing-paren 2) end))) - ((prefix-match "m(") ; C++ member pointer - (multiple-value-bind (class-type class-end-index) - (parse-swigtype type-string :junk-ok t - :start (+ start 2) :end end) - (unless (eql (type-char class-end-index) #\)) - (bad-type-error "missing right paren")) - (unless (eql (type-char (+ class-end-index 1)) #\.) - (bad-type-error "missing dot")) - (cons-and-recurse (list 'MEMBER-POINTER class-type) - (+ class-end-index 2) end))) - ((prefix-match "f(") ; function - (loop with index = (+ start 2) - until (eql (type-char index) #\)) - collect (multiple-value-bind (arg-type arg-end-index) - (parse-swigtype type-string :junk-ok t - :start index :end end) - (case (type-char arg-end-index) - (#\, (setq index (+ arg-end-index 1))) - (#\) (setq index arg-end-index)) - (otherwise (bad-type-error "comma or right paren expected"))) - arg-type) - into arg-types - finally (unless (eql (type-char (+ index 1)) #\.) - (bad-type-error "missing dot")) - (return (cons-and-recurse (cons 'FUNCTION arg-types) - (+ index 2) end)))) - ((prefix-match "v(") ;varargs - (let ((closing-paren (position #\) type-string - :start (+ start 2) - :end end))) - (unless closing-paren - (bad-type-error "missing right paren")) - (values (list 'VARARGS (subseq type-string (+ start 2) closing-paren)) - (+ closing-paren 1)))) - (t (let ((junk-position (position-if (lambda (char) - (member char '(#\, #\( #\) #\.))) - type-string - :start start :end end))) - (cond (junk-position ; found junk - (unless junk-ok - (bad-type-error "trailing junk")) - (values (subseq type-string start junk-position) - junk-position)) - (t - (values (subseq type-string start end) - end)))))))) - -(defun swigtype-function-p (swigtype) - "Check whether SWIGTYPE designates a function. If so, the second -value is the list of argument types, and the third value is the return -type." - (if (and (consp swigtype) - (consp (first swigtype)) - (eql (first (first swigtype)) 'FUNCTION)) - (values t (rest (first swigtype)) (rest swigtype)) - (values nil nil nil))) - - -;; UFFI - -(defvar *uffi-definitions* '()) - -(defconstant *uffi-default-primitive-type-alist* - '(("char" . :char) - ("unsigned char" . :unsigned-byte) - ("signed char" . :byte) - ("short" . :short) - ("signed short" . :short) - ("unsigned short" . :unsigned-short) - ("int" . :int) - ("signed int" . :int) - ("unsigned int" . :unsigned-int) - ("long" . :long) - ("signed long" . :long) - ("unsigned long" . :unsigned-long) - ("float" . :float) - ("double" . :double) - ((* . "char") . :cstring) - ((* . "void") . :pointer-void) - ("void" . :void))) - -(defvar *uffi-primitive-type-alist* *uffi-default-primitive-type-alist*) - -(defun uffi-type-spec (type-list) - "Return the UFFI type spec equivalent to TYPE-LIST, or NIL if there -is no representation." - (let ((primitive-type-pair - (assoc type-list *uffi-primitive-type-alist* :test 'equal))) - (cond - (primitive-type-pair - (cdr primitive-type-pair)) - ((and (consp type-list) - (eql (first type-list) '*)) - (let ((base-type-spec (uffi-type-spec (rest type-list)))) - (cond - ((not base-type-spec) - :pointer-void) - (t - (list '* base-type-spec))))) - (t nil)))) - -;; Parse tree - -(defvar *uffi-output* nil) - -(defun emit-uffi-definition (uffi-definition) - (format *uffi-output* "~&~S~%" uffi-definition) - (push uffi-definition *uffi-definitions*)) - -(defun make-cl-symbol (c-identifier &key uninterned) - (let ((name (substitute #\- #\_ (string-upcase c-identifier)))) - (if uninterned - (make-symbol name) - (intern name)))) - -(defvar *class-scope* '() "A stack of names of nested C++ classes.") - -(defvar *struct-fields* '()) - -(defvar *linkage* :C "NIL or :C") - -(defgeneric handle-node (node-type &key &allow-other-keys) - (:documentation "Handle a node of SWIG's parse tree of a C/C++ program")) - -(defmethod handle-node ((node-type t) &key &allow-other-keys) - ;; do nothing for unknown node types - nil) - -(defmethod handle-node ((node-type (eql 'cdecl)) &key name decl storage parms type &allow-other-keys) - (let ((swigtype (parse-swigtype (concatenate 'string decl type)))) - (let ((*print-pretty* nil) ; or FUNCTION would be printed as #' by cmucl - (*print-circle* t)) - (format *uffi-output* "~&;; C Declaration: ~A ~A ~A ~A~%;; with-parms ~W~%;; of-type ~W~%" - storage type name decl parms swigtype)) - (multiple-value-bind (function-p arg-swigtype-list return-swigtype) - (swigtype-function-p swigtype) - (declare (ignore arg-swigtype-list)) - (cond - ((and (null *class-scope*) function-p - (or (eql *linkage* :c) - (string= storage "externc"))) - ;; ordinary top-level function with C linkage - (let ((argnum 0) - (argname-list '())) - (flet ((unique-argname (name) - ;; Sometimes the functions in SWIG interfaces - ;; do not have unique names. Make them unique - ;; by adding a suffix. Also avoid symbols - ;; that are specially bound. - (unless name - (setq name (format nil "arg~D" argnum))) - (let ((argname (make-cl-symbol name))) - (when (boundp argname) ;specially bound - (setq argname (make-cl-symbol name :uninterned t))) - (push argname argname-list) - argname))) - (let ((uffi-arg-list - (mapcan (lambda (param) - (incf argnum) - (destructuring-bind (&key name type &allow-other-keys) param - (let ((uffi-type (uffi-type-spec (parse-swigtype type)))) - (cond - ((not uffi-type) - (format *uffi-output* "~&;; Warning: Cannot handle type ~S of argument `~A'~%" - type name) - (return-from handle-node)) - ((eq uffi-type :void) - '()) - (t - (let ((symbol (unique-argname name))) - (list `(,symbol ,uffi-type)))))))) - parms)) - (uffi-return-type - (uffi-type-spec return-swigtype))) - (unless uffi-return-type - (format *uffi-output* "~&;; Warning: Cannot handle return type `~S'~%" - return-swigtype) - (return-from handle-node)) - (emit-uffi-definition `(UFFI:DEF-FUNCTION ,name ,uffi-arg-list :RETURNING ,uffi-return-type)))))) - ((and (not (null *class-scope*)) (null (rest *class-scope*)) - (not function-p)) ; class/struct member (no nested structs) - (let ((uffi-type (uffi-type-spec swigtype))) - (unless uffi-type - (format *uffi-output* "~&;; Warning: Cannot handle type ~S of struct field `~A'~%" - type name) - (return-from handle-node)) - (push `(,(make-cl-symbol name) ,uffi-type) *struct-fields*))))))) - -(defmethod handle-node ((node-type (eql 'class)) &key name children kind &allow-other-keys) - (format *uffi-output* "~&;; Class ~A~%" name) - (let ((*class-scope* (cons name *class-scope*)) - (*struct-fields* '())) - (dolist (child children) - (apply 'handle-node child)) - (emit-uffi-definition `(,(if (string= kind "union") - 'UFFI:DEF-UNION - 'UFFI:DEF-STRUCT) - ,(make-cl-symbol name) ,@(nreverse *struct-fields*))))) - -(defmethod handle-node ((node-type (eql 'top)) &key children &allow-other-keys) - (dolist (child children) - (apply 'handle-node child))) - -(defmethod handle-node ((node-type (eql 'include)) &key name children &allow-other-keys) - (format *uffi-output* ";; INCLUDE ~A~%" name) - (dolist (child children) - (apply 'handle-node child))) - -(defmethod handle-node ((node-type (eql 'extern)) &key name children &allow-other-keys) - (format *uffi-output* ";; EXTERN \"C\" ~A~%" name) - (let ((*linkage* :c)) - (dolist (child children) - (apply 'handle-node child)))) - -;;(defun compute-uffi-definitions (swig-interface) -;; (let ((*uffi-definitions* '())) -;; (handle-node swig-interface) -;; *uffi-definitions*)) - -;; Test instances - -;;; Link to SWIG itself - -#|| - -(defparameter *c++-compiler* "g++") - -(defun stdc++-library (&key env) - (let ((error-output (make-string-output-stream))) - (let ((name-output (make-string-output-stream))) - (let ((proc (ext:run-program - *c++-compiler* - '("-print-file-name=libstdc++.so") - :env env - :input nil - :output name-output - :error error-output))) - (unless proc - (error "Could not run ~A" *c++-compiler*)) - (unless (zerop (ext:process-exit-code proc)) - (system:serve-all-events 0) - (error "~A failed:~%~A" *c++-compiler* - (get-output-stream-string error-output)))) - (string-right-trim '(#\Newline) (get-output-stream-string name-output))))) - -(defvar *swig-interface* nil) - -(defvar *swig-uffi-pathname* #p"/tmp/swig-uffi.lisp") - -(defun link-swig () - (setq *swig-interface* - (run-swig (merge-pathnames "Source/swig.i" *swig-source-directory*) - :directory-search-list - (list (merge-pathnames "Source/" *swig-source-directory*)) - :module "swig" - :ignore-errors t - :c++ t)) - (with-open-file (f *swig-uffi-pathname* :direction :output) - (let ((*linkage* :c++) - (*uffi-definitions* '()) - (*uffi-output* f) - (*uffi-primitive-type-alist* *uffi-default-primitive-type-alist*)) - (apply 'handle-node *swig-interface*))) - (compile-file *swig-uffi-pathname*) - (alien:load-foreign (merge-pathnames "Source/libswig.a" - *swig-source-directory*) - :libraries (list (stdc++-library))) - ;; FIXME: UFFI stuffes a "-l" in front of the passed library names - ;; (uffi:load-foreign-library (merge-pathnames "Source/libswig.a" - ;; *swig-source-directory*) - ;; :supporting-libraries - ;; (list (stdc++-library))) - (load (compile-file-pathname *swig-uffi-pathname*))) - -||# - -;;;; TODO: - -;; * How to do type lookups? Is everything important that SWIG knows -;; about the types written out? What to make of typemaps? -;; -;; * Wrapped functions should probably automatically COERCE their -;; arguments (as of type DOUBLE-FLOAT), to make the functions more -;; flexible? -;; -;; * Why are the functions created by FFI interpreted? -;; -;; * We can't deal with more complicated structs and C++ classes -;; directly with the FFI; we have to emit SWIG wrappers that access -;; those classes. -;; -;; * A CLOS layer where structure fields are mapped as slots. It -;; looks like we need MOP functions to implement this. -;; -;; * Maybe modify SWIG so that key-value hashes are distinguished from -;; value-value hashes. diff --git a/Examples/scilab/check.list b/Examples/scilab/check.list index 0bcf457c2..d57cfab64 100644 --- a/Examples/scilab/check.list +++ b/Examples/scilab/check.list @@ -13,4 +13,3 @@ std_vector struct template variables - diff --git a/Examples/test-suite/abstract_basecast.i b/Examples/test-suite/abstract_basecast.i new file mode 100644 index 000000000..b6a21aa64 --- /dev/null +++ b/Examples/test-suite/abstract_basecast.i @@ -0,0 +1,20 @@ +%module abstract_basecast + +%inline %{ +class BaseClass { +public: + virtual ~BaseClass() { } + + virtual void g() = 0; +}; + +class DerivedClass : public BaseClass { +public: + + virtual void g() { } + + BaseClass& f() { + return *this; + } +}; +%} diff --git a/Examples/test-suite/abstract_signature.i b/Examples/test-suite/abstract_signature.i index 5d68fd0a9..8d4199844 100644 --- a/Examples/test-suite/abstract_signature.i +++ b/Examples/test-suite/abstract_signature.i @@ -7,8 +7,8 @@ class abstract_foo { public: - abstract_foo() { }; - virtual ~abstract_foo() { }; + abstract_foo() { } + virtual ~abstract_foo() { } virtual int meth(int meth_param) = 0; }; @@ -16,9 +16,9 @@ public: class abstract_bar : public abstract_foo { public: - abstract_bar() { }; + abstract_bar() { } - virtual ~abstract_bar() { }; + virtual ~abstract_bar() { } virtual int meth(int meth_param) = 0; int meth(int meth_param_1, int meth_param_2) { return 0; } }; diff --git a/Examples/test-suite/aggregate.i b/Examples/test-suite/aggregate.i index dc00f0605..8ac31ece7 100644 --- a/Examples/test-suite/aggregate.i +++ b/Examples/test-suite/aggregate.i @@ -6,7 +6,7 @@ To support contracts, you need to add a macro to the runtime. For Python, it looks like this: -#define SWIG_contract_assert(expr, msg) if (!(expr)) { PyErr_SetString(PyExc_RuntimeError, (char *) msg #expr ); goto fail; } else +#define SWIG_contract_assert(expr, msg) do { if (!(expr)) { PyErr_SetString(PyExc_RuntimeError, (char *) msg #expr ); goto fail; } } while (0) Note: It is used like this: SWIG_contract_assert(x == 1, "Some kind of error message"); diff --git a/Examples/test-suite/allegrocl/Makefile.in b/Examples/test-suite/allegrocl/Makefile.in deleted file mode 100644 index b13d546da..000000000 --- a/Examples/test-suite/allegrocl/Makefile.in +++ /dev/null @@ -1,126 +0,0 @@ -####################################################################### -# Makefile for allegrocl test-suite -####################################################################### - -LANGUAGE = allegrocl -ALLEGROCL = @ALLEGROCLBIN@ -SCRIPTSUFFIX = _runme.lisp - -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ -top_builddir = @top_builddir@ - - -# these cpp tests generate warnings/errors when compiling -# the wrapper .cxx file. -CPP_TEST_BROKEN_CXX = -# the error is wrap:action code generated by swig. \ -# error: can't convert [std::string] 'b' to 'bool' \ -# might just need a bool overload op for std::string. \ - global_vars \ -# same as w/ global_vars but with more errors in cxx file \ - naturalvar \ - -# these cpp tests aren't working. Fix 'em -# need to further separate these into tests requiring -# std libraries, or the $ldestructor problem. -CPP_TEST_BROKEN_ACL = \ - contract \ - allprotected \ -# 'throws' typemap entries. \ - cplusplus_throw \ -# 'throws' typemap entries. \ - default_args \ -# missing typemaps. suspect module support needed \ - dynamic_cast \ - extend_variable \ -# cdata.i support needed \ - li_cdata_cpp \ -# warning generated. otherwise all good. \ - operator_overload \ -# std_common.i support \ - sizet \ -# std_vector.i support. \ - template_default \ -# *** line 31. can't copy typemap?? \ - typemap_namespace \ - -# these aren't working due to longlong support. (low hanging fruit) -CPP_TEST_BROKEN_LONGLONG = \ - arrays_dimensionless \ - arrays_global \ - arrays_global_twodim \ - li_typemaps \ - li_windows \ - long_long_apply \ - primitive_ref \ - reference_global_vars \ - template_default_arg - -# These are currently unsupported. -CPP_TEST_CASES_ACL_UNSUPPORTED = \ -# contract support \ - aggregate \ -# directors support \ - apply_signed_char \ -# contract support \ - contract \ - director_exception \ - director_protected \ - exception_order \ -# 'throws' typemap support \ - extern_throws \ - throw_exception \ - using_pointers \ - -C_TEST_CASES_ACL_BROKEN = \ -# 'cdate.i' module support \ - li_cdata \ -# adding an existing type defnition... \ - typedef_struct \ -# swigrun.swg support. \ - typemap_subst - -C_TEST_BROKEN_LONGLONG = \ - long_long - - -# std lib support hasn't been done yet. -SKIP_CPP_STD_CASES = Yes - -include $(srcdir)/../common.mk - -# Overridden variables here -# SWIGOPT += -debug-module 4 - -# Custom tests - tests with additional commandline options -# none! - -# Rules for the different types of tests -%.cpptest: - $(setup) - +$(swig_and_compile_cpp) - $(run_testcase) - -%.ctest: - $(setup) - +$(swig_and_compile_c) - $(run_testcase) - -%.multicpptest: - $(setup) - +$(swig_and_compile_multi_cpp) - $(run_testcase) - -# Runs the testcase. A testcase is only run if -# a file is found which has _runme.lisp appended after the testcase name. -run_testcase = \ - if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(ALLEGROCLBIN) -batch -s $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ - fi - -%.clean: - @rm -f $*.cl - -clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" allegrocl_clean diff --git a/Examples/test-suite/allowexcept.i b/Examples/test-suite/allowexcept.i index c901295df..229e65cc9 100644 --- a/Examples/test-suite/allowexcept.i +++ b/Examples/test-suite/allowexcept.i @@ -26,17 +26,6 @@ UVW Bar::static_member_variable; struct XYZ { }; -// The operator& trick doesn't work for SWIG/PHP because the generated code -// takes the address of the variable in the code in the "vinit" section. -#ifdef SWIGPHP -%{ -struct XYZ { - void foo() {} -private: - XYZ& operator=(const XYZ& other); // prevent assignment used in normally generated set method -}; -%} -#else %{ struct XYZ { void foo() {} @@ -45,7 +34,6 @@ private: XYZ* operator&(); // prevent dereferencing used in normally generated get method }; %} -#endif #if defined(SWIGUTL) %exception { /* diff --git a/Examples/test-suite/apply_signed_char.i b/Examples/test-suite/apply_signed_char.i index d3116f024..a33b285a3 100644 --- a/Examples/test-suite/apply_signed_char.i +++ b/Examples/test-suite/apply_signed_char.i @@ -35,7 +35,5 @@ const char memberconstchar; virtual ~DirectorTest() {} - private: - DirectorTest& operator=(const DirectorTest &); }; %} diff --git a/Examples/test-suite/apply_strings.i b/Examples/test-suite/apply_strings.i index 695dd068f..14283bb11 100644 --- a/Examples/test-suite/apply_strings.i +++ b/Examples/test-suite/apply_strings.i @@ -44,8 +44,6 @@ // unsigned char* as strings #if defined(SWIGJAVA) || defined(SWIGCSHARP) -/* Note: Chicken does not allow unsigned char * in strings */ - %apply char [ANY] {TAscii[ANY]} %apply char [] {TAscii []} %apply char * {TAscii *} diff --git a/Examples/test-suite/bools.i b/Examples/test-suite/bools.i index 2ef3d93a6..0c4f9d661 100644 --- a/Examples/test-suite/bools.i +++ b/Examples/test-suite/bools.i @@ -62,8 +62,6 @@ struct BoolStructure { m_rbool(m_bool2), m_const_pbool(m_pbool), m_const_rbool(m_rbool) {} -private: - BoolStructure& operator=(const BoolStructure &); }; %} diff --git a/Examples/test-suite/callback.i b/Examples/test-suite/callback.i index 4db63353b..e406615bb 100644 --- a/Examples/test-suite/callback.i +++ b/Examples/test-suite/callback.i @@ -13,6 +13,7 @@ %callback("%s") A::foom; #endif %callback("%(uppercase)s_Cb_Ptr") foo_T; // this works in Python too +%callback("%s_cb") identity_finger; %inline %{ @@ -85,6 +86,15 @@ const T& ident(const T& x) { return x; } + + // Test callbacks for enum types + typedef enum {One, Two, Three, Four, Five} finger; + typedef finger (*finger_finger)(finger); + finger identity_finger(finger f) { return f; } + finger apply_finger_cb(finger f, finger_finger cb) { + return cb(f); + } + %} %template(foo_i) foo_T; diff --git a/Examples/test-suite/ccomplextest.i b/Examples/test-suite/ccomplextest.i new file mode 100644 index 000000000..c631dc02e --- /dev/null +++ b/Examples/test-suite/ccomplextest.i @@ -0,0 +1,81 @@ +%module ccomplextest + +%include + +%{ +#include + +#if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199001L +#define HAS_C99_COMPLEX_FOR_TESTING 1 +#else +/* c99 complex not supported - super hack tests to just test plain floating point numbers */ +/* some pre c99 compilers (gcc-4.x) don't define _Complex but do define complex */ +#define _Complex +#if !defined(complex) +# define complex +#endif +#define conj +#define conjf +#define creal +#define cimag +#if defined(I) +# undef I +# define I 1 +#endif +#define HAS_C99_COMPLEX_FOR_TESTING 0 +#endif +%} + +%inline +{ + int has_c99_complex(void) { + return HAS_C99_COMPLEX_FOR_TESTING; + } + + complex double Conj(complex double a) + { + return conj(a); + } + + + complex float Conjf(complex float a) + { + return conjf(a); + } + + + double complex Conj1(double complex a) + { + return conj(a); + } + + + float complex Conjf1(float complex a) + { + return conjf(a); + } + + + _Complex double Conj2(_Complex double a) + { + return conj(a); + } + + + _Complex float Conjf2(_Complex float a) + { + return conjf(a); + } + + + double _Complex Conj3(double _Complex a) + { + return conj(a); + } + + + float _Complex Conjf3(float _Complex a) + { + return conjf(a); + } +} diff --git a/Examples/test-suite/cffi/Makefile.in b/Examples/test-suite/cffi/Makefile.in index 6eebaa07c..b2e86e102 100644 --- a/Examples/test-suite/cffi/Makefile.in +++ b/Examples/test-suite/cffi/Makefile.in @@ -43,7 +43,7 @@ run_testcase = \ env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(CFFI) -batch -s $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ fi -# Clean: (does nothing, we dont generate extra cffi code) +# Clean: (does nothing, we don't generate extra cffi code) %.clean: @exit 0 diff --git a/Examples/test-suite/char_strings.i b/Examples/test-suite/char_strings.i index 9a87df4e3..aa3b125ce 100644 --- a/Examples/test-suite/char_strings.i +++ b/Examples/test-suite/char_strings.i @@ -11,6 +11,7 @@ below. %{ #include +#include #define OTHERLAND_MSG "Little message from the safe world." #define CPLUSPLUS_MSG "A message from the deep dark world of C++, where anything is possible." @@ -150,11 +151,11 @@ const char global_const_char_array2[sizeof(CPLUSPLUS_MSG)+1] = CPLUSPLUS_MSG; %inline { struct Formatpos; struct OBFormat; - + static int GetNextFormat(Formatpos& itr, const char*& str,OBFormat*& pFormat) { return 0; } - + } diff --git a/Examples/test-suite/chicken/Makefile.in b/Examples/test-suite/chicken/Makefile.in deleted file mode 100644 index b3dccc9c3..000000000 --- a/Examples/test-suite/chicken/Makefile.in +++ /dev/null @@ -1,101 +0,0 @@ -####################################################################### -# Makefile for chicken test-suite -####################################################################### - -LANGUAGE = chicken -VARIANT = -SCRIPTSUFFIX = _runme.ss -PROXYSUFFIX = _runme_proxy.ss - -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ -top_builddir = @top_builddir@ - -CHICKEN_CSI = @CHICKEN_CSI@ -quiet -batch -no-init -SO = @SO@ - -#C_TEST_CASES = long_long list_vector pointer_in_out multivalue - -# Skip the STD cases for now, except for li_std_string.i -SKIP_CPP_STD_CASES = Yes - -CPP_TEST_CASES += li_std_string - -EXTRA_TEST_CASES += chicken_ext_test.externaltest - -include $(srcdir)/../common.mk - -# Overridden variables here -SWIGOPT += -nounit - -# Custom tests - tests with additional commandline options -# If there exists a PROXYSUFFIX runme file, we also generate the wrapper -# with the -proxy argument -%.cppproxy: SWIGOPT += -proxy -%.cppproxy: SCRIPTSUFFIX = $(PROXYSUFFIX) - -%.cproxy: SWIGOPT += -proxy -%.cproxy: SCRIPTSUFFIX = $(PROXYSUFFIX) - -%.multiproxy: SWIGOPT += -proxy -noclosuses -%.multiproxy: SCRIPTSUFFIX = $(PROXYSUFFIX) - -# Rules for the different types of tests -%.cpptest: - $(setup) - +$(swig_and_compile_cpp) - $(run_testcase) - if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(PROXYSUFFIX) ]; then \ - $(MAKE) $*.cppproxy; \ - fi - -%.ctest: - $(setup) - +$(swig_and_compile_c) - $(run_testcase) - if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(PROXYSUFFIX) ]; then \ - $(MAKE) $*.cproxy; \ - fi - -%.multicpptest: - $(setup) - +$(swig_and_compile_multi_cpp) - $(run_testcase) - if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(PROXYSUFFIX) ]; then \ - $(MAKE) $*.multiproxy; \ - fi - -%.externaltest: - $(setup) - +$(swig_and_compile_external) - $(run_testcase) - -%.cppproxy: - echo "$(ACTION)ing $(LANGUAGE) testcase $* (with run test) with -proxy" - +$(swig_and_compile_cpp) - $(run_testcase) - -%.cproxy: - echo "$(ACTION)ing $(LANGUAGE) testcase $* (with run test) with -proxy" - +$(swig_and_compile_c) - $(run_testcase) - -%.multiproxy: - echo "$(ACTION)ing $(LANGUAGE) testcase $* (with run test) with -proxy" - +$(swig_and_compile_multi_cpp) - $(run_testcase) - -# Runs the testcase. A testcase is only run if -# a file is found which has _runme.scm appended after the testcase name. -run_testcase = \ - if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(CHICKEN_CSI) $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ - fi - -# Clean -%.clean: - @exit 0 - -clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' chicken_clean - rm -f *.scm diff --git a/Examples/test-suite/chicken/README b/Examples/test-suite/chicken/README deleted file mode 100644 index aad730ec4..000000000 --- a/Examples/test-suite/chicken/README +++ /dev/null @@ -1,11 +0,0 @@ -See ../README for common README file. - -Any testcases which have _runme.ss appended after the testcase name will be detected and run. -NOTE: I had to use _runme.ss because otherwise it would be hard to implement make clean -Since when SWIG runs it generates an example.scm file for every test, to clean those files -I needed to add a rm -f *.scm to make clean. But we don't want the runme scripts to -disappear as well! - -Any testcases which have _runme_proxy.ss appended after the testcase name will be detected -and run with the -proxy argument passed to SWIG. SWIG will not be run with the -unhide-primitive -option, so the _runme_proxy.ss file must use only the tinyclos exported interface. diff --git a/Examples/test-suite/chicken/casts_runme.ss b/Examples/test-suite/chicken/casts_runme.ss deleted file mode 100644 index 2eca46149..000000000 --- a/Examples/test-suite/chicken/casts_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "casts.so") -(include "../schemerunme/casts.scm") diff --git a/Examples/test-suite/chicken/char_constant_runme.ss b/Examples/test-suite/chicken/char_constant_runme.ss deleted file mode 100644 index 50dff3018..000000000 --- a/Examples/test-suite/chicken/char_constant_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "char_constant.so") -(include "../schemerunme/char_constant.scm") diff --git a/Examples/test-suite/chicken/chicken_ext_test_external.cxx b/Examples/test-suite/chicken/chicken_ext_test_external.cxx deleted file mode 100644 index 1dd6a7d53..000000000 --- a/Examples/test-suite/chicken/chicken_ext_test_external.cxx +++ /dev/null @@ -1,21 +0,0 @@ -#include -#include - -void test_create(C_word,C_word,C_word) C_noret; -void test_create(C_word argc, C_word closure, C_word continuation) { - C_word resultobj; - swig_type_info *type; - A *newobj; - C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER); - - C_trace("test-create"); - if (argc!=2) C_bad_argc(argc,2); - - - newobj = new A(); - - type = SWIG_TypeQuery("A *"); - resultobj = SWIG_NewPointerObj(newobj, type, 1); - - C_kontinue(continuation, resultobj); -} diff --git a/Examples/test-suite/chicken/chicken_ext_test_runme.ss b/Examples/test-suite/chicken/chicken_ext_test_runme.ss deleted file mode 100644 index 65fa4e085..000000000 --- a/Examples/test-suite/chicken/chicken_ext_test_runme.ss +++ /dev/null @@ -1,5 +0,0 @@ -(load "chicken_ext_test.so") - -(define a (test-create)) - -(A-hello a) diff --git a/Examples/test-suite/chicken/class_ignore_runme.ss b/Examples/test-suite/chicken/class_ignore_runme.ss deleted file mode 100644 index ba84810a3..000000000 --- a/Examples/test-suite/chicken/class_ignore_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "class_ignore.so") -(include "../schemerunme/class_ignore.scm") diff --git a/Examples/test-suite/chicken/clientdata_prop_runme_proxy.ss b/Examples/test-suite/chicken/clientdata_prop_runme_proxy.ss deleted file mode 100644 index 62f2c2053..000000000 --- a/Examples/test-suite/chicken/clientdata_prop_runme_proxy.ss +++ /dev/null @@ -1,95 +0,0 @@ -(require 'clientdata_prop_a) -(require 'clientdata_prop_b) - -(define a (make )) -(test-A a) -(test-tA a) -(test-t2A a) -(test-t3A a) -(fA a) - -(define b (make )) -(test-A b) -(test-tA b) -(test-t2A b) -(test-t3A b) -(test-B b) -(fA b) -(fB b) - -(define c (make )) -(test-A c) -(test-tA c) -(test-t2A c) -(test-t3A c) -(test-C c) -(fA c) -(fC c) - -(define d (make )) -(test-A d) -(test-tA d) -(test-t2A d) -(test-t3A d) -(test-D d) -(test-tD d) -(test-t2D d) -(fA d) -(fD d) - -;; here are the real tests... if the clientdata is correctly -;; propegated, new-tA, new-t2A, should all return wrapped proxy's -;; of class - -(define a2 (new-tA)) -(if (not (eq? (class-of a2) )) - (error "Error 1")) -(test-A a2) -(test-tA a2) -(test-t2A a2) -(test-t3A a2) -(fA a2) - -(define a3 (new-t2A)) -(if (not (eq? (class-of a3) )) - (error "Error 2")) -(test-A a3) -(test-tA a3) -(test-t2A a3) -(test-t3A a3) -(fA a3) - -(define a4 (new-t3A)) -(if (not (eq? (class-of a4) )) - (error "Error 3")) -(test-A a4) -(test-tA a4) -(test-t2A a4) -(test-t3A a4) -(fA a4) - -(define d2 (new-tD)) -(if (not (eq? (class-of d2) )) - (error "Error 4")) -(test-A d2) -(test-tA d2) -(test-t2A d2) -(test-t3A d2) -(test-D d2) -(test-tD d2) -(fA d2) -(fD d2) - -(define d3 (new-t2D)) -(if (not (eq? (class-of d3) )) - (error "Error 5")) -(test-A d3) -(test-tA d3) -(test-t2A d3) -(test-t3A d3) -(test-D d3) -(test-tD d3) -(fA d3) -(fD d3) - -(exit 0) diff --git a/Examples/test-suite/chicken/constover_runme.ss b/Examples/test-suite/chicken/constover_runme.ss deleted file mode 100644 index eb39c7ff0..000000000 --- a/Examples/test-suite/chicken/constover_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "constover.so") -(include "../schemerunme/constover.scm") diff --git a/Examples/test-suite/chicken/contract_runme.ss b/Examples/test-suite/chicken/contract_runme.ss deleted file mode 100644 index 006bcfdec..000000000 --- a/Examples/test-suite/chicken/contract_runme.ss +++ /dev/null @@ -1,3 +0,0 @@ -(load "contract.so") -(include "testsuite.ss") -(include "../schemerunme/contract.scm") diff --git a/Examples/test-suite/chicken/cpp_basic_runme_proxy.ss b/Examples/test-suite/chicken/cpp_basic_runme_proxy.ss deleted file mode 100644 index 7b0b6d722..000000000 --- a/Examples/test-suite/chicken/cpp_basic_runme_proxy.ss +++ /dev/null @@ -1,64 +0,0 @@ -(require 'cpp_basic) - -(define-macro (check test) - `(if (not ,test) (error "Error in test " ',test))) - -(define f (make 4)) -(check (= (slot-ref f 'num) 4)) -(slot-set! f 'num -17) -(check (= (slot-ref f 'num) -17)) - -(define b (make )) - -(slot-set! b 'fptr f) -(check (= (slot-ref (slot-ref b 'fptr) 'num) -17)) -(check (= (test b -3 (slot-ref b 'fptr)) -5)) -(slot-set! f 'num 12) -(check (= (slot-ref (slot-ref b 'fptr) 'num) 12)) - -(check (= (slot-ref (slot-ref b 'fref) 'num) -4)) -(check (= (test b 12 (slot-ref b 'fref)) 23)) -;; references don't take ownership, so if we didn't define this here it might get garbage collected -(define f2 (make 23)) -(slot-set! b 'fref f2) -(check (= (slot-ref (slot-ref b 'fref) 'num) 23)) -(check (= (test b -3 (slot-ref b 'fref)) 35)) - -(check (= (slot-ref (slot-ref b 'fval) 'num) 15)) -(check (= (test b 3 (slot-ref b 'fval)) 33)) -(slot-set! b 'fval (make -15)) -(check (= (slot-ref (slot-ref b 'fval) 'num) -15)) -(check (= (test b 3 (slot-ref b 'fval)) -27)) - -(define f3 (testFoo b 12 (slot-ref b 'fref))) -(check (= (slot-ref f3 'num) 32)) - -;; now test global -(define f4 (make 6)) -(Bar-global-fptr f4) -(check (= (slot-ref (Bar-global-fptr) 'num) 6)) -(slot-set! f4 'num 8) -(check (= (slot-ref (Bar-global-fptr) 'num) 8)) - -(check (= (slot-ref (Bar-global-fref) 'num) 23)) -(Bar-global-fref (make -7)) -(check (= (slot-ref (Bar-global-fref) 'num) -7)) - -(check (= (slot-ref (Bar-global-fval) 'num) 3)) -(Bar-global-fval (make -34)) -(check (= (slot-ref (Bar-global-fval) 'num) -34)) - -;; Now test function pointers -(define func1ptr (get-func1-ptr)) -(define func2ptr (get-func2-ptr)) - -(slot-set! f 'num 4) -(check (= (func1 f 2) 16)) -(check (= (func2 f 2) -8)) - -(slot-set! f 'func-ptr func1ptr) -(check (= (test-func-ptr f 2) 16)) -(slot-set! f 'func-ptr func2ptr) -(check (= (test-func-ptr f 2) -8)) - -(exit 0) diff --git a/Examples/test-suite/chicken/cpp_enum_runme.ss b/Examples/test-suite/chicken/cpp_enum_runme.ss deleted file mode 100644 index 4d4ec7623..000000000 --- a/Examples/test-suite/chicken/cpp_enum_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "cpp_enum.so") -(include "../schemerunme/cpp_enum.scm") diff --git a/Examples/test-suite/chicken/cpp_namespace_runme.ss b/Examples/test-suite/chicken/cpp_namespace_runme.ss deleted file mode 100644 index 800172ed8..000000000 --- a/Examples/test-suite/chicken/cpp_namespace_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "cpp_namespace.so") -(include "../schemerunme/cpp_namespace.scm") diff --git a/Examples/test-suite/chicken/dynamic_cast_runme.ss b/Examples/test-suite/chicken/dynamic_cast_runme.ss deleted file mode 100644 index 1e81d5555..000000000 --- a/Examples/test-suite/chicken/dynamic_cast_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "dynamic_cast.so") -(include "../schemerunme/dynamic_cast.scm") diff --git a/Examples/test-suite/chicken/global_vars_runme.ss b/Examples/test-suite/chicken/global_vars_runme.ss deleted file mode 100644 index 802205b7c..000000000 --- a/Examples/test-suite/chicken/global_vars_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(require 'global_vars) -(load "../schemerunme/global_vars.scm") diff --git a/Examples/test-suite/chicken/global_vars_runme_proxy.ss b/Examples/test-suite/chicken/global_vars_runme_proxy.ss deleted file mode 100644 index 3c4500d6b..000000000 --- a/Examples/test-suite/chicken/global_vars_runme_proxy.ss +++ /dev/null @@ -1,2 +0,0 @@ -(require 'global_vars) -(load "../schemerunme/global_vars_proxy.scm") diff --git a/Examples/test-suite/chicken/import_nomodule_runme.ss b/Examples/test-suite/chicken/import_nomodule_runme.ss deleted file mode 100644 index 7e64053bc..000000000 --- a/Examples/test-suite/chicken/import_nomodule_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "import_nomodule.so") -(include "../schemerunme/import_nomodule.scm") diff --git a/Examples/test-suite/chicken/imports_runme.ss b/Examples/test-suite/chicken/imports_runme.ss deleted file mode 100644 index ac5fb9890..000000000 --- a/Examples/test-suite/chicken/imports_runme.ss +++ /dev/null @@ -1,3 +0,0 @@ -(load "imports_a.so") -(load "imports_b.so") -(include "../schemerunme/imports.scm") diff --git a/Examples/test-suite/chicken/inherit_missing_runme.ss b/Examples/test-suite/chicken/inherit_missing_runme.ss deleted file mode 100644 index 50a084a95..000000000 --- a/Examples/test-suite/chicken/inherit_missing_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "inherit_missing.so") -(include "../schemerunme/inherit_missing.scm") diff --git a/Examples/test-suite/chicken/li_std_string_runme.ss b/Examples/test-suite/chicken/li_std_string_runme.ss deleted file mode 100644 index cc64287dd..000000000 --- a/Examples/test-suite/chicken/li_std_string_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "li_std_string.so") -(include "../schemerunme/li_std_string.scm") diff --git a/Examples/test-suite/chicken/li_std_string_runme_proxy.ss b/Examples/test-suite/chicken/li_std_string_runme_proxy.ss deleted file mode 100644 index e1e240970..000000000 --- a/Examples/test-suite/chicken/li_std_string_runme_proxy.ss +++ /dev/null @@ -1,47 +0,0 @@ -(load "li_std_string.so") - -(define x "hello") - -(if (not (string=? (test-value x) x)) - (begin (error "Error 1") (exit 1))) - -(if (not (string=? (test-const-reference x) x)) - (begin (error "Error 2") (exit 1))) - -(define y (test-pointer-out)) -(test-pointer y) -(define z (test-const-pointer-out)) -(test-const-pointer z) - -(define a (test-reference-out)) -(test-reference a) - -;; test global variables -(GlobalString "whee") -(if (not (string=? (GlobalString) "whee")) - (error "Error 3")) -(if (not (string=? (GlobalString2) "global string 2")) - (error "Error 4")) - -(define struct (make )) - -;; MemberString should be a wrapped class -(if (not (string=? (slot-ref struct 'MemberString) "")) - (error "Error 4.5")) -;(slot-set! (slot-ref struct 'MemberString) "and how") -;;(if (not (string=? (slot-ref struct 'MemberString) "and how")) -;; (error "Error 5")) -(if (not (string=? (slot-ref struct 'MemberString2) "member string 2")) - (error "Error 6")) -(Structure-StaticMemberString "static str") -(if (not (string=? (Structure-StaticMemberString) "static str")) - (error "Error 7")) -(if (not (string=? (Structure-StaticMemberString2) "static member string 2")) - (error "Error 8")) - -;(if (not (string=? (Structure-ConstMemberString-get struct) "const member string")) -; (error "Error 9")) -(if (not (string=? (Structure-ConstStaticMemberString) "const static member string")) - (error "Error 10")) - -(exit 0) diff --git a/Examples/test-suite/chicken/li_typemaps_runme.ss b/Examples/test-suite/chicken/li_typemaps_runme.ss deleted file mode 100644 index 1ad6e921e..000000000 --- a/Examples/test-suite/chicken/li_typemaps_runme.ss +++ /dev/null @@ -1,12 +0,0 @@ -(require 'li_typemaps) -(load "../schemerunme/li_typemaps.scm") - -(call-with-values (lambda () (inoutr-int2 3 -2)) - (lambda (a b) - (if (not (and (= a 3) (= b -2))) - (error "Error in inoutr-int2")))) -(call-with-values (lambda () (out-foo 4)) - (lambda (a b) - (if (not (and (= (Foo-a-get a) 4) (= b 8))) - (error "Error in out-foo")))) -(exit 0) diff --git a/Examples/test-suite/chicken/li_typemaps_runme_proxy.ss b/Examples/test-suite/chicken/li_typemaps_runme_proxy.ss deleted file mode 100644 index 52997c6fe..000000000 --- a/Examples/test-suite/chicken/li_typemaps_runme_proxy.ss +++ /dev/null @@ -1,13 +0,0 @@ -(require 'li_typemaps) -(load "../schemerunme/li_typemaps_proxy.scm") - -(call-with-values (lambda () (inoutr-int2 3 -2)) - (lambda (a b) - (if (not (and (= a 3) (= b -2))) - (error "Error in inoutr-int2")))) -(call-with-values (lambda () (out-foo 4)) - (lambda (a b) - (if (not (and (= (slot-ref a 'a) 4) (= b 8))) - (error "Error in out-foo")))) - -(exit 0) diff --git a/Examples/test-suite/chicken/list_vector_runme.ss b/Examples/test-suite/chicken/list_vector_runme.ss deleted file mode 100644 index 67d52f609..000000000 --- a/Examples/test-suite/chicken/list_vector_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "list_vector.so") -(include "../schemerunme/list_vector.scm") diff --git a/Examples/test-suite/chicken/member_pointer_runme.ss b/Examples/test-suite/chicken/member_pointer_runme.ss deleted file mode 100644 index f2226b20a..000000000 --- a/Examples/test-suite/chicken/member_pointer_runme.ss +++ /dev/null @@ -1,28 +0,0 @@ -(require 'member_pointer) - -(define (check-eq? msg expected actual) - (if (not (= expected actual)) - (error "Error " msg ": expected " expected " got " actual))) - -(define area-pt (areapt)) -(define perim-pt (perimeterpt)) - -(define s (new-Square 10)) - -(check-eq? "Square area" 100.0 (do-op s area-pt)) -(check-eq? "Square perim" 40.0 (do-op s perim-pt)) - -(check-eq? "Square area" 100.0 (do-op s (areavar))) -(check-eq? "Square perim" 40.0 (do-op s (perimetervar))) - -;; Set areavar to return value of function -(areavar perim-pt) -(check-eq? "Square perim" 40 (do-op s (areavar))) - -(check-eq? "Square area" 100.0 (do-op s (AREAPT))) -(check-eq? "Square perim" 40.0 (do-op s (PERIMPT))) - -(define test (NULLPT)) - -(perimetervar (AREAPT)) -(check-eq? "Square area" 100.0 (do-op s (perimetervar))) diff --git a/Examples/test-suite/chicken/multiple_inheritance_runme_proxy.ss b/Examples/test-suite/chicken/multiple_inheritance_runme_proxy.ss deleted file mode 100644 index 313157c70..000000000 --- a/Examples/test-suite/chicken/multiple_inheritance_runme_proxy.ss +++ /dev/null @@ -1,2 +0,0 @@ -(require 'multiple_inheritance) -(load "../schemerunme/multiple_inheritance_proxy.scm") diff --git a/Examples/test-suite/chicken/multivalue_runme.ss b/Examples/test-suite/chicken/multivalue_runme.ss deleted file mode 100644 index f5aafcbf4..000000000 --- a/Examples/test-suite/chicken/multivalue_runme.ss +++ /dev/null @@ -1,4 +0,0 @@ -;; this doesn't work yet :( -(load "multivalue.so") -(include "../schemerunme/multivalue.scm") -(exit 0) diff --git a/Examples/test-suite/chicken/name_runme.ss b/Examples/test-suite/chicken/name_runme.ss deleted file mode 100644 index 938915dcb..000000000 --- a/Examples/test-suite/chicken/name_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "name.so") -(include "../schemerunme/name.scm") diff --git a/Examples/test-suite/chicken/newobject1_runme_proxy.ss b/Examples/test-suite/chicken/newobject1_runme_proxy.ss deleted file mode 100644 index 7bc5a241a..000000000 --- a/Examples/test-suite/chicken/newobject1_runme_proxy.ss +++ /dev/null @@ -1,30 +0,0 @@ -(require 'newobject1) - -(define-macro (check-count val) - `(if (not (= (Foo-fooCount) ,val)) (error "Error checking val " ,val " != " ,(Foo-fooCount)))) - -(define f (Foo-makeFoo)) - -(check-count 1) - -(define f2 (makeMore f)) - -(check-count 2) - -(set! f #f) -(gc #t) - -(check-count 1) - -(define f3 (makeMore f2)) - -(check-count 2) - -(set! f3 #f) -(set! f2 #f) - -(gc #t) - -(check-count 0) - -(exit 0) diff --git a/Examples/test-suite/chicken/newobject2_runme.ss b/Examples/test-suite/chicken/newobject2_runme.ss deleted file mode 100644 index cc445f477..000000000 --- a/Examples/test-suite/chicken/newobject2_runme.ss +++ /dev/null @@ -1,29 +0,0 @@ -(load "newobject2.so") - -(define f (new-Foo)) - -(Foo-dummy-set f 14) -(if (not (= (Foo-dummy-get f) 14)) - (error "Bad dummy value")) - -(if (not (= (fooCount) 0)) - (error "Bad foo count 1")) - -(define f2 (makeFoo)) - -(if (not (= (fooCount) 1)) - (error "Bad foo count 2")) - -(Foo-dummy-set f2 16) -(if (not (= (Foo-dummy-get f2) 16)) - (error "Bad dummy value for f2")) - -(set! f #f) -(set! f2 #f) - -(gc #t) - -(if (not (= (fooCount) -1)) - (error "Bad foo count 3")) - -(exit 0) diff --git a/Examples/test-suite/chicken/newobject2_runme_proxy.ss b/Examples/test-suite/chicken/newobject2_runme_proxy.ss deleted file mode 100644 index 36b8cda7f..000000000 --- a/Examples/test-suite/chicken/newobject2_runme_proxy.ss +++ /dev/null @@ -1,29 +0,0 @@ -(load "newobject2.so") - -(define f (make )) - -(slot-set! f 'dummy 14) -(if (not (= (slot-ref f 'dummy) 14)) - (error "Bad dummy value")) - -(if (not (= (fooCount) 0)) - (error "Bad foo count 1")) - -(define f2 (makeFoo)) - -(if (not (= (fooCount) 1)) - (error "Bad foo count 2")) - -(slot-set! f2 'dummy 16) -(if (not (= (slot-ref f2 'dummy) 16)) - (error "Bad dummy value for f2")) - -(set! f #f) -(set! f2 #f) - -(gc #t) - -(if (not (= (fooCount) -1)) - (error "Bad foo count 3")) - -(exit 0) diff --git a/Examples/test-suite/chicken/overload_complicated_runme.ss b/Examples/test-suite/chicken/overload_complicated_runme.ss deleted file mode 100644 index f89f70bde..000000000 --- a/Examples/test-suite/chicken/overload_complicated_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "overload_complicated.so") -(include "../schemerunme/overload_complicated.scm") diff --git a/Examples/test-suite/chicken/overload_copy_runme.ss b/Examples/test-suite/chicken/overload_copy_runme.ss deleted file mode 100644 index 4ec542205..000000000 --- a/Examples/test-suite/chicken/overload_copy_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "overload_copy.so") -(include "../schemerunme/overload_copy.scm") diff --git a/Examples/test-suite/chicken/overload_copy_runme_proxy.ss b/Examples/test-suite/chicken/overload_copy_runme_proxy.ss deleted file mode 100644 index 5f4808070..000000000 --- a/Examples/test-suite/chicken/overload_copy_runme_proxy.ss +++ /dev/null @@ -1,6 +0,0 @@ -(load "./overload_copy.so") - -(define f (make )) -(define g (make f)) - -(exit 0) diff --git a/Examples/test-suite/chicken/overload_extend_c_runme.ss b/Examples/test-suite/chicken/overload_extend_c_runme.ss deleted file mode 100644 index 75c0ea8a8..000000000 --- a/Examples/test-suite/chicken/overload_extend_c_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "overload_extend_c.so") -(include "../schemerunme/overload_extend_c.scm") diff --git a/Examples/test-suite/chicken/overload_extend_runme.ss b/Examples/test-suite/chicken/overload_extend_runme.ss deleted file mode 100644 index a19cb29a9..000000000 --- a/Examples/test-suite/chicken/overload_extend_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "overload_extend.so") -(include "../schemerunme/overload_extend.scm") diff --git a/Examples/test-suite/chicken/overload_extend_runme_proxy.ss b/Examples/test-suite/chicken/overload_extend_runme_proxy.ss deleted file mode 100644 index 2a6867e22..000000000 --- a/Examples/test-suite/chicken/overload_extend_runme_proxy.ss +++ /dev/null @@ -1,14 +0,0 @@ -(load "./overload_extend.so") - -(define f (make )) - -(if (not (= (test f 3) 1)) - (error "test integer bad")) - -(if (not (= (test f "hello") 2)) - (error "test string bad")) - -(if (not (= (test f 3.5 2.5) 6.0)) - (error "test reals bad")) - -(exit 0) diff --git a/Examples/test-suite/chicken/overload_simple_runme.ss b/Examples/test-suite/chicken/overload_simple_runme.ss deleted file mode 100644 index 24fa67aec..000000000 --- a/Examples/test-suite/chicken/overload_simple_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "overload_simple.so") -(include "../schemerunme/overload_simple.scm") diff --git a/Examples/test-suite/chicken/overload_simple_runme_proxy.ss b/Examples/test-suite/chicken/overload_simple_runme_proxy.ss deleted file mode 100644 index 0ae3e6215..000000000 --- a/Examples/test-suite/chicken/overload_simple_runme_proxy.ss +++ /dev/null @@ -1,56 +0,0 @@ -(load "overload_simple.so") - -(define-macro (check test) - `(if (not ,test) (error ',test))) - -(check (string=? (foo) "foo:")) -(check (string=? (foo 3) "foo:int")) -(check (string=? (foo 3.01) "foo:double")) -(check (string=? (foo "hey") "foo:char *")) - -(define f (make )) -(define b (make )) -(define b2 (make 3)) - -(check (= (slot-ref b 'num) 0)) -(check (= (slot-ref b2 'num) 3)) - -(check (string=? (foo f) "foo:Foo *")) -(check (string=? (foo b) "foo:Bar *")) -(check (string=? (foo f 3) "foo:Foo *,int")) -(check (string=? (foo 3.2 b) "foo:double,Bar *")) - -;; now check blah -(check (string=? (blah 2.01) "blah:double")) -(check (string=? (blah "hey") "blah:char *")) - -;; now check spam member functions -(define s (make )) -(define s2 (make 3)) -(define s3 (make 3.2)) -(define s4 (make "whee")) -(define s5 (make f)) -(define s6 (make b)) - -(check (string=? (slot-ref s 'type) "none")) -(check (string=? (slot-ref s2 'type) "int")) -(check (string=? (slot-ref s3 'type) "double")) -(check (string=? (slot-ref s4 'type) "char *")) -(check (string=? (slot-ref s5 'type) "Foo *")) -(check (string=? (slot-ref s6 'type) "Bar *")) - -;; now check Spam member functions -(check (string=? (foo s 2) "foo:int")) -(check (string=? (foo s 2.1) "foo:double")) -(check (string=? (foo s "hey") "foo:char *")) -(check (string=? (foo s f) "foo:Foo *")) -(check (string=? (foo s b) "foo:Bar *")) - -;; check static member funcs -(check (string=? (Spam-bar 3) "bar:int")) -(check (string=? (Spam-bar 3.2) "bar:double")) -(check (string=? (Spam-bar "hey") "bar:char *")) -(check (string=? (Spam-bar f) "bar:Foo *")) -(check (string=? (Spam-bar b) "bar:Bar *")) - -(exit 0) diff --git a/Examples/test-suite/chicken/overload_subtype_runme.ss b/Examples/test-suite/chicken/overload_subtype_runme.ss deleted file mode 100644 index b3663b719..000000000 --- a/Examples/test-suite/chicken/overload_subtype_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "overload_subtype.so") -(include "../schemerunme/overload_subtype.scm") diff --git a/Examples/test-suite/chicken/overload_subtype_runme_proxy.ss b/Examples/test-suite/chicken/overload_subtype_runme_proxy.ss deleted file mode 100644 index d83d59a11..000000000 --- a/Examples/test-suite/chicken/overload_subtype_runme_proxy.ss +++ /dev/null @@ -1,12 +0,0 @@ -(load "./overload_subtype.so") - -(define f (make )) -(define b (make )) - -(if (not (= (spam f) 1)) - (error "Error in foo")) - -(if (not (= (spam b) 2)) - (error "Error in bar")) - -(exit 0) diff --git a/Examples/test-suite/chicken/pointer_in_out_runme.ss b/Examples/test-suite/chicken/pointer_in_out_runme.ss deleted file mode 100644 index 807c4ebad..000000000 --- a/Examples/test-suite/chicken/pointer_in_out_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "pointer_in_out.so") -(include "../schemerunme/pointer_in_out.scm") diff --git a/Examples/test-suite/chicken/reference_global_vars_runme.ss b/Examples/test-suite/chicken/reference_global_vars_runme.ss deleted file mode 100644 index 1e1914be3..000000000 --- a/Examples/test-suite/chicken/reference_global_vars_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "reference_global_vars.so") -(include "../schemerunme/reference_global_vars.scm") diff --git a/Examples/test-suite/chicken/testsuite.ss b/Examples/test-suite/chicken/testsuite.ss deleted file mode 100644 index e1152a6fe..000000000 --- a/Examples/test-suite/chicken/testsuite.ss +++ /dev/null @@ -1,12 +0,0 @@ -(define (lookup-ext-tag tag) - (cond - ((equal? tag '(quote swig-contract-assertion-failed)) - '( ((exn type) #f)) ) - (#t '()))) - -(define-macro (expect-throw tag-form form) - `(if (condition-case (begin ,form #t) - ,@(lookup-ext-tag tag-form) - ((exn) (print "The form threw a different error than expected: " ',form) (exit 1)) - (var () (print "The form did not error as expected: " ',form) (exit 1))) - (begin (print "The form returned normally when it was expected to throw an error: " ',form) (exit 1)))) diff --git a/Examples/test-suite/chicken/throw_exception_runme.ss b/Examples/test-suite/chicken/throw_exception_runme.ss deleted file mode 100644 index 62bc7befb..000000000 --- a/Examples/test-suite/chicken/throw_exception_runme.ss +++ /dev/null @@ -1,29 +0,0 @@ -(load "throw_exception.so") - -(define-macro (check-throw expr check) - `(if (handle-exceptions exvar (if ,check #f (begin (print "Error executing: " ',expr " " exvar) (exit 1))) ,expr #t) - (print "Expression did not throw an error: " ',expr))) - -(define f (new-Foo)) - -(check-throw (Foo-test-int f) (= exvar 37)) -(check-throw (Foo-test-msg f) (string=? exvar "Dead")) -(check-throw (Foo-test-cls f) (test-is-Error exvar)) -(check-throw (Foo-test-cls-ptr f) (test-is-Error exvar)) -(check-throw (Foo-test-cls-ref f) (test-is-Error exvar)) -(check-throw (Foo-test-cls-td f) (test-is-Error exvar)) -(check-throw (Foo-test-cls-ptr-td f) (test-is-Error exvar)) -(check-throw (Foo-test-cls-ref-td f) (test-is-Error exvar)) -(check-throw (Foo-test-enum f) (= exvar (enum2))) - -; don't know how to test this... it is returning a SWIG wrapped int * -;(check-throw (Foo-test-array f) (equal? exvar '(0 1 2 3 4 5 6 7 8 9))) - -(check-throw (Foo-test-multi f 1) (= exvar 37)) -(check-throw (Foo-test-multi f 2) (string=? exvar "Dead")) -(check-throw (Foo-test-multi f 3) (test-is-Error exvar)) - -(set! f #f) -(gc #t) - -(exit 0) diff --git a/Examples/test-suite/chicken/typedef_inherit_runme.ss b/Examples/test-suite/chicken/typedef_inherit_runme.ss deleted file mode 100644 index 111296d60..000000000 --- a/Examples/test-suite/chicken/typedef_inherit_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "typedef_inherit.so") -(include "../schemerunme/typedef_inherit.scm") diff --git a/Examples/test-suite/chicken/typename_runme.ss b/Examples/test-suite/chicken/typename_runme.ss deleted file mode 100644 index 60fc3203b..000000000 --- a/Examples/test-suite/chicken/typename_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "typename.so") -(include "../schemerunme/typename.scm") diff --git a/Examples/test-suite/chicken/unions_runme.ss b/Examples/test-suite/chicken/unions_runme.ss deleted file mode 100644 index 465784a43..000000000 --- a/Examples/test-suite/chicken/unions_runme.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "unions.so") -(include "../schemerunme/unions.scm") diff --git a/Examples/test-suite/chicken/unions_runme_proxy.ss b/Examples/test-suite/chicken/unions_runme_proxy.ss deleted file mode 100644 index 4dd14148d..000000000 --- a/Examples/test-suite/chicken/unions_runme_proxy.ss +++ /dev/null @@ -1,2 +0,0 @@ -(load "unions.so") -(include "../schemerunme/unions_proxy.scm") diff --git a/Examples/test-suite/chicken_ext_test.i b/Examples/test-suite/chicken_ext_test.i deleted file mode 100644 index b4f726cc7..000000000 --- a/Examples/test-suite/chicken_ext_test.i +++ /dev/null @@ -1,21 +0,0 @@ -%module chicken_ext_test - -/* just use the imports_a.h header... for this test we only need a class */ -%{ -#include "imports_a.h" -%} - -%include "imports_a.h" - -%{ -void test_create(C_word,C_word,C_word) C_noret; -%} - -%init %{ - { - C_word *space = C_alloc(2 + C_SIZEOF_INTERNED_SYMBOL(11)); - sym = C_intern (&space, 11, "test-create"); - C_mutate ((C_word*)sym+1, (*space=C_CLOSURE_TYPE|1, space[1]=(C_word)test_create, tmp=(C_word)space, space+=2, tmp)); - } -%} - diff --git a/Examples/test-suite/class_case.i b/Examples/test-suite/class_case.i new file mode 100644 index 000000000..e9438d80b --- /dev/null +++ b/Examples/test-suite/class_case.i @@ -0,0 +1,18 @@ +%module class_case + +// Regression test for SWIG/Go bug #676 + +%inline %{ + +class ClassA {}; + +class classB {}; +class classB2 : public classB {}; + +int Test1(ClassA* a) { return 1; } +int Test1(int i) { return 0; } + +int Test2(classB* a) { return 1; } +int Test2(int i) { return 0; } + +%} diff --git a/Examples/test-suite/class_scope_namespace.i b/Examples/test-suite/class_scope_namespace.i index 47d918157..a24932a6e 100644 --- a/Examples/test-suite/class_scope_namespace.i +++ b/Examples/test-suite/class_scope_namespace.i @@ -15,6 +15,7 @@ namespace Space1 { void aaa(Space1::SubSpace1::A, SubSpace1::A, A) {} } } +void global_namespace_a(A*) {} namespace Space2 { struct B; diff --git a/Examples/test-suite/clientdata_prop_a.h b/Examples/test-suite/clientdata_prop_a.h index 5f82e98bc..52c54066d 100644 --- a/Examples/test-suite/clientdata_prop_a.h +++ b/Examples/test-suite/clientdata_prop_a.h @@ -6,7 +6,7 @@ class A { typedef A tA; -void test_A(A *a) {} -void test_tA(tA *a) {} +inline void test_A(A *a) {} +inline void test_tA(tA *a) {} -tA *new_tA() { return new tA(); } +inline tA *new_tA() { return new tA(); } diff --git a/Examples/test-suite/clisp/Makefile.in b/Examples/test-suite/clisp/Makefile.in deleted file mode 100644 index 3d207178f..000000000 --- a/Examples/test-suite/clisp/Makefile.in +++ /dev/null @@ -1,51 +0,0 @@ -####################################################################### -# Makefile for clisp test-suite -####################################################################### - -LANGUAGE = clisp -CLISP = @CLISPBIN@ -SCRIPTSUFFIX = _runme.lisp - -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ -top_builddir = @top_builddir@ - -include $(srcdir)/../common.mk - -# Overridden variables here -# no C++ tests for now -CPP_TEST_CASES = -#C_TEST_CASES += - -# Custom tests - tests with additional commandline options -# none! - -# Rules for the different types of tests -%.cpptest: - $(setup) - +$(swig_and_compile_cpp) - $(run_testcase) - -%.ctest: - $(setup) - +$(swig_and_compile_c) - $(run_testcase) - -%.multicpptest: - $(setup) - +$(swig_and_compile_multi_cpp) - $(run_testcase) - -# Runs the testcase. A testcase is only run if -# a file is found which has _runme.lisp appended after the testcase name. -run_testcase = \ - if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(CLISP) -batch -s $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ - fi - -# Clean: (does nothing, we dont generate extra clisp code) -%.clean: - @exit 0 - -clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' clisp_clean diff --git a/Examples/test-suite/command_line_define.i b/Examples/test-suite/command_line_define.i new file mode 100644 index 000000000..842add7fd --- /dev/null +++ b/Examples/test-suite/command_line_define.i @@ -0,0 +1,7 @@ +%module command_line_define + +// Test handling of -D without a value specified. + +#if FOO-0 != 1 +# error "-DFOO didn't set FOO to 1" +#endif diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index abc1e9997..9371e3dcf 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -102,6 +102,7 @@ C_TEST_BROKEN += \ # C++ test cases. (Can be run individually using: make testcase.cpptest) CPP_TEST_CASES += \ abstract_access \ + abstract_basecast \ abstract_inherit \ abstract_inherit_ok \ abstract_signature \ @@ -134,6 +135,7 @@ CPP_TEST_CASES += \ char_binary \ char_strings \ chartest \ + class_case \ class_scope_namespace \ class_forward \ class_ignore \ @@ -141,6 +143,7 @@ CPP_TEST_CASES += \ compactdefaultargs \ const_const_2 \ constant_directive \ + constant_expr \ constant_pointers \ constover \ constructor_copy \ @@ -184,6 +187,7 @@ CPP_TEST_CASES += \ director_classes \ director_classic \ director_constructor \ + director_comparison_operators \ director_conversion_operators \ director_default \ director_detect \ @@ -210,6 +214,7 @@ CPP_TEST_CASES += \ director_protected_overloaded \ director_redefined \ director_ref \ + director_simple \ director_smartptr \ director_thread \ director_unroll \ @@ -232,6 +237,7 @@ CPP_TEST_CASES += \ evil_diamond_ns \ evil_diamond_prop \ exception_classname \ + exception_memory_leak \ exception_order \ extend \ extend_constructor_destructor \ @@ -313,6 +319,7 @@ CPP_TEST_CASES += \ namespace_forward_declaration \ namespace_nested \ namespace_spaces \ + namespace_struct \ namespace_template \ namespace_typedef_class \ namespace_typemap \ @@ -330,7 +337,7 @@ CPP_TEST_CASES += \ nested_ignore \ nested_inheritance_interface \ nested_in_template \ - nested_scope \ + nested_scope_flat \ nested_template_base \ nested_workaround \ newobject1 \ @@ -418,6 +425,7 @@ CPP_TEST_CASES += \ struct_value \ swig_exception \ symbol_clash \ + sym \ template_arg_replace \ template_arg_scope \ template_arg_typename \ @@ -460,6 +468,7 @@ CPP_TEST_CASES += \ template_using_directive_and_declaration_forward \ template_using_directive_typedef \ template_nested \ + template_nested_flat \ template_nested_typemaps \ template_ns \ template_ns2 \ @@ -545,6 +554,7 @@ CPP_TEST_CASES += \ using_directive_and_declaration_forward \ using_extend \ using_inherit \ + using_member \ using_namespace \ using_namespace_loop \ using_pointers \ @@ -675,7 +685,7 @@ ifndef SKIP_CPP_STD_CASES CPP_TEST_CASES += ${CPP_STD_TEST_CASES} endif -ifneq (,$(HAVE_CXX11_COMPILER)) +ifeq (1,$(HAVE_CXX11)) CPP_TEST_CASES += $(CPP11_TEST_CASES) endif @@ -686,8 +696,10 @@ C_TEST_CASES += \ c_delete \ c_delete_function \ char_constant \ + command_line_define \ const_const \ - constant_expr \ + constant_expr_c \ + contract_c \ default_args_c \ empty_c \ enums \ @@ -718,6 +730,7 @@ C_TEST_CASES += \ nested_extend_c \ nested_structs \ newobject2 \ + not_c_keywords \ overload_extend_c \ overload_extend2 \ preproc \ @@ -754,6 +767,7 @@ MULTI_CPP_TEST_CASES += \ # Custom tests - tests with additional commandline options wallkw.cpptest: SWIGOPT += -Wallkw preproc_include.ctest: SWIGOPT += -includeall +command_line_define.ctest: SWIGOPT += -DFOO # Allow modules to define temporarily failing tests. C_TEST_CASES := $(filter-out $(FAILING_C_TESTS),$(C_TEST_CASES)) @@ -858,8 +872,6 @@ setup = \ echo "$(ACTION)ing $(LANGUAGE) testcase $*" ; \ fi - - ####################################################################### # Clean ####################################################################### diff --git a/Examples/test-suite/complextest.i b/Examples/test-suite/complextest.i index 592512b45..6c7b1f44a 100644 --- a/Examples/test-suite/complextest.i +++ b/Examples/test-suite/complextest.i @@ -2,7 +2,6 @@ %include -#ifdef __cplusplus %{ #include #include @@ -10,9 +9,7 @@ %} %include -#if 1 %template(VectorStdCplx) std::vector >; -#endif %inline { @@ -63,26 +60,3 @@ } } - -#else - - -%{ -%} - -%inline -{ - complex Conj(complex a) - { - return conj(a); - } - - - complex float Conjf(float complex a) - { - return conj(a); - } -} - - -#endif diff --git a/Examples/test-suite/constant_expr.i b/Examples/test-suite/constant_expr.i index 8e5c8aee6..0a9984055 100644 --- a/Examples/test-suite/constant_expr.i +++ b/Examples/test-suite/constant_expr.i @@ -1,11 +1,26 @@ %module constant_expr; -/* Tests of constant expressions. */ +/* Tests of constant expressions (C++ version). */ + +%include "constant_expr_c.i" %inline %{ -/* % didn't work in SWIG 1.3.40 and earlier. */ -const int X = 123%7; -#define FOO 12 % 9 -double d_array[12 % 9]; +// Testcase from https://sourceforge.net/p/swig/bugs/1139/ +template +struct SizeInfo { +enum { +isLarge = (sizeof(Tp)>sizeof(void*)), +isPointer = false +}; +}; + +/* Regression test for #300, fixed in 4.1.0. + * + * Now `a%b` without a space after the `%` is handled as a modulus operator, + * but it gave a cryptic `Syntax error in input(1)` before SWIG 3.0.4, and from + * SWIG 3.0.4 until 4.1.0, `Unknown directive '%a'`. + */ +int a; +int test2(int b = 9%a) { return b; } %} diff --git a/Examples/test-suite/constant_expr_c.i b/Examples/test-suite/constant_expr_c.i new file mode 100644 index 000000000..aae0b953c --- /dev/null +++ b/Examples/test-suite/constant_expr_c.i @@ -0,0 +1,56 @@ +%module constant_expr_c; +/* Tests of constant expressions (C version). */ + +%inline %{ + +/* % didn't work in SWIG 1.3.40 and earlier. */ +const int X = 123%7; +#define FOO 12 % 9 +double d_array[12 % 9]; + +/* `<` and `>` in constant expressions caused parse errors before SWIG 4.1.0. + * They're now supported if inside parentheses (and with some restrictions + * on the LHS of `<`. + */ + +// Testcase from https://github.com/swig/swig/issues/635 +#define TEST_A 1 +#define TEST_B 2 +#define TEST_C (TEST_A < TEST_B) +#define TEST_D (TEST_A > TEST_B) +// These have been supported since 1.3.41. +#define TEST_E (TEST_A <= TEST_B) +#define TEST_F (TEST_A >= TEST_B) +// For completeness +#define TEST_G (TEST_A == TEST_B) +#define TEST_H (TEST_A != TEST_B) + +// No warning +#if (TEST_A < TEST_B) +#define TEST_I 1 +#else +#define TEST_I 0 +#endif + +/* sizeof didn't work on an expression before SWIG 4.1.0 except for cases where + * the expression was in parentheses and looked syntactically like a type (so + * sizeof(X) worked because X could be a type syntactically). + */ +const int s1a = sizeof(X); /* worked before 4.1.0 */ +//const int s1b = sizeof X; /* not currently supported */ +const int s2a = sizeof("a string" ); +const int s2b = sizeof "a string"; +const int s3a = sizeof('c'); +const int s3b = sizeof('c'); +const int s4a = sizeof(L"a wstring"); +const int s4b = sizeof L"a wstring"; +const int s5a = sizeof(L'C'); +const int s5b = sizeof L'C'; +const int s6a = sizeof(sizeof(X)); +const int s6b = sizeof sizeof(X); +const int s7a = sizeof(3.14); +const int s7b = sizeof 3.14; +const int s8a = sizeof(2.1e-6); +const int s8b = sizeof 2.1e-6; + +%} diff --git a/Examples/test-suite/constant_pointers.i b/Examples/test-suite/constant_pointers.i index 9094e9dea..1e03b29ca 100644 --- a/Examples/test-suite/constant_pointers.i +++ b/Examples/test-suite/constant_pointers.i @@ -53,8 +53,6 @@ public: int* array_member1[ARRAY_SIZE]; ParametersTest* array_member2[ARRAY_SIZE]; MemberVariablesTest() : member3(NULL), member4(NULL) {} -private: - MemberVariablesTest& operator=(const MemberVariablesTest&); }; void foofunction(const int *const i) {} @@ -80,8 +78,6 @@ public: void ret8(int*const& a) {} int*const& ret9() {return GlobalIntPtr;} ReturnValuesTest() : int3(NULL) {} -private: - ReturnValuesTest& operator=(const ReturnValuesTest&); }; const int* globalRet1() {return &GlobalInt;} @@ -113,8 +109,6 @@ int* const globalRet2() {return &GlobalInt;} A* ap; const A* cap; Acptr acptr; - private: - B& operator=(const B&); }; const B* bar(const B* b) { diff --git a/Examples/test-suite/contract.i b/Examples/test-suite/contract.i index 0ad7e8e7c..de662c108 100644 --- a/Examples/test-suite/contract.i +++ b/Examples/test-suite/contract.i @@ -48,6 +48,7 @@ int test_prepost(int x, int y) { } %} +#ifdef __cplusplus /* Class tests */ %contract Foo::test_preassert(int x, int y) { @@ -235,4 +236,4 @@ class myClass }; } - +#endif diff --git a/Examples/test-suite/contract_c.i b/Examples/test-suite/contract_c.i new file mode 100644 index 000000000..465a7ded6 --- /dev/null +++ b/Examples/test-suite/contract_c.i @@ -0,0 +1,5 @@ +%module contract_c; + +%include + +%include "contract.i" diff --git a/Examples/test-suite/cpp11_alternate_function_syntax.i b/Examples/test-suite/cpp11_alternate_function_syntax.i index b3ecabc8c..2f5aaa41a 100644 --- a/Examples/test-suite/cpp11_alternate_function_syntax.i +++ b/Examples/test-suite/cpp11_alternate_function_syntax.i @@ -3,6 +3,8 @@ %module cpp11_alternate_function_syntax %inline %{ +struct Hello {}; + struct SomeStruct { int addNormal(int x, int y); auto addAlternate(int x, int y) -> int; @@ -12,6 +14,9 @@ struct SomeStruct { auto addAlternateMemberPtrParm(int x, int (SomeStruct::*mp)(int, int)) -> int; auto addAlternateMemberPtrConstParm(int x, int (SomeStruct::*mp)(int, int) const) const -> int; + // Returning a reference didn't parse in SWIG < 4.1.0 (#231) + auto output() -> Hello&; + virtual auto addFinal(int x, int y) const noexcept -> int final { return x + y; } virtual ~SomeStruct() = default; }; @@ -27,5 +32,6 @@ auto SomeStruct::addAlternateMemberPtrParm(int x, int (SomeStruct::*mp)(int, int auto SomeStruct::addAlternateMemberPtrConstParm(int x, int (SomeStruct::*mp)(int, int) const) const -> int { return 1000*x + (this->*mp)(x, x); } +auto SomeStruct::output() -> Hello& { static Hello h; return h; } %} diff --git a/Examples/test-suite/cpp11_constexpr.i b/Examples/test-suite/cpp11_constexpr.i index 420db4f83..5ba9ff243 100644 --- a/Examples/test-suite/cpp11_constexpr.i +++ b/Examples/test-suite/cpp11_constexpr.i @@ -53,3 +53,12 @@ int Array300[ConstExpressions::LLL]; //int Array400[ConstExpressions::MMM()]; //int Array500[ConstExpressions::NNN()]; %} + +%{ +// Test handling of ID PERIOD ID in constant expressions (supported since 4.1.0). +struct A { + int i; +}; +constexpr A a{42}; +constexpr int N = a.i; +%} diff --git a/Examples/test-suite/cpp11_final_override.i b/Examples/test-suite/cpp11_final_override.i index c31ae73b6..849655b16 100644 --- a/Examples/test-suite/cpp11_final_override.i +++ b/Examples/test-suite/cpp11_final_override.i @@ -90,7 +90,7 @@ struct FinalOverrideMethods { virtual void override(int) {} virtual ~FinalOverrideMethods() = default; }; -struct FinalOverrideVariables { +struct FinalOverrideVars { int final; double override; }; diff --git a/Examples/test-suite/cpp11_lambda_functions.i b/Examples/test-suite/cpp11_lambda_functions.i index 3d7d76d60..0096eef11 100644 --- a/Examples/test-suite/cpp11_lambda_functions.i +++ b/Examples/test-suite/cpp11_lambda_functions.i @@ -56,7 +56,7 @@ auto lambda4 = [](int x, int y) { return x+y; }; auto lambda5 = []() { return thing; }; #endif -void fn() { +void fn1() { int stuff = 0; auto lambdaxxxx = [=,&stuff]() { return thing; }; } diff --git a/Examples/test-suite/cpp11_raw_string_literals.i b/Examples/test-suite/cpp11_raw_string_literals.i index b50b768b9..813374928 100644 --- a/Examples/test-suite/cpp11_raw_string_literals.i +++ b/Examples/test-suite/cpp11_raw_string_literals.i @@ -21,6 +21,11 @@ %include #endif +#if defined(SWIGLUA) +// Lua uses a parameter called L in every wrapper function +%ignore L; +#endif + %inline %{ #include #include diff --git a/Examples/test-suite/cpp11_rvalue_reference3.i b/Examples/test-suite/cpp11_rvalue_reference3.i index 8ebf45366..55a55bac9 100644 --- a/Examples/test-suite/cpp11_rvalue_reference3.i +++ b/Examples/test-suite/cpp11_rvalue_reference3.i @@ -24,19 +24,19 @@ void takeit3(Thing const*&& t) {} void takeit4(Thing *const&& t) {} void takeit5(Thing const*const&& t) {} -struct Containing { - Thing && member_rvalue_ref; - Thing *&& member_rvalue_ref_ptr1; - Thing const*&& member_rvalue_ref_ptr2; - Thing *const&& member_rvalue_ref_ptr3; - Thing const*const &&member_rvalue_ref_ptr4; +struct Contain { + Thing && m_ref; + Thing *&& m_ref_ptr1; + Thing const*&& m_ref_ptr2; + Thing *const&& m_ref_ptr3; + Thing const*const &&m_ref_ptr4; - Containing(Thing&&r, Thing*&& r1, Thing const*&& r2, Thing *const&& r3, Thing const*const && r4) : - member_rvalue_ref(std::move(r)), - member_rvalue_ref_ptr1(std::move(r1)), - member_rvalue_ref_ptr2(std::move(r2)), - member_rvalue_ref_ptr3(std::move(r3)), - member_rvalue_ref_ptr4(std::move(r4)) + Contain(Thing&&r, Thing*&& r1, Thing const*&& r2, Thing *const&& r3, Thing const*const && r4) : + m_ref(std::move(r)), + m_ref_ptr1(std::move(r1)), + m_ref_ptr2(std::move(r2)), + m_ref_ptr3(std::move(r3)), + m_ref_ptr4(std::move(r4)) {} }; %} @@ -61,19 +61,19 @@ void int_takeit3(int const*&& t) {} void int_takeit4(int *const&& t) {} void int_takeit5(int const*const&& t) {} -struct IntContaining { - int && member_rvalue_ref; - int *&& member_rvalue_ref_ptr1; - int const*&& member_rvalue_ref_ptr2; - int *const&& member_rvalue_ref_ptr3; - int const*const &&member_rvalue_ref_ptr4; +struct IContain { + int && m_ref; + int *&& m_ref_ptr1; + int const*&& m_ref_ptr2; + int *const&& m_ref_ptr3; + int const*const &&m_ref_ptr4; - IntContaining(int&& r, int*&& r1, int const*&& r2, int *const&& r3, int const*const && r4) : - member_rvalue_ref(std::move(r)), - member_rvalue_ref_ptr1(std::move(r1)), - member_rvalue_ref_ptr2(std::move(r2)), - member_rvalue_ref_ptr3(std::move(r3)), - member_rvalue_ref_ptr4(std::move(r4)) + IContain(int&& r, int*&& r1, int const*&& r2, int *const&& r3, int const*const && r4) : + m_ref(std::move(r)), + m_ref_ptr1(std::move(r1)), + m_ref_ptr2(std::move(r2)), + m_ref_ptr3(std::move(r3)), + m_ref_ptr4(std::move(r4)) {} }; %} diff --git a/Examples/test-suite/cpp11_std_array.i b/Examples/test-suite/cpp11_std_array.i index 3d4771551..9dc11ce9e 100644 --- a/Examples/test-suite/cpp11_std_array.i +++ b/Examples/test-suite/cpp11_std_array.i @@ -1,6 +1,6 @@ %module cpp11_std_array -#if defined(SWIGPYTHON) || defined(SWIGRUBY) || defined(SWIGJAVA) || defined(SWIGCSHARP) +#if defined(SWIGPYTHON) || defined(SWIGRUBY) || defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGGO) %{ #include diff --git a/Examples/test-suite/cpp11_template_double_brackets.i b/Examples/test-suite/cpp11_template_double_brackets.i index ba5caa5c5..d7522c9f0 100644 --- a/Examples/test-suite/cpp11_template_double_brackets.i +++ b/Examples/test-suite/cpp11_template_double_brackets.i @@ -1,5 +1,5 @@ /* This interface checks whether SWIG supports the new double angled brackets - in the template syntax without having a space inbetween. This feature was + in the template syntax without having a space in between. This feature was introduced in new C++11 standard. */ %module cpp11_template_double_brackets diff --git a/Examples/test-suite/cpp11_template_explicit.i b/Examples/test-suite/cpp11_template_explicit.i index 71752f822..630342862 100644 --- a/Examples/test-suite/cpp11_template_explicit.i +++ b/Examples/test-suite/cpp11_template_explicit.i @@ -4,7 +4,9 @@ */ %module cpp11_template_explicit +/* Suppress SWIG warnings related to explicit template instantiation and extern templates */ #pragma SWIG nowarn=SWIGWARN_PARSE_EXPLICIT_TEMPLATE +#pragma SWIG nowarn=SWIGWARN_PARSE_EXTERN_TEMPLATE %inline %{ @@ -33,6 +35,30 @@ extern template class Temper; template class Temper; extern template class Temper; + +/* Templated function to check support for extern template functions */ +template +T my_templated_function(int a, double b) +{ + return T(); +} + +/* Explicit extern function template instantiation with simple type */ +extern template int my_templated_function(int, double); +template int my_templated_function(int, double); + +/* Explicit extern function template instantiation with more complex types */ +extern template A my_templated_function(int, double); +template A my_templated_function(int, double); + +extern template Temper my_templated_function>(int, double); +template Temper my_templated_function>(int, double); + %} %template(TemperInt) Temper; + +/* Enable several versions of the templated function */ +%template(my_templated_function_int ) my_templated_function; +%template(my_templated_function_A ) my_templated_function; +%template(my_templated_function_TemperInt) my_templated_function>; diff --git a/Examples/test-suite/cpp11_thread_local.i b/Examples/test-suite/cpp11_thread_local.i index 21f21859b..a85289149 100644 --- a/Examples/test-suite/cpp11_thread_local.i +++ b/Examples/test-suite/cpp11_thread_local.i @@ -16,7 +16,9 @@ thread_local static int tsval; extern thread_local int etval; thread_local extern int teval; extern "C" thread_local int ectval; +extern "C" { thread_local int ectval2 = 56; } extern "C++" thread_local int ecpptval; +extern "C++" { thread_local int ecpptval2 = 67; } thread_local int ThreadLocals::stval = 11; thread_local int ThreadLocals::tsval = 22; @@ -30,6 +32,10 @@ thread_local const int ThreadLocals::tscval99; // externs thread_local int etval = 33; thread_local int teval = 44; +extern "C" { thread_local int ectval = 55; +} +extern "C++" { thread_local int ecpptval = 66; +} %} diff --git a/Examples/test-suite/cpp11_type_aliasing.i b/Examples/test-suite/cpp11_type_aliasing.i index abc1642c4..ea4048408 100644 --- a/Examples/test-suite/cpp11_type_aliasing.i +++ b/Examples/test-suite/cpp11_type_aliasing.i @@ -63,12 +63,14 @@ using IntArray = Int[]; // Test that SWIG understands these new types +%{ +Int mult2(Int x) { return x * 2; } +%} %callback("%s_cb"); Int mult2(Int x); %nocallback; %inline %{ -Int mult2(Int x) { return x * 2; } IntPtr allocate_int() { return new Int(12); } void free_int(int* ptr) { delete ptr; } void inplace_mult2(IntRef x) { x *= 2; } diff --git a/Examples/test-suite/cpp_basic.i b/Examples/test-suite/cpp_basic.i index a228af289..c39206b13 100644 --- a/Examples/test-suite/cpp_basic.i +++ b/Examples/test-suite/cpp_basic.i @@ -1,4 +1,4 @@ -/* This is a basic test of proxy classes, used by chicken */ +/* This is a basic test of proxy classes */ %warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK); /* memory leak when setting a ptr/ref variable */ @@ -45,6 +45,9 @@ class FooSubSub : public FooSub { const char* __str__() const { return "FooSubSub"; } }; +Foo& get_reference(Foo& other) { return other; } +const Foo& get_const_reference(const Foo& other) { return other; } + %} %{ @@ -74,8 +77,16 @@ class Bar { Foo *testFoo(int a, Foo *f) { return new Foo(2 * a + (f ? f->num : 0) + fval.num); } +/* Const member data and references mean this class can't be assigned. private: Bar& operator=(const Bar&); +*/ +}; + +// This class is valid C++ but cannot be assigned to because it has const member data. +struct JustConst { +explicit JustConst(int i_inp) : i(i_inp) {} +const int i; }; %} diff --git a/Examples/test-suite/cpp_typedef.i b/Examples/test-suite/cpp_typedef.i index b782a3bd3..d77485c77 100644 --- a/Examples/test-suite/cpp_typedef.i +++ b/Examples/test-suite/cpp_typedef.i @@ -3,6 +3,9 @@ %module cpp_typedef %{ +#if defined(_MSC_VER) + #pragma warning( disable : 5208) // warning C5208: unnamed class used in typedef name cannot declare members other than non-static data members, member enumerations, or member classes +#endif class Bar { public: diff --git a/Examples/test-suite/csharp/Makefile.in b/Examples/test-suite/csharp/Makefile.in index b0ad0c7cf..02dcaafb0 100644 --- a/Examples/test-suite/csharp/Makefile.in +++ b/Examples/test-suite/csharp/Makefile.in @@ -28,6 +28,7 @@ CPP_TEST_CASES = \ enum_thorough_typesafe \ exception_partial_info \ intermediary_classname \ + nested_scope \ li_boost_intrusive_ptr \ li_std_list \ diff --git a/Examples/test-suite/csharp/director_classes_runme.cs b/Examples/test-suite/csharp/director_classes_runme.cs index 700492fb1..cea4949c6 100644 --- a/Examples/test-suite/csharp/director_classes_runme.cs +++ b/Examples/test-suite/csharp/director_classes_runme.cs @@ -177,7 +177,7 @@ public class CSharpDerived : Base // Note the following method can never be called from unmanaged code. // It is here only for code that calls it directly from managed code. // But should always be defined to ensure behaviour is consistent - // independent of where DefaultParsms is called from (managed or unmanaged code). + // independent of where DefaultParams is called from (managed or unmanaged code). // Note this method can never be called from unmanaged code public override String DefaultParms(int x) { diff --git a/Examples/test-suite/csharp/director_default_runme.cs b/Examples/test-suite/csharp/director_default_runme.cs new file mode 100644 index 000000000..af14c1eb4 --- /dev/null +++ b/Examples/test-suite/csharp/director_default_runme.cs @@ -0,0 +1,58 @@ +using System; + +namespace director_defaultNamespace { + +public class runme +{ + static void Main() + { + { + MyFoo a = new MyFoo(); + a = new MyFoo(10); + a.Dispose(); + } + + { + MyFoo a = new MyFoo(); + if (a.GetMsg() != "MyFoo-default") { + throw new Exception( "Test 1 failed" ); + } + if (a.GetMsg("boo") != "MyFoo-boo") { + throw new Exception( "Test 2 failed" ); + } + a.Dispose(); + } + + { + Foo b = new Foo(); + if (b.GetMsg() != "Foo-default") { + throw new Exception( "Test 1 failed" ); + } + if (b.GetMsg("boo") != "Foo-boo") { + throw new Exception( "Test 2 failed" ); + } + b.Dispose(); + } + } +} + +public class MyFoo : Foo +{ + public MyFoo() + : base() + { + } + + public MyFoo(int i) + : base(i) + { + } + + public override string Msg(string msg) + { + return "MyFoo-" + msg; + } +} + +} + diff --git a/Examples/test-suite/csharp/director_property_runme.cs b/Examples/test-suite/csharp/director_property_runme.cs new file mode 100644 index 000000000..b93e8e29d --- /dev/null +++ b/Examples/test-suite/csharp/director_property_runme.cs @@ -0,0 +1,64 @@ +using System; + +namespace director_propertyNamespace { + +public class runme +{ + static void Main() + { + { + Foo a = new MyFoo(); + if (a.getA() != "") { + throw new Exception( "Test failed" ); + } + a.setA("Hello"); + if (a.getA() != "Hello set from MyFoo") { + throw new Exception( "Test failed" ); + } + a.setAByRef("Hello"); + if (a.getA() != "Hello setAByRef from MyFoo") { + throw new Exception( "Test failed" ); + } + a.Dispose(); + } + + { + Foo a_original = new MyFoo(); + Foo a = Foo.get_self(a_original); + if (a.getA() != "") { + throw new Exception( "Test failed" ); + } + a.setA("Hello"); + if (a.getA() != "Hello set from MyFoo") { + throw new Exception( "Test failed" ); + } + a.setAByRef("Hello"); + if (a.getA() != "Hello setAByRef from MyFoo") { + throw new Exception( "Test failed" ); + } + a.Dispose(); + } + } +} + +public class MyFoo : Foo +{ + public MyFoo() + : base() + { + } + + public override void setA(string a) + { + base.setA(a + " set from MyFoo"); + } + + public override void setAByRef(string a) + { + base.setA(a + " setAByRef from MyFoo"); + } +} + +} + + diff --git a/Examples/test-suite/csharp/director_void_runme.cs b/Examples/test-suite/csharp/director_void_runme.cs index 24b470f11..ef440a76a 100644 --- a/Examples/test-suite/csharp/director_void_runme.cs +++ b/Examples/test-suite/csharp/director_void_runme.cs @@ -67,6 +67,12 @@ public class runme if (x != 1334) throw new Exception("Bad4 should be 1334, got " + x); } + { + MemberVoid mv = new MemberVoid(); + global::System.IntPtr zero = global::System.IntPtr.Zero; + mv.memberVariable = zero; + zero = mv.memberVariable; + } } } diff --git a/Examples/test-suite/csharp/li_std_wstring_runme.cs b/Examples/test-suite/csharp/li_std_wstring_runme.cs index 8b7ba1b30..d2927287f 100644 --- a/Examples/test-suite/csharp/li_std_wstring_runme.cs +++ b/Examples/test-suite/csharp/li_std_wstring_runme.cs @@ -75,6 +75,13 @@ public class runme check_equal(li_std_wstring.test_ccvalue(x), "abc"); check_equal(li_std_wstring.test_wchar_overload(x), "abc"); + // Member variables + var s = new wchar_test_struct(); + s.wchar_t_member = h; + check_equal(s.wchar_t_member, h); + s.wchar_t_ptr_member = x; + check_equal(s.wchar_t_ptr_member, "abc"); + { // Unicode strings string[] test_strings = { @@ -99,6 +106,13 @@ public class runme check_equal(received, expected); } + foreach (string expected in test_strings) + { + s.wchar_t_ptr_member = expected; + string received = s.wchar_t_ptr_member; + check_equal(received, expected); + } + /* Not working for Japanese and Russian characters on Windows, okay on Linux * Is fixed by adding CharSet=CharSet.Unicode to the DllImport, so change to: * [global::System.Runtime.InteropServices.DllImport("li_std_wstring", CharSet=global::System.Runtime.InteropServices.CharSet.Unicode, EntryPoint="CSharp_li_std_wstringNamespace_test_wcvalue")] diff --git a/Examples/test-suite/csharp/multiple_inheritance_abstract_runme.cs b/Examples/test-suite/csharp/multiple_inheritance_abstract_runme.cs index 4584be399..512fbf2db 100644 --- a/Examples/test-suite/csharp/multiple_inheritance_abstract_runme.cs +++ b/Examples/test-suite/csharp/multiple_inheritance_abstract_runme.cs @@ -216,6 +216,7 @@ public class multiple_inheritance_abstract_runme { check(multiple_inheritance_abstract.InputCPtrRefBottom1(b1)!=103+104, "InputCPtrRefBottom1() failed"); check(multiple_inheritance_abstract.InputCPtrRefBottom2(b2)!=206+205, "InputCPtrRefBottom2() failed"); check(multiple_inheritance_abstract.InputCPtrRefBottom3(b3)!=307+308+309, "InputCPtrRefBottom3() failed"); + // Return pointers check(multiple_inheritance_abstract.MakePtrDerived1_CBase1().cbase1y()!=3, "MakePtrDerived1_CBase1 failed"); check(multiple_inheritance_abstract.MakePtrDerived1_CBase2().cbase2()!=4, "MakePtrDerived1_CBase2 failed"); @@ -234,6 +235,15 @@ public class multiple_inheritance_abstract_runme { check(multiple_inheritance_abstract.MakeRefDerived3_CBase1().cbase1y()!=7, "MakeRefDerived3_CBase1 failed"); check(multiple_inheritance_abstract.MakeRefDerived3_CBase2().cbase2()!=8, "MakeRefDerived3_CBase2 failed"); + // Return const pointer references + check(multiple_inheritance_abstract.MakeConstPtrRefDerived1_CBase1().cbase1y()!=3, "MakeConstPtrRefDerived1_CBase1 failed"); + check(multiple_inheritance_abstract.MakeConstPtrRefDerived1_CBase2().cbase2()!=4, "MakeConstPtrRefDerived1_CBase2 failed"); + check(multiple_inheritance_abstract.MakeConstPtrRefDerived2_CBase1().cbase1y()!=6, "MakeConstPtrRefDerived2_CBase1 failed"); + check(multiple_inheritance_abstract.MakeConstPtrRefDerived2_ABase1().abase1()!=5, "MakeConstPtrRefDerived2_ABase1 failed"); + check(multiple_inheritance_abstract.MakeConstPtrRefDerived3_ABase1().abase1()!=9, "MakeConstPtrRefDerived3_ABase1 failed"); + check(multiple_inheritance_abstract.MakeConstPtrRefDerived3_CBase1().cbase1y()!=7, "MakeConstPtrRefDerived3_CBase1 failed"); + check(multiple_inheritance_abstract.MakeConstPtrRefDerived3_CBase2().cbase2()!=8, "MakeConstPtrRefDerived3_CBase2 failed"); + // Return by value (sliced objects) check(multiple_inheritance_abstract.MakeValDerived1_CBase1().cbase1y()!=1, "MakeValDerived1_CBase1 failed"); check(multiple_inheritance_abstract.MakeValDerived1_CBase2().cbase2()!=2, "MakeValDerived1_CBase2 failed"); diff --git a/Examples/test-suite/csharp/multiple_inheritance_nspace_runme.cs b/Examples/test-suite/csharp/multiple_inheritance_nspace_runme.cs index 6ed13a6ff..c2792517d 100644 --- a/Examples/test-suite/csharp/multiple_inheritance_nspace_runme.cs +++ b/Examples/test-suite/csharp/multiple_inheritance_nspace_runme.cs @@ -217,6 +217,7 @@ public class multiple_inheritance_nspace_runme { check(multiple_inheritance_nspace.InputCPtrRefBottom1(b1)!=103+104, "InputCPtrRefBottom1() failed"); check(multiple_inheritance_nspace.InputCPtrRefBottom2(b2)!=206+205, "InputCPtrRefBottom2() failed"); check(multiple_inheritance_nspace.InputCPtrRefBottom3(b3)!=307+308+309, "InputCPtrRefBottom3() failed"); + // Return pointers check(multiple_inheritance_nspace.MakePtrDerived1_CBase1().cbase1y()!=3, "MakePtrDerived1_CBase1 failed"); check(multiple_inheritance_nspace.MakePtrDerived1_CBase2().cbase2()!=4, "MakePtrDerived1_CBase2 failed"); @@ -235,6 +236,15 @@ public class multiple_inheritance_nspace_runme { check(multiple_inheritance_nspace.MakeRefDerived3_CBase1().cbase1y()!=7, "MakeRefDerived3_CBase1 failed"); check(multiple_inheritance_nspace.MakeRefDerived3_CBase2().cbase2()!=8, "MakeRefDerived3_CBase2 failed"); + // Return const pointer references + check(multiple_inheritance_nspace.MakeConstPtrRefDerived1_CBase1().cbase1y()!=3, "MakeConstPtrRefDerived1_CBase1 failed"); + check(multiple_inheritance_nspace.MakeConstPtrRefDerived1_CBase2().cbase2()!=4, "MakeConstPtrRefDerived1_CBase2 failed"); + check(multiple_inheritance_nspace.MakeConstPtrRefDerived2_CBase1().cbase1y()!=6, "MakeConstPtrRefDerived2_CBase1 failed"); + check(multiple_inheritance_nspace.MakeConstPtrRefDerived2_ABase1().abase1()!=5, "MakeConstPtrRefDerived2_ABase1 failed"); + check(multiple_inheritance_nspace.MakeConstPtrRefDerived3_ABase1().abase1()!=9, "MakeConstPtrRefDerived3_ABase1 failed"); + check(multiple_inheritance_nspace.MakeConstPtrRefDerived3_CBase1().cbase1y()!=7, "MakeConstPtrRefDerived3_CBase1 failed"); + check(multiple_inheritance_nspace.MakeConstPtrRefDerived3_CBase2().cbase2()!=8, "MakeConstPtrRefDerived3_CBase2 failed"); + // Return by value (sliced objects) check(multiple_inheritance_nspace.MakeValDerived1_CBase1().cbase1y()!=1, "MakeValDerived1_CBase1 failed"); check(multiple_inheritance_nspace.MakeValDerived1_CBase2().cbase2()!=2, "MakeValDerived1_CBase2 failed"); diff --git a/Examples/test-suite/csharp/multiple_inheritance_shared_ptr_runme.cs b/Examples/test-suite/csharp/multiple_inheritance_shared_ptr_runme.cs index 13ffc62a4..fc2263ef5 100644 --- a/Examples/test-suite/csharp/multiple_inheritance_shared_ptr_runme.cs +++ b/Examples/test-suite/csharp/multiple_inheritance_shared_ptr_runme.cs @@ -301,6 +301,15 @@ public class multiple_inheritance_shared_ptr_runme { check(multiple_inheritance_shared_ptr.MakeRefDerived3_CBase1().cbase1y()!=7, "MakeRefDerived3_CBase1 failed"); check(multiple_inheritance_shared_ptr.MakeRefDerived3_CBase2().cbase2()!=8, "MakeRefDerived3_CBase2 failed"); + // Return const pointer references + check(multiple_inheritance_shared_ptr.MakeConstPtrRefDerived1_CBase1().cbase1y()!=3, "MakeConstPtrRefDerived1_CBase1 failed"); + check(multiple_inheritance_shared_ptr.MakeConstPtrRefDerived1_CBase2().cbase2()!=4, "MakeConstPtrRefDerived1_CBase2 failed"); + check(multiple_inheritance_shared_ptr.MakeConstPtrRefDerived2_CBase1().cbase1y()!=6, "MakeConstPtrRefDerived2_CBase1 failed"); + check(multiple_inheritance_shared_ptr.MakeConstPtrRefDerived2_ABase1().abase1()!=5, "MakeConstPtrRefDerived2_ABase1 failed"); + check(multiple_inheritance_shared_ptr.MakeConstPtrRefDerived3_ABase1().abase1()!=9, "MakeConstPtrRefDerived3_ABase1 failed"); + check(multiple_inheritance_shared_ptr.MakeConstPtrRefDerived3_CBase1().cbase1y()!=7, "MakeConstPtrRefDerived3_CBase1 failed"); + check(multiple_inheritance_shared_ptr.MakeConstPtrRefDerived3_CBase2().cbase2()!=8, "MakeConstPtrRefDerived3_CBase2 failed"); + // Return by value (sliced objects) check(multiple_inheritance_shared_ptr.MakeValDerived1_CBase1().cbase1y()!=1, "MakeValDerived1_CBase1 failed"); check(multiple_inheritance_shared_ptr.MakeValDerived1_CBase2().cbase2()!=2, "MakeValDerived1_CBase2 failed"); diff --git a/Examples/test-suite/csharp/preproc_constants_c_runme.cs b/Examples/test-suite/csharp/preproc_constants_c_runme.cs index 5966d5266..8cdb705c9 100644 --- a/Examples/test-suite/csharp/preproc_constants_c_runme.cs +++ b/Examples/test-suite/csharp/preproc_constants_c_runme.cs @@ -51,6 +51,8 @@ public class runme { assert( typeof(int) == preproc_constants_c.EXPR_MINUS.GetType() ); assert( typeof(int) == preproc_constants_c.EXPR_LSHIFT.GetType() ); assert( typeof(int) == preproc_constants_c.EXPR_RSHIFT.GetType() ); + assert( typeof(int) == preproc_constants_c.EXPR_LT.GetType() ); + assert( typeof(int) == preproc_constants_c.EXPR_GT.GetType() ); assert( typeof(int) == preproc_constants_c.EXPR_LTE.GetType() ); assert( typeof(int) == preproc_constants_c.EXPR_GTE.GetType() ); assert( typeof(int) == preproc_constants_c.EXPR_INEQUALITY.GetType() ); diff --git a/Examples/test-suite/csharp/preproc_constants_runme.cs b/Examples/test-suite/csharp/preproc_constants_runme.cs index 6af8f20a4..d79e2c302 100644 --- a/Examples/test-suite/csharp/preproc_constants_runme.cs +++ b/Examples/test-suite/csharp/preproc_constants_runme.cs @@ -50,6 +50,8 @@ public class runme { assert( typeof(int) == preproc_constants.EXPR_MINUS.GetType() ); assert( typeof(int) == preproc_constants.EXPR_LSHIFT.GetType() ); assert( typeof(int) == preproc_constants.EXPR_RSHIFT.GetType() ); + assert( typeof(bool) == preproc_constants.EXPR_LT.GetType() ); + assert( typeof(bool) == preproc_constants.EXPR_GT.GetType() ); assert( typeof(bool) == preproc_constants.EXPR_LTE.GetType() ); assert( typeof(bool) == preproc_constants.EXPR_GTE.GetType() ); assert( typeof(bool) == preproc_constants.EXPR_INEQUALITY.GetType() ); diff --git a/Examples/test-suite/csharp/template_nested_flat_runme.cs b/Examples/test-suite/csharp/template_nested_flat_runme.cs new file mode 100644 index 000000000..afdbe5ff6 --- /dev/null +++ b/Examples/test-suite/csharp/template_nested_flat_runme.cs @@ -0,0 +1,25 @@ +using System; +using template_nested_flatNamespace; +#pragma warning disable 219 + +public class runme { + static void Main() { + new T_NormalTemplateNormalClass().tmethod(new NormalClass()); + new OuterClass().T_OuterTMethodNormalClass(new NormalClass()); + + TemplateFuncs tf = new TemplateFuncs(); + if (tf.T_TemplateFuncs1Int(-10) != -10) + throw new Exception("it failed"); + if (tf.T_TemplateFuncs2Double(-12.3) != -12.3) + throw new Exception("it failed"); + + T_NestedOuterTemplateDouble tn = new T_NestedOuterTemplateDouble(); + if (tn.hohum(-12.3) != -12.3) + throw new Exception("it failed"); + T_OuterClassInner1Int inner1 = new OuterClass().useInner1(new T_OuterClassInner1Int()); + T_OuterClassInner2NormalClass inner2 = new T_OuterClassInner2NormalClass(); + inner2.embeddedVar = 2; + T_OuterClassInner2NormalClass inner22 = new OuterClass().useInner2Again(inner2); + } +} + diff --git a/Examples/test-suite/d/li_std_vector_runme.2.d b/Examples/test-suite/d/li_std_vector_runme.2.d index f4a666716..3f97062f1 100644 --- a/Examples/test-suite/d/li_std_vector_runme.2.d +++ b/Examples/test-suite/d/li_std_vector_runme.2.d @@ -47,7 +47,7 @@ void main() { enforce(countUntil(vector[], i * 10) == i, "indexOf test failed, i: " ~ to!string(i)); } - enforce(countUntil(vector[], 42) == -1, "non-existant item indexOf test failed"); + enforce(countUntil(vector[], 42) == -1, "non-existent item indexOf test failed"); vector.clear(); enforce(vector.length == 0, "clear test failed"); diff --git a/Examples/test-suite/d/preproc_constants_c_runme.1.d b/Examples/test-suite/d/preproc_constants_c_runme.1.d index a6c2f3d10..f98f37b5f 100644 --- a/Examples/test-suite/d/preproc_constants_c_runme.1.d +++ b/Examples/test-suite/d/preproc_constants_c_runme.1.d @@ -51,6 +51,8 @@ void main() { static assert(is(int == typeof(EXPR_MINUS()))); static assert(is(int == typeof(EXPR_LSHIFT()))); static assert(is(int == typeof(EXPR_RSHIFT()))); + static assert(is(int == typeof(EXPR_LT()))); + static assert(is(int == typeof(EXPR_GT()))); static assert(is(int == typeof(EXPR_LTE()))); static assert(is(int == typeof(EXPR_GTE()))); static assert(is(int == typeof(EXPR_INEQUALITY()))); diff --git a/Examples/test-suite/d/preproc_constants_c_runme.2.d b/Examples/test-suite/d/preproc_constants_c_runme.2.d index 786cb48cc..caf3029b2 100644 --- a/Examples/test-suite/d/preproc_constants_c_runme.2.d +++ b/Examples/test-suite/d/preproc_constants_c_runme.2.d @@ -51,6 +51,8 @@ void main() { static assert(is(int == typeof(EXPR_MINUS()))); static assert(is(int == typeof(EXPR_LSHIFT()))); static assert(is(int == typeof(EXPR_RSHIFT()))); + static assert(is(int == typeof(EXPR_LT()))); + static assert(is(int == typeof(EXPR_GT()))); static assert(is(int == typeof(EXPR_LTE()))); static assert(is(int == typeof(EXPR_GTE()))); static assert(is(int == typeof(EXPR_INEQUALITY()))); diff --git a/Examples/test-suite/d/preproc_constants_runme.1.d b/Examples/test-suite/d/preproc_constants_runme.1.d index 85fa918e4..95f3c4757 100644 --- a/Examples/test-suite/d/preproc_constants_runme.1.d +++ b/Examples/test-suite/d/preproc_constants_runme.1.d @@ -50,6 +50,8 @@ void main() { static assert(is(int == typeof(EXPR_MINUS()))); static assert(is(int == typeof(EXPR_LSHIFT()))); static assert(is(int == typeof(EXPR_RSHIFT()))); + static assert(is(int == typeof(EXPR_LT()))); + static assert(is(int == typeof(EXPR_GT()))); static assert(is(bool == typeof(EXPR_LTE()))); static assert(is(bool == typeof(EXPR_GTE()))); static assert(is(bool == typeof(EXPR_INEQUALITY()))); diff --git a/Examples/test-suite/d/preproc_constants_runme.2.d b/Examples/test-suite/d/preproc_constants_runme.2.d index c81e53160..416384a11 100644 --- a/Examples/test-suite/d/preproc_constants_runme.2.d +++ b/Examples/test-suite/d/preproc_constants_runme.2.d @@ -50,6 +50,8 @@ void main() { static assert(is(int == typeof(EXPR_MINUS()))); static assert(is(int == typeof(EXPR_LSHIFT()))); static assert(is(int == typeof(EXPR_RSHIFT()))); + static assert(is(bool == typeof(EXPR_LT()))); + static assert(is(bool == typeof(EXPR_GT()))); static assert(is(bool == typeof(EXPR_LTE()))); static assert(is(bool == typeof(EXPR_GTE()))); static assert(is(bool == typeof(EXPR_INEQUALITY()))); diff --git a/Examples/test-suite/default_arg_expressions.i b/Examples/test-suite/default_arg_expressions.i index d83dc05bc..99d54c3b9 100644 --- a/Examples/test-suite/default_arg_expressions.i +++ b/Examples/test-suite/default_arg_expressions.i @@ -8,20 +8,29 @@ %warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK_MSG) UsdGeomTokensPtr; %immutable UsdGeomTokens; +// Don't call our getters get_xxx() as that collides with generated getters in +// some languages (e.g. csharp). + %inline %{ struct Numbers { int val; int *ptr; + const int& g_val() const { return val; } + const int* g_ptr() const { return ptr; } Numbers() : val(), ptr(&val) {} }; struct TfToken { Numbers val; Numbers *ptr; + const Numbers& g_val() const { return val; } + const Numbers* g_ptr() const { return ptr; } TfToken() : val(), ptr(&val) {} }; struct Tokens { const TfToken face; const TfToken *pface; + const TfToken& g_face() const { return face; } + const TfToken* g_pface() const { return pface; } Tokens() : face(), pface(&face) {} }; static Tokens UsdGeomTokens; @@ -30,5 +39,33 @@ void CreateMaterialBindSubset1(const Tokens &elementType = UsdGeomTokens) {} void CreateMaterialBindSubset2(int num = UsdGeomTokensPtr->pface->val.val) {} void CreateMaterialBindSubset3(int num = UsdGeomTokensPtr->pface->ptr->val) {} void CreateMaterialBindSubset4(int num = UsdGeomTokensPtr->face.val.val) {} -//void CreateMaterialBindSubset5(int num = UsdGeomTokens.face.val.val) {} +void CreateMaterialBindSubset5(int num = UsdGeomTokens.face.val.val) {} +void CreateMaterialBindSubset6(int num = UsdGeomTokensPtr->pface->val.g_val()) {} +void CreateMaterialBindSubset7(int num = UsdGeomTokensPtr->pface->ptr->g_val()) {} +void CreateMaterialBindSubset8(int num = UsdGeomTokensPtr->face.val.g_val()) {} +void CreateMaterialBindSubset9(int num = UsdGeomTokens.face.val.g_val()) {} +void CreateMaterialBindSubseta(int num = UsdGeomTokensPtr->pface->g_val().val) {} +void CreateMaterialBindSubsetb(int num = UsdGeomTokensPtr->pface->g_ptr()->val) {} +void CreateMaterialBindSubsetc(int num = UsdGeomTokensPtr->face.g_val().val) {} +void CreateMaterialBindSubsetd(int num = UsdGeomTokens.face.g_val().val) {} +void CreateMaterialBindSubsete(int num = UsdGeomTokensPtr->pface->g_val().g_val()) {} +void CreateMaterialBindSubsetf(int num = UsdGeomTokensPtr->pface->g_ptr()->g_val()) {} +void CreateMaterialBindSubsetg(int num = UsdGeomTokensPtr->face.g_val().g_val()) {} +void CreateMaterialBindSubseth(int num = UsdGeomTokens.face.g_val().g_val()) {} +void CreateMaterialBindSubseti(int num = UsdGeomTokensPtr->g_pface()->val.val) {} +void CreateMaterialBindSubsetj(int num = UsdGeomTokensPtr->g_pface()->ptr->val) {} +void CreateMaterialBindSubsetk(int num = UsdGeomTokensPtr->g_face().val.val) {} +void CreateMaterialBindSubsetl(int num = UsdGeomTokens.g_face().val.val) {} +void CreateMaterialBindSubsetm(int num = UsdGeomTokensPtr->g_pface()->val.g_val()) {} +void CreateMaterialBindSubsetn(int num = UsdGeomTokensPtr->g_pface()->ptr->g_val()) {} +void CreateMaterialBindSubseto(int num = UsdGeomTokensPtr->g_face().val.g_val()) {} +void CreateMaterialBindSubsetp(int num = UsdGeomTokens.g_face().val.g_val()) {} +void CreateMaterialBindSubsetq(int num = UsdGeomTokensPtr->g_pface()->g_val().val) {} +void CreateMaterialBindSubsetr(int num = UsdGeomTokensPtr->g_pface()->g_ptr()->val) {} +void CreateMaterialBindSubsets(int num = UsdGeomTokensPtr->g_face().g_val().val) {} +void CreateMaterialBindSubsett(int num = UsdGeomTokens.g_face().g_val().val) {} +void CreateMaterialBindSubsetu(int num = UsdGeomTokensPtr->g_pface()->g_val().g_val()) {} +void CreateMaterialBindSubsetv(int num = UsdGeomTokensPtr->g_pface()->g_ptr()->g_val()) {} +void CreateMaterialBindSubsetw(int num = UsdGeomTokensPtr->g_face().g_val().g_val()) {} +void CreateMaterialBindSubsetx(int num = UsdGeomTokens.g_face().g_val().g_val()) {} %} diff --git a/Examples/test-suite/default_args.i b/Examples/test-suite/default_args.i index 6b680f561..2f8fdbbd2 100644 --- a/Examples/test-suite/default_args.i +++ b/Examples/test-suite/default_args.i @@ -18,6 +18,7 @@ %{ #define TESTCASE_THROW1(T1) #define TESTCASE_THROW2(T1, T2) +#include %} %include @@ -71,7 +72,7 @@ class EnumClass { public: enum speed { FAST, SLOW }; - // Note: default values should be EnumClass::FAST and SWEET + // Note: default values should be EnumClass::FAST and SWEET bool blah(speed s = FAST, flavor f = SWEET) { return (s == FAST && f == SWEET); }; }; @@ -83,16 +84,16 @@ // casts const char * casts1(const char *m = (const char *) NULL) { - char *ret = NULL; - if (m) { + char *ret = NULL; + if (m) { ret = new char[strlen(m)+1]; strcpy(ret, m); } return ret; } const char * casts2(const char *m = (const char *) "Hello") { - char *ret = NULL; - if (m) { + char *ret = NULL; + if (m) { ret = new char[strlen(m)+1]; strcpy(ret, m); } @@ -108,16 +109,16 @@ char chartest6(char c = '\x43') { return c; } // 'C' // namespaces - namespace AType { - enum AType { NoType }; - } + namespace AType { + enum AType { NoType }; + } void dummy(AType::AType aType = AType::NoType) {} - namespace A { - namespace B { - int CONST_NUM = 10; - } + namespace A { + namespace B { + int CONST_NUM = 10; + } int afunction(int i = B::CONST_NUM) { return i; } - } + } // references int reftest1(const int &x = 42) { return x; } @@ -131,7 +132,7 @@ void test(int x = Oak + Fir + Cedar) {} }; enum Tree::types chops(enum Tree::types type) { return type; } - + %} // Rename a class member @@ -155,11 +156,11 @@ static int spam; Foo(){} - + Foo(int x, int y = 0, int z = 0){} void meth(int x, int y = 0, int z = 0){} - + // Use a renamed member as a default argument. SWIG has to resolve // bar to Foo::bar and not Foo::spam. SWIG-1.3.11 got this wrong. // (Different default parameter wrapping in SWIG-1.3.23 ensures SWIG doesn't have to resolve these symbols). @@ -189,20 +190,20 @@ // tests valuewrapper %feature("compactdefaultargs") MyClass2::set; %inline %{ - enum MyType { Val1, Val2 }; + enum MyType { Val1, Val2 }; - class MyClass1 - { - public: + class MyClass1 + { + public: MyClass1(MyType myType) {} - }; + }; - class MyClass2 - { - public : + class MyClass2 + { + public : void set(MyClass1 cl1 = Val1) {} - // This could have been written : set(MyClass1 cl1 = MyClass1(Val1)) - // But it works in C++ since there is a "conversion" constructor in MyClass1. + // This could have been written : set(MyClass1 cl1 = MyClass1(Val1)) + // But it works in C++ since there is a "conversion" constructor in MyClass1. void set2(MyClass1 cl1 = Val1) {} }; %} @@ -281,7 +282,7 @@ struct ConstMethods { }; %} -// const methods +// const methods // runtime test needed to check that the const method is called struct ConstMethods { int coo(double d = 0.0) const; @@ -305,8 +306,8 @@ struct ConstMethods { return(x+p); } - typedef struct Pointf { - double x,y; + typedef struct Pointf { + double x,y; } Pointf; } %} diff --git a/Examples/test-suite/derived_byvalue.i b/Examples/test-suite/derived_byvalue.i index 21de809a5..34aedaa64 100644 --- a/Examples/test-suite/derived_byvalue.i +++ b/Examples/test-suite/derived_byvalue.i @@ -83,7 +83,7 @@ Hash { and by checking the typemaps. The typemap code also calls SwigType_remember(), if your typemaps defined an object type, it will be added into the SwigType table. - its normally a + it's normally a SWIG_ConvertPtr(....$descriptor...) when it should have been a $&descriptor or $*descriptor diff --git a/Examples/test-suite/director_basic.i b/Examples/test-suite/director_basic.i index 07d627589..23d910324 100644 --- a/Examples/test-suite/director_basic.i +++ b/Examples/test-suite/director_basic.i @@ -5,6 +5,7 @@ #endif %warnfilter(SWIGWARN_TYPEMAP_THREAD_UNSAFE,SWIGWARN_TYPEMAP_DIRECTOROUT_PTR) MyClass::pmethod; +%warnfilter(SWIGWARN_TYPEMAP_DIRECTOROUT_PTR) ConstPtrClass::getConstPtr; %{ #include @@ -174,7 +175,19 @@ public: } }; - -%} + %} %template(MyClassT_i) MyClassT; + + %feature("director") ConstPtrClass; + + %inline %{ + +class ConstPtrClass { +public: + virtual ~ConstPtrClass() {} + virtual int *const getConstPtr() = 0; +}; + + %} + diff --git a/Examples/test-suite/director_binary_string.i b/Examples/test-suite/director_binary_string.i index 17bdc1b64..40d899fe1 100644 --- a/Examples/test-suite/director_binary_string.i +++ b/Examples/test-suite/director_binary_string.i @@ -8,6 +8,7 @@ %inline %{ #include +#include #define BUFFER_SIZE_AA 8 #define BUFFER_SIZE_BB 5 diff --git a/Examples/test-suite/director_comparison_operators.i b/Examples/test-suite/director_comparison_operators.i new file mode 100644 index 000000000..f2251ed6d --- /dev/null +++ b/Examples/test-suite/director_comparison_operators.i @@ -0,0 +1,23 @@ +%module(directors="1") director_comparison_operators + +%include "std_string.i" +%feature("director"); + +#if !defined(SWIGLUA) && !defined(SWIGR) +%rename(EqualEqual) operator ==; +%rename(NotEqual) operator !=; +%rename(LessThanEqual) operator <=; +%rename(GreaterThanEqual) operator >=; +#endif + +%inline %{ +class Foo { +public: + virtual ~Foo() { } + virtual bool operator==(const Foo&) const = 0; + virtual bool operator>=(const Foo&) const = 0; + virtual bool operator<=(const Foo&) const = 0; + virtual bool operator!=(const Foo&) const = 0; + virtual std::string test(const char *foo="a=1,b=2") { return foo; } +}; +%} diff --git a/Examples/test-suite/director_exception.i b/Examples/test-suite/director_exception.i index 71366bef0..8e76c0781 100644 --- a/Examples/test-suite/director_exception.i +++ b/Examples/test-suite/director_exception.i @@ -18,22 +18,7 @@ namespace Swig { %include "std_string.i" -#ifdef SWIGPHP - -%feature("director:except") { - if ($error == FAILURE) { - Swig::DirectorMethodException::raise("$symname"); - } -} - -%exception { - try { $action } - catch (Swig::DirectorException &) { SWIG_fail; } -} - -#endif - -#ifdef SWIGPYTHON +#if defined SWIGPHP || defined SWIGPYTHON %feature("director:except") { if ($error != NULL) { @@ -63,7 +48,7 @@ namespace Swig { %feature("director:except") { jthrowable $error = jenv->ExceptionOccurred(); if ($error) { - // Dont clear exception, still be active when return to java execution + // Don't clear exception, still be active when return to java execution // Essentially ignore exception occurred -- old behavior. return $null; } diff --git a/Examples/test-suite/director_nspace.i b/Examples/test-suite/director_nspace.i index f24227c68..016f61ddf 100644 --- a/Examples/test-suite/director_nspace.i +++ b/Examples/test-suite/director_nspace.i @@ -15,7 +15,6 @@ namespace TopLevel class FooBar { public: FooBar() {} - FooBar(const FooBar&) {} virtual ~FooBar() {} std::string FooBarDo() { return "Bar::Foo2::Foo2Bar()"; } @@ -56,7 +55,6 @@ namespace TopLevel class FooBar { public: FooBar(); - FooBar(const FooBar&); virtual ~FooBar(); std::string FooBarDo(); diff --git a/Examples/test-suite/director_overload.i b/Examples/test-suite/director_overload.i index 604ffe5ca..d6feb122b 100644 --- a/Examples/test-suite/director_overload.i +++ b/Examples/test-suite/director_overload.i @@ -47,5 +47,14 @@ public: virtual void notover(int *p) const {} }; -%} +class OverloadedGetSet +{ + int v; +public: + OverloadedGetSet() : v(42) { } + virtual ~OverloadedGetSet() { } + virtual int rw() const { return v; } + virtual void rw(int new_v) { v = new_v; } +}; +%} diff --git a/Examples/test-suite/director_overload2.i b/Examples/test-suite/director_overload2.i index e467c18ce..ddfa65bb4 100644 --- a/Examples/test-suite/director_overload2.i +++ b/Examples/test-suite/director_overload2.i @@ -14,11 +14,15 @@ struct OverloadDerived1 : OverloadBase { virtual void nnn(int vvv) {} #if defined(__SUNPRO_CC) virtual void nnn() {} +#elif defined(SWIGPHP) // FIXME: Hack to stop director_overload2 failing for PHP8 + virtual void nnn() {} #endif }; struct OverloadDerived2 : OverloadBase { #if defined(__SUNPRO_CC) virtual void nnn(int vvv) {} +#elif defined(SWIGPHP) // FIXME: Hack to stop director_overload2 failing for PHP8 + virtual void nnn(int vvv) {} #endif virtual void nnn() {} }; diff --git a/Examples/test-suite/director_property.i b/Examples/test-suite/director_property.i index d64e0c439..3f4f57aaa 100644 --- a/Examples/test-suite/director_property.i +++ b/Examples/test-suite/director_property.i @@ -18,9 +18,9 @@ virtual std::string pong() { return "Foo::pong();" + ping(); } virtual std::string getA() { return this->a_; } virtual void setA(std::string a) { this->a_ = a; } + virtual void setAByRef(const std::string &a) { this->a_ = a; } static Foo* get_self(Foo *slf) {return slf;} - }; %} @@ -37,9 +37,9 @@ virtual std::string pong(); virtual std::string getA(); virtual void setA(std::string a); + virtual void setAByRef(const std::string &a); static Foo* get_self(Foo *slf); - }; %{ diff --git a/Examples/test-suite/director_protected.i b/Examples/test-suite/director_protected.i index 0299b238d..122addb70 100644 --- a/Examples/test-suite/director_protected.i +++ b/Examples/test-suite/director_protected.i @@ -11,13 +11,6 @@ %newobject *::create(); -#ifdef SWIGPHP -// TODO: Currently we do not track the dynamic type of returned objects -// in PHP, so we need the factory helper. -%include factory.i -%factory(Foo *Bar::create, Bar); -#endif - %rename(a) Bar::hello; %rename(s) Foo::p; %rename(q) Foo::r; diff --git a/Examples/test-suite/director_simple.i b/Examples/test-suite/director_simple.i new file mode 100644 index 000000000..0883cae12 --- /dev/null +++ b/Examples/test-suite/director_simple.i @@ -0,0 +1,42 @@ +%module(directors="1") director_simple + +%feature("director") IntBase; +%feature("director") BoolBase; + +%inline %{ +class IntBase { + public: + virtual ~IntBase() {} + IntBase(int i = 3) { (void)i; } + virtual int apply(int x) const { return x * 2; } +}; + +class IntDerived : public IntBase { + public: + virtual int apply(int x) const { return x * 3; } +}; + +int apply(const IntBase& b, int x) +{ + return b.apply(x); +} + +class BoolBase { + public: + virtual ~BoolBase() {} + BoolBase() {} + virtual bool apply(bool a, bool b) const = 0; +}; + +class BoolDerived : public BoolBase { + public: + virtual bool apply(bool a, bool b) const { return a != b; } +}; + +bool apply(const BoolBase& base, bool a, bool b) +{ + return base.apply(a, b); +} + +%} + diff --git a/Examples/test-suite/director_stl.i b/Examples/test-suite/director_stl.i index 46946e513..cbcb4ba85 100644 --- a/Examples/test-suite/director_stl.i +++ b/Examples/test-suite/director_stl.i @@ -17,11 +17,7 @@ %feature("director") Foo; %feature("director:except") { -#ifndef SWIGPHP if ($error != NULL) { -#else - if ($error == FAILURE) { -#endif throw Swig::DirectorMethodException(); } } diff --git a/Examples/test-suite/director_thread.i b/Examples/test-suite/director_thread.i index c4564737f..ac48060ed 100644 --- a/Examples/test-suite/director_thread.i +++ b/Examples/test-suite/director_thread.i @@ -20,7 +20,6 @@ #ifdef _WIN32 #include #include -#include #else #include #include @@ -30,6 +29,7 @@ #endif #include +#include #include "swig_examples_lock.h" class Foo; @@ -42,15 +42,15 @@ extern "C" { static pthread_t thread; #endif - static int thread_terminate = 0; + static int swig_thread_terminate = 0; static SwigExamples::CriticalSection critical_section; int get_thread_terminate() { SwigExamples::Lock lock(critical_section); - return thread_terminate; + return swig_thread_terminate; } void set_thread_terminate(int value) { SwigExamples::Lock lock(critical_section); - thread_terminate = value; + swig_thread_terminate = value; } } %} diff --git a/Examples/test-suite/director_void.i b/Examples/test-suite/director_void.i index 40f53b6e2..d9d99aaac 100644 --- a/Examples/test-suite/director_void.i +++ b/Examples/test-suite/director_void.i @@ -43,5 +43,9 @@ struct Caller { return *(int *)p; } }; + +struct MemberVoid { + void *memberVariable; +}; %} diff --git a/Examples/test-suite/doxygen_parsing.i b/Examples/test-suite/doxygen_parsing.i index 40f37a4c2..3a559053d 100644 --- a/Examples/test-suite/doxygen_parsing.i +++ b/Examples/test-suite/doxygen_parsing.i @@ -29,6 +29,7 @@ enum SomeEnum */ struct SomeStruct { + int width; ///< \**immutable** image width in pixels }; /** diff --git a/Examples/test-suite/enum_thorough.i b/Examples/test-suite/enum_thorough.i index 3beefccc0..b8eb3df0d 100644 --- a/Examples/test-suite/enum_thorough.i +++ b/Examples/test-suite/enum_thorough.i @@ -89,8 +89,6 @@ struct SpeedClass { const colour myColour2; speedtd1 mySpeedtd1; SpeedClass() : myColour2(red), mySpeedtd1(slow) { } -private: - SpeedClass& operator=(const SpeedClass&); }; int speedTest0(int s) { return s; } diff --git a/Examples/test-suite/errors/c_extra_rbrace.stderr b/Examples/test-suite/errors/c_extra_rbrace.stderr index 23bd41f3c..a7b19389d 100644 --- a/Examples/test-suite/errors/c_extra_rbrace.stderr +++ b/Examples/test-suite/errors/c_extra_rbrace.stderr @@ -1 +1 @@ -c_extra_rbrace.i:5: Error: Syntax error. Extraneous '}' +c_extra_rbrace.i:5: Error: Syntax error. Extraneous closing brace ('}') diff --git a/Examples/test-suite/errors/c_missing_semi.stderr b/Examples/test-suite/errors/c_missing_semi.stderr index 18befaa1b..9b35037ae 100644 --- a/Examples/test-suite/errors/c_missing_semi.stderr +++ b/Examples/test-suite/errors/c_missing_semi.stderr @@ -1 +1 @@ -c_missing_semi.i:3: Error: Syntax error - possibly a missing semicolon. +c_missing_semi.i:3: Error: Syntax error - possibly a missing semicolon (';'). diff --git a/Examples/test-suite/errors/cpp_extra_brackets.stderr b/Examples/test-suite/errors/cpp_extra_brackets.stderr index f1fabc78d..901bed6a9 100644 --- a/Examples/test-suite/errors/cpp_extra_brackets.stderr +++ b/Examples/test-suite/errors/cpp_extra_brackets.stderr @@ -1 +1 @@ -cpp_extra_brackets.i:5: Error: Unexpected ')'. +cpp_extra_brackets.i:5: Error: Unexpected closing parenthesis (')'). diff --git a/Examples/test-suite/errors/cpp_namewarn.i b/Examples/test-suite/errors/cpp_namewarn.i index c0edc4b4e..5c62cebeb 100644 --- a/Examples/test-suite/errors/cpp_namewarn.i +++ b/Examples/test-suite/errors/cpp_namewarn.i @@ -1,10 +1,10 @@ %module xxx -%namewarn("314:'key1' is a keyword, renaming to '_key1'", rename="_%s") "key1"; -%namewarn("314:'key2' is a keyword, renaming to '_key2'", rename="_%s") "key2"; -%namewarn("314:'key3' is a keyword, renaming to '_key3'", rename="_%s") "key3"; -%namewarn("314:'key4' is a keyword, renaming to '_key4'", rename="_%s") "key4"; -%namewarn("314:'key5' is a keyword, renaming to '_key5'", rename="_%s") "key5"; +%namewarn("314:'key1' is a keyword", rename="_%s") "key1"; +%namewarn("314:'key2' is a keyword", rename="_%s") "key2"; +%namewarn("314:'key3' is a keyword", rename="_%s") "key3"; +%namewarn("314:'key4' is a keyword", rename="_%s") "key4"; +%namewarn("314:'key5' is a keyword", rename="_%s") "key5"; // Non-templated %ignore KlassA::key1; diff --git a/Examples/test-suite/errors/cpp_namewarn.stderr b/Examples/test-suite/errors/cpp_namewarn.stderr index e5b893268..7cc640e28 100644 --- a/Examples/test-suite/errors/cpp_namewarn.stderr +++ b/Examples/test-suite/errors/cpp_namewarn.stderr @@ -7,4 +7,4 @@ cpp_namewarn.i:67: Warning 314: 'key3' is a keyword, renaming to '_key3' cpp_namewarn.i:72: Warning 314: 'key1' is a keyword, renaming to '_key1' cpp_namewarn.i:73: Warning 314: 'key2' is a keyword, renaming to '_key2' cpp_namewarn.i:74: Warning 314: 'key3' is a keyword, renaming to '_key3' -cpp_namewarn.i:80: Warning 314: 'key5' is a keyword, renaming to '_key5' +cpp_namewarn.i:80: Warning 314: 'key5' is a keyword diff --git a/Examples/test-suite/errors/cpp_template_explicit_instantiation.i b/Examples/test-suite/errors/cpp_template_explicit_instantiation.i new file mode 100644 index 000000000..97513724b --- /dev/null +++ b/Examples/test-suite/errors/cpp_template_explicit_instantiation.i @@ -0,0 +1,24 @@ +%module xxx + +%inline %{ +namespace std { + template class vector {}; +} +template void Func() {} +%} + +%inline %{ +// Class template +template class std::vector; // C++03 template explicit instantiation definition in C++ +extern template class std::vector; // C++11 template explicit instantiation declaration (extern template) +%} +%template(VectorInt) std::vector; // SWIG template instantiation + +%inline %{ +// Function template +template void Func(); // C++03 template explicit instantiation definition in C++ +extern template void Func(); // C++11 template explicit instantiation declaration (extern template) +%} +%template(FuncInt) Func; // SWIG template instantiation + + diff --git a/Examples/test-suite/errors/cpp_template_explicit_instantiation.stderr b/Examples/test-suite/errors/cpp_template_explicit_instantiation.stderr new file mode 100644 index 000000000..052d3de27 --- /dev/null +++ b/Examples/test-suite/errors/cpp_template_explicit_instantiation.stderr @@ -0,0 +1,4 @@ +cpp_template_explicit_instantiation.i:12: Warning 320: Explicit template instantiation ignored. +cpp_template_explicit_instantiation.i:13: Warning 327: Extern template ignored. +cpp_template_explicit_instantiation.i:19: Warning 320: Explicit template instantiation ignored. +cpp_template_explicit_instantiation.i:20: Warning 327: Extern template ignored. diff --git a/Examples/test-suite/errors/cpp_using_declaration_overload.i b/Examples/test-suite/errors/cpp_using_declaration_overload.i new file mode 100644 index 000000000..9ec633f3f --- /dev/null +++ b/Examples/test-suite/errors/cpp_using_declaration_overload.i @@ -0,0 +1,9 @@ +%module xxx + +struct Base { + void m(bool) {} +}; +struct Derived : Base { + void m(bool) const {} + using Base::m; +}; diff --git a/Examples/test-suite/errors/cpp_using_declaration_overload.stderr b/Examples/test-suite/errors/cpp_using_declaration_overload.stderr new file mode 100644 index 000000000..a6d4ea6d8 --- /dev/null +++ b/Examples/test-suite/errors/cpp_using_declaration_overload.stderr @@ -0,0 +1,2 @@ +cpp_using_declaration_overload.i:7: Warning 512: Overloaded method Derived::m(bool) const ignored, +cpp_using_declaration_overload.i:8: Warning 512: using non-const method m(bool) instead. diff --git a/Examples/test-suite/errors/cpp_using_rename.i b/Examples/test-suite/errors/cpp_using_rename.i new file mode 100644 index 000000000..4b6453ca0 --- /dev/null +++ b/Examples/test-suite/errors/cpp_using_rename.i @@ -0,0 +1,22 @@ +%module xxx + +%rename(UseMe) use_me(int i); +%rename(UseMeToo) Derived::use_me_too; + +class Base +{ +public: + void use_me(Base *); + void use_me(int i); + bool use_me_too(double d) const; + bool use_me_too(bool b) const; +}; + +class Derived : public Base +{ +public: + using Base::use_me; + using Base::use_me_too; + using Base::does_not_exist; +}; + diff --git a/Examples/test-suite/errors/cpp_using_rename.stderr b/Examples/test-suite/errors/cpp_using_rename.stderr new file mode 100644 index 000000000..546489655 --- /dev/null +++ b/Examples/test-suite/errors/cpp_using_rename.stderr @@ -0,0 +1,7 @@ +cpp_using_rename.i:18: Warning 526: Using declaration Base::use_me, with name 'use_me', is not actually using +cpp_using_rename.i:10: Warning 526: the method from Base::use_me(int), with name 'UseMe', as the names are different. +cpp_using_rename.i:19: Warning 526: Using declaration Base::use_me_too, with name 'UseMeToo', is not actually using +cpp_using_rename.i:11: Warning 526: the method from Base::use_me_too(double) const, with name 'use_me_too', as the names are different. +cpp_using_rename.i:19: Warning 526: Using declaration Base::use_me_too, with name 'UseMeToo', is not actually using +cpp_using_rename.i:12: Warning 526: the method from Base::use_me_too(bool) const, with name 'use_me_too', as the names are different. +cpp_using_rename.i:20: Warning 315: Nothing known about 'Base::does_not_exist'. diff --git a/Examples/test-suite/errors/doxygen_unclosed_tag.i b/Examples/test-suite/errors/doxygen_unclosed_tag.i new file mode 100644 index 000000000..fbc359627 --- /dev/null +++ b/Examples/test-suite/errors/doxygen_unclosed_tag.i @@ -0,0 +1,6 @@ +%module xxx + +/** + * Return a random variate with uniform distribution in the range [a,b), where a') found. diff --git a/Examples/test-suite/errors/pp_badeval.stderr b/Examples/test-suite/errors/pp_badeval.stderr index 80f5037ea..bfaa17f59 100644 --- a/Examples/test-suite/errors/pp_badeval.stderr +++ b/Examples/test-suite/errors/pp_badeval.stderr @@ -1,2 +1,2 @@ pp_badeval.i:4: Warning 202: Could not evaluate expression 'FOO==4+' -pp_badeval.i:4: Warning 202: Error: 'Expected an expression' +pp_badeval.i:4: Warning 202: Expected an expression diff --git a/Examples/test-suite/errors/pp_expressions_bad.i b/Examples/test-suite/errors/pp_expressions_bad.i index 454437f95..445ed7949 100644 --- a/Examples/test-suite/errors/pp_expressions_bad.i +++ b/Examples/test-suite/errors/pp_expressions_bad.i @@ -41,3 +41,28 @@ #if(1) #warning Warning okay: #if(1) #endif + +/* The SWIG preprocessor support strings with equality/inequality tests. + * Check error cases. + */ +#if "TWO" == 1 +#endif + +/* This didn't fail prior with SWIG < 4.1. Github #1384. */ +#if 1 == ("TWO") +#endif + +/* These should all give errors. */ +#if "1" +#endif +#if -"1" +#endif +#if "1" == -"-1" +#endif +#if "1" == !"-1" +#endif +#if "1" == ~"1" +#endif +/* Unary + was a no-op and so this didn't give an error in SWIG < 4.1.0. */ +#if "1" == +"1" +#endif diff --git a/Examples/test-suite/errors/pp_expressions_bad.stderr b/Examples/test-suite/errors/pp_expressions_bad.stderr index 84104c6a8..37f846c03 100644 --- a/Examples/test-suite/errors/pp_expressions_bad.stderr +++ b/Examples/test-suite/errors/pp_expressions_bad.stderr @@ -1,19 +1,33 @@ pp_expressions_bad.i:7: Warning 202: Could not evaluate expression '1%ZERO' -pp_expressions_bad.i:7: Warning 202: Error: 'Modulo by zero in expression' +pp_expressions_bad.i:7: Warning 202: Modulo by zero in expression pp_expressions_bad.i:9: Warning 202: Could not evaluate expression '2/ZERO' -pp_expressions_bad.i:9: Warning 202: Error: 'Division by zero in expression' +pp_expressions_bad.i:9: Warning 202: Division by zero in expression pp_expressions_bad.i:12: Warning 202: Could not evaluate expression '1%(5-5)' -pp_expressions_bad.i:12: Warning 202: Error: 'Modulo by zero in expression' +pp_expressions_bad.i:12: Warning 202: Modulo by zero in expression pp_expressions_bad.i:14: Warning 202: Could not evaluate expression '2/(55-55)' -pp_expressions_bad.i:14: Warning 202: Error: 'Division by zero in expression' +pp_expressions_bad.i:14: Warning 202: Division by zero in expression pp_expressions_bad.i:18: Warning 202: Could not evaluate expression '1.2' -pp_expressions_bad.i:18: Warning 202: Error: 'Floating point constant in preprocessor expression' +pp_expressions_bad.i:18: Warning 202: Floating point constant in preprocessor expression pp_expressions_bad.i:21: Warning 202: Could not evaluate expression '2e3' -pp_expressions_bad.i:21: Warning 202: Error: 'Floating point constant in preprocessor expression' +pp_expressions_bad.i:21: Warning 202: Floating point constant in preprocessor expression pp_expressions_bad.i:25: Warning 202: Could not evaluate expression '8.8' -pp_expressions_bad.i:25: Warning 202: Error: 'Floating point constant in preprocessor expression' +pp_expressions_bad.i:25: Warning 202: Floating point constant in preprocessor expression pp_expressions_bad.i:29: Error: Unknown SWIG preprocessor directive: if123 (if this is a block of target language code, delimit it with %{ and %}) pp_expressions_bad.i:30: Error: Extraneous #endif. pp_expressions_bad.i:32: Error: Unknown SWIG preprocessor directive: if456e (if this is a block of target language code, delimit it with %{ and %}) pp_expressions_bad.i:33: Error: Extraneous #endif. pp_expressions_bad.i:42: Warning 204: CPP #warning, "Warning okay: #if(1)". +pp_expressions_bad.i:48: Warning 202: Could not evaluate expression '"TWO" == 1' +pp_expressions_bad.i:48: Warning 202: Can't mix strings and integers in expression +pp_expressions_bad.i:52: Warning 202: Could not evaluate expression '1 == ("TWO")' +pp_expressions_bad.i:52: Warning 202: Can't mix strings and integers in expression +pp_expressions_bad.i:58: Warning 202: Could not evaluate expression '-"1"' +pp_expressions_bad.i:58: Warning 202: Syntax error: attempt to apply unary operator to string +pp_expressions_bad.i:60: Warning 202: Could not evaluate expression '"1" == -"-1"' +pp_expressions_bad.i:60: Warning 202: Syntax error: attempt to apply unary operator to string +pp_expressions_bad.i:62: Warning 202: Could not evaluate expression '"1" == !"-1"' +pp_expressions_bad.i:62: Warning 202: Syntax error: attempt to apply unary operator to string +pp_expressions_bad.i:64: Warning 202: Could not evaluate expression '"1" == ~"1"' +pp_expressions_bad.i:64: Warning 202: Syntax error: attempt to apply unary operator to string +pp_expressions_bad.i:67: Warning 202: Could not evaluate expression '"1" == +"1"' +pp_expressions_bad.i:67: Warning 202: Syntax error: attempt to apply unary operator to string diff --git a/Examples/test-suite/errors/pp_invalid_exponents.stderr b/Examples/test-suite/errors/pp_invalid_exponents.stderr index 735a31ceb..2ad1b5c6b 100644 --- a/Examples/test-suite/errors/pp_invalid_exponents.stderr +++ b/Examples/test-suite/errors/pp_invalid_exponents.stderr @@ -1,6 +1,6 @@ :EOF: Error: Exponent does not have any digits pp_invalid_exponents.i:3: Warning 202: Could not evaluate expression '123e' -pp_invalid_exponents.i:3: Warning 202: Error: 'Syntax error' +pp_invalid_exponents.i:3: Warning 202: Syntax error :EOF: Error: Exponent does not have any digits pp_invalid_exponents.i:6: Warning 202: Could not evaluate expression '456.e' -pp_invalid_exponents.i:6: Warning 202: Error: 'Syntax error' +pp_invalid_exponents.i:6: Warning 202: Syntax error diff --git a/Examples/test-suite/errors/pp_unknowndirective.i b/Examples/test-suite/errors/pp_unknowndirective.i index b4e608b34..659a997d3 100644 --- a/Examples/test-suite/errors/pp_unknowndirective.i +++ b/Examples/test-suite/errors/pp_unknowndirective.i @@ -1,10 +1,5 @@ %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 2cc2377c7..d0d5e249f 100644 --- a/Examples/test-suite/errors/pp_unknowndirective.stderr +++ b/Examples/test-suite/errors/pp_unknowndirective.stderr @@ -1 +1 @@ -pp_unknowndirective.i:12: Error: Unknown directive '%remane'. +pp_unknowndirective.i:7: Error: Unknown directive '%remane'. diff --git a/Examples/test-suite/errors/pp_unknowndirective4.i b/Examples/test-suite/errors/pp_unknowndirective4.i new file mode 100644 index 000000000..c9d95e1f0 --- /dev/null +++ b/Examples/test-suite/errors/pp_unknowndirective4.i @@ -0,0 +1,7 @@ +%module xxx + +/* Regression test for bug #368 introduced in 3.0.4 and fully fixed in 4.1.0. + * The `%std` here led to SWIG calling abort() before 3.0.6, and was quietly + * ignored in from 3.0.6 until 4.1.0. + */ +%typemap(jstype) std::vector, const %std::vector&, std::vector& "List" diff --git a/Examples/test-suite/errors/pp_unknowndirective4.stderr b/Examples/test-suite/errors/pp_unknowndirective4.stderr new file mode 100644 index 000000000..efb6afe6e --- /dev/null +++ b/Examples/test-suite/errors/pp_unknowndirective4.stderr @@ -0,0 +1 @@ +pp_unknowndirective4.i:7: Error: Unknown directive '%std'. diff --git a/Examples/test-suite/errors/swig_command_encoder.i b/Examples/test-suite/errors/swig_command_encoder.i new file mode 100644 index 000000000..aaae82bb5 --- /dev/null +++ b/Examples/test-suite/errors/swig_command_encoder.i @@ -0,0 +1,6 @@ +%module xxx + +// This feature was removed in SWIG 4.1.0 so check it gives an error. +%define SedCmd "%(command:sed -e 's/\([a-z]\)/\U\\1/' -e 's/\(_\)\([a-z]\)/\U\\2/g' <<<)s" %enddef +%rename(SedCmd) ""; +int x; diff --git a/Examples/test-suite/errors/swig_command_encoder.stderr b/Examples/test-suite/errors/swig_command_encoder.stderr new file mode 100644 index 000000000..0fcf2dfb8 --- /dev/null +++ b/Examples/test-suite/errors/swig_command_encoder.stderr @@ -0,0 +1 @@ +SWIG:1: Error: Command encoder no longer supported - use regex encoder instead. diff --git a/Examples/test-suite/errors/swig_constant_missing_semi.i b/Examples/test-suite/errors/swig_constant_missing_semi.i new file mode 100644 index 000000000..3fa1f3bd2 --- /dev/null +++ b/Examples/test-suite/errors/swig_constant_missing_semi.i @@ -0,0 +1,3 @@ +%module xxx +%constant int BAR=0 +int foo(int); diff --git a/Examples/test-suite/errors/swig_constant_missing_semi.stderr b/Examples/test-suite/errors/swig_constant_missing_semi.stderr new file mode 100644 index 000000000..f86d37356 --- /dev/null +++ b/Examples/test-suite/errors/swig_constant_missing_semi.stderr @@ -0,0 +1 @@ +swig_constant_missing_semi.i:3: Warning 305: Bad constant value (ignored). diff --git a/Examples/test-suite/errors/swig_typemap_old.stderr b/Examples/test-suite/errors/swig_typemap_old.stderr index 23741164e..91bf1151d 100644 --- a/Examples/test-suite/errors/swig_typemap_old.stderr +++ b/Examples/test-suite/errors/swig_typemap_old.stderr @@ -1,5 +1,5 @@ -swig_typemap_old.i:6: Warning 450: Deprecated typemap feature ($source/$target). -swig_typemap_old.i:6: Warning 450: The use of $source and $target in a typemap declaration is deprecated. +swig_typemap_old.i:6: Error: Obsolete typemap feature ($source/$target). +swig_typemap_old.i:6: Error: The use of $source and $target in a typemap declaration is no longer supported. For typemaps related to argument input (in,ignore,default,arginit,check), replace $source by $input and $target by $1. For typemaps related to return values (out, argout,ret,except), replace $source by $1 and $target by $result. See the file diff --git a/Examples/test-suite/r_memory_leak.i b/Examples/test-suite/exception_memory_leak.i similarity index 68% rename from Examples/test-suite/r_memory_leak.i rename to Examples/test-suite/exception_memory_leak.i index a240097e3..835c936fc 100644 --- a/Examples/test-suite/r_memory_leak.i +++ b/Examples/test-suite/exception_memory_leak.i @@ -1,4 +1,4 @@ -%module r_memory_leak +%module exception_memory_leak %include @@ -8,33 +8,38 @@ } %typemap(freearg) Foo* foo { - printf(" \" Object deleted\"\n"); + Foo::inc_freearg_count(); delete $1; } %typemap(out) Foo* verify_no_memory_leak { if ($1 == NULL) SWIG_exception_fail(SWIG_RuntimeError, "Let's see how the bindings manage this exception!"); + $1 = NULL; } -%typemap(scoerceout) Foo* - %{ if (!is.null($result) && !is.logical($result)) {$result <- new("$R_class", ref=$result) ;}; %} %inline %{ #include class Foo { static unsigned count; + static unsigned freearg_count; public: Foo() { ++count; } ~Foo() { --count; } static unsigned get_count() { return count; } + static unsigned get_freearg_count() { return freearg_count; } +#ifndef SWIG + static void inc_freearg_count() { ++freearg_count; } +#endif }; unsigned Foo::count = 0; + unsigned Foo::freearg_count = 0; static Foo* trigger_internal_swig_exception(const std::string& message, Foo* foo) { return (message == "null") ? NULL : foo; - }; + } %} diff --git a/Examples/test-suite/exception_partial_info.i b/Examples/test-suite/exception_partial_info.i index 3ac465cf6..0ff6abc26 100644 --- a/Examples/test-suite/exception_partial_info.i +++ b/Examples/test-suite/exception_partial_info.i @@ -30,8 +30,6 @@ class ex2 : public myException #if !defined(SWIGUTL) -#if !defined(SWIGCHICKEN) - %inline %{ class Impl { @@ -41,10 +39,6 @@ class Impl }; %} -#else -#warning "Chicken needs fixing for partial exception information" -#endif - #else #warning "UTL needs fixing for partial exception information" #endif diff --git a/Examples/test-suite/extern_c.i b/Examples/test-suite/extern_c.i index e56d9f128..78c9d1061 100644 --- a/Examples/test-suite/extern_c.i +++ b/Examples/test-suite/extern_c.i @@ -5,6 +5,7 @@ extern "C" { void RealFunction(int value); typedef void Function1(int value); // Fails typedef int Integer1; +int Integer3; } typedef void Function2(int value); // Works typedef int Integer2; @@ -27,5 +28,14 @@ Hook2_t hook2; extern "C" typedef int Integer; Integer int1; +extern "C" int int2; +extern "C" { extern int int3; } +extern "C" { int int4 = 789; } %} +%{ +extern "C" { + int int2 = 123; + int int3 = 456; +} +%} diff --git a/Examples/test-suite/fragments.i b/Examples/test-suite/fragments.i index 4bf399a21..0fad6cf68 100644 --- a/Examples/test-suite/fragments.i +++ b/Examples/test-suite/fragments.i @@ -34,3 +34,107 @@ int foo(int hola) } %} + +/* Instantiate multiple fragments at once using fragments in comma separated list */ +typedef int comma_frag3; + +%fragment("comma_frag1","header", noblock=1) { +typedef int comma_frag1; +} + +%fragment("comma_frag2","header", noblock=1, noblock=1) { +typedef comma_frag1 comma_frag2; +} + +%fragment("comma_frag3","header", + fragment="comma_frag1,comma_frag2") +%{typedef comma_frag2 comma_frag3;%} + +%fragment("comma_frag3"); +%inline %{ +comma_frag3 my_comma_frag_int = 0; +%} + + +/* Instantiate multiple fragments at once using multiple keywords */ +typedef int explicit_frag3; + +%fragment("explicit_frag1","header", noblock=1) { +typedef int explicit_frag1; +} + +%fragment("explicit_frag2","header", noblock=1) { +typedef explicit_frag1 explicit_frag2; +} + +%fragment("explicit_frag3","header", + fragment="explicit_frag1", fragment="explicit_frag2") +%{typedef explicit_frag2 explicit_frag3;%} + +%fragment("explicit_frag3"); +%inline %{ +explicit_frag3 my_int = 0; +%} + +/* Test typemap's ability to instantiate multiple fragments on demand */ +typedef int int_infrag1; +typedef int int_infrag2; +typedef int int_outfrag1; +typedef int int_outfrag2; +typedef int int_outfrag3; + +%fragment("infrag2","runtime") %{ +typedef int_infrag1 int_infrag2; +%} + +%fragment("infrag1","runtime") %{ +typedef int int_infrag1; +%} +%fragment("infrag2","runtime") %{ +__second_infrag2_fragment_is_ignored_this_will_not_compile_if_emitted_ +typedef int_infrag1 int_infrag2; +%} + +%fragment("outfrag1","runtime") %{ +typedef int int_outfrag1; +%} +%fragment("outfrag2","runtime") %{ +typedef int_outfrag1 int_outfrag2; +%} + +%fragment("tcfrag1","runtime") %{ +typedef int int_tcfrag1; +%} +%fragment("tcfrag2","runtime") %{ +typedef int_tcfrag1 int_tcfrag2; +%} + +%fragment("outspecial"{bool},"runtime") %{ +typedef int int_outfrag3_temp; +%} +%fragment("outfrag3","runtime") %{ +typedef int_outfrag3_temp int_outfrag3; +%} + +%typemap(in, fragment="infrag1", fragment="infrag2") int_infrag2 +%{$typemap(in,int)%} + +%typemap(check, fragment="tcfrag1", noblock=1, fragment="tcfrag2") int_infrag2 +{(void)sizeof(int_tcfrag2);} + +%typemap(out, fragment="outfrag1", fragment="outfrag2", noblock=1) int_outfrag2 +{$typemap(out,int)} + +/* Test another permutation of keyword order */ +%typemap(out, noblock=1, fragment="outfrag1", fragment="outfrag2") int_outfrag1 +{$typemap(out,int)} + +/* Test fragment specialization */ +%typemap(out, noblock=1, fragment="outspecial"{bool}, fragment="outfrag3") int_outfrag3 +{$typemap(out,int)} + +%inline %{ +int identity_in(int_infrag2 inp) { return inp; } +int_outfrag2 identity_out(int inp) { return inp; } +int_outfrag3 identity_out_2(int inp) { return inp; } +%} diff --git a/Examples/test-suite/global_vars.i b/Examples/test-suite/global_vars.i index d562d1eaa..46133fed9 100644 --- a/Examples/test-suite/global_vars.i +++ b/Examples/test-suite/global_vars.i @@ -33,4 +33,8 @@ b = "string b"; x = 1234; } + + int read_x() { return x; } + + std::string read_b() { return b; } %} diff --git a/Examples/test-suite/go/Makefile.in b/Examples/test-suite/go/Makefile.in index 8283327d6..e905a1060 100644 --- a/Examples/test-suite/go/Makefile.in +++ b/Examples/test-suite/go/Makefile.in @@ -67,7 +67,7 @@ multi_import.multicpptest: if ! test -d gopath/multi_import/src/swigtests; then \ (cd gopath/multi_import/src && ln -s . swigtests); \ fi - for f in multi_import_b multi_import_a; do \ + for f in multi_import_d multi_import_b multi_import_a; do \ $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ LIBS='$(LIBS)' INCLUDES='$(INCLUDES)' SWIGOPT='$(SWIGOPT)' NOLINK=true \ @@ -173,16 +173,18 @@ run_multi_testcase = \ clean: $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' go_clean - 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 import_stl_a.go import_stl_a.gox + rm -f import_stl_b.go import_stl_b.gox + rm -f imports_a.go imports_a.gox imports_b.go imports_b.gox + rm -f mod_a.go mod_a.gox mod_b.go mod_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 multi_import_d.go multi_import_d.gox 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 -f template_typedef_cplx2.go template_typedef_cplx2.gox + rm -rf go_subdir_import_a.go go_subdir_import_a.gox testdir rm -rf gopath diff --git a/Examples/test-suite/go/class_case_runme.go b/Examples/test-suite/go/class_case_runme.go new file mode 100644 index 000000000..7d0870b47 --- /dev/null +++ b/Examples/test-suite/go/class_case_runme.go @@ -0,0 +1,12 @@ +package main + +import . "swigtests/class_case" + +func main() { + b2 := NewClassB2() + // This used to fail with: + // panic: interface conversion: interface {} is class_case.SwigcptrClassB2, not int + if Test2(b2) != 1 { + panic("Unexpected overload used") + } +} diff --git a/Examples/test-suite/go/cpp11_std_array_runme.go b/Examples/test-suite/go/cpp11_std_array_runme.go new file mode 100644 index 000000000..97b5df2ec --- /dev/null +++ b/Examples/test-suite/go/cpp11_std_array_runme.go @@ -0,0 +1,68 @@ +package main + +import ( + "fmt" + "swigtests/cpp11_std_array" +) + +func CompareContainers(actual cpp11_std_array.ArrayInt6, expected [6]int) error { + if int(actual.Size()) != len(expected) { + return fmt.Errorf("Sizes are different: %d %d", actual.Size(), len(expected)) + } + for i := 0; i < int(actual.Size()); i++ { + actualValue := actual.Get(i) + expectedValue := expected[i] + if actualValue != expectedValue { + return fmt.Errorf("Value is wrong for element %d. Expected %d got: %d", i, expectedValue, actualValue) + } + } + if actual.IsEmpty() { + return fmt.Errorf("ai should not be empty") + } + return nil +} + +func main() { + ai := cpp11_std_array.NewArrayInt6() + ps := [6]int{0, 0, 0, 0, 0, 0} + CompareContainers(ai, ps) + + vals := [6]int{10, 20, 30, 40, 50, 60} + for i := 0; i < len(vals); i++ { + ai.Set(i, vals[i]) + } + CompareContainers(ai, vals); + + // Check return + vals = [6]int{-2, -1, 0, 0, 1, 2} + CompareContainers(cpp11_std_array.ArrayOutVal(), vals); + CompareContainers(cpp11_std_array.ArrayOutConstRef(), vals); + CompareContainers(cpp11_std_array.ArrayOutRef(), vals); + CompareContainers(cpp11_std_array.ArrayOutPtr(), vals); + + // Check passing arguments + vals = [6]int{9, 8, 7, 6, 5, 4} + valsArrayInt6 := cpp11_std_array.NewArrayInt6() + for i := 0; i < len(vals); i++ { + valsArrayInt6.Set(i, vals[i]) + } + + ai = cpp11_std_array.ArrayInVal(valsArrayInt6); + CompareContainers(ai, vals); + + ai = cpp11_std_array.ArrayInConstRef(valsArrayInt6); + CompareContainers(ai, vals); + + ai = cpp11_std_array.NewArrayInt6(valsArrayInt6); + cpp11_std_array.ArrayInRef(ai); + CompareContainers(ai, vals); + + ai = cpp11_std_array.NewArrayInt6(valsArrayInt6); + cpp11_std_array.ArrayInPtr(ai); + CompareContainers(ai, vals); + + // Fill + ai.Fill(111) + vals = [6]int{111, 111, 111, 111, 111, 111} + CompareContainers(ai, vals); +} diff --git a/Examples/test-suite/go_subdir_import_a.i b/Examples/test-suite/go_subdir_import_a.i index 3fc36e6f9..5a35c8f51 100644 --- a/Examples/test-suite/go_subdir_import_a.i +++ b/Examples/test-suite/go_subdir_import_a.i @@ -6,7 +6,7 @@ * 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 + * 2) Importing a module whose 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 diff --git a/Examples/test-suite/grouping.i b/Examples/test-suite/grouping.i index 5632231d0..24acf6922 100644 --- a/Examples/test-suite/grouping.i +++ b/Examples/test-suite/grouping.i @@ -14,7 +14,7 @@ int *(test2)(int x) { return &y; } -int (test3) = 37; +int test3 = 37; typedef Integer (UnaryOp)(Integer); diff --git a/Examples/test-suite/guile/overload_null_runme.scm b/Examples/test-suite/guile/overload_null_runme.scm index f764d9c20..6824707d0 100644 --- a/Examples/test-suite/guile/overload_null_runme.scm +++ b/Examples/test-suite/guile/overload_null_runme.scm @@ -39,15 +39,15 @@ ;(check (=~ 15 (Overload-byval2cpr o #nil))) ;(check (=~ 16 (Overload-byval2cpr o x))) -; forward class declaration -(check (=~ 17 (Overload-byval1forwardptr o x))) -(check (=~ 18 (Overload-byval1forwardptr o #nil))) +; fwd class declaration +(check (=~ 17 (Overload-byval1fwdptr o x))) +(check (=~ 18 (Overload-byval1fwdptr o #nil))) -(check (=~ 19 (Overload-byval2forwardptr o #nil))) -(check (=~ 20 (Overload-byval2forwardptr o x))) +(check (=~ 19 (Overload-byval2fwdptr o #nil))) +(check (=~ 20 (Overload-byval2fwdptr o x))) -(check (=~ 21 (Overload-byval1forwardref o x))) +(check (=~ 21 (Overload-byval1fwdref o x))) -(check (=~ 22 (Overload-byval2forwardref o x))) +(check (=~ 22 (Overload-byval2fwdref o x))) (exit 0) diff --git a/Examples/test-suite/ignore_parameter.i b/Examples/test-suite/ignore_parameter.i index 604ee3b84..5650f388c 100644 --- a/Examples/test-suite/ignore_parameter.i +++ b/Examples/test-suite/ignore_parameter.i @@ -3,14 +3,23 @@ %module ignore_parameter %typemap(in,numinputs=0) char* a "static const char* hi = \"hello\"; $1 = const_cast(hi);"; -%typemap(in,numinputs=0) int bb "$1 = 101;"; +%typemap(in,numinputs=0) int bb "$1 = 101; called_argout = 0;"; %typemap(in,numinputs=0) double ccc "$1 = 8.8;"; %typemap(freearg) char* a ""; // ensure freearg is not generated (needed for Java at least) +%typemap(argout) int bb "called_argout = 1;" + %ignore unignorable; +// Don't let SWIG expand this function with its default parameter: instead, +// always "require" the version of the function with a single argument, but +// then ignore it using `numinputs=0`. +%ignore audi(); %inline %{ +// constant for detecting correct "argout" call +int called_argout = 0; + // global function tests char* jaguar(char* a, int b, double c) { return a; } int lotus(char* aa, int bb, double cc) { return bb; } @@ -25,6 +34,7 @@ struct SportsCars { double bugatti(char* aaa, int bbb, double ccc) { return ccc; } int lamborghini(int bb) { return bb; } int maseratti(int unignorable) { return unignorable; } + double audi(double ccc=9.5) { return ccc; } }; // constructor tests diff --git a/Examples/test-suite/import_nomodule.i b/Examples/test-suite/import_nomodule.i index 60ef7e0f6..48e119517 100644 --- a/Examples/test-suite/import_nomodule.i +++ b/Examples/test-suite/import_nomodule.i @@ -8,7 +8,7 @@ %import "import_nomodule.h" -#if !defined(SWIGJAVA) && !defined(SWIGRUBY) && !defined(SWIGCSHARP) && !defined(SWIGD) && !defined(SWIGPYTHON_BUILTIN) +#if !defined(SWIGJAVA) && !defined(SWIGRUBY) && !defined(SWIGCSHARP) && !defined(SWIGD) && !defined(SWIGPYTHON_BUILTIN) && !defined(SWIGPHP) /** * The proxy class does not have Bar derived from Foo, yet an instance of Bar @@ -16,8 +16,8 @@ * language modules). * * This violation of the type system is not possible in Java, C# and D due to - * static type checking. It's also not (currently) possible in Ruby, but this may - * be fixable (needs more investigation). + * static type checking. It's also not (currently) possible in PHP or Ruby, but + * this may be fixable (needs more investigation). */ %newobject create_Foo; diff --git a/Examples/test-suite/integers.i b/Examples/test-suite/integers.i index 6a9ede4bc..9569df767 100644 --- a/Examples/test-suite/integers.i +++ b/Examples/test-suite/integers.i @@ -17,6 +17,41 @@ signed long long signed_long_long_identity(signed long long x) { return x; } unsigned long long unsigned_long_long_identity(unsigned long long x) { return x; } +#ifdef __cplusplus + signed char & signed_char_ref_identity( signed char & x) { return x; } + unsigned char & unsigned_char_ref_identity( unsigned char & x) { return x; } + signed short & signed_short_ref_identity( signed short & x) { return x; } + unsigned short & unsigned_short_ref_identity( unsigned short & x) { return x; } + signed int & signed_int_ref_identity( signed int & x) { return x; } + unsigned int & unsigned_int_ref_identity( unsigned int & x) { return x; } + signed long & signed_long_ref_identity( signed long & x) { return x; } + unsigned long & unsigned_long_ref_identity( unsigned long & x) { return x; } + signed long long & signed_long_long_ref_identity( signed long long & x) { return x; } + unsigned long long & unsigned_long_long_ref_identity(unsigned long long & x) { return x; } + + const signed char & const_signed_char_ref_identity( const signed char & x) { return x; } + const unsigned char & const_unsigned_char_ref_identity( const unsigned char & x) { return x; } + const signed short & const_signed_short_ref_identity( const signed short & x) { return x; } + const unsigned short & const_unsigned_short_ref_identity( const unsigned short & x) { return x; } + const signed int & const_signed_int_ref_identity( const signed int & x) { return x; } + const unsigned int & const_unsigned_int_ref_identity( const unsigned int & x) { return x; } + const signed long & const_signed_long_ref_identity( const signed long & x) { return x; } + const unsigned long & const_unsigned_long_ref_identity( const unsigned long & x) { return x; } + const signed long long & const_signed_long_long_ref_identity( const signed long long & x) { return x; } + const unsigned long long & const_unsigned_long_long_ref_identity(const unsigned long long & x) { return x; } +#endif + + signed char * signed_char_ptr() { return NULL; } + unsigned char * unsigned_char_ptr() { return NULL; } + signed short * signed_short_ptr() { return NULL; } + unsigned short * unsigned_short_ptr() { return NULL; } + signed int * signed_int_ptr() { return NULL; } + unsigned int * unsigned_int_ptr() { return NULL; } + signed long * signed_long_ptr() { return NULL; } + unsigned long * unsigned_long_ptr() { return NULL; } + signed long long * signed_long_long_ptr() { return NULL; } + unsigned long long * unsigned_long_long_ptr() { return NULL; } + size_t signed_char_size() { return sizeof (signed char); } size_t unsigned_char_size() { return sizeof (unsigned char); } size_t signed_short_size() { return sizeof (signed short); } diff --git a/Examples/test-suite/java/Makefile.in b/Examples/test-suite/java/Makefile.in index a449f287c..e2a3d2472 100644 --- a/Examples/test-suite/java/Makefile.in +++ b/Examples/test-suite/java/Makefile.in @@ -44,8 +44,8 @@ CPP_TEST_CASES = \ java_throws \ java_typemaps_proxy \ java_typemaps_typewrapper \ + nested_scope \ li_std_list \ - li_std_map \ li_std_set \ # li_boost_intrusive_ptr diff --git a/Examples/test-suite/java/director_classes_runme.java b/Examples/test-suite/java/director_classes_runme.java index 5992b5dd9..9ee6302de 100644 --- a/Examples/test-suite/java/director_classes_runme.java +++ b/Examples/test-suite/java/director_classes_runme.java @@ -205,7 +205,7 @@ class JavaDerived extends Base // Note the following method can never be called from unmanaged code. // It is here only for code that calls it directly from managed code. // But should always be defined to ensure behaviour is consistent - // independent of where DefaultParsms is called from (managed or unmanaged code). + // independent of where DefaultParams is called from (managed or unmanaged code). // Note this method can never be called from unmanaged code public String DefaultParms(int x) { diff --git a/Examples/test-suite/java/director_default_runme.java b/Examples/test-suite/java/director_default_runme.java index b71e45e25..1ab13237a 100644 --- a/Examples/test-suite/java/director_default_runme.java +++ b/Examples/test-suite/java/director_default_runme.java @@ -16,22 +16,29 @@ public class director_default_runme { { director_default_MyFoo a = new director_default_MyFoo(); a = new director_default_MyFoo(10); + a.delete(); } - director_default_MyFoo a = new director_default_MyFoo(); - if (!a.GetMsg().equals("director_default_MyFoo-default")) { - throw new RuntimeException ( "Test 1 failed" ); - } - if (!a.GetMsg("boo").equals("director_default_MyFoo-boo")) { - throw new RuntimeException ( "Test 2 failed" ); + { + director_default_MyFoo a = new director_default_MyFoo(); + if (!a.GetMsg().equals("director_default_MyFoo-default")) { + throw new RuntimeException ( "Test 1 failed" ); + } + if (!a.GetMsg("boo").equals("director_default_MyFoo-boo")) { + throw new RuntimeException ( "Test 2 failed" ); + } + a.delete(); } - Foo b = new Foo(); - if (!b.GetMsg().equals("Foo-default")) { - throw new RuntimeException ( "Test 1 failed" ); - } - if (!b.GetMsg("boo").equals("Foo-boo")) { - throw new RuntimeException ( "Test 2 failed" ); + { + Foo b = new Foo(); + if (!b.GetMsg().equals("Foo-default")) { + throw new RuntimeException ( "Test 1 failed" ); + } + if (!b.GetMsg("boo").equals("Foo-boo")) { + throw new RuntimeException ( "Test 2 failed" ); + } + b.delete(); } } diff --git a/Examples/test-suite/java/director_property_runme.java b/Examples/test-suite/java/director_property_runme.java new file mode 100644 index 000000000..cc8727740 --- /dev/null +++ b/Examples/test-suite/java/director_property_runme.java @@ -0,0 +1,66 @@ + +import director_property.*; + +public class director_property_runme { + + static { + try { + System.loadLibrary("director_property"); + } 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[]) { + + { + Foo a = new director_property_MyFoo(); + if (!a.getA().equals("")) { + throw new RuntimeException( "Test failed" ); + } + a.setA("Hello"); + if (!a.getA().equals("Hello set from MyFoo")) { + throw new RuntimeException( "Test failed" ); + } + a.setAByRef("Hello"); + if (!a.getA().equals("Hello setAByRef from MyFoo")) { + throw new RuntimeException( "Test failed" ); + } + a.delete(); + } + + { + Foo a_original = new director_property_MyFoo(); + Foo a = Foo.get_self(a_original); + if (!a.getA().equals("")) { + throw new RuntimeException( "Test failed" ); + } + a.setA("Hello"); + if (!a.getA().equals("Hello set from MyFoo")) { + throw new RuntimeException( "Test failed" ); + } + a.setAByRef("Hello"); + if (!a.getA().equals("Hello setAByRef from MyFoo")) { + throw new RuntimeException( "Test failed" ); + } + a.delete(); + } + } +} + +class director_property_MyFoo extends Foo { + public director_property_MyFoo() { + super(); + } + @Override + public void setA(String a) { + super.setA(a + " set from MyFoo"); + } + @Override + public void setAByRef(String a) { + super.setA(a + " setAByRef from MyFoo"); + } +} + + diff --git a/Examples/test-suite/java/doxygen_parsing_runme.java b/Examples/test-suite/java/doxygen_parsing_runme.java index 10d65fca8..29e524f78 100644 --- a/Examples/test-suite/java/doxygen_parsing_runme.java +++ b/Examples/test-suite/java/doxygen_parsing_runme.java @@ -45,6 +45,12 @@ public class doxygen_parsing_runme { " The struct comment \n" + " \n" + ""); + wantedComments.put("doxygen_parsing.SomeStruct.setWidth(int)", + "**immutable** image width in pixels \n" + + ""); + wantedComments.put("doxygen_parsing.SomeStruct.getWidth()", + "**immutable** image width in pixels \n" + + ""); wantedComments.put("doxygen_parsing.doxygen_parsing.setSomeVar(int)", " The var comment \n" + " \n" + diff --git a/Examples/test-suite/java/multiple_inheritance_abstract_runme.java b/Examples/test-suite/java/multiple_inheritance_abstract_runme.java index 1489d92a7..4230e7b9a 100644 --- a/Examples/test-suite/java/multiple_inheritance_abstract_runme.java +++ b/Examples/test-suite/java/multiple_inheritance_abstract_runme.java @@ -224,6 +224,7 @@ public class multiple_inheritance_abstract_runme { check(multiple_inheritance_abstract.InputCPtrRefBottom1(b1)!=103+104, "InputCPtrRefBottom1() failed"); check(multiple_inheritance_abstract.InputCPtrRefBottom2(b2)!=206+205, "InputCPtrRefBottom2() failed"); check(multiple_inheritance_abstract.InputCPtrRefBottom3(b3)!=307+308+309, "InputCPtrRefBottom3() failed"); + // Return pointers check(multiple_inheritance_abstract.MakePtrDerived1_CBase1().cbase1y()!=3, "MakePtrDerived1_CBase1 failed"); check(multiple_inheritance_abstract.MakePtrDerived1_CBase2().cbase2()!=4, "MakePtrDerived1_CBase2 failed"); @@ -242,6 +243,15 @@ public class multiple_inheritance_abstract_runme { check(multiple_inheritance_abstract.MakeRefDerived3_CBase1().cbase1y()!=7, "MakeRefDerived3_CBase1 failed"); check(multiple_inheritance_abstract.MakeRefDerived3_CBase2().cbase2()!=8, "MakeRefDerived3_CBase2 failed"); + // Return const pointer references + check(multiple_inheritance_abstract.MakeConstPtrRefDerived1_CBase1().cbase1y()!=3, "MakeConstPtrRefDerived1_CBase1 failed"); + check(multiple_inheritance_abstract.MakeConstPtrRefDerived1_CBase2().cbase2()!=4, "MakeConstPtrRefDerived1_CBase2 failed"); + check(multiple_inheritance_abstract.MakeConstPtrRefDerived2_CBase1().cbase1y()!=6, "MakeConstPtrRefDerived2_CBase1 failed"); + check(multiple_inheritance_abstract.MakeConstPtrRefDerived2_ABase1().abase1()!=5, "MakeConstPtrRefDerived2_ABase1 failed"); + check(multiple_inheritance_abstract.MakeConstPtrRefDerived3_ABase1().abase1()!=9, "MakeConstPtrRefDerived3_ABase1 failed"); + check(multiple_inheritance_abstract.MakeConstPtrRefDerived3_CBase1().cbase1y()!=7, "MakeConstPtrRefDerived3_CBase1 failed"); + check(multiple_inheritance_abstract.MakeConstPtrRefDerived3_CBase2().cbase2()!=8, "MakeConstPtrRefDerived3_CBase2 failed"); + // Return by value (sliced objects) check(multiple_inheritance_abstract.MakeValDerived1_CBase1().cbase1y()!=1, "MakeValDerived1_CBase1 failed"); check(multiple_inheritance_abstract.MakeValDerived1_CBase2().cbase2()!=2, "MakeValDerived1_CBase2 failed"); diff --git a/Examples/test-suite/java/multiple_inheritance_nspace_runme.java b/Examples/test-suite/java/multiple_inheritance_nspace_runme.java index 461c7a131..ed2d3377a 100644 --- a/Examples/test-suite/java/multiple_inheritance_nspace_runme.java +++ b/Examples/test-suite/java/multiple_inheritance_nspace_runme.java @@ -244,6 +244,15 @@ public class multiple_inheritance_nspace_runme { check(multiple_inheritance_nspace.MakeRefDerived3_CBase1().cbase1y()!=7, "MakeRefDerived3_CBase1 failed"); check(multiple_inheritance_nspace.MakeRefDerived3_CBase2().cbase2()!=8, "MakeRefDerived3_CBase2 failed"); + // Return const pointer references + check(multiple_inheritance_nspace.MakeConstPtrRefDerived1_CBase1().cbase1y()!=3, "MakeConstPtrRefDerived1_CBase1 failed"); + check(multiple_inheritance_nspace.MakeConstPtrRefDerived1_CBase2().cbase2()!=4, "MakeConstPtrRefDerived1_CBase2 failed"); + check(multiple_inheritance_nspace.MakeConstPtrRefDerived2_CBase1().cbase1y()!=6, "MakeConstPtrRefDerived2_CBase1 failed"); + check(multiple_inheritance_nspace.MakeConstPtrRefDerived2_ABase1().abase1()!=5, "MakeConstPtrRefDerived2_ABase1 failed"); + check(multiple_inheritance_nspace.MakeConstPtrRefDerived3_ABase1().abase1()!=9, "MakeConstPtrRefDerived3_ABase1 failed"); + check(multiple_inheritance_nspace.MakeConstPtrRefDerived3_CBase1().cbase1y()!=7, "MakeConstPtrRefDerived3_CBase1 failed"); + check(multiple_inheritance_nspace.MakeConstPtrRefDerived3_CBase2().cbase2()!=8, "MakeConstPtrRefDerived3_CBase2 failed"); + // Return by value (sliced objects) check(multiple_inheritance_nspace.MakeValDerived1_CBase1().cbase1y()!=1, "MakeValDerived1_CBase1 failed"); check(multiple_inheritance_nspace.MakeValDerived1_CBase2().cbase2()!=2, "MakeValDerived1_CBase2 failed"); diff --git a/Examples/test-suite/java/multiple_inheritance_shared_ptr_runme.java b/Examples/test-suite/java/multiple_inheritance_shared_ptr_runme.java index 6472a911e..910913027 100644 --- a/Examples/test-suite/java/multiple_inheritance_shared_ptr_runme.java +++ b/Examples/test-suite/java/multiple_inheritance_shared_ptr_runme.java @@ -309,6 +309,15 @@ public class multiple_inheritance_shared_ptr_runme { check(multiple_inheritance_shared_ptr.MakeRefDerived3_CBase1().cbase1y()!=7, "MakeRefDerived3_CBase1 failed"); check(multiple_inheritance_shared_ptr.MakeRefDerived3_CBase2().cbase2()!=8, "MakeRefDerived3_CBase2 failed"); + // Return const pointer references + check(multiple_inheritance_shared_ptr.MakeConstPtrRefDerived1_CBase1().cbase1y()!=3, "MakeConstPtrRefDerived1_CBase1 failed"); + check(multiple_inheritance_shared_ptr.MakeConstPtrRefDerived1_CBase2().cbase2()!=4, "MakeConstPtrRefDerived1_CBase2 failed"); + check(multiple_inheritance_shared_ptr.MakeConstPtrRefDerived2_CBase1().cbase1y()!=6, "MakeConstPtrRefDerived2_CBase1 failed"); + check(multiple_inheritance_shared_ptr.MakeConstPtrRefDerived2_ABase1().abase1()!=5, "MakeConstPtrRefDerived2_ABase1 failed"); + check(multiple_inheritance_shared_ptr.MakeConstPtrRefDerived3_ABase1().abase1()!=9, "MakeConstPtrRefDerived3_ABase1 failed"); + check(multiple_inheritance_shared_ptr.MakeConstPtrRefDerived3_CBase1().cbase1y()!=7, "MakeConstPtrRefDerived3_CBase1 failed"); + check(multiple_inheritance_shared_ptr.MakeConstPtrRefDerived3_CBase2().cbase2()!=8, "MakeConstPtrRefDerived3_CBase2 failed"); + // Return by value (sliced objects) check(multiple_inheritance_shared_ptr.MakeValDerived1_CBase1().cbase1y()!=1, "MakeValDerived1_CBase1 failed"); check(multiple_inheritance_shared_ptr.MakeValDerived1_CBase2().cbase2()!=2, "MakeValDerived1_CBase2 failed"); diff --git a/Examples/test-suite/java/rname_runme.java b/Examples/test-suite/java/rname_runme.java index dac0a1ecf..4af6581c2 100644 --- a/Examples/test-suite/java/rname_runme.java +++ b/Examples/test-suite/java/rname_runme.java @@ -25,7 +25,7 @@ public class rname_runme { bar.foo_u((long)10); RenamedBase base = new RenamedBase(); - base.fn(base, base, base); + base.fn1(base, base, base); if (!base.newname(10.0).equals("Base")) throw new RuntimeException("base.newname"); diff --git a/Examples/test-suite/java/template_nested_flat_runme.java b/Examples/test-suite/java/template_nested_flat_runme.java new file mode 100644 index 000000000..023c18590 --- /dev/null +++ b/Examples/test-suite/java/template_nested_flat_runme.java @@ -0,0 +1,35 @@ + +import template_nested_flat.*; + +public class template_nested_flat_runme { + + static { + try { + System.loadLibrary("template_nested_flat"); + } 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[]) { + new T_NormalTemplateNormalClass().tmethod(new NormalClass()); + new OuterClass().T_OuterTMethodNormalClass(new NormalClass()); + + TemplateFuncs tf = new TemplateFuncs(); + if (tf.T_TemplateFuncs1Int(-10) != -10) + throw new RuntimeException("it failed"); + if (tf.T_TemplateFuncs2Double(-12.3) != -12.3) + throw new RuntimeException("it failed"); + + T_NestedOuterTemplateDouble tn = new T_NestedOuterTemplateDouble(); + if (tn.hohum(-12.3) != -12.3) + throw new RuntimeException("it failed"); + T_OuterClassInner1Int inner1 = new OuterClass().useInner1(new T_OuterClassInner1Int()); + T_OuterClassInner2NormalClass inner2 = new T_OuterClassInner2NormalClass(); + inner2.setEmbeddedVar(2); + T_OuterClassInner2NormalClass inner22 = new OuterClass().useInner2Again(inner2); + T_OuterClassInner1Double inner3 = new T_OuterClassInner1Double(); + } +} + diff --git a/Examples/test-suite/java/template_template_parameters_runme.java b/Examples/test-suite/java/template_template_parameters_runme.java index 42135b982..613f9087c 100644 --- a/Examples/test-suite/java/template_template_parameters_runme.java +++ b/Examples/test-suite/java/template_template_parameters_runme.java @@ -14,15 +14,33 @@ public class template_template_parameters_runme { } public static void main(String argv[]) { + // Test first part ListFastBool listBool = new ListFastBool(); listBool.setItem(true); + boolean x_boolean = listBool.getAllotype(); if (listBool.getItem() != true) throw new RuntimeException("Failed"); ListDefaultDouble listDouble = new ListDefaultDouble(); listDouble.setItem(10.2); + double x_double = listDouble.getAllotype(); if (listDouble.getItem() != 10.2) throw new RuntimeException("Failed"); + + // Test second part + FloatTestStruct floatTestStruct = new FloatTestStruct(); + FloatContainer2 floatContainer2 = floatTestStruct.getX(); + floatContainer2.setX(8.1f); + IntTestStruct intTestStruct = new IntTestStruct(); + IntContainer1 intContainer1 = intTestStruct.getX(); + intContainer1.setX(91); + if (intContainer1.getX() != 91) + throw new RuntimeException("Failed"); + if (intTestStruct.getX().getX() != 91) + throw new RuntimeException("Failed"); + IntTestStruct intTestStructReturned = template_template_parameters.TestStructContainer1Method(intTestStruct); + if (intTestStructReturned.getX().getX() != 101) + throw new RuntimeException("Failed"); } } diff --git a/Examples/test-suite/java_typemaps_proxy.i b/Examples/test-suite/java_typemaps_proxy.i index 3e9b18335..77d706835 100644 --- a/Examples/test-suite/java_typemaps_proxy.i +++ b/Examples/test-suite/java_typemaps_proxy.i @@ -119,8 +119,6 @@ public: void const_member_method(const ConstWithout *p) const {} const ConstWithout * const_var; const ConstWithout * const var_const; -private: - ConstWithout& operator=(const ConstWithout &); }; const ConstWithout * global_constwithout = 0; void global_method_constwithout(const ConstWithout *p) {} diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index bf7f24236..f07ba239d 100644 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -13,6 +13,9 @@ srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +CPP_TEST_CASES += \ + javascript_lib_arrays \ + SWIGEXE = $(top_builddir)/swig SWIG_LIB_DIR = $(top_srcdir)/Lib @@ -44,14 +47,14 @@ ifeq (node,$(JSENGINE)) SWIGOPT += -v8 -DBUILDING_NODE_EXTENSION=1 # shut up some warnings - # contract macro has an empty 'else' at the end... - aggregate.cpptest: GYP_CFLAGS = \"-Wno-empty-body\" - contract.cpptest: GYP_CFLAGS = \"-Wno-empty-body\" # dunno... ignoring generously apply_signed_char.cpptest: GYP_CFLAGS = \"-Wno-ignored-qualifiers\" constant_pointers.cpptest: GYP_CFLAGS = \"-Wno-ignored-qualifiers\" + cpp11_ref_qualifiers.cpptest: GYP_CFLAGS = \"-Wno-ignored-qualifiers\" + director_basic.cpptest: GYP_CFLAGS = \"-Wno-ignored-qualifiers\" enum_thorough.cpptest: GYP_CFLAGS = \"-Wno-ignored-qualifiers\" + member_funcptr_galore.cpptest: GYP_CFLAGS = \"-Wno-ignored-qualifiers\" director_unwrap_result.cpptest: GYP_CFLAGS = \"-Wno-ignored-qualifiers\" setup_node = \ @@ -132,6 +135,7 @@ clean: rm -f imports_a$${ext} imports_b$${ext}; \ rm -f import_stl_a$${ext} import_stl_b$${ext}; \ rm -f mod_a$${ext} mod_b$${ext}; \ - rm -f multi_import_a$${ext} multi_import_b$${ext}; \ + rm -f multi_import_a$${ext} multi_import_b$${ext} multi_import_d$${ext}; \ rm -f packageoption_a$${ext} packageoption_b$${ext} packageoption_c$${ext}; \ + rm -f template_typedef_cplx2$${ext}; \ done diff --git a/Examples/test-suite/javascript/class_scope_weird_runme.js b/Examples/test-suite/javascript/class_scope_weird_runme.js index 73c118d61..ca18c1b4d 100644 --- a/Examples/test-suite/javascript/class_scope_weird_runme.js +++ b/Examples/test-suite/javascript/class_scope_weird_runme.js @@ -4,3 +4,14 @@ f = new class_scope_weird.Foo(); g = new class_scope_weird.Foo(3); if (f.bar(3) != 3) throw RuntimeError; + +// Test missing new keyword during constructor call +var caughtException = false; +try { + g = class_scope_weird.Foo(4); +} catch (err) { + caughtException = true; +} +if (!caughtException) { + throw new Error("Instantiation exception not thrown"); +} diff --git a/Examples/test-suite/javascript/inherit_missing_runme.js b/Examples/test-suite/javascript/inherit_missing_runme.js new file mode 100644 index 000000000..05f5760e2 --- /dev/null +++ b/Examples/test-suite/javascript/inherit_missing_runme.js @@ -0,0 +1,19 @@ +var inherit_missing = require("inherit_missing"); + +a = inherit_missing.new_Foo() +b = new inherit_missing.Bar() +c = new inherit_missing.Spam() + +x = inherit_missing.do_blah(a) +if (x != "Foo::blah") + throw new Error("Whoa! Bad return {}".format(x)) + +x = inherit_missing.do_blah(b) +if (x != "Bar::blah") + throw new Error("Whoa! Bad return {}".format(x)) + +x = inherit_missing.do_blah(c) +if (x != "Spam::blah") + throw new Error("Whoa! Bad return {}".format(x)) + +inherit_missing.delete_Foo(a) diff --git a/Examples/test-suite/javascript/integers_runme.js b/Examples/test-suite/javascript/integers_runme.js new file mode 100644 index 000000000..0356176ad --- /dev/null +++ b/Examples/test-suite/javascript/integers_runme.js @@ -0,0 +1,18 @@ +var integers = require("integers"); + +var val = 3902408827 +ret = integers.signed_long_identity(val) +if (ret != val) + throw "Incorrect value: " + ret + +ret = integers.unsigned_long_identity(val) +if (ret != val) + throw "Incorrect value: " + ret + +ret = integers.signed_long_long_identity(val) +if (ret != val) + throw "Incorrect value: " + ret + +ret = integers.unsigned_long_long_identity(val) +if (ret != val) + throw "Incorrect value: " + ret diff --git a/Examples/test-suite/javascript/javascript_lib_arrays_runme.js b/Examples/test-suite/javascript/javascript_lib_arrays_runme.js new file mode 100644 index 000000000..1eb586134 --- /dev/null +++ b/Examples/test-suite/javascript/javascript_lib_arrays_runme.js @@ -0,0 +1,20 @@ +var javascript_lib_arrays = require("javascript_lib_arrays"); + +var arr = [1, 2, 3, 4, 5]; + +function check(a, b) { + if (a !== b) { + throw new Error("Not equal: " + a + " " + b) + } +} + +function check_array(a, b) { + if (a.length != b.length) + throw new Error("Array length mismatch " + a.length + " " + b.length) + if (!a.every(function(element, index) { return element === b[index]; })) + throw new Error("Arrays don't match a:" + a + " b:" + b) +} + +check(15, javascript_lib_arrays.sum1(arr, arr.length)); +check(6, javascript_lib_arrays.sum2(arr)); +check_array([1, 2, 3, 4], javascript_lib_arrays.data3) diff --git a/Examples/test-suite/javascript/li_typemaps_runme.js b/Examples/test-suite/javascript/li_typemaps_runme.js new file mode 100644 index 000000000..c0b1b43b0 --- /dev/null +++ b/Examples/test-suite/javascript/li_typemaps_runme.js @@ -0,0 +1,50 @@ +var li_typemaps = require("li_typemaps"); + +function check(a, b) { + if (a !== b) { + throw new Error("Not equal: " + a + " " + b) + } +} + +function check_array(a, b) { + if (a.length != b.length) + throw new Error("Array length mismatch " + a.length + " " + b.length) + if (!a.every(function(element, index) { return element === b[index]; })) + throw new Error("Arrays don't match a:" + a + " b:" + b) +} + +// Check double INPUT typemaps +check(li_typemaps.in_double(22.22), 22.22) +check(li_typemaps.inr_double(22.22), 22.22) + +// Check double OUTPUT typemaps +check_array(li_typemaps.out_double(22.22), [22.22]) +check_array(li_typemaps.outr_double(22.22), [22.22]) + +// Check double INOUT typemaps +check_array(li_typemaps.inout_double(22.22), [22.22]) +check_array(li_typemaps.inoutr_double(22.22), [22.22]) + +// check long long +check(li_typemaps.in_ulonglong(20), 20) +check(li_typemaps.inr_ulonglong(20), 20) +check_array(li_typemaps.out_ulonglong(20), [20]) +check_array(li_typemaps.outr_ulonglong(20), [20]) +check_array(li_typemaps.inout_ulonglong(20), [20]) +check_array(li_typemaps.inoutr_ulonglong(20), [20]) + +// check bools +check(li_typemaps.in_bool(true), true) +check(li_typemaps.inr_bool(false), false) +check_array(li_typemaps.out_bool(true), [true]) +check_array(li_typemaps.outr_bool(false), [false]) +check_array(li_typemaps.inout_bool(true), [true]) +check_array(li_typemaps.inoutr_bool(false), [false]) + +// the others +check_array(li_typemaps.inoutr_int2(1,2), [1, 2]) + +fi = li_typemaps.out_foo(10) +check(fi[0].a, 10) +check(fi[1], 20) +check(fi[2], 30) diff --git a/Examples/test-suite/javascript/overload_null_runme.js b/Examples/test-suite/javascript/overload_null_runme.js index f1e35cac7..f6c31a436 100644 --- a/Examples/test-suite/javascript/overload_null_runme.js +++ b/Examples/test-suite/javascript/overload_null_runme.js @@ -37,13 +37,13 @@ check(13, o.byval1cpr(x)); // check(15, o.byval2cpr(null)); check(16, o.byval2cpr(x)); -// forward class declaration -check(17, o.byval1forwardptr(x)); -// check(18, o.byval1forwardptr(null)); +// fwd class declaration +check(17, o.byval1fwdptr(x)); +// check(18, o.byval1fwdptr(null)); -// check(19, o.byval2forwardptr(null)); -check(20, o.byval2forwardptr(x)); +// check(19, o.byval2fwdptr(null)); +check(20, o.byval2fwdptr(x)); -check(21, o.byval1forwardref(x)); +check(21, o.byval1fwdref(x)); -check(22, o.byval2forwardref(x)); +check(22, o.byval2fwdref(x)); diff --git a/Examples/test-suite/javascript/types_directive_runme.js b/Examples/test-suite/javascript/types_directive_runme.js new file mode 100644 index 000000000..f4f0a2b7a --- /dev/null +++ b/Examples/test-suite/javascript/types_directive_runme.js @@ -0,0 +1,14 @@ +var types_directive = require("types_directive"); + +d1 = new types_directive.Time1(2001, 2, 3, 60) +// check that a Time1 instance is accepted where Date is expected +newDate = types_directive.add(d1, 7) +if (newDate.day != 10) + throw new Error("newDate mismatch") + +d2 = new types_directive.Time2(1999, 8, 7, 60) +// check that a Time2 instance is accepted where Date is expected +newDate = types_directive.add(d2, 7) +if (newDate.day != 14) + throw new Error("newDate mismatch") + diff --git a/Examples/test-suite/javascript/virtual_derivation_runme.js b/Examples/test-suite/javascript/virtual_derivation_runme.js new file mode 100644 index 000000000..be87a5d9a --- /dev/null +++ b/Examples/test-suite/javascript/virtual_derivation_runme.js @@ -0,0 +1,8 @@ +var virtual_derivation = require("virtual_derivation"); +// +// very innocent example +// +b = new virtual_derivation.B(3) +if (b.get_a() != b.get_b()) + throw new Error("something is really wrong") + diff --git a/Examples/test-suite/javascript_lib_arrays.i b/Examples/test-suite/javascript_lib_arrays.i new file mode 100644 index 000000000..512084ad5 --- /dev/null +++ b/Examples/test-suite/javascript_lib_arrays.i @@ -0,0 +1,30 @@ +%module javascript_lib_arrays + +%include + +%apply int[] { int *data1 } +%apply int[3] { int data2[3] } +%apply int[4] { int data3[4] } + +%inline %{ + +int sum1(int *data1, int size) { + int sum = 0; + for (int i = 0; i < size; i++) { + sum += data1[i]; + } + return sum; +} + +int sum2(int data2[3]) { + int sum = 0; + for (int i = 0; i < 3; i++) { + sum += data2[i]; + } + return sum; +} + +int data3[4] = {1, 2, 3, 4}; + +%} + diff --git a/Examples/test-suite/keyword_rename.i b/Examples/test-suite/keyword_rename.i index 23c01087d..645f02661 100644 --- a/Examples/test-suite/keyword_rename.i +++ b/Examples/test-suite/keyword_rename.i @@ -27,7 +27,7 @@ KW(synchronized, final) /* C# Keywords */ KW(string, out) -struct sealed {int i;}; +struct stackalloc {int i;}; /* Go Keywords */ KW(go, defer) diff --git a/Examples/test-suite/kwargs_feature.i b/Examples/test-suite/kwargs_feature.i index 2b662caeb..5b9418129 100644 --- a/Examples/test-suite/kwargs_feature.i +++ b/Examples/test-suite/kwargs_feature.i @@ -27,6 +27,7 @@ virtual int foo(int a = 1, int b = 0) {return a + b; } static int statfoo(int a = 1, int b = 0) {return a + b; } + static int statfoo_onearg(int x = 10) {return x + x; } static Foo *create(int a = 1, int b = 0) { @@ -126,3 +127,26 @@ struct Extending2 {}; struct ExtendingOptArgs1 {}; struct ExtendingOptArgs2 {}; %} + +// For strlen/strcpy +%{ +#include +%} + +// Varargs +%warnfilter(SWIGWARN_LANG_VARARGS_KEYWORD) VarargConstructor::VarargConstructor; // Can't wrap varargs with keyword arguments enabled +%warnfilter(SWIGWARN_LANG_VARARGS_KEYWORD) VarargConstructor::vararg_method; // Can't wrap varargs with keyword arguments enabled +%inline %{ +struct VarargConstructor { + char *str; + VarargConstructor(const char *fmt, ...) { + str = new char[strlen(fmt) + 1]; + strcpy(str, fmt); + } + void vararg_method(const char *fmt, ...) { + delete [] str; + str = new char[strlen(fmt) + 1]; + strcpy(str, fmt); + } +}; +%} diff --git a/Examples/test-suite/li_attribute.i b/Examples/test-suite/li_attribute.i index 4f9497afb..95389b2b6 100644 --- a/Examples/test-suite/li_attribute.i +++ b/Examples/test-suite/li_attribute.i @@ -95,6 +95,7 @@ struct MyFoo; // %attribute2 does not work with templates // class/struct attribute with get/set methods using return/pass by reference %attribute2(MyClass, MyFoo, Foo, GetFoo, SetFoo); +%attribute2ref(MyClass, MyFoo, Foo2); %inline %{ struct MyFoo { MyFoo() : x(-1) {} @@ -102,9 +103,11 @@ struct MyFoo; // %attribute2 does not work with templates }; class MyClass { MyFoo foo; + MyFoo foo2; public: MyFoo& GetFoo() { return foo; } void SetFoo(const MyFoo& other) { foo = other; } + MyFoo& Foo2() { return foo2; } }; %} diff --git a/Examples/test-suite/li_boost_shared_ptr.i b/Examples/test-suite/li_boost_shared_ptr.i index b64197be1..001eacb78 100644 --- a/Examples/test-suite/li_boost_shared_ptr.i +++ b/Examples/test-suite/li_boost_shared_ptr.i @@ -242,6 +242,10 @@ std::string nullsmartpointerpointertest(SwigBoost::shared_ptr* k) { else return "also not null"; } + +SwigBoost::shared_ptr* sp_pointer_null() { return NULL; } +SwigBoost::shared_ptr* null_sp_pointer() { static SwigBoost::shared_ptr static_sp; return &static_sp; } +SwigBoost::shared_ptr sp_value_null() { return SwigBoost::shared_ptr(); } // $owner Klass *pointerownertest() { return new Klass("pointerownertest"); diff --git a/Examples/test-suite/li_cdata.i b/Examples/test-suite/li_cdata.i index 2180af96e..4e1a01e4e 100644 --- a/Examples/test-suite/li_cdata.i +++ b/Examples/test-suite/li_cdata.i @@ -5,4 +5,8 @@ %cdata(int); %cdata(double); +%{ +#include +%} + void *malloc(size_t size); diff --git a/Examples/test-suite/li_cdata_cpp.i b/Examples/test-suite/li_cdata_cpp.i index 2d7d300e4..80ff2932b 100644 --- a/Examples/test-suite/li_cdata_cpp.i +++ b/Examples/test-suite/li_cdata_cpp.i @@ -5,4 +5,8 @@ %cdata(int); %cdata(double); +%{ +#include +%} + void *malloc(size_t size); diff --git a/Examples/test-suite/li_factory.i b/Examples/test-suite/li_factory.i index 7c59d53b2..0de3791b3 100644 --- a/Examples/test-suite/li_factory.i +++ b/Examples/test-suite/li_factory.i @@ -16,34 +16,33 @@ struct Geometry { enum GeomType{ POINT, - CIRCLE + CIRCLE, + SHAPELESS }; - - virtual ~Geometry() {} + + virtual ~Geometry() {} virtual int draw() = 0; static Geometry *create(GeomType i); - virtual Geometry *clone() = 0; + virtual Geometry *clone() = 0; }; struct Point : Geometry { int draw() { return 1; } - double width() { return 1.0; } - Geometry *clone() { return new Point(); } + double width() { return 1.0; } + Geometry *clone() { return new Point(); } }; struct Circle : Geometry { int draw() { return 2; } - double radius() { return 1.5; } - Geometry *clone() { return new Circle(); } - }; + double radius() { return 1.5; } + Geometry *clone() { return new Circle(); } + }; Geometry *Geometry::create(GeomType type) { switch (type) { case POINT: return new Point(); - case CIRCLE: return new Circle(); + case CIRCLE: return new Circle(); default: return 0; } } } - - diff --git a/Examples/test-suite/li_math.i b/Examples/test-suite/li_math.i index 3aa3db303..db39cd3de 100644 --- a/Examples/test-suite/li_math.i +++ b/Examples/test-suite/li_math.i @@ -1,7 +1,2 @@ %module li_math -#ifdef SWIGPHP -// PHP already provides these functions with the same names, so just kill that -// warning. -%warnfilter(SWIGWARN_PARSE_KEYWORD); -#endif %include math.i diff --git a/Examples/test-suite/li_std_except.i b/Examples/test-suite/li_std_except.i index 60bce999d..9bf70cd3f 100644 --- a/Examples/test-suite/li_std_except.i +++ b/Examples/test-suite/li_std_except.i @@ -9,6 +9,8 @@ %} %inline %{ + #include + #include struct E1 : public std::exception { }; diff --git a/Examples/test-suite/li_std_vector.i b/Examples/test-suite/li_std_vector.i index 33fb79720..64d057d75 100644 --- a/Examples/test-suite/li_std_vector.i +++ b/Examples/test-suite/li_std_vector.i @@ -140,3 +140,13 @@ std::vector RevStringVec (const std::vector &In) return(result); } %} + +// regression test for Tcl typecheck bug with empty list fixed in 4.1.0 +%inline %{ +int sum(const std::vector &v) { + return std::accumulate(v.begin(),v.end(),0); +} +int sum(int v) { + return v; +} +%} diff --git a/Examples/test-suite/li_std_wstring.i b/Examples/test-suite/li_std_wstring.i index 55d45383e..a790ca7e0 100644 --- a/Examples/test-suite/li_std_wstring.i +++ b/Examples/test-suite/li_std_wstring.i @@ -70,6 +70,11 @@ size_t size_wstring(const std::wstring& s) { return s.size(); } +struct wchar_test_struct { + wchar_t wchar_t_member; + wchar_t* wchar_t_ptr_member; +}; + %} #endif diff --git a/Examples/test-suite/li_typemaps.i b/Examples/test-suite/li_typemaps.i index a53c1c74a..d508c1c84 100644 --- a/Examples/test-suite/li_typemaps.i +++ b/Examples/test-suite/li_typemaps.i @@ -2,6 +2,7 @@ %include "typemaps.i" +%apply int *OUTPUT { int *OUTPUT2 }; %apply int &INOUT { int &INOUT2 }; %newobject out_foo; %inline %{ @@ -51,10 +52,13 @@ void out_longlong(long long x, long long *OUTPUT) { *OUTPUT = x; } void out_ulonglong(unsigned long long x, unsigned long long *OUTPUT) { *OUTPUT = x; } /* Tests a returning a wrapped pointer and an output argument */ -struct Foo *out_foo(int a, int *OUTPUT) { +struct Foo *out_foo(int a, int *OUTPUT, int *OUTPUT2) { struct Foo *f = new struct Foo(); f->a = a; *OUTPUT = a * 2; + struct Foo *f2 = new struct Foo(); + f2->a = a; + *OUTPUT2 = a * 3; return f; } diff --git a/Examples/test-suite/lua/Makefile.in b/Examples/test-suite/lua/Makefile.in index 92559bb8f..c0730466f 100644 --- a/Examples/test-suite/lua/Makefile.in +++ b/Examples/test-suite/lua/Makefile.in @@ -53,7 +53,7 @@ run_testcase = \ env LUA_PATH="$(srcdir)/?.lua;" $(RUNTOOL) $(LUA) $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ fi -# Clean: (does nothing, we dont generate extra lua code) +# Clean: (does nothing, we don't generate extra lua code) %.clean: @exit 0 diff --git a/Examples/test-suite/lua/li_std_string_runme.lua b/Examples/test-suite/lua/li_std_string_runme.lua index a36bf7ef6..40de81e44 100644 --- a/Examples/test-suite/lua/li_std_string_runme.lua +++ b/Examples/test-suite/lua/li_std_string_runme.lua @@ -36,7 +36,7 @@ test_const_pointer(cobj) -- swig doesn't appear to diff between const object ptrs & object ptrs very well test_pointer(cobj) -- this wants an non const object (give it a const one!) --- refs are also wrappered as ptrs (unless the correct typemaps are applied) +-- refs are also wrapped as ptrs (unless the correct typemaps are applied) robj=test_reference_out() assert(is_std_string(robj) and robj:c_str()=="test_reference_out message") -- check type & value diff --git a/Examples/test-suite/lua/li_typemaps_runme.lua b/Examples/test-suite/lua/li_typemaps_runme.lua index 7456d8245..342634a5b 100644 --- a/Examples/test-suite/lua/li_typemaps_runme.lua +++ b/Examples/test-suite/lua/li_typemaps_runme.lua @@ -38,5 +38,5 @@ assert(li_typemaps.inoutr_bool(false)==false) a,b=li_typemaps.inoutr_int2(1,2) assert(a==1 and b==2) -f,i=li_typemaps.out_foo(10) -assert(f.a==10 and i==20) +f,i,i2=li_typemaps.out_foo(10) +assert(f.a==10 and i==20 and i2==30) diff --git a/Examples/test-suite/lua/overload_null_runme.lua b/Examples/test-suite/lua/overload_null_runme.lua index 69b7de2db..9b5ef5674 100644 --- a/Examples/test-suite/lua/overload_null_runme.lua +++ b/Examples/test-suite/lua/overload_null_runme.lua @@ -29,13 +29,13 @@ assert(14 == o:byval1cpr(nil)) assert(15 == o:byval2cpr(nil)) assert(16 == o:byval2cpr(x)) --- forward class declaration -assert(17 == o:byval1forwardptr(x)) -assert(18 == o:byval1forwardptr(nil)) +-- fwd class declaration +assert(17 == o:byval1fwdptr(x)) +assert(18 == o:byval1fwdptr(nil)) -assert(19 == o:byval2forwardptr(nil)) -assert(20 == o:byval2forwardptr(x)) +assert(19 == o:byval2fwdptr(nil)) +assert(20 == o:byval2fwdptr(x)) -assert(21 == o:byval1forwardref(x)) +assert(21 == o:byval1fwdref(x)) -assert(22 == o:byval2forwardref(x)) +assert(22 == o:byval2fwdref(x)) diff --git a/Examples/test-suite/memberin_extend.i b/Examples/test-suite/memberin_extend.i index c6eb10526..43251973f 100644 --- a/Examples/test-suite/memberin_extend.i +++ b/Examples/test-suite/memberin_extend.i @@ -11,6 +11,7 @@ struct ExtendMe { %{ #include +#include std::map ExtendMeStringMap; void ExtendMe_thing_set(ExtendMe *self, const char *val) { char *old_val = ExtendMeStringMap[self]; diff --git a/Examples/test-suite/memberin_extend_c.i b/Examples/test-suite/memberin_extend_c.i index 0599e65a0..c7e017305 100644 --- a/Examples/test-suite/memberin_extend_c.i +++ b/Examples/test-suite/memberin_extend_c.i @@ -32,7 +32,8 @@ char *Person_name_get(Person *p) { } void Person_name_set(Person *p, char *val) { - strncpy(p->name,val,50); + p->name[0] = '\0'; + strncat(p->name, val, sizeof(p->name) - 1); make_upper(p->name); } %} diff --git a/Examples/test-suite/mod.h b/Examples/test-suite/mod.h index aae629850..60eb36b77 100644 --- a/Examples/test-suite/mod.h +++ b/Examples/test-suite/mod.h @@ -1,4 +1,4 @@ - +#include class C; diff --git a/Examples/test-suite/multi_import.h b/Examples/test-suite/multi_import.h index fa7a460e9..f893e3de0 100644 --- a/Examples/test-suite/multi_import.h +++ b/Examples/test-suite/multi_import.h @@ -1,3 +1,11 @@ +#ifndef MULTI_IMPORT_H +#define MULTI_IMPORT_H + +class WWW { + public: + void nullop() const {} +}; + class XXX { public: @@ -15,3 +23,5 @@ class ZZZ : public XXX public: int testz() { return 2;} }; + +#endif /* MULTI_IMPORT_H */ diff --git a/Examples/test-suite/multi_import.list b/Examples/test-suite/multi_import.list index 6f7f98cae..a42944f48 100644 --- a/Examples/test-suite/multi_import.list +++ b/Examples/test-suite/multi_import.list @@ -1,2 +1,3 @@ -multi_import_a +multi_import_d multi_import_b +multi_import_a diff --git a/Examples/test-suite/multi_import_a.i b/Examples/test-suite/multi_import_a.i index 62d7cc0b8..7cb311051 100644 --- a/Examples/test-suite/multi_import_a.i +++ b/Examples/test-suite/multi_import_a.i @@ -2,7 +2,8 @@ %module multi_import_a -%import multi_import_b.i +%import multi_import_d.i +%import "multi_import_b.i" %{ #include "multi_import.h" @@ -13,3 +14,7 @@ class ZZZ : public XXX public: int testz(); }; + +%inline %{ +void use_www_a(const WWW& w) {w.nullop();} +%} diff --git a/Examples/test-suite/multi_import_b.i b/Examples/test-suite/multi_import_b.i index a2be27055..f19608292 100644 --- a/Examples/test-suite/multi_import_b.i +++ b/Examples/test-suite/multi_import_b.i @@ -11,3 +11,7 @@ class YYY : public XXX public: int testy(); }; + +%inline %{ +void use_www_b(const WWW& w) {w.nullop();} +%} diff --git a/Examples/test-suite/multi_import_c.i b/Examples/test-suite/multi_import_c.i index 854e6b136..0e5a02e74 100644 --- a/Examples/test-suite/multi_import_c.i +++ b/Examples/test-suite/multi_import_c.i @@ -1,3 +1,8 @@ +%import "multi_import_d.i" + +// NB: this module is only imported, never compiled, so it's not necessary to +// include the header for testing purposes. + class XXX { public: diff --git a/Examples/test-suite/multi_import_d.i b/Examples/test-suite/multi_import_d.i new file mode 100644 index 000000000..bb9cf0137 --- /dev/null +++ b/Examples/test-suite/multi_import_d.i @@ -0,0 +1,12 @@ +%module multi_import_d + +%constant int myval = 1234; + +%{ +#include "multi_import.h" +%} + +class WWW { + public: + void nullop() const; +}; diff --git a/Examples/test-suite/multiple_inheritance_abstract.i b/Examples/test-suite/multiple_inheritance_abstract.i index b54a37dea..9ac16a235 100644 --- a/Examples/test-suite/multiple_inheritance_abstract.i +++ b/Examples/test-suite/multiple_inheritance_abstract.i @@ -1,9 +1,8 @@ // This is a copy of the multiple_inheritance_abstract test -%module multiple_inheritance_abstract +%module(ruby_minherit="1") multiple_inheritance_abstract -%warnfilter(SWIGWARN_RUBY_MULTIPLE_INHERITANCE, - SWIGWARN_D_MULTIPLE_INHERITANCE, - SWIGWARN_PHP_MULTIPLE_INHERITANCE); /* languages not supporting multiple inheritance or %interface */ +%warnfilter(SWIGWARN_D_MULTIPLE_INHERITANCE, + SWIGWARN_PHP_MULTIPLE_INHERITANCE); /* languages not supporting multiple inheritance */ #if defined(SWIGJAVA) || defined(SWIGCSHARP) %include "swiginterface.i" @@ -23,7 +22,7 @@ namespace Space { struct CBase1 { virtual void cbase1x() { return; - } + } virtual int cbase1y() { return 1; } @@ -307,6 +306,36 @@ namespace Space { return d; } + // Return const pointer references + CBase1 *const&MakeConstPtrRefDerived1_CBase1() { + static CBase1 *d = new Derived1(); + return d; + } + CBase2 *const&MakeConstPtrRefDerived1_CBase2() { + static CBase2 *const& d = new Derived1(); + return d; + } + CBase1 *const&MakeConstPtrRefDerived2_CBase1() { + static CBase1 *const& d = new Derived2(); + return d; + } + ABase1 *const&MakeConstPtrRefDerived2_ABase1() { + static ABase1 *const& d = new Derived2(); + return d; + } + ABase1 *const&MakeConstPtrRefDerived3_ABase1() { + static ABase1 *const& d = new Derived3(); + return d; + } + CBase1 *const&MakeConstPtrRefDerived3_CBase1() { + static CBase1 *const& d = new Derived3(); + return d; + } + CBase2 *const&MakeConstPtrRefDerived3_CBase2() { + static CBase2 *const& d = new Derived3(); + return d; + } + // Return by value (sliced objects) CBase1 MakeValDerived1_CBase1() { return Derived1(); diff --git a/Examples/test-suite/multiple_inheritance_interfaces.i b/Examples/test-suite/multiple_inheritance_interfaces.i index 2972922fb..6bb1d50cb 100644 --- a/Examples/test-suite/multiple_inheritance_interfaces.i +++ b/Examples/test-suite/multiple_inheritance_interfaces.i @@ -1,8 +1,7 @@ -%module multiple_inheritance_interfaces +%module(ruby_minherit="1") multiple_inheritance_interfaces -%warnfilter(SWIGWARN_RUBY_MULTIPLE_INHERITANCE, - SWIGWARN_D_MULTIPLE_INHERITANCE, - SWIGWARN_PHP_MULTIPLE_INHERITANCE); /* languages not supporting multiple inheritance or %interface */ +%warnfilter(SWIGWARN_D_MULTIPLE_INHERITANCE, + SWIGWARN_PHP_MULTIPLE_INHERITANCE); /* languages not supporting multiple inheritance */ #if defined(SWIGJAVA) || defined(SWIGCSHARP) %include "swiginterface.i" @@ -64,3 +63,32 @@ struct DerivedOverloaded : public BaseOverloaded { virtual void identical_overload(int i, const PTypedef &p = PTypedef()) {} }; %} + + +#if defined(SWIGJAVA) || defined(SWIGCSHARP) +%interface(Space::X) +#endif + +// Test the csinterfacemodifiers and javainterfacemodifiers typemaps. +#if defined(SWIGCSHARP) +/* change access from default "public class" to "internal class" */ +%typemap(csclassmodifiers) InternalAccess "internal class" +/* The following modifiers are also needed with the above access modifier change */ +%typemap(csclassmodifiers) Space::X "internal class" +%typemap(csinterfacemodifiers) Space::X "internal interface" +#elif defined(SWIGJAVA) +%typemap(javaclassmodifiers) InternalAccess "final /*notpublic*/ class" +%typemap(javaclassmodifiers) Space::X "final class" +%typemap(javainterfacemodifiers) Space::X "/*notpublic*/ interface" +#endif + +%inline %{ +struct InternalAccess {}; +namespace Space { + class X { + public: + virtual void x(const InternalAccess& date) const = 0; + virtual ~X() {} + }; +} +%} diff --git a/Examples/test-suite/multiple_inheritance_nspace.i b/Examples/test-suite/multiple_inheritance_nspace.i index 4faef5749..002e6d6ee 100644 --- a/Examples/test-suite/multiple_inheritance_nspace.i +++ b/Examples/test-suite/multiple_inheritance_nspace.i @@ -1,9 +1,8 @@ // This is a copy of the multiple_inheritance_abstract test -%module multiple_inheritance_nspace +%module(ruby_minherit="1") multiple_inheritance_nspace -%warnfilter(SWIGWARN_RUBY_MULTIPLE_INHERITANCE, - SWIGWARN_D_MULTIPLE_INHERITANCE, - SWIGWARN_PHP_MULTIPLE_INHERITANCE); /* languages not supporting multiple inheritance or %interface */ +%warnfilter(SWIGWARN_D_MULTIPLE_INHERITANCE, + SWIGWARN_PHP_MULTIPLE_INHERITANCE); /* languages not supporting multiple inheritance */ // nspace feature only supported by these languages #if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGD) || defined(SWIGLUA) || defined(SWIGJAVASCRIPT) @@ -32,7 +31,7 @@ namespace Space { struct CBase1 { virtual void cbase1x() { return; - } + } virtual int cbase1y() { return 1; } @@ -316,6 +315,36 @@ namespace Space { return d; } + // Return const pointer references + CBase1 *const&MakeConstPtrRefDerived1_CBase1() { + static CBase1 *d = new Derived1(); + return d; + } + CBase2 *const&MakeConstPtrRefDerived1_CBase2() { + static CBase2 *const& d = new Derived1(); + return d; + } + CBase1 *const&MakeConstPtrRefDerived2_CBase1() { + static CBase1 *const& d = new Derived2(); + return d; + } + ABase1 *const&MakeConstPtrRefDerived2_ABase1() { + static ABase1 *const& d = new Derived2(); + return d; + } + ABase1 *const&MakeConstPtrRefDerived3_ABase1() { + static ABase1 *const& d = new Derived3(); + return d; + } + CBase1 *const&MakeConstPtrRefDerived3_CBase1() { + static CBase1 *const& d = new Derived3(); + return d; + } + CBase2 *const&MakeConstPtrRefDerived3_CBase2() { + static CBase2 *const& d = new Derived3(); + return d; + } + // Return by value (sliced objects) CBase1 MakeValDerived1_CBase1() { return Derived1(); diff --git a/Examples/test-suite/multiple_inheritance_shared_ptr.i b/Examples/test-suite/multiple_inheritance_shared_ptr.i index 3c061e1a9..061db57d9 100644 --- a/Examples/test-suite/multiple_inheritance_shared_ptr.i +++ b/Examples/test-suite/multiple_inheritance_shared_ptr.i @@ -1,9 +1,8 @@ // This is a copy of the multiple_inheritance_abstract test and extended for testing %shared_ptr and %interface_impl -%module multiple_inheritance_shared_ptr +%module(ruby_minherit="1") multiple_inheritance_shared_ptr -%warnfilter(SWIGWARN_RUBY_MULTIPLE_INHERITANCE, - SWIGWARN_D_MULTIPLE_INHERITANCE, - SWIGWARN_PHP_MULTIPLE_INHERITANCE); /* languages not supporting multiple inheritance or %interface */ +%warnfilter(SWIGWARN_D_MULTIPLE_INHERITANCE, + SWIGWARN_PHP_MULTIPLE_INHERITANCE); /* languages not supporting multiple inheritance */ // Typemap changes required to mix %shared_ptr and %interface_impl // Note we don't have a way to use $javainterfacename/$csinterfacename (yet), @@ -425,6 +424,36 @@ namespace Space { return d; } + // Return const pointer references + CBase1 *const&MakeConstPtrRefDerived1_CBase1() { + static CBase1 *d = new Derived1(); + return d; + } + CBase2 *const&MakeConstPtrRefDerived1_CBase2() { + static CBase2 *const& d = new Derived1(); + return d; + } + CBase1 *const&MakeConstPtrRefDerived2_CBase1() { + static CBase1 *const& d = new Derived2(); + return d; + } + ABase1 *const&MakeConstPtrRefDerived2_ABase1() { + static ABase1 *const& d = new Derived2(); + return d; + } + ABase1 *const&MakeConstPtrRefDerived3_ABase1() { + static ABase1 *const& d = new Derived3(); + return d; + } + CBase1 *const&MakeConstPtrRefDerived3_CBase1() { + static CBase1 *const& d = new Derived3(); + return d; + } + CBase2 *const&MakeConstPtrRefDerived3_CBase2() { + static CBase2 *const& d = new Derived3(); + return d; + } + // Return by value (sliced objects) CBase1 MakeValDerived1_CBase1() { return Derived1(); diff --git a/Examples/test-suite/name_warnings.i b/Examples/test-suite/name_warnings.i index 0b62ec5d7..12e46ac9d 100644 --- a/Examples/test-suite/name_warnings.i +++ b/Examples/test-suite/name_warnings.i @@ -69,3 +69,20 @@ namespace std #endif double bar(double native, bool boolean) { return 1.0; } } + +// Test that anonymous template instantiations are ignored from +// %rename/%namewarn +%namewarn(%warningmsg(SWIGWARN_LANG_IDENTIFIER, "incorrectly warning about non-wrapped instantiated template"), error=1) "__dummy_0__"; +%inline %{ +template struct Foo { + typedef T value_type; +}; +%} +%template() Foo; + +// But they should still generate the correct typemaps etc +%inline %{ +int double_an_int(Foo::value_type v) { + return v * 2; +} +%} diff --git a/Examples/test-suite/namespace_struct.i b/Examples/test-suite/namespace_struct.i new file mode 100644 index 000000000..2d2bf555a --- /dev/null +++ b/Examples/test-suite/namespace_struct.i @@ -0,0 +1,8 @@ +%module namespace_struct + +%inline %{ + +// SWIG/R generated bad code for copyToR for a struct in a namespace in SWIG < 4.1.0 +namespace X { struct Y { int x, y; }; } + +%} diff --git a/Examples/test-suite/namespace_typemap.i b/Examples/test-suite/namespace_typemap.i index 9c74715f0..2571b5a81 100644 --- a/Examples/test-suite/namespace_typemap.i +++ b/Examples/test-suite/namespace_typemap.i @@ -2,6 +2,7 @@ %module namespace_typemap %{ +#include namespace test { /* A minimalistic string class */ class string_class { @@ -15,7 +16,7 @@ namespace test { strcpy(data,s); } ~string_class() { - if (data) delete [] data; + delete [] data; } char *c_str() { return data; diff --git a/Examples/test-suite/native_directive.i b/Examples/test-suite/native_directive.i index 9ae76e0b7..3d4858032 100644 --- a/Examples/test-suite/native_directive.i +++ b/Examples/test-suite/native_directive.i @@ -53,7 +53,7 @@ extern "C" JNIEXPORT jint JNICALL Java_native_1directive_native_1directiveJNI_Co static SwigV8ReturnValue JavaScript_alpha_count(const SwigV8Arguments &args) { SWIGV8_HANDLESCOPE(); - v8::Handle jsresult; + SWIGV8_VALUE jsresult; char *arg1 = (char *)0; int res1; char *buf1 = 0; diff --git a/Examples/test-suite/nested_class.i b/Examples/test-suite/nested_class.i index b10c33949..c778a12cf 100644 --- a/Examples/test-suite/nested_class.i +++ b/Examples/test-suite/nested_class.i @@ -201,7 +201,7 @@ struct Outer { Integer xx; } MultipleInstanceAnonDerived1, MultipleInstanceAnonDerived2, *MultipleInstanceAnonDerived3, MultipleInstanceAnonDerived4[2]; -#if defined(__GNUC__) || defined(_MSC_VER) || defined(SWIG) +#if (defined(__GNUC__) && __GNUC__ < 12) || defined(_MSC_VER) || defined(SWIG) /* some compilers do not accept these */ struct : public InnerMultiple { Integer xx; diff --git a/Examples/test-suite/nested_extend_c.i b/Examples/test-suite/nested_extend_c.i index f1d7ff2c8..67ca86578 100644 --- a/Examples/test-suite/nested_extend_c.i +++ b/Examples/test-suite/nested_extend_c.i @@ -12,6 +12,10 @@ #endif +%{ +#include "stdlib.h" +%} + #if !defined(SWIGOCTAVE) && !defined(SWIG_JAVASCRIPT_V8) %extend hiA { hiA() { diff --git a/Examples/test-suite/nested_scope.i b/Examples/test-suite/nested_scope.i index bd66eec73..dabea310e 100644 --- a/Examples/test-suite/nested_scope.i +++ b/Examples/test-suite/nested_scope.i @@ -1,9 +1,5 @@ %module nested_scope -#if !defined(SWIGCSHARP) && !defined(SWIGJAVA) -%feature ("flatnested"); -#endif - %inline %{ namespace ns { // "global" is a case-insensitive keyword in PHP. @@ -31,9 +27,9 @@ namespace ns { public: struct Nested2; #ifdef __clang__ - struct Nested2 { - int data; - }; + struct Nested2 { + int data; + }; #endif template class AbstractClass; class Real; diff --git a/Examples/test-suite/nested_scope_flat.i b/Examples/test-suite/nested_scope_flat.i new file mode 100644 index 000000000..6aab72349 --- /dev/null +++ b/Examples/test-suite/nested_scope_flat.i @@ -0,0 +1,5 @@ +%module nested_scope_flat + +%feature ("flatnested"); + +%include "nested_scope.i" diff --git a/Examples/test-suite/not_c_keywords.i b/Examples/test-suite/not_c_keywords.i new file mode 100644 index 000000000..013575bc6 --- /dev/null +++ b/Examples/test-suite/not_c_keywords.i @@ -0,0 +1,13 @@ +%module not_c_keywords + +%extend ComplexStruct { +void init() { + $self->complex = 123; +} +} + +%inline %{ +struct ComplexStruct { + int complex; /* complex as variable name */ +}; +%} diff --git a/Examples/test-suite/ocaml/Makefile.in b/Examples/test-suite/ocaml/Makefile.in index 775b1ea71..10b537e4c 100644 --- a/Examples/test-suite/ocaml/Makefile.in +++ b/Examples/test-suite/ocaml/Makefile.in @@ -20,6 +20,7 @@ apply_strings \ cpp_enum \ default_constructor \ director_binary_string \ +director_comparison_operators \ director_enum \ director_primitives \ director_redefined \ @@ -101,6 +102,10 @@ $(MULTI_CPP_TEST_CASES:=.multicpptest): extra_objects clean: $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' ocaml_clean - rm -f clientdata_prop_a.ml clientdata_prop_b.ml import_stl_a.ml import_stl_b.ml - rm -f imports_a.ml imports_b.ml mod_a.ml mod_b.ml multi_import_a.ml - rm -f multi_import_b.ml packageoption_a.ml packageoption_b.ml packageoption_c.ml + rm -f clientdata_prop_a.ml clientdata_prop_b.ml + rm -f import_stl_a.ml import_stl_b.ml + rm -f imports_a.ml imports_b.ml + rm -f mod_a.ml mod_b.ml + rm -f multi_import_a.ml multi_import_b.ml multi_import_d.ml + rm -f packageoption_a.ml packageoption_b.ml packageoption_c.ml + rm -f template_typedef_cplx2.ml diff --git a/Examples/test-suite/octave/Makefile.in b/Examples/test-suite/octave/Makefile.in index 1d54a47bb..9602d85f5 100644 --- a/Examples/test-suite/octave/Makefile.in +++ b/Examples/test-suite/octave/Makefile.in @@ -29,14 +29,6 @@ CPP_TEST_BROKEN += \ li_std_set \ li_std_stream -#C_TEST_CASES += - -# -# This test only works with modern C compilers -# -#C_TEST_CASES += \ -# complextest - include $(srcdir)/../common.mk # Overridden variables here diff --git a/Examples/test-suite/octave/abstract_access_runme.m b/Examples/test-suite/octave/abstract_access_runme.m index e49343a92..e47223c47 100644 --- a/Examples/test-suite/octave/abstract_access_runme.m +++ b/Examples/test-suite/octave/abstract_access_runme.m @@ -2,6 +2,6 @@ abstract_access d = abstract_access.D(); if (d.do_x() != 1) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/abstract_typedef_runme.m b/Examples/test-suite/octave/abstract_typedef_runme.m index e57f71504..6f90b8159 100644 --- a/Examples/test-suite/octave/abstract_typedef_runme.m +++ b/Examples/test-suite/octave/abstract_typedef_runme.m @@ -10,7 +10,7 @@ a = A(); if (a.write(e) != 1) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/callback_runme.m b/Examples/test-suite/octave/callback_runme.m index db9f7888d..95df598f1 100644 --- a/Examples/test-suite/octave/callback_runme.m +++ b/Examples/test-suite/octave/callback_runme.m @@ -2,39 +2,39 @@ _callback callback if (foo(2) != 2) - error + error("failed"); endif if (A_bar(2) != 4) - error + error("failed"); endif if (foobar(3, _callback.foo) != foo(3)) - error + error("failed"); endif if (foobar(3, foo) != foo(3)) - error + error("failed"); endif if (foobar(3, A_bar) != A_bar(3)) - error + error("failed"); endif if (foobar(3, foof) != foof(3)) - error + error("failed"); endif if (foobar_i(3, foo_i) != foo_i(3)) - error + error("failed"); endif if (foobar_d(3.5, foo_d) != foo_d(3.5)) - error + error("failed"); endif a = A(); if (foobarm(3, a, A.foom_cb_ptr) != a.foom(3)) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/class_ignore_runme.m b/Examples/test-suite/octave/class_ignore_runme.m index 3e52047c2..53cad9570 100644 --- a/Examples/test-suite/octave/class_ignore_runme.m +++ b/Examples/test-suite/octave/class_ignore_runme.m @@ -8,5 +8,5 @@ class_ignore a = class_ignore.Bar(); if (!strcmp(class_ignore.do_blah(a),"Bar::blah")) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/class_scope_weird_runme.m b/Examples/test-suite/octave/class_scope_weird_runme.m index 2fc857808..b0e975359 100644 --- a/Examples/test-suite/octave/class_scope_weird_runme.m +++ b/Examples/test-suite/octave/class_scope_weird_runme.m @@ -3,5 +3,5 @@ class_scope_weird f = class_scope_weird.Foo(); g = class_scope_weird.Foo(3); if (f.bar(3) != 3) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/compactdefaultargs_runme.m b/Examples/test-suite/octave/compactdefaultargs_runme.m index 08e872724..ada60dcbe 100644 --- a/Examples/test-suite/octave/compactdefaultargs_runme.m +++ b/Examples/test-suite/octave/compactdefaultargs_runme.m @@ -4,21 +4,21 @@ defaults1 = Defaults1(1000); defaults1 = Defaults1(); if (defaults1.ret(10.0) != 10.0) - error + error("failed"); endif if (defaults1.ret() != -1.0) - error + error("failed"); endif defaults2 = Defaults2(1000); defaults2 = Defaults2(); if (defaults2.ret(10.0) != 10.0) - error + error("failed"); endif if (defaults2.ret() != -1.0) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/constructor_copy_runme.m b/Examples/test-suite/octave/constructor_copy_runme.m index e450214c6..b6d3c3b6a 100644 --- a/Examples/test-suite/octave/constructor_copy_runme.m +++ b/Examples/test-suite/octave/constructor_copy_runme.m @@ -10,7 +10,7 @@ f11 = Foo1(f1); if (f1.x != f11.x) - error + error("failed"); endif @@ -23,7 +23,7 @@ catch end_try_catch if (!good) - error + error("failed"); endif @@ -31,7 +31,7 @@ bi = Bari(5); bc = Bari(bi); if (bi.x != bc.x) - error + error("failed"); endif @@ -44,6 +44,6 @@ catch end_try_catch if (!good) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/default_args_runme.m b/Examples/test-suite/octave/default_args_runme.m index 3d00f63e0..d2c6b4a6f 100644 --- a/Examples/test-suite/octave/default_args_runme.m +++ b/Examples/test-suite/octave/default_args_runme.m @@ -7,19 +7,19 @@ default_args if (default_args.Statics.staticmethod() != 60) - error + error("failed"); endif if (default_args.cfunc1(1) != 2) - error + error("failed"); endif if (default_args.cfunc2(1) != 3) - error + error("failed"); endif if (default_args.cfunc3(1) != 4) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/director_abstract_runme.m b/Examples/test-suite/octave/director_abstract_runme.m index 657e2e1d9..c96cf7554 100644 --- a/Examples/test-suite/octave/director_abstract_runme.m +++ b/Examples/test-suite/octave/director_abstract_runme.m @@ -28,17 +28,17 @@ MyExample3=@() subclass(director_abstract.Example3_i(),'Color',@(self,r,g,b) b); me1 = MyExample1(); if (director_abstract.Example1.get_color(me1, 1,2,3) != 1) - error + error("failed"); endif me2 = MyExample2(1,2); if (me2.get_color(me2, 1,2,3) != 2) - error + error("failed"); endif me3 = MyExample3(); if (me3.get_color(me3, 1,2,3) != 3) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/director_basic_runme.m b/Examples/test-suite/octave/director_basic_runme.m index 9de54a385..9a411a703 100644 --- a/Examples/test-suite/octave/director_basic_runme.m +++ b/Examples/test-suite/octave/director_basic_runme.m @@ -33,7 +33,7 @@ endif a = director_basic.A1(1); if (a.rg(2) != 2) - error + error("failed"); endif function self=OctClass() @@ -62,16 +62,16 @@ bd = dd.cmethod(b); cc.method(b); if (c.cmethod != 7) - error + error("failed"); endif if (bc.x != 34) - error + error("failed"); endif if (bd.x != 16) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/director_enum_runme.m b/Examples/test-suite/octave/director_enum_runme.m index 96f158d39..59a5ccf8b 100644 --- a/Examples/test-suite/octave/director_enum_runme.m +++ b/Examples/test-suite/octave/director_enum_runme.m @@ -6,5 +6,5 @@ b = director_enum.Foo(); a = MyFoo(); if (a.say_hi(director_enum.hello) != b.say_hello(director_enum.hi)) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/director_nested_runme.m b/Examples/test-suite/octave/director_nested_runme.m index 6e1d0ded9..614af0c60 100644 --- a/Examples/test-suite/octave/director_nested_runme.m +++ b/Examples/test-suite/octave/director_nested_runme.m @@ -31,9 +31,9 @@ c = FooBar_int_get_self(cc); c.advance(); if (!strcmp(c.get_name(),"FooBar::get_name hello")) - error + error("failed"); endif if (!strcmp(c.name(),"FooBar::get_name hello")) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/director_unroll_runme.m b/Examples/test-suite/octave/director_unroll_runme.m index 6ca213c4c..607b9d5ef 100644 --- a/Examples/test-suite/octave/director_unroll_runme.m +++ b/Examples/test-suite/octave/director_unroll_runme.m @@ -11,6 +11,6 @@ c = b.get(); if (swig_this(a) != swig_this(c)) a,c - error + error("failed"); endif diff --git a/Examples/test-suite/octave/enum_template_runme.m b/Examples/test-suite/octave/enum_template_runme.m index a9f940a9f..1474ce1cc 100644 --- a/Examples/test-suite/octave/enum_template_runme.m +++ b/Examples/test-suite/octave/enum_template_runme.m @@ -6,13 +6,13 @@ endif enum_template if (enum_template.MakeETest() != 1) - error + error("failed"); endif enum_template.TakeETest(0); try a=enum_template.TakeETest(0); - error + error("failed"); catch end_try_catch diff --git a/Examples/test-suite/octave/enums_runme.m b/Examples/test-suite/octave/enums_runme.m index b654d9d04..5f6bd6951 100644 --- a/Examples/test-suite/octave/enums_runme.m +++ b/Examples/test-suite/octave/enums_runme.m @@ -6,18 +6,18 @@ enums.bar3(1) enums.bar1(1) if (enums.cvar.enumInstance != 2) - error + error("failed"); endif if (enums.cvar.Slap != 10) - error + error("failed"); endif if (enums.cvar.Mine != 11) - error + error("failed"); endif if (enums.cvar.Thigh != 12) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/extend_template_ns_runme.m b/Examples/test-suite/octave/extend_template_ns_runme.m index e79a00dda..7196fac73 100644 --- a/Examples/test-suite/octave/extend_template_ns_runme.m +++ b/Examples/test-suite/octave/extend_template_ns_runme.m @@ -7,9 +7,9 @@ extend_template_ns f = Foo_One(); if (f.test1(37) != 37) - error + error("failed"); endif if (f.test2(42) != 42) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/extend_template_runme.m b/Examples/test-suite/octave/extend_template_runme.m index 1cad7bfc9..125bd4a5a 100644 --- a/Examples/test-suite/octave/extend_template_runme.m +++ b/Examples/test-suite/octave/extend_template_runme.m @@ -2,9 +2,9 @@ extend_template f = extend_template.Foo_0(); if (f.test1(37) != 37) - error + error("failed"); endif if (f.test2(42) != 42) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/extend_variable_runme.m b/Examples/test-suite/octave/extend_variable_runme.m index c55b6c55c..89af26c9d 100644 --- a/Examples/test-suite/octave/extend_variable_runme.m +++ b/Examples/test-suite/octave/extend_variable_runme.m @@ -1,6 +1,6 @@ extend_variable if (Foo.Bar != 42) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/friends_runme.m b/Examples/test-suite/octave/friends_runme.m index 31211567f..50a5b20ef 100644 --- a/Examples/test-suite/octave/friends_runme.m +++ b/Examples/test-suite/octave/friends_runme.m @@ -8,25 +8,25 @@ friends a = friends.A(2); if (friends.get_val1(a) != 2) - error + error("failed"); endif if (friends.get_val2(a) != 4) - error + error("failed"); endif if (friends.get_val3(a) != 6) - error + error("failed"); endif # nice overload working fine if (friends.get_val1(1,2,3) != 1) - error + error("failed"); endif b = friends.B(3); # David's case if (friends.mix(a,b) != 5) - error + error("failed"); endif di = friends.D_d(2); @@ -34,18 +34,18 @@ dd = friends.D_d(3.3); # incredible template overloading working just fine if (friends.get_val1(di) != 2) - error + error("failed"); endif if (friends.get_val1(dd) != 3.3) - error + error("failed"); endif friends.set(di, 4); friends.set(dd, 1.3); if (friends.get_val1(di) != 4) - error + error("failed"); endif if (friends.get_val1(dd) != 1.3) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/grouping_runme.m b/Examples/test-suite/octave/grouping_runme.m index 6d1a2d673..4e2c9ea2d 100644 --- a/Examples/test-suite/octave/grouping_runme.m +++ b/Examples/test-suite/octave/grouping_runme.m @@ -7,14 +7,14 @@ grouping x = grouping.test1(42); if (x != 42) - error + error("failed"); endif grouping.test2(42); x = (grouping.do_unary(37, grouping.NEGATE)); if (x != -37) - error + error("failed"); endif grouping.cvar.test3 = 42; diff --git a/Examples/test-suite/octave/iadd_runme.m b/Examples/test-suite/octave/iadd_runme.m index c386c669e..70cd75dae 100644 --- a/Examples/test-suite/octave/iadd_runme.m +++ b/Examples/test-suite/octave/iadd_runme.m @@ -6,5 +6,5 @@ f.AsA.x = 3; f.AsA += f.AsA; if (f.AsA.x != 6) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/inout_runme.m b/Examples/test-suite/octave/inout_runme.m index 74caaff46..c5d293eb6 100644 --- a/Examples/test-suite/octave/inout_runme.m +++ b/Examples/test-suite/octave/inout_runme.m @@ -2,26 +2,26 @@ inout a = inout.AddOne1(1); if (a != 2) - error + error("failed"); endif a = inout.AddOne3(1,1,1); if (a != [2,2,2]) - error + error("failed"); endif a = inout.AddOne1p((1,1)); if (a != (2,2)) - error + error("failed"); endif a = inout.AddOne2p((1,1),1); if (a != [(2,2),2]) - error + error("failed"); endif a = inout.AddOne3p(1,(1,1),1); if (a != [2,(2,2),2]) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/inplaceadd_runme.m b/Examples/test-suite/octave/inplaceadd_runme.m index 2bc193793..50b680aba 100644 --- a/Examples/test-suite/octave/inplaceadd_runme.m +++ b/Examples/test-suite/octave/inplaceadd_runme.m @@ -3,22 +3,22 @@ a = inplaceadd.A(7); a += 5; if (a.val != 12) - error + error("failed"); endif a -= 5; if a.val != 7: - error + error("failed"); endif a *= 2; if (a.val != 14) - error + error("failed"); endif a += a; if (a.val != 28) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/input_runme.m b/Examples/test-suite/octave/input_runme.m index 1a92d032b..477ffaac1 100644 --- a/Examples/test-suite/octave/input_runme.m +++ b/Examples/test-suite/octave/input_runme.m @@ -7,21 +7,21 @@ input f = Foo(); if (f.foo(2) != 4) - error + error("failed"); endif try a=f.foo(); - error + error("failed"); catch end_try_catch if (!strcmp(sfoo("Hello"),"Hello world")) - error + error("failed"); endif try a=sfoo(); - error + error("failed"); catch end_try_catch diff --git a/Examples/test-suite/octave/li_attribute_runme.m b/Examples/test-suite/octave/li_attribute_runme.m index ed051d9df..5e239045f 100644 --- a/Examples/test-suite/octave/li_attribute_runme.m +++ b/Examples/test-suite/octave/li_attribute_runme.m @@ -8,7 +8,7 @@ li_attribute aa = li_attribute.A(1,2,3); if (aa.a != 1) - error + error("failed"); endif aa.a = 3; if (aa.a != 3) @@ -20,31 +20,31 @@ if (aa.b != 2) endif aa.b = 5; if (aa.b != 5) - error + error("failed"); endif if (aa.d != aa.b) - error + error("failed"); endif if (aa.c != 3) - error + error("failed"); endif pi = li_attribute.Param_i(7); if (pi.value != 7) - error + error("failed"); endif pi.value=3; if (pi.value != 3) - error + error("failed"); endif b = li_attribute.B(aa); if (b.a.c != 3) - error + error("failed"); endif # class/struct attribute with get/set methods using return/pass by reference @@ -53,38 +53,38 @@ myFoo.x = 8; myClass = li_attribute.MyClass(); myClass.Foo = myFoo; if (myClass.Foo.x != 8) - error + error("failed"); endif # class/struct attribute with get/set methods using return/pass by value myClassVal = li_attribute.MyClassVal(); if (myClassVal.ReadWriteFoo.x != -1) - error + error("failed"); endif if (myClassVal.ReadOnlyFoo.x != -1) - error + error("failed"); endif myClassVal.ReadWriteFoo = myFoo; if (myClassVal.ReadWriteFoo.x != 8) - error + error("failed"); endif if (myClassVal.ReadOnlyFoo.x != 8) - error + error("failed"); endif # string attribute with get/set methods using return/pass by value myStringyClass = li_attribute.MyStringyClass("initial string"); if (myStringyClass.ReadWriteString != "initial string") - error + error("failed"); endif if (myStringyClass.ReadOnlyString != "initial string") - error + error("failed"); endif myStringyClass.ReadWriteString = "changed string"; if (myStringyClass.ReadWriteString != "changed string") - error + error("failed"); endif if (myStringyClass.ReadOnlyString != "changed string") - error + error("failed"); endif diff --git a/Examples/test-suite/octave/li_carrays_cpp_runme.m b/Examples/test-suite/octave/li_carrays_cpp_runme.m index b3b520920..57e3e9a87 100644 --- a/Examples/test-suite/octave/li_carrays_cpp_runme.m +++ b/Examples/test-suite/octave/li_carrays_cpp_runme.m @@ -11,5 +11,5 @@ d(0) = 7; d(5) = d(0) + 3; if (d(5) + d(0) != 17) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/li_carrays_runme.m b/Examples/test-suite/octave/li_carrays_runme.m index c6b5f1619..5f180cce3 100644 --- a/Examples/test-suite/octave/li_carrays_runme.m +++ b/Examples/test-suite/octave/li_carrays_runme.m @@ -11,5 +11,5 @@ d(0) = 7; d(5) = d(0) + 3; if (d(5) + d(0) != 17) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/li_cmalloc_runme.m b/Examples/test-suite/octave/li_cmalloc_runme.m index 92bcd9515..5daea2cb9 100644 --- a/Examples/test-suite/octave/li_cmalloc_runme.m +++ b/Examples/test-suite/octave/li_cmalloc_runme.m @@ -17,6 +17,6 @@ catch end_try_catch if (ok != 1) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/li_cpointer_cpp_runme.m b/Examples/test-suite/octave/li_cpointer_cpp_runme.m index 463cf44f8..3551a17a9 100644 --- a/Examples/test-suite/octave/li_cpointer_cpp_runme.m +++ b/Examples/test-suite/octave/li_cpointer_cpp_runme.m @@ -5,7 +5,7 @@ p = new_intp(); intp_assign(p,3); if (intp_value(p) != 3) - error + error("failed"); endif delete_intp(p); diff --git a/Examples/test-suite/octave/li_cpointer_runme.m b/Examples/test-suite/octave/li_cpointer_runme.m index ce055cddd..995cc2abf 100644 --- a/Examples/test-suite/octave/li_cpointer_runme.m +++ b/Examples/test-suite/octave/li_cpointer_runme.m @@ -10,7 +10,7 @@ p = new_intp(); intp_assign(p,3); if (intp_value(p) != 3) - error + error("failed"); endif delete_intp(p); diff --git a/Examples/test-suite/octave/li_cstring_runme.m b/Examples/test-suite/octave/li_cstring_runme.m index 8aea6b709..4a706d33f 100644 --- a/Examples/test-suite/octave/li_cstring_runme.m +++ b/Examples/test-suite/octave/li_cstring_runme.m @@ -7,15 +7,15 @@ li_cstring if (count("ab\0ab\0ab\0", 0) != 3) - error + error("failed"); endif if (!strcmp(test1(),"Hello World")) - error + error("failed"); endif if (!strcmp(test2()," !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_")) - error + error("failed"); endif if (!strcmp(test3("hello"),"hello-suffix")) @@ -27,18 +27,18 @@ if (!strcmp(test4("hello"),"hello-suffix")) endif if (!strcmp(test5(4),'xxxx')) - error + error("failed"); endif if (!strcmp(test6(10),'xxxxx')) - error + error("failed"); endif if (!strcmp(test7(),"Hello world!")) - error + error("failed"); endif if (!strcmp(test8()," !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_")) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/li_cwstring_runme.m b/Examples/test-suite/octave/li_cwstring_runme.m index 1fb0962e7..5b9055110 100644 --- a/Examples/test-suite/octave/li_cwstring_runme.m +++ b/Examples/test-suite/octave/li_cwstring_runme.m @@ -6,38 +6,38 @@ endif li_cwstring if (count("ab\0ab\0ab\0", 0) != 3) - error + error("failed"); endif if (!strcmp(test1(),"Hello World")) - error + error("failed"); endif if (!strcmp(test2()," !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_")) - error + error("failed"); endif if (!strcmp(test3("hello"),"hello-suffix")) - error + error("failed"); endif if (!strcmp(test4("hello"),"hello-suffix")) - error + error("failed"); endif if (!strcmp(test5(4),'xxxx')) - error + error("failed"); endif if (!strcmp(test6(10),'xxxxx')) - error + error("failed"); endif if (!strcmp(test7(),"Hello world!")) - error + error("failed"); endif if (!strcmp(test8()," !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_")) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/li_factory_runme.m b/Examples/test-suite/octave/li_factory_runme.m index 5ea9b779f..7c07825f4 100644 --- a/Examples/test-suite/octave/li_factory_runme.m +++ b/Examples/test-suite/octave/li_factory_runme.m @@ -8,11 +8,11 @@ li_factory circle = Geometry_create(Geometry.CIRCLE); r = circle.radius(); if (r != 1.5) - error + error("failed"); endif point = Geometry_create(Geometry.POINT); w = point.width(); if (w != 1.0) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/li_std_carray_runme.m b/Examples/test-suite/octave/li_std_carray_runme.m index 4943fa8a2..f7212dc9a 100644 --- a/Examples/test-suite/octave/li_std_carray_runme.m +++ b/Examples/test-suite/octave/li_std_carray_runme.m @@ -9,7 +9,7 @@ endfor i = 0; for d in v3, if (d != i) - error + error("failed"); endif i = i + 1; endfor @@ -29,7 +29,7 @@ for v3 in m3, j = 0; for d in v3, if (d != i + j) - error + error("failed"); endif j = j + 1; endfor @@ -39,7 +39,7 @@ endfor for i=0:len(m3), for j=0:len(m3), if (m3(i,j) != i + j) - error + error("failed"); endif endfor endfor diff --git a/Examples/test-suite/octave/li_std_set_runme.m b/Examples/test-suite/octave/li_std_set_runme.m index 9bd4f152c..7f43f2f13 100644 --- a/Examples/test-suite/octave/li_std_set_runme.m +++ b/Examples/test-suite/octave/li_std_set_runme.m @@ -11,15 +11,15 @@ for i in s: sum = sum + i if (sum != "abc") - error + error("failed"); i = s.__iter__() if i.next() != "a": - error + error("failed"); if i.next() != "b": - error + error("failed"); if i.next() != "c": - error + error("failed"); b = s.begin() @@ -28,7 +28,7 @@ sum = "" while (b != e): sum = sum + b.next() if sum != "abc": - error + error("failed"); b = s.rbegin() e = s.rend() @@ -37,7 +37,7 @@ while (b != e): sum = sum + b.next() if sum != "cba": - error + error("failed"); @@ -49,11 +49,11 @@ si.append(3) i = si.__iter__() if i.next() != 1: - error + error("failed"); if i.next() != 2: - error + error("failed"); if i.next() != 3: - error + error("failed"); @@ -68,17 +68,17 @@ sum = "" while (b != e): sum = sum + b.next() if sum != "ac": - error + error("failed"); b = s.begin() e = s.end() if e - b != 2: - error + error("failed"); m = b + 1 if m.value() != "c": - error + error("failed"); @@ -93,4 +93,4 @@ for i in s: sum = sum + (i,) if sum != (1, 'hello', (1, 2)): - error + error("failed"); diff --git a/Examples/test-suite/octave/li_std_stream_runme.m b/Examples/test-suite/octave/li_std_stream_runme.m index bf9402e16..cedc8e59c 100644 --- a/Examples/test-suite/octave/li_std_stream_runme.m +++ b/Examples/test-suite/octave/li_std_stream_runme.m @@ -8,6 +8,6 @@ o << a << " " << 2345 << " " << 1.435; if (o.str() != "A class 2345 1.435") - error + error("failed"); endif diff --git a/Examples/test-suite/octave/li_std_string_extra_runme.m b/Examples/test-suite/octave/li_std_string_extra_runme.m index 8d506af8a..15e18eec7 100644 --- a/Examples/test-suite/octave/li_std_string_extra_runme.m +++ b/Examples/test-suite/octave/li_std_string_extra_runme.m @@ -140,23 +140,23 @@ endif if (li_std_string_extra.test_reference_input("hello") != "hello") - error + error("failed"); endif s = li_std_string_extra.test_reference_inout("hello"); if (s != "hellohello") - error + error("failed"); endif if (li_std_string_extra.stdstring_empty() != "") - error + error("failed"); endif if (li_std_string_extra.c_empty() != "") - error + error("failed"); endif #if (li_std_string_extra.c_null() != None) -# error +# error("failed"); #endif diff --git a/Examples/test-suite/octave/li_std_wstream_runme.m b/Examples/test-suite/octave/li_std_wstream_runme.m index a017e8acd..4f1c62166 100644 --- a/Examples/test-suite/octave/li_std_wstream_runme.m +++ b/Examples/test-suite/octave/li_std_wstream_runme.m @@ -9,6 +9,6 @@ o = wostringstream(); o << a << u" " << 2345 << u" " << 1.435 << wends; if (o.str() != "A class 2345 1.435\0") - error + error("failed"); endif diff --git a/Examples/test-suite/octave/multi_import_runme.m b/Examples/test-suite/octave/multi_import_runme.m index 2b7a610d4..d22ff5c81 100644 --- a/Examples/test-suite/octave/multi_import_runme.m +++ b/Examples/test-suite/octave/multi_import_runme.m @@ -8,22 +8,22 @@ multi_import_b; x = multi_import_b.XXX(); if (x.testx() != 0) - error + error("failed"); endif y = multi_import_b.YYY(); if (y.testx() != 0) - error + error("failed"); endif if (y.testy() != 1) - error + error("failed"); endif z = multi_import_a.ZZZ(); if (z.testx() != 0) - error + error("failed"); endif if (z.testz() != 2) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/namespace_typemap_runme.m b/Examples/test-suite/octave/namespace_typemap_runme.m index ca3730773..d7e338104 100644 --- a/Examples/test-suite/octave/namespace_typemap_runme.m +++ b/Examples/test-suite/octave/namespace_typemap_runme.m @@ -1,106 +1,106 @@ namespace_typemap if (!strcmp(stest1("hello"),"hello")) - error + error("failed"); endif if (!strcmp(stest2("hello"),"hello")) - error + error("failed"); endif if (!strcmp(stest3("hello"),"hello")) - error + error("failed"); endif if (!strcmp(stest4("hello"),"hello")) - error + error("failed"); endif if (!strcmp(stest5("hello"),"hello")) - error + error("failed"); endif if (!strcmp(stest6("hello"),"hello")) - error + error("failed"); endif if (!strcmp(stest7("hello"),"hello")) - error + error("failed"); endif if (!strcmp(stest8("hello"),"hello")) - error + error("failed"); endif if (!strcmp(stest9("hello"),"hello")) - error + error("failed"); endif if (!strcmp(stest10("hello"),"hello")) - error + error("failed"); endif if (!strcmp(stest11("hello"),"hello")) - error + error("failed"); endif if (!strcmp(stest12("hello"),"hello")) - error + error("failed"); endif c = complex(2,3); r = real(c); if (ctest1(c) != r) - error + error("failed"); endif if (ctest2(c) != r) - error + error("failed"); endif if (ctest3(c) != r) - error + error("failed"); endif if (ctest4(c) != r) - error + error("failed"); endif if (ctest5(c) != r) - error + error("failed"); endif if (ctest6(c) != r) - error + error("failed"); endif if (ctest7(c) != r) - error + error("failed"); endif if (ctest8(c) != r) - error + error("failed"); endif if (ctest9(c) != r) - error + error("failed"); endif if (ctest10(c) != r) - error + error("failed"); endif if (ctest11(c) != r) - error + error("failed"); endif if (ctest12(c) != r) - error + error("failed"); endif try ttest1(-14) - error + error("failed"); catch end_try_catch diff --git a/Examples/test-suite/octave/naturalvar_runme.m b/Examples/test-suite/octave/naturalvar_runme.m index 6059b0273..40546f26c 100644 --- a/Examples/test-suite/octave/naturalvar_runme.m +++ b/Examples/test-suite/octave/naturalvar_runme.m @@ -14,6 +14,6 @@ cvar.s = "hello"; b.s = "hello"; if (b.s != cvar.s) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/overload_extend2_runme.m b/Examples/test-suite/octave/overload_extend2_runme.m index 6db6b66bb..e4611948e 100644 --- a/Examples/test-suite/octave/overload_extend2_runme.m +++ b/Examples/test-suite/octave/overload_extend2_runme.m @@ -2,29 +2,29 @@ overload_extend2 f = overload_extend2.Foo(); if (f.test(3) != 1) - error + error("failed"); endif if (f.test("hello") != 2) - error + error("failed"); endif if (f.test(3.5,2.5) != 3) - error + error("failed"); endif if (f.test("hello",20) != 1020) - error + error("failed"); endif if (f.test("hello",20,100) != 120) - error + error("failed"); endif # C default args if (f.test(f) != 30) - error + error("failed"); endif if (f.test(f,100) != 120) - error + error("failed"); endif if (f.test(f,100,200) != 300) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/overload_extend_c_runme.m b/Examples/test-suite/octave/overload_extend_c_runme.m index 79b92ca47..2a6c5c21e 100644 --- a/Examples/test-suite/octave/overload_extend_c_runme.m +++ b/Examples/test-suite/octave/overload_extend_c_runme.m @@ -7,18 +7,18 @@ overload_extend_c f = overload_extend_c.Foo(); if (f.test() != 0) - error + error("failed"); endif if (f.test(3) != 1) - error + error("failed"); endif if (f.test("hello") != 2) - error + error("failed"); endif if (f.test(3,2) != 5) - error + error("failed"); endif if (f.test(3.1)-.1 != 1003) # :) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/overload_extend_runme.m b/Examples/test-suite/octave/overload_extend_runme.m index d9959804f..a29f1910e 100644 --- a/Examples/test-suite/octave/overload_extend_runme.m +++ b/Examples/test-suite/octave/overload_extend_runme.m @@ -7,18 +7,18 @@ overload_extend f = overload_extend.Foo(); if (f.test() != 0) - error + error("failed"); endif if (f.test(3) != 1) - error + error("failed"); endif if (f.test("hello") != 2) - error + error("failed"); endif if (f.test(3,2) != 5) - error + error("failed"); endif if (f.test(3.1)-.1 != 1003) # :) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/overload_null_runme.m b/Examples/test-suite/octave/overload_null_runme.m index a7c346c26..83c11a199 100644 --- a/Examples/test-suite/octave/overload_null_runme.m +++ b/Examples/test-suite/octave/overload_null_runme.m @@ -40,13 +40,13 @@ check(14, o.byval1cpr(null)); check(15, o.byval2cpr(null)); check(16, o.byval2cpr(x)); -# forward class declaration -check(17, o.byval1forwardptr(x)); -check(18, o.byval1forwardptr(null)); +# fwd class declaration +check(17, o.byval1fwdptr(x)); +check(18, o.byval1fwdptr(null)); -check(19, o.byval2forwardptr(null)); -check(20, o.byval2forwardptr(x)); +check(19, o.byval2fwdptr(null)); +check(20, o.byval2fwdptr(x)); -check(21, o.byval1forwardref(x)); +check(21, o.byval1fwdref(x)); -check(22, o.byval2forwardref(x)); +check(22, o.byval2fwdref(x)); diff --git a/Examples/test-suite/octave/preproc_runme.m b/Examples/test-suite/octave/preproc_runme.m index e9af66e78..80f1d32ba 100644 --- a/Examples/test-suite/octave/preproc_runme.m +++ b/Examples/test-suite/octave/preproc_runme.m @@ -6,18 +6,18 @@ endif preproc if (preproc.cvar.endif != 1) - error + error("failed"); endif if (preproc.cvar.define != 1) - error + error("failed"); endif if (preproc.cvar.defined != 1) - error + error("failed"); endif if (2*preproc.one != preproc.two) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/primitive_ref_runme.m b/Examples/test-suite/octave/primitive_ref_runme.m index 68a5750c3..799b6db17 100644 --- a/Examples/test-suite/octave/primitive_ref_runme.m +++ b/Examples/test-suite/octave/primitive_ref_runme.m @@ -1,53 +1,53 @@ primitive_ref if (ref_int(3) != 3) - error + error("failed"); endif if (ref_uint(3) != 3) - error + error("failed"); endif if (ref_short(3) != 3) - error + error("failed"); endif if (ref_ushort(3) != 3) - error + error("failed"); endif if (ref_long(3) != 3) - error + error("failed"); endif if (ref_ulong(3) != 3) - error + error("failed"); endif if (ref_schar(3) != 3) - error + error("failed"); endif if (ref_uchar(3) != 3) - error + error("failed"); endif if (ref_float(3.5) != 3.5) - error + error("failed"); endif if (ref_double(3.5) != 3.5) - error + error("failed"); endif if (ref_bool(true) != true) - error + error("failed"); endif if (!strcmp(ref_char('x'),'x')) - error + error("failed"); endif if (ref_over(0) != 0) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/reference_global_vars_runme.m b/Examples/test-suite/octave/reference_global_vars_runme.m index 67ad9c514..c7f4f56b7 100644 --- a/Examples/test-suite/octave/reference_global_vars_runme.m +++ b/Examples/test-suite/octave/reference_global_vars_runme.m @@ -2,90 +2,90 @@ reference_global_vars # const class reference variable if (getconstTC().num != 33) - error + error("failed"); endif # primitive reference variables cvar.var_bool = createref_bool(false); if (value_bool(cvar.var_bool) != 0) - error + error("failed"); endif cvar.var_bool = createref_bool(true); if (value_bool(cvar.var_bool) != 1) - error + error("failed"); endif cvar.var_char = createref_char('w'); if (!strcmp(value_char(cvar.var_char),'w')) - error + error("failed"); endif cvar.var_unsigned_char = createref_unsigned_char(10); if (value_unsigned_char(cvar.var_unsigned_char) != 10) - error + error("failed"); endif cvar.var_signed_char = createref_signed_char(10); if (value_signed_char(cvar.var_signed_char) != 10) - error + error("failed"); endif cvar.var_short = createref_short(10); if (value_short(cvar.var_short) != 10) - error + error("failed"); endif cvar.var_unsigned_short = createref_unsigned_short(10); if (value_unsigned_short(cvar.var_unsigned_short) != 10) - error + error("failed"); endif cvar.var_int = createref_int(10); if (value_int(cvar.var_int) != 10) - error + error("failed"); endif cvar.var_unsigned_int = createref_unsigned_int(10); if (value_unsigned_int(cvar.var_unsigned_int) != 10) - error + error("failed"); endif cvar.var_long = createref_long(10); if (value_long(cvar.var_long) != 10) - error + error("failed"); endif cvar.var_unsigned_long = createref_unsigned_long(10); if (value_unsigned_long(cvar.var_unsigned_long) != 10) - error + error("failed"); endif cvar.var_long_long = createref_long_long(int64(0x6FFFFFFFFFFFFFF8)); if (value_long_long(cvar.var_long_long) != int64(0x6FFFFFFFFFFFFFF8)) - error + error("failed"); endif #ull = abs(0xFFFFFFF2FFFFFFF0) ull = uint64(55834574864); cvar.var_unsigned_long_long = createref_unsigned_long_long(ull); if (value_unsigned_long_long(cvar.var_unsigned_long_long) != ull) - error + error("failed"); endif cvar.var_float = createref_float(10.5); if (value_float(cvar.var_float) != 10.5) - error + error("failed"); endif cvar.var_double = createref_double(10.5); if (value_double(cvar.var_double) != 10.5) - error + error("failed"); endif # class reference variable cvar.var_TestClass = createref_TestClass(TestClass(20)); if (value_TestClass(cvar.var_TestClass).num != 20) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/rename_scope_runme.m b/Examples/test-suite/octave/rename_scope_runme.m index 154f99dfe..776d218c5 100644 --- a/Examples/test-suite/octave/rename_scope_runme.m +++ b/Examples/test-suite/octave/rename_scope_runme.m @@ -4,11 +4,11 @@ a = Natural_UP(); b = Natural_BP(); if (a.rtest() != 1) - error + error("failed"); endif if (b.rtest() != 1) - error + error("failed"); endif f = @equals; diff --git a/Examples/test-suite/octave/ret_by_value_runme.m b/Examples/test-suite/octave/ret_by_value_runme.m index 67f80aae2..c1c508353 100644 --- a/Examples/test-suite/octave/ret_by_value_runme.m +++ b/Examples/test-suite/octave/ret_by_value_runme.m @@ -7,9 +7,9 @@ ret_by_value a = ret_by_value.get_test(); if (a.myInt != 100) - error + error("failed"); endif if (a.myShort != 200) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/smart_pointer_extend_runme.m b/Examples/test-suite/octave/smart_pointer_extend_runme.m index 6c9258e6d..cf82f7350 100644 --- a/Examples/test-suite/octave/smart_pointer_extend_runme.m +++ b/Examples/test-suite/octave/smart_pointer_extend_runme.m @@ -9,7 +9,7 @@ f = Foo(); b = Bar(f); if (b.extension() != f.extension()) - error + error("failed"); endif @@ -18,15 +18,15 @@ d = CDerived(); p = CPtr(); if (b.bar() != p.bar()) - error + error("failed"); endif if (d.foo() != p.foo()) - error + error("failed"); endif if (b.hello() != p.hello()) - error + error("failed"); endif @@ -36,11 +36,11 @@ d = DFoo(); dp = DPtrFoo(d); if (d.SExt(1) != dp.SExt(1)) - error + error("failed"); endif if (d.Ext(1) != dp.Ext(1)) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/smart_pointer_member_runme.m b/Examples/test-suite/octave/smart_pointer_member_runme.m index 30251c3a8..1c2d0e9ed 100644 --- a/Examples/test-suite/octave/smart_pointer_member_runme.m +++ b/Examples/test-suite/octave/smart_pointer_member_runme.m @@ -4,7 +4,7 @@ f = Foo(); f.y = 1; if (f.y != 1) - error + error("failed"); endif b = Bar(f); @@ -15,18 +15,18 @@ if (f.y != 2) endif if (swig_this(b.x) != swig_this(f.x)) - error + error("failed"); endif if (b.z != f.z) - error + error("failed"); endif try if (Foo.z == Bar.z) - error + error("failed"); endif - error + error("failed"); catch end_try_catch diff --git a/Examples/test-suite/octave/smart_pointer_multi_runme.m b/Examples/test-suite/octave/smart_pointer_multi_runme.m index 71ef9109a..ea15d04b9 100644 --- a/Examples/test-suite/octave/smart_pointer_multi_runme.m +++ b/Examples/test-suite/octave/smart_pointer_multi_runme.m @@ -7,11 +7,11 @@ g = Grok(b); s.x = 3; if (s.getx() != 3) - error + error("failed"); endif g.x = 4; if (g.getx() != 4) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/smart_pointer_multi_typedef_runme.m b/Examples/test-suite/octave/smart_pointer_multi_typedef_runme.m index 4b77e0eea..c2ab78714 100644 --- a/Examples/test-suite/octave/smart_pointer_multi_typedef_runme.m +++ b/Examples/test-suite/octave/smart_pointer_multi_typedef_runme.m @@ -7,12 +7,12 @@ g = Grok(b); s.x = 3; if (s.getx() != 3) - error + error("failed"); endif g.x = 4; if (g.getx() != 4) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/smart_pointer_overload_runme.m b/Examples/test-suite/octave/smart_pointer_overload_runme.m index a5df0ded4..1bfb68354 100644 --- a/Examples/test-suite/octave/smart_pointer_overload_runme.m +++ b/Examples/test-suite/octave/smart_pointer_overload_runme.m @@ -10,23 +10,23 @@ b = Bar(f); if (f.test(3) != 1) - error + error("failed"); endif if (f.test(3.5) != 2) - error + error("failed"); endif if (f.test("hello") != 3) - error + error("failed"); endif if (b.test(3) != 1) - error + error("failed"); endif if (b.test(3.5) != 2) - error + error("failed"); endif if (b.test("hello") != 3) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/smart_pointer_rename_runme.m b/Examples/test-suite/octave/smart_pointer_rename_runme.m index 5eb6d4c3c..307bd8f95 100644 --- a/Examples/test-suite/octave/smart_pointer_rename_runme.m +++ b/Examples/test-suite/octave/smart_pointer_rename_runme.m @@ -9,14 +9,14 @@ f = Foo(); b = Bar(f); if (b.test() != 3) - error + error("failed"); endif if (b.ftest1(1) != 1) - error + error("failed"); endif if (b.ftest2(2,3) != 2) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/smart_pointer_simple_runme.m b/Examples/test-suite/octave/smart_pointer_simple_runme.m index 30b1387c4..c15c43ca9 100644 --- a/Examples/test-suite/octave/smart_pointer_simple_runme.m +++ b/Examples/test-suite/octave/smart_pointer_simple_runme.m @@ -10,11 +10,11 @@ b = Bar(f); b.x = 3; if (b.getx() != 3) - error + error("failed"); endif fp = b.__deref__(); fp.x = 4; if (fp.getx() != 4) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/smart_pointer_templatevariables_runme.m b/Examples/test-suite/octave/smart_pointer_templatevariables_runme.m index 4884fa24b..ee45f68f9 100644 --- a/Examples/test-suite/octave/smart_pointer_templatevariables_runme.m +++ b/Examples/test-suite/octave/smart_pointer_templatevariables_runme.m @@ -3,17 +3,17 @@ smart_pointer_templatevariables d = DiffImContainerPtr_D(create(1234, 5678)); if (d.id != 1234) - error + error("failed"); endif #if (d.xyz != 5678): -# error +# error("failed"); d.id = 4321; #d.xyz = 8765 if (d.id != 4321) - error + error("failed"); endif #if (d.xyz != 8765): -# error +# error("failed"); diff --git a/Examples/test-suite/octave/smart_pointer_typedef_runme.m b/Examples/test-suite/octave/smart_pointer_typedef_runme.m index 0e1c8a61e..3a094670f 100644 --- a/Examples/test-suite/octave/smart_pointer_typedef_runme.m +++ b/Examples/test-suite/octave/smart_pointer_typedef_runme.m @@ -10,11 +10,11 @@ b = Bar(f); b.x = 3; if (b.getx() != 3) - error + error("failed"); endif fp = b.__deref__(); fp.x = 4; if (fp.getx() != 4) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/static_const_member_2_runme.m b/Examples/test-suite/octave/static_const_member_2_runme.m index 73260bae7..8619fd1eb 100644 --- a/Examples/test-suite/octave/static_const_member_2_runme.m +++ b/Examples/test-suite/octave/static_const_member_2_runme.m @@ -18,6 +18,6 @@ end_try_catch if (Foo.BAZ.val != 2*Foo.BAR.val) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/std_containers_runme.m b/Examples/test-suite/octave/std_containers_runme.m index eae3d5d9f..d069b585c 100644 --- a/Examples/test-suite/octave/std_containers_runme.m +++ b/Examples/test-suite/octave/std_containers_runme.m @@ -132,7 +132,7 @@ s.append(3); j=1; for i in s, if (i != j) - error + error("failed"); endif j = j + 1; endfor diff --git a/Examples/test-suite/octave/struct_value_runme.m b/Examples/test-suite/octave/struct_value_runme.m index ff344047e..7f7448bb6 100644 --- a/Examples/test-suite/octave/struct_value_runme.m +++ b/Examples/test-suite/octave/struct_value_runme.m @@ -9,10 +9,10 @@ b = struct_value.Bar(); b.a.x = 3; if (b.a.x != 3) - error + error("failed"); endif b.b.x = 3; if (b.b.x != 3) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/swigobject_runme.m b/Examples/test-suite/octave/swigobject_runme.m index 73167e497..9ab3aa8c6 100644 --- a/Examples/test-suite/octave/swigobject_runme.m +++ b/Examples/test-suite/octave/swigobject_runme.m @@ -11,7 +11,7 @@ a1 = a_ptr(a); a2 = a_ptr(a); if (swig_this(a1) != swig_this(a2)) - error + error("failed"); endif @@ -20,7 +20,7 @@ xstr1 = printf("0x%x",lthis); xstr2 = pointer_str(a); if (xstr1 != xstr2) - error + error("failed"); endif s = str(a.this); @@ -29,5 +29,5 @@ r = repr(a.this); v1 = v_ptr(a); v2 = v_ptr(a); if (uint64(v1) != uint64(v2)) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/template_extend1_runme.m b/Examples/test-suite/octave/template_extend1_runme.m index 5035debf5..05e534107 100644 --- a/Examples/test-suite/octave/template_extend1_runme.m +++ b/Examples/test-suite/octave/template_extend1_runme.m @@ -9,9 +9,9 @@ a = template_extend1.lBaz(); b = template_extend1.dBaz(); if (!strcmp(a.foo(),"lBaz::foo")) - error + error("failed"); endif if (!strcmp(b.foo(),"dBaz::foo")) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/template_extend2_runme.m b/Examples/test-suite/octave/template_extend2_runme.m index 24472a9ed..e9b5fb799 100644 --- a/Examples/test-suite/octave/template_extend2_runme.m +++ b/Examples/test-suite/octave/template_extend2_runme.m @@ -9,9 +9,9 @@ a = template_extend2.lBaz(); b = template_extend2.dBaz(); if (!strcmp(a.foo(),"lBaz::foo")) - error + error("failed"); endif if (!strcmp(b.foo(),"dBaz::foo")) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/template_inherit_runme.m b/Examples/test-suite/octave/template_inherit_runme.m index 368cce227..72d7e7511 100644 --- a/Examples/test-suite/octave/template_inherit_runme.m +++ b/Examples/test-suite/octave/template_inherit_runme.m @@ -12,62 +12,62 @@ e = FooUInt(); f = BarUInt(); if (!strcmp(a.blah(),"Foo")) - error + error("failed"); endif if (!strcmp(b.blah(),"Foo")) - error + error("failed"); endif if (!strcmp(e.blah(),"Foo")) - error + error("failed"); endif if (!strcmp(c.blah(),"Bar")) - error + error("failed"); endif if (!strcmp(d.blah(),"Bar")) - error + error("failed"); endif if (!strcmp(f.blah(),"Bar")) - error + error("failed"); endif if (!strcmp(c.foomethod(),"foomethod")) - error + error("failed"); endif if (!strcmp(d.foomethod(),"foomethod")) - error + error("failed"); endif if (!strcmp(f.foomethod(),"foomethod")) - error + error("failed"); endif if (!strcmp(invoke_blah_int(a),"Foo")) - error + error("failed"); endif if (!strcmp(invoke_blah_int(c),"Bar")) - error + error("failed"); endif if (!strcmp(invoke_blah_double(b),"Foo")) - error + error("failed"); endif if (!strcmp(invoke_blah_double(d),"Bar")) - error + error("failed"); endif if (!strcmp(invoke_blah_uint(e),"Foo")) - error + error("failed"); endif if (!strcmp(invoke_blah_uint(f),"Bar")) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/template_ns4_runme.m b/Examples/test-suite/octave/template_ns4_runme.m index b5746427b..6dff55694 100644 --- a/Examples/test-suite/octave/template_ns4_runme.m +++ b/Examples/test-suite/octave/template_ns4_runme.m @@ -7,5 +7,5 @@ template_ns4 d = make_Class_DD(); if (!strcmp(d.test(),"test")) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/template_ns_runme.m b/Examples/test-suite/octave/template_ns_runme.m index 29a2f53f6..44b13e62c 100644 --- a/Examples/test-suite/octave/template_ns_runme.m +++ b/Examples/test-suite/octave/template_ns_runme.m @@ -3,19 +3,19 @@ p1 = pairii(2,3); p2 = pairii(p1); if (p2.first != 2) - error + error("failed"); endif if (p2.second != 3) - error + error("failed"); endif p3 = pairdd(3.5,2.5); p4 = pairdd(p3); if (p4.first != 3.5) - error + error("failed"); endif if (p4.second != 2.5) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/template_tbase_template_runme.m b/Examples/test-suite/octave/template_tbase_template_runme.m index da8ec4c69..b1bfd8f7d 100644 --- a/Examples/test-suite/octave/template_tbase_template_runme.m +++ b/Examples/test-suite/octave/template_tbase_template_runme.m @@ -2,5 +2,5 @@ template_tbase_template a = make_Class_dd(); if (!strcmp(a.test(),"test")) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/template_typedef_cplx2_runme.m b/Examples/test-suite/octave/template_typedef_cplx2_runme.m index a72e0f1e0..eb783fe81 100644 --- a/Examples/test-suite/octave/template_typedef_cplx2_runme.m +++ b/Examples/test-suite/octave/template_typedef_cplx2_runme.m @@ -15,7 +15,7 @@ end_try_catch if (strfind('ArithUnaryFunction',swig_type(d)) != 1) d error("is not an ArithUnaryFunction") - error + error("failed"); endif try @@ -77,7 +77,7 @@ end_try_catch if (strfind('ArithUnaryFunction',swig_type(g)) != 1) g error("is not an ArithUnaryFunction") - error + error("failed"); endif @@ -98,6 +98,6 @@ try a = g.get_value(); catch error(g, "has not get_value() method") - error + error("failed"); end_try_catch diff --git a/Examples/test-suite/octave/template_typedef_runme.m b/Examples/test-suite/octave/template_typedef_runme.m index 8d8af795b..2a734e207 100644 --- a/Examples/test-suite/octave/template_typedef_runme.m +++ b/Examples/test-suite/octave/template_typedef_runme.m @@ -8,7 +8,7 @@ try a = swig_this(d); a = swig_this(c); catch - error + error("failed"); end_try_catch try @@ -37,15 +37,15 @@ end_try_catch # the old large format if (strcmp("",swig_typequery("vfncs::ArithUnaryFunction::argument_type,vfncs::arith_traits::result_type > *"))) - error + error("failed"); endif # the reduced format if (strcmp("",swig_typequery("vfncs::ArithUnaryFunction *"))) - error + error("failed"); endif # this is a bad name if (!strcmp("",swig_typequery("vfncs::ArithUnaryFunction *"))) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/typemap_namespace_runme.m b/Examples/test-suite/octave/typemap_namespace_runme.m index ec62a3910..e67781c66 100644 --- a/Examples/test-suite/octave/typemap_namespace_runme.m +++ b/Examples/test-suite/octave/typemap_namespace_runme.m @@ -1,10 +1,10 @@ typemap_namespace if (!strcmp(test1("hello"),"hello")) - error + error("failed"); endif if (!strcmp(test2("hello"),"hello")) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/typemap_ns_using_runme.m b/Examples/test-suite/octave/typemap_ns_using_runme.m index dd3f657f0..d94241b9c 100644 --- a/Examples/test-suite/octave/typemap_ns_using_runme.m +++ b/Examples/test-suite/octave/typemap_ns_using_runme.m @@ -1,5 +1,5 @@ typemap_ns_using if (typemap_ns_using.spam(37) != 37) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/types_directive_runme.m b/Examples/test-suite/octave/types_directive_runme.m index 0757c6c39..5ad4af1bb 100644 --- a/Examples/test-suite/octave/types_directive_runme.m +++ b/Examples/test-suite/octave/types_directive_runme.m @@ -3,13 +3,13 @@ types_directive d1 = Time1(2001, 2, 3, 60); newDate = add(d1, 7); # check that a Time1 instance is accepted where Date is expected if (newDate.day != 10) - error + error("failed"); endif d2 = Time2(1999, 8, 7, 60); newDate = add(d2, 7); # check that a Time2 instance is accepted where Date is expected if (newDate.day != 14) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/using1_runme.m b/Examples/test-suite/octave/using1_runme.m index 9253a1d35..e25128ec7 100644 --- a/Examples/test-suite/octave/using1_runme.m +++ b/Examples/test-suite/octave/using1_runme.m @@ -6,5 +6,5 @@ endif using1 if (using1.spam(37) != 37) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/using2_runme.m b/Examples/test-suite/octave/using2_runme.m index 7cc668940..0213ee7c6 100644 --- a/Examples/test-suite/octave/using2_runme.m +++ b/Examples/test-suite/octave/using2_runme.m @@ -6,5 +6,5 @@ endif using2 if (using2.spam(37) != 37) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/virtual_poly_runme.m b/Examples/test-suite/octave/virtual_poly_runme.m index 0c7c95153..363f86798 100644 --- a/Examples/test-suite/octave/virtual_poly_runme.m +++ b/Examples/test-suite/octave/virtual_poly_runme.m @@ -10,23 +10,23 @@ dc = d.copy(); ic = i.copy(); if (d.get() != dc.get()) - error + error("failed"); endif if (i.get() != ic.get()) - error + error("failed"); endif virtual_poly.incr(ic); if ((i.get() + 1) != ic.get()) - error + error("failed"); endif dr = d.ref_this(); if (d.get() != dr.get()) - error + error("failed"); endif @@ -35,10 +35,10 @@ endif # ddc = virtual_poly.NDouble_narrow(d.nnumber()); if (d.get() != ddc.get()) - error + error("failed"); endif dic = virtual_poly.NInt_narrow(i.nnumber()); if (i.get() != dic.get()) - error + error("failed"); endif diff --git a/Examples/test-suite/octave/voidtest_runme.m b/Examples/test-suite/octave/voidtest_runme.m index fb411ee4e..c4815a597 100644 --- a/Examples/test-suite/octave/voidtest_runme.m +++ b/Examples/test-suite/octave/voidtest_runme.m @@ -27,16 +27,16 @@ end_try_catch v1 = voidtest.vfunc1(f); v2 = voidtest.vfunc2(f); if (swig_this(v1) != swig_this(v2)) - error + error("failed"); endif v3 = voidtest.vfunc3(v1); if (swig_this(v3) != swig_this(f)) - error + error("failed"); endif v4 = voidtest.vfunc1(f); if (swig_this(v4) != swig_this(v1)) - error + error("failed"); endif diff --git a/Examples/test-suite/operator_overload_break.i b/Examples/test-suite/operator_overload_break.i index a948f2d49..809498fa7 100644 --- a/Examples/test-suite/operator_overload_break.i +++ b/Examples/test-suite/operator_overload_break.i @@ -18,6 +18,7 @@ %{ #include +#include using namespace std; %} diff --git a/Examples/test-suite/operator_pointer_ref.i b/Examples/test-suite/operator_pointer_ref.i index 84182da0d..cd4ed2db0 100644 --- a/Examples/test-suite/operator_pointer_ref.i +++ b/Examples/test-suite/operator_pointer_ref.i @@ -4,6 +4,8 @@ #if defined(_MSC_VER) #pragma warning(disable: 4996) // 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup. See online help for details. #endif +#include +#include %} %rename(AsCharStarRef) operator char*&; diff --git a/Examples/test-suite/overload_arrays.i b/Examples/test-suite/overload_arrays.i index 272c96a3d..e6bd09adf 100644 --- a/Examples/test-suite/overload_arrays.i +++ b/Examples/test-suite/overload_arrays.i @@ -2,10 +2,6 @@ // Based on overload_simple testcase %module overload_arrays -#ifdef SWIGCHICKEN -%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) fbool; -#endif - #ifdef SWIGLUA // lua only has one numeric type, so most of the overloads shadow each other creating warnings %warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) foo; diff --git a/Examples/test-suite/overload_null.i b/Examples/test-suite/overload_null.i index d4879fdb5..0ec970399 100644 --- a/Examples/test-suite/overload_null.i +++ b/Examples/test-suite/overload_null.i @@ -35,18 +35,18 @@ struct Overload { int byval2cpr(Y*const& y) { return 15; } int byval2cpr(X x) { return 16; } - // forward class declaration - int byval1forwardptr(X x) { return 17; } - int byval1forwardptr(F* f) { return 18; } + // fwd class declaration + int byval1fwdptr(X x) { return 17; } + int byval1fwdptr(F* f) { return 18; } - int byval2forwardptr(F* f) { return 19; } - int byval2forwardptr(X x) { return 20; } + int byval2fwdptr(F* f) { return 19; } + int byval2fwdptr(X x) { return 20; } - int byval1forwardref(X x) { return 21; } - int byval1forwardref(F& f) { return -21; } + int byval1fwdref(X x) { return 21; } + int byval1fwdref(F& f) { return -21; } - int byval2forwardref(F& f) { return -22; } - int byval2forwardref(X x) { return 22; } + int byval2fwdref(F& f) { return -22; } + int byval2fwdref(X x) { return 22; } }; %} diff --git a/Examples/test-suite/overload_polymorphic.i b/Examples/test-suite/overload_polymorphic.i index ac004f948..72aabd840 100644 --- a/Examples/test-suite/overload_polymorphic.i +++ b/Examples/test-suite/overload_polymorphic.i @@ -23,4 +23,7 @@ class Unknown; int test2(Unknown* unknown) { return 0; } int test2(Base* base) { return 1; } +int test3(const char*, const Base* = 0, bool = false) { return 0; } +int test3(Base&, const char* = 0, const Base* = 0, bool = false) { return 1; } + %} diff --git a/Examples/test-suite/overload_simple.i b/Examples/test-suite/overload_simple.i index ba1900b40..fa2e335bb 100644 --- a/Examples/test-suite/overload_simple.i +++ b/Examples/test-suite/overload_simple.i @@ -1,10 +1,6 @@ // Simple tests of overloaded functions %module overload_simple -#ifdef SWIGCHICKEN -%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) fbool; -#endif - #ifdef SWIGLUA // lua only has one numeric type, so most of the overloads shadow each other creating warnings %warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) foo; diff --git a/Examples/test-suite/perl5/Makefile.in b/Examples/test-suite/perl5/Makefile.in index 48d5fa5d1..6388e5b32 100644 --- a/Examples/test-suite/perl5/Makefile.in +++ b/Examples/test-suite/perl5/Makefile.in @@ -16,11 +16,13 @@ CPP_TEST_CASES += \ li_cstring \ li_cdata_carrays_cpp \ li_reference \ + memberin1 \ director_nestedmodule \ C_TEST_CASES += \ li_cstring \ li_cdata_carrays \ + multivalue \ include $(srcdir)/../common.mk diff --git a/Examples/test-suite/perl5/li_typemaps_runme.pl b/Examples/test-suite/perl5/li_typemaps_runme.pl index a573b89a0..2755862a2 100644 --- a/Examples/test-suite/perl5/li_typemaps_runme.pl +++ b/Examples/test-suite/perl5/li_typemaps_runme.pl @@ -1,7 +1,7 @@ #!/usr/bin/perl use strict; use warnings; -use Test::More tests => 415; +use Test::More tests => 416; BEGIN { use_ok('li_typemaps') } require_ok('li_typemaps'); @@ -75,10 +75,11 @@ SKIP: { batch('ulonglong', $c); } -my($foo, $int) = li_typemaps::out_foo(10); +my($foo, $int, $int2) = li_typemaps::out_foo(10); isa_ok($foo, 'li_typemaps::Foo'); is($foo->{a}, 10); is($int, 20); +is($int2, 30); my($a, $b) = li_typemaps::inoutr_int2(13, 31); is($a, 13); diff --git a/Examples/test-suite/perl5/multivalue_runme.pl b/Examples/test-suite/perl5/multivalue_runme.pl new file mode 100644 index 000000000..b58a58a11 --- /dev/null +++ b/Examples/test-suite/perl5/multivalue_runme.pl @@ -0,0 +1,20 @@ +use strict; +use warnings; +use Test::More tests => 8; + +BEGIN { use_ok('multivalue') } +require_ok('multivalue'); + +my ($q, $r); + +($q, $r) = multivalue::divide_l(37, 5); +is($q, 7, "Test divide_l quotient"); +is($r, 2, "Test divide_l remainder"); + +($q, $r) = multivalue::divide_v(41, 7); +is($q, 5, "Test divide_v quotient"); +is($r, 6, "Test divide_v remainder"); + +($q, $r) = multivalue::divide_mv(91, 13); +is($q, 7, "Test divide_mv quotient"); +is($r, 0, "Test divide_mv remainder"); diff --git a/Examples/test-suite/perl5/operator_overload_break_runme.pl b/Examples/test-suite/perl5/operator_overload_break_runme.pl index fd3fe3303..c692dfac7 100644 --- a/Examples/test-suite/perl5/operator_overload_break_runme.pl +++ b/Examples/test-suite/perl5/operator_overload_break_runme.pl @@ -4,15 +4,6 @@ use Test::More tests => 9; use operator_overload_break; -# Workaround for -# ok( not (expression) , "test description" ); -# does not working in older versions of Perl, eg 5.004_04 -sub ok_not ($;$) { - my($test, $name) = @_; - $test = not $test; - ok($test, $name); -} - pass("loaded"); my $op = operator_overload_break::Op->new(5); @@ -32,7 +23,7 @@ $op->{k} = 22; ok((10 == (32 - $op)), "reversed subtraction"); -ok_not((3 == $op), +ok(not(3 == $op), 'not equal'); $op->{k} = 3; diff --git a/Examples/test-suite/perl5/operator_overload_runme.pl b/Examples/test-suite/perl5/operator_overload_runme.pl index ba3f33a64..43a77a961 100644 --- a/Examples/test-suite/perl5/operator_overload_runme.pl +++ b/Examples/test-suite/perl5/operator_overload_runme.pl @@ -4,15 +4,6 @@ use Test::More tests => 39; use operator_overload; -# Workaround for -# ok( not (expression) , "test description" ); -# does not working in older versions of Perl, eg 5.004_04 -sub ok_not ($;$) { - my($test, $name) = @_; - $test = not $test; - ok($test, $name); -} - pass("loaded"); # first check all the operators are implemented correctly from pure C++ code @@ -30,7 +21,7 @@ isa_ok($op2, "operator_overload::Op"); $op->{i} = 5; $op2->{i} = 3; -ok_not(($op == $op2), "operator equal: not equal"); +ok(not($op == $op2), "operator equal: not equal"); $op->{i} = 3; ok(($op == $op2), "operator equal: equal"); @@ -42,7 +33,7 @@ $op2->{i} = 3; ok(($op != $op2), "operator not equal: not equal"); $op->{i} = 3; -ok_not(($op != $op2), "operator not equal: equal"); +ok(not($op != $op2), "operator not equal: equal"); # stringify operator $op->{i} = 3; @@ -99,16 +90,16 @@ is($op3->{i}, 2, "operator modulus"); $op->{i} = 8; $op2->{i} = 3; ok($op > $op2, "operator greater than"); -ok_not(($op2 > $op), "operator greater than"); +ok(not($op2 > $op), "operator greater than"); $op->{i} = 3; -ok_not(($op2 > $op), "operator greater than"); -ok_not(($op > $op2), "operator greater than"); +ok(not($op2 > $op), "operator greater than"); +ok(not($op > $op2), "operator greater than"); # greater than or equal operator $op->{i} = 8; $op2->{i} = 3; ok($op >= $op2, "operator greater than or equal"); -ok_not(($op2 >= $op), "operator greater than or equal"); +ok(not($op2 >= $op), "operator greater than or equal"); $op->{i} = 3; ok(($op2 >= $op), "operator greater than or equal"); ok(($op >= $op2), "operator greater than or equal"); @@ -117,16 +108,16 @@ ok(($op >= $op2), "operator greater than or equal"); $op2->{i} = 8; $op->{i} = 3; ok($op < $op2, "operator lesser than"); -ok_not(($op2 < $op), "operator lesser than"); +ok(not($op2 < $op), "operator lesser than"); $op2->{i} = 3; -ok_not(($op2 < $op), "operator lesser than"); -ok_not(($op < $op2), "operator lesser than"); +ok(not($op2 < $op), "operator lesser than"); +ok(not($op < $op2), "operator lesser than"); # less than or equal operator $op2->{i} = 8; $op->{i} = 3; ok($op <= $op2, "operator lesser than or equal"); -ok_not(($op2 <= $op), "operator lesser than or equal"); +ok(not($op2 <= $op), "operator lesser than or equal"); $op2->{i} = 3; ok(($op2 <= $op), "operator less than or equal"); ok(($op <= $op2), "operator less than or equal"); diff --git a/Examples/test-suite/perl5/overload_null_runme.pl b/Examples/test-suite/perl5/overload_null_runme.pl index 7cc5090de..6c01b58a2 100644 --- a/Examples/test-suite/perl5/overload_null_runme.pl +++ b/Examples/test-suite/perl5/overload_null_runme.pl @@ -32,13 +32,13 @@ is(14, $o->byval1cpr(undef)); is(15, $o->byval2cpr(undef)); is(16, $o->byval2cpr($x)); -# forward class declaration -is(17, $o->byval1forwardptr($x)); -is(18, $o->byval1forwardptr(undef)); +# fwd class declaration +is(17, $o->byval1fwdptr($x)); +is(18, $o->byval1fwdptr(undef)); -is(19, $o->byval2forwardptr(undef)); -is(20, $o->byval2forwardptr($x)); +is(19, $o->byval2fwdptr(undef)); +is(20, $o->byval2fwdptr($x)); -is(21, $o->byval1forwardref($x)); +is(21, $o->byval1fwdref($x)); -is(22, $o->byval2forwardref($x)); +is(22, $o->byval2fwdref($x)); diff --git a/Examples/test-suite/perl5/packageoption_runme.pl b/Examples/test-suite/perl5/packageoption_runme.pl index d94a7a1fd..02e95f7a8 100644 --- a/Examples/test-suite/perl5/packageoption_runme.pl +++ b/Examples/test-suite/perl5/packageoption_runme.pl @@ -5,15 +5,6 @@ use Test::More tests => 4; BEGIN { use_ok('packageoption_a'); } BEGIN { use_ok('packageoption_b'); } -# Workaround for -# ok( not (expression) , "test description" ); -# does not working in older versions of Perl, eg 5.004_04 -sub ok_not ($;$) { - my($test, $name) = @_; - $test = not $test; - ok($test, $name); -} - my $a = CommonPackage::A->new(); isa_ok($a, 'CommonPackage::A'); diff --git a/Examples/test-suite/php/Makefile.in b/Examples/test-suite/php/Makefile.in index 64f0d1f9d..a31eedbee 100644 --- a/Examples/test-suite/php/Makefile.in +++ b/Examples/test-suite/php/Makefile.in @@ -11,10 +11,19 @@ top_builddir = @top_builddir@ CPP_TEST_CASES += \ callback \ + director_stl \ + exception_partial_info \ + inout \ + li_cdata_carrays_cpp \ li_factory \ php_iterator \ php_namewarn_rename \ php_pragma \ + prefix \ + +C_TEST_CASES += \ + li_cdata_carrays \ + multivalue \ include $(srcdir)/../common.mk @@ -62,9 +71,9 @@ missingtests: missingcpptests missingctests # found, runs testcase.php, except for multicpptests. run_testcase = \ if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile PHP_SCRIPT=$(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) RUNTOOL='$(RUNTOOL)' php_run; \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile PHP_EXTENSION=$(TARGETPREFIX)$*@PHP_SO@ PHP_SCRIPT=$(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) RUNTOOL='$(RUNTOOL)' php_run; \ elif [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*.php -a ! -f $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$*.list ]; then \ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile PHP_SCRIPT=$(SCRIPTDIR)/$(SCRIPTPREFIX)$*.php RUNTOOL='$(RUNTOOL)' php_run; \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile PHP_EXTENSION=$(TARGETPREFIX)$*@PHP_SO@ PHP_SCRIPT=$(SCRIPTDIR)/$(SCRIPTPREFIX)$*.php RUNTOOL='$(RUNTOOL)' php_run; \ fi # Clean: remove the generated .php file @@ -77,5 +86,6 @@ clean: rm -f import_stl_a.php import_stl_b.php php_import_stl_a.h php_import_stl_b.h rm -f imports_a.php imports_b.php php_imports_a.h php_imports_b.h rm -f mod_a.php mod_b.php php_mod_a.h php_mod_b.h - rm -f multi_import_a.php multi_import_b.php php_multi_import_a.h php_multi_import_b.h + rm -f multi_import_a.php multi_import_b.php multi_import_d.php php_multi_import_a.h php_multi_import_b.h php_multi_import_d.h rm -f packageoption_a.php packageoption_b.php packageoption_c.php php_packageoption_a.h php_packageoption_b.h php_packageoption_c.h + rm -f template_typedef_cplx2.php php_template_typedef_cplx2.h diff --git a/Examples/test-suite/php/abstract_inherit_ok_runme.php b/Examples/test-suite/php/abstract_inherit_ok_runme.php index c2c343dac..add4191c2 100644 --- a/Examples/test-suite/php/abstract_inherit_ok_runme.php +++ b/Examples/test-suite/php/abstract_inherit_ok_runme.php @@ -1,12 +1,25 @@ getMessage(), "Cannot instantiate abstract class $class", "Unexpected exception: {$e->getMessage()}"); +} + +$spam=new Spam(); check::equal(0,$spam->blah(),"spam object method"); check::done(); -?> diff --git a/Examples/test-suite/php/abstract_inherit_runme.php b/Examples/test-suite/php/abstract_inherit_runme.php index 514bbc3b0..376a2adaa 100644 --- a/Examples/test-suite/php/abstract_inherit_runme.php +++ b/Examples/test-suite/php/abstract_inherit_runme.php @@ -1,14 +1,19 @@ blah(),"spam object method"); -//check::equal(0,Spam::blah($spam),"spam class method"); +// We shouldn't be able to instantiate any of these classes since they are all +// abstract (in each case there's a pure virtual function in the base class +// which isn't implemented). +foreach (array('Foo','Bar','Spam','NRFilter_i','NRRCFilter_i','NRRCFilterpro_i','NRRCFilterpri_i')as $class) { + try { + $obj = eval("new $class();"); + check::fail("Should not be able to instantiate abstract class $class"); + } catch (Error $e) { + check::equal($e->getMessage(), "Cannot instantiate abstract class $class", "Unexpected exception: {$e->getMessage()}"); + } +} check::done(); -?> diff --git a/Examples/test-suite/php/add_link_runme.php b/Examples/test-suite/php/add_link_runme.php index 3e16fa1df..073dee36d 100644 --- a/Examples/test-suite/php/add_link_runme.php +++ b/Examples/test-suite/php/add_link_runme.php @@ -1,10 +1,9 @@ diff --git a/Examples/test-suite/php/argout_runme.php b/Examples/test-suite/php/argout_runme.php index 8b66613fd..554d07756 100644 --- a/Examples/test-suite/php/argout_runme.php +++ b/Examples/test-suite/php/argout_runme.php @@ -1,7 +1,6 @@ diff --git a/Examples/test-suite/php/arrayptr_runme.php b/Examples/test-suite/php/arrayptr_runme.php deleted file mode 100644 index 86b7f8628..000000000 --- a/Examples/test-suite/php/arrayptr_runme.php +++ /dev/null @@ -1,14 +0,0 @@ - diff --git a/Examples/test-suite/php/arrays_global_runme.php b/Examples/test-suite/php/arrays_global_runme.php index 95a300775..6a97db91e 100644 --- a/Examples/test-suite/php/arrays_global_runme.php +++ b/Examples/test-suite/php/arrays_global_runme.php @@ -1,11 +1,11 @@ diff --git a/Examples/test-suite/php/arrays_global_twodim_runme.php b/Examples/test-suite/php/arrays_global_twodim_runme.php index d9f50a6de..e6fbf52d9 100644 --- a/Examples/test-suite/php/arrays_global_twodim_runme.php +++ b/Examples/test-suite/php/arrays_global_twodim_runme.php @@ -1,11 +1,11 @@ diff --git a/Examples/test-suite/php/arrays_runme.php b/Examples/test-suite/php/arrays_runme.php index c6e9e8f70..eb06fbfd8 100644 --- a/Examples/test-suite/php/arrays_runme.php +++ b/Examples/test-suite/php/arrays_runme.php @@ -1,10 +1,10 @@ array_c,"a",'$as->array_c=="a"'); check::equal(isset($as->array_const_i),TRUE,'isset($as->array_const_i)'); check::done(); -?> diff --git a/Examples/test-suite/php/arrays_scope_runme.php b/Examples/test-suite/php/arrays_scope_runme.php index 11c180870..8455b837c 100644 --- a/Examples/test-suite/php/arrays_scope_runme.php +++ b/Examples/test-suite/php/arrays_scope_runme.php @@ -1,16 +1,18 @@ blah($bar->adata, $bar->bdata, $bar->cdata); +// Like C/C++, SWIG treats `int asize[ASIZE]` as `int*` so there's no checking +// of the passed array size. +$bar->blah($bar->bdata, $bar->cdata, $bar->adata); check::done(); -?> diff --git a/Examples/test-suite/php/callback_runme.php b/Examples/test-suite/php/callback_runme.php index fefa32502..717185649 100644 --- a/Examples/test-suite/php/callback_runme.php +++ b/Examples/test-suite/php/callback_runme.php @@ -1,9 +1,10 @@ diff --git a/Examples/test-suite/php/casts_runme.php b/Examples/test-suite/php/casts_runme.php index a9623a328..6234f0fab 100644 --- a/Examples/test-suite/php/casts_runme.php +++ b/Examples/test-suite/php/casts_runme.php @@ -1,13 +1,12 @@ hello(); check::done(); -?> diff --git a/Examples/test-suite/php/char_strings_runme.php b/Examples/test-suite/php/char_strings_runme.php index e06ee9d2b..7dc8fe74d 100644 --- a/Examples/test-suite/php/char_strings_runme.php +++ b/Examples/test-suite/php/char_strings_runme.php @@ -1,7 +1,6 @@ diff --git a/Examples/test-suite/php/class_ignore_runme.php b/Examples/test-suite/php/class_ignore_runme.php index ae4881f27..f52bc1a13 100644 --- a/Examples/test-suite/php/class_ignore_runme.php +++ b/Examples/test-suite/php/class_ignore_runme.php @@ -1,9 +1,8 @@ diff --git a/Examples/test-suite/php/conversion_namespace_runme.php b/Examples/test-suite/php/conversion_namespace_runme.php index e21ff7438..858bf89d9 100644 --- a/Examples/test-suite/php/conversion_namespace_runme.php +++ b/Examples/test-suite/php/conversion_namespace_runme.php @@ -1,7 +1,6 @@ toFoo(); check::classname("foo",$foo); check::done(); -?> diff --git a/Examples/test-suite/php/conversion_ns_template_runme.php b/Examples/test-suite/php/conversion_ns_template_runme.php index 9702eedb7..4157b106a 100644 --- a/Examples/test-suite/php/conversion_ns_template_runme.php +++ b/Examples/test-suite/php/conversion_ns_template_runme.php @@ -1,10 +1,8 @@ diff --git a/Examples/test-suite/php/conversion_runme.php b/Examples/test-suite/php/conversion_runme.php index 1a10ff4f4..858bf89d9 100644 --- a/Examples/test-suite/php/conversion_runme.php +++ b/Examples/test-suite/php/conversion_runme.php @@ -1,7 +1,6 @@ toFoo(); check::classname("foo",$foo); check::done(); -?> diff --git a/Examples/test-suite/php/cpp11_final_directors_runme.php b/Examples/test-suite/php/cpp11_final_directors_runme.php new file mode 100644 index 000000000..07e04b15f --- /dev/null +++ b/Examples/test-suite/php/cpp11_final_directors_runme.php @@ -0,0 +1,16 @@ +meth(), 3, "Wrong return value"); diff --git a/Examples/test-suite/php/cpp11_strongly_typed_enumerations_runme.php b/Examples/test-suite/php/cpp11_strongly_typed_enumerations_runme.php index bee59b209..ca327d502 100644 --- a/Examples/test-suite/php/cpp11_strongly_typed_enumerations_runme.php +++ b/Examples/test-suite/php/cpp11_strongly_typed_enumerations_runme.php @@ -1,7 +1,6 @@ +check::done(); diff --git a/Examples/test-suite/php/cpp_basic_runme.php b/Examples/test-suite/php/cpp_basic_runme.php index b24cf7000..daca7d35d 100644 --- a/Examples/test-suite/php/cpp_basic_runme.php +++ b/Examples/test-suite/php/cpp_basic_runme.php @@ -1,14 +1,13 @@ func_ptr = get_func1_ptr(); @@ -16,5 +15,12 @@ check::equal(test_func_ptr($f, 7), 2*7*3, "get_func1_ptr() didn't work"); $f->func_ptr = get_func2_ptr(); check::equal(test_func_ptr($f, 7), -7*3, "get_func2_ptr() didn't work"); +// Test that custom properties work - standard PHP objects support them, +// so PHP developers will expect them to work for SWIG-wrapped objects too. +check::equal($f->custom_prop, NULL, "Test unset custom property"); +$f->custom_prop = "test"; +check::equal($f->custom_prop, "test", "Test custom property setting"); +$f->custom_prop = 42; +check::equal($f->custom_prop, 42, "Test custom property setting"); + check::done(); -?> diff --git a/Examples/test-suite/php/cpp_static_runme.php b/Examples/test-suite/php/cpp_static_runme.php index 20b50dd9e..a1fd85c2e 100644 --- a/Examples/test-suite/php/cpp_static_runme.php +++ b/Examples/test-suite/php/cpp_static_runme.php @@ -1,14 +1,12 @@ diff --git a/Examples/test-suite/php/director_abstract_runme.php b/Examples/test-suite/php/director_abstract_runme.php index 1a119cfd5..bb424f9ea 100644 --- a/Examples/test-suite/php/director_abstract_runme.php +++ b/Examples/test-suite/php/director_abstract_runme.php @@ -1,13 +1,12 @@ isAbstract(), true, "Example3_i abstractness failed"); check::done(); -?> diff --git a/Examples/test-suite/php/director_alternating_runme.php b/Examples/test-suite/php/director_alternating_runme.php new file mode 100644 index 000000000..de33038be --- /dev/null +++ b/Examples/test-suite/php/director_alternating_runme.php @@ -0,0 +1,11 @@ +id(); +check::equal($id, director_alternating::idFromGetBar(), "idFromGetBar() failed"); diff --git a/Examples/test-suite/php/director_basic_runme.php b/Examples/test-suite/php/director_basic_runme.php index 478a36f80..db7adefc1 100644 --- a/Examples/test-suite/php/director_basic_runme.php +++ b/Examples/test-suite/php/director_basic_runme.php @@ -1,14 +1,12 @@ x, 34, "bc failed"); check::equal($bd->x, 16, "bd failed"); check::done(); -?> diff --git a/Examples/test-suite/php/director_classic_runme.php b/Examples/test-suite/php/director_classic_runme.php index a44881e04..e2ac1f7a7 100644 --- a/Examples/test-suite/php/director_classic_runme.php +++ b/Examples/test-suite/php/director_classic_runme.php @@ -1,13 +1,12 @@ id(); if ($debug) print $ret . "\n"; - # TODO: Currently we do not track the dynamic type of returned - # objects, so in case it's possible that the dynamic type is not equal - # to the static type, we skip this check. - if (get_parent_class($person) === false) - check::equal($ret, $expected, "#3 failed"); + check::equal($ret, $expected, "#3 failed"); $caller->resetCallback(); if ($debug) @@ -147,4 +142,3 @@ mycheck($person, "TargetLangOrphanChild"); unset($person); check::done(); -?> diff --git a/Examples/test-suite/php/director_default_runme.php b/Examples/test-suite/php/director_default_runme.php index c459ce3ec..92e415041 100644 --- a/Examples/test-suite/php/director_default_runme.php +++ b/Examples/test-suite/php/director_default_runme.php @@ -1,13 +1,12 @@ diff --git a/Examples/test-suite/php/director_detect_runme.php b/Examples/test-suite/php/director_detect_runme.php index a6d3aebd6..ae92f7a0c 100644 --- a/Examples/test-suite/php/director_detect_runme.php +++ b/Examples/test-suite/php/director_detect_runme.php @@ -1,13 +1,12 @@ val, 5, "b: Bad virtual detection"); check::equal($vc, 6, "c: Bad virtual detection"); check::done(); -?> diff --git a/Examples/test-suite/php/director_enum_runme.php b/Examples/test-suite/php/director_enum_runme.php index 0571ec0da..21e07a57b 100644 --- a/Examples/test-suite/php/director_enum_runme.php +++ b/Examples/test-suite/php/director_enum_runme.php @@ -1,13 +1,12 @@ say_hi(director_enum::hello), $b->say_hello(director_enum::hi), "say failed"); check::done(); -?> diff --git a/Examples/test-suite/php/director_exception_runme.php b/Examples/test-suite/php/director_exception_runme.php index dd2d04e8a..e49c12da6 100644 --- a/Examples/test-suite/php/director_exception_runme.php +++ b/Examples/test-suite/php/director_exception_runme.php @@ -1,13 +1,12 @@ pong(); @@ -124,4 +121,3 @@ try { } check::done(); -?> diff --git a/Examples/test-suite/php/director_extend_runme.php b/Examples/test-suite/php/director_extend_runme.php index 7aa2e0f78..418985476 100644 --- a/Examples/test-suite/php/director_extend_runme.php +++ b/Examples/test-suite/php/director_extend_runme.php @@ -1,13 +1,12 @@ dummy(), 666, "1st call"); check::equal($m->dummy(), 666, "2st call"); // Locked system check::done(); -?> diff --git a/Examples/test-suite/php/director_finalizer_runme.php b/Examples/test-suite/php/director_finalizer_runme.php index 96bb5c179..f3a0c2c40 100644 --- a/Examples/test-suite/php/director_finalizer_runme.php +++ b/Examples/test-suite/php/director_finalizer_runme.php @@ -1,18 +1,22 @@ orStatus(2); + # It's not safe to call methods on the C++ object from the PHP destructor + # if the object has been disowned, since the C++ object will already have + # been destroyed by the time the PHP destructor runs. + if ($this->thisown) { + $this->orStatus(2); + } if (method_exists(get_parent_class(), "__destruct")) { parent::__destruct(); } @@ -41,21 +45,24 @@ resetStatus(); $a = new MyFoo(); $a->thisown = 0; +check::equal(getStatus(), 0, "shadow release does not fire destructor of disowned object"); + deleteFoo($a); unset($a); -check::equal(getStatus(), 3, "getStatus() failed #4"); +# getStatus() would ideally return 3 here. +check::equal(getStatus(), 1, "getStatus() failed #4"); resetStatus(); $a = new MyFoo(); $a->thisown = 0; -deleteFoo(launder($a)); +$g = launder($a); unset($a); - -check::equal(getStatus(), 3, "getStatus() failed #5"); +deleteFoo($g); +# getStatus() would ideally return 3 here. +check::equal(getStatus(), 1, "getStatus() failed #5"); resetStatus(); check::done(); -?> diff --git a/Examples/test-suite/php/director_frob_runme.php b/Examples/test-suite/php/director_frob_runme.php index 450a1234b..732b9d500 100644 --- a/Examples/test-suite/php/director_frob_runme.php +++ b/Examples/test-suite/php/director_frob_runme.php @@ -1,14 +1,13 @@ abs_method(); @@ -16,4 +15,3 @@ $s = $foo->abs_method(); check::equal($s, "Bravo::abs_method()", "s failed"); check::done(); -?> diff --git a/Examples/test-suite/php/director_ignore_runme.php b/Examples/test-suite/php/director_ignore_runme.php new file mode 100644 index 000000000..87bc4757d --- /dev/null +++ b/Examples/test-suite/php/director_ignore_runme.php @@ -0,0 +1,24 @@ +Triple(5), 15, "Wrong return value"); + +$b = new DAbstractIgnoresDerived(); +check::equal($b->Quadruple(5), 20, "Wrong return value"); diff --git a/Examples/test-suite/php/director_nested_runme.php b/Examples/test-suite/php/director_nested_runme.php index 9a094a182..adf9f6206 100644 --- a/Examples/test-suite/php/director_nested_runme.php +++ b/Examples/test-suite/php/director_nested_runme.php @@ -1,13 +1,12 @@ advance(); check::equal($c->get_name(), "FooBar::get_name hello", "get_name failed"); @@ -71,4 +67,3 @@ check::equal($c->get_name(), "FooBar::get_name hello", "get_name failed"); check::equal($c->name(), "FooBar::get_name hello", "name failed"); check::done(); -?> diff --git a/Examples/test-suite/php/director_overload_runme.php b/Examples/test-suite/php/director_overload_runme.php new file mode 100644 index 000000000..07b485d95 --- /dev/null +++ b/Examples/test-suite/php/director_overload_runme.php @@ -0,0 +1,14 @@ +rw(), 42, "get_set() initial value not 42"); +check::equal($o->rw(7), null, "get_set() failed to set"); +check::equal($o->rw(), 7, "get_set() didn't return back set value"); + +check::done(); diff --git a/Examples/test-suite/php/director_ownership_runme.php b/Examples/test-suite/php/director_ownership_runme.php new file mode 100644 index 000000000..a78fb9c03 --- /dev/null +++ b/Examples/test-suite/php/director_ownership_runme.php @@ -0,0 +1,28 @@ +thisown = false; + $container->set_content($content); +} + +$container = new Container(); + +// make a content in PHP (newobject is 1) +$content_php = new ContentDerived(); + +// make a content in C++ (newobject is 1) +$content_cpp = make_content(); + +set_content_and_release($container, $content_php); +check::equal($container->get_content()->get_name(), "ContentDerived", "get_content() not ContentDerived"); + +set_content_and_release($container, $content_cpp); +check::equal($container->get_content()->get_name(), "ContentDerived", "get_content() not ContentDerived"); + +check::done(); diff --git a/Examples/test-suite/php/director_pass_by_value_runme.php b/Examples/test-suite/php/director_pass_by_value_runme.php index 8a8b84d67..d3763292f 100644 --- a/Examples/test-suite/php/director_pass_by_value_runme.php +++ b/Examples/test-suite/php/director_pass_by_value_runme.php @@ -1,7 +1,6 @@ diff --git a/Examples/test-suite/php/director_profile_runme.php b/Examples/test-suite/php/director_profile_runme.php index c6f4c3c94..219ec815a 100644 --- a/Examples/test-suite/php/director_profile_runme.php +++ b/Examples/test-suite/php/director_profile_runme.php @@ -1,13 +1,12 @@ diff --git a/Examples/test-suite/php/director_protected_runme.php b/Examples/test-suite/php/director_protected_runme.php index e759fed25..b73c8f872 100644 --- a/Examples/test-suite/php/director_protected_runme.php +++ b/Examples/test-suite/php/director_protected_runme.php @@ -1,11 +1,12 @@ callping(), "Bar::ping();", "bad fb3::callping"); check::equal($fb3->callcheer(), "FooBar3::cheer();", "bad fb3::callcheer"); check::done(); -?> diff --git a/Examples/test-suite/php/director_stl_runme.php b/Examples/test-suite/php/director_stl_runme.php index f7a5c0aa0..654251a30 100644 --- a/Examples/test-suite/php/director_stl_runme.php +++ b/Examples/test-suite/php/director_stl_runme.php @@ -1,13 +1,12 @@ tvidents($vs);*/ check::done(); -?> diff --git a/Examples/test-suite/php/director_string_runme.php b/Examples/test-suite/php/director_string_runme.php index 77e84c9bf..3127f13fb 100644 --- a/Examples/test-suite/php/director_string_runme.php +++ b/Examples/test-suite/php/director_string_runme.php @@ -1,14 +1,13 @@ call_process_func(); check::equal($b->smem, "hello", "smem failed"); check::done(); -?> diff --git a/Examples/test-suite/php/director_thread_runme.php b/Examples/test-suite/php/director_thread_runme.php index 2a640a022..190dbad71 100644 --- a/Examples/test-suite/php/director_thread_runme.php +++ b/Examples/test-suite/php/director_thread_runme.php @@ -1,18 +1,17 @@ val >= 0) { $d->stop(); check::done(); -?> diff --git a/Examples/test-suite/php/director_unroll_runme.php b/Examples/test-suite/php/director_unroll_runme.php index e3101887d..7f94753f5 100644 --- a/Examples/test-suite/php/director_unroll_runme.php +++ b/Examples/test-suite/php/director_unroll_runme.php @@ -1,14 +1,13 @@ set($a); $c = $b->get(); -// FIXME: This doesn't work for checking that they wrap the same C++ object -// because the two objects have different PHP resources, and we can't easily -// look inside those resources to see which C++ objects they refer to. -//check::equal($a->_cPtr, $c->_cPtr, "_cPtr check failed"); +// FIXME: The python version checks that a.this == c.this, but we don't seem +// to have a way to check this with the PHP bindings we generate. check::done(); -?> diff --git a/Examples/test-suite/php/director_wombat_runme.php b/Examples/test-suite/php/director_wombat_runme.php new file mode 100644 index 000000000..3e308044f --- /dev/null +++ b/Examples/test-suite/php/director_wombat_runme.php @@ -0,0 +1,52 @@ +meth(); +check::equal(get_class($fooIntsObj), "Foo_integers", "wrong class"); + +check::equal($fooIntsObj->meth(42) , 42, "Foo_integers::meth(n) should return n"); + +// +// Now subclass Foo_integers, but override its virtual method +// meth(n) so that it returns the number plus one. +// +class MyFooInts extends Foo_integers { + function meth($n) { + return $n + 1; + } +} + +// +// Subclass Bar and override its virtual method meth() +// so that it returns a new MyFooInts instance instead of +// a Foo_integers instance. +// +class MyBar extends Bar { + function meth() { + return new MyFooInts(); + } +} + +// +// Now repeat previous tests: +// +// Create a MyBar instance... +// +$barObj = new MyBar(); + +// MyBar::meth should return a MyFooInts instance +$fooIntsObj = $barObj->meth(); +check::equal(get_class($fooIntsObj), "MyFooInts", "wrong class"); + +check::equal($fooIntsObj->meth(42) , 43, "MyFooInts::meth(n) should return n + 1"); diff --git a/Examples/test-suite/php/enum_scope_template_runme.php b/Examples/test-suite/php/enum_scope_template_runme.php index 85ba467b7..d5aed62f7 100644 --- a/Examples/test-suite/php/enum_scope_template_runme.php +++ b/Examples/test-suite/php/enum_scope_template_runme.php @@ -1,15 +1,16 @@ diff --git a/Examples/test-suite/php/evil_diamond_ns_runme.php b/Examples/test-suite/php/evil_diamond_ns_runme.php index fcce0f767..f2115bf36 100644 --- a/Examples/test-suite/php/evil_diamond_ns_runme.php +++ b/Examples/test-suite/php/evil_diamond_ns_runme.php @@ -1,7 +1,6 @@ diff --git a/Examples/test-suite/php/evil_diamond_prop_runme.php b/Examples/test-suite/php/evil_diamond_prop_runme.php index 9bdb7435f..611f17d6a 100644 --- a/Examples/test-suite/php/evil_diamond_prop_runme.php +++ b/Examples/test-suite/php/evil_diamond_prop_runme.php @@ -1,7 +1,6 @@ _foo,"1==spam->_foo"); check::equal(2,$spam->_bar,"2==spam->_bar"); // multiple inheritance not supported in PHP -set_error_handler(NULL, 0); // Don't complain that _baz is unknown. check::equal(null,$spam->_baz,"null==spam->_baz"); -restore_error_handler(); check::equal(4,$spam->_spam,"4==spam->_spam"); check::done(); -?> diff --git a/Examples/test-suite/php/evil_diamond_runme.php b/Examples/test-suite/php/evil_diamond_runme.php index a587ca359..7d01c98ec 100644 --- a/Examples/test-suite/php/evil_diamond_runme.php +++ b/Examples/test-suite/php/evil_diamond_runme.php @@ -1,7 +1,6 @@ diff --git a/Examples/test-suite/php/exception_memory_leak_runme.php b/Examples/test-suite/php/exception_memory_leak_runme.php new file mode 100644 index 000000000..6ff035cde --- /dev/null +++ b/Examples/test-suite/php/exception_memory_leak_runme.php @@ -0,0 +1,23 @@ +getMessage(), 'C++ E2 * exception thrown', ''); } -?> + +check::done(); diff --git a/Examples/test-suite/php/extend_template_ns_runme.php b/Examples/test-suite/php/extend_template_ns_runme.php index e6d3e9f73..46158672b 100644 --- a/Examples/test-suite/php/extend_template_ns_runme.php +++ b/Examples/test-suite/php/extend_template_ns_runme.php @@ -1,7 +1,6 @@ test1(2),"test1"); check::equal(3,$foo->test2(3),"test2"); check::done(); -?> diff --git a/Examples/test-suite/php/extend_template_runme.php b/Examples/test-suite/php/extend_template_runme.php index 41bde4458..a6579dce9 100644 --- a/Examples/test-suite/php/extend_template_runme.php +++ b/Examples/test-suite/php/extend_template_runme.php @@ -1,7 +1,6 @@ test1(2),"test1"); check::equal(3,$foo->test2(3),"test2"); check::done(); -?> diff --git a/Examples/test-suite/php/global_vars_runme.php b/Examples/test-suite/php/global_vars_runme.php new file mode 100644 index 000000000..c3fe7d8aa --- /dev/null +++ b/Examples/test-suite/php/global_vars_runme.php @@ -0,0 +1,27 @@ + diff --git a/Examples/test-suite/php/ignore_parameter_runme.php b/Examples/test-suite/php/ignore_parameter_runme.php index b9c2b777d..90b82d7da 100644 --- a/Examples/test-suite/php/ignore_parameter_runme.php +++ b/Examples/test-suite/php/ignore_parameter_runme.php @@ -1,14 +1,13 @@ daimler(2,3.4),"hello",'$sc->daimler(2,3.4)=="hello"'); -check::equal($sc->astonmartin("eek",3.4),101,'$sc->mastonmartin("eek",3.4)==101'); +check::equal($sc->astonmartin("eek",3.4),101,'$sc->astonmartin("eek",3.4)==101'); check::equal($sc->bugatti("eek",2),8.8,'$sc->bugatti("eek",2)==8.8'); check::equal($sc->lamborghini(),101,'$sc->lamborghini(2)==101'); @@ -35,4 +34,3 @@ $aa=new austinallegro(); check::classname("austinallegro",$aa); check::done(); -?> diff --git a/Examples/test-suite/php/import_nomodule_runme.php b/Examples/test-suite/php/import_nomodule_runme.php index e5ea761f7..e639c781d 100644 --- a/Examples/test-suite/php/import_nomodule_runme.php +++ b/Examples/test-suite/php/import_nomodule_runme.php @@ -1,14 +1,16 @@ diff --git a/Examples/test-suite/php/li_carrays_cpp_runme.php b/Examples/test-suite/php/li_carrays_cpp_runme.php index 3e8a443f6..ccbcf7dde 100644 --- a/Examples/test-suite/php/li_carrays_cpp_runme.php +++ b/Examples/test-suite/php/li_carrays_cpp_runme.php @@ -1,16 +1,16 @@ setitem(5, $d->getitem(0) + 3); check::equal($d->getitem(0) + $d->getitem(5), 17., "7+10==17"); check::done(); -?> diff --git a/Examples/test-suite/php/li_carrays_runme.php b/Examples/test-suite/php/li_carrays_runme.php index abe358101..df54e04f5 100644 --- a/Examples/test-suite/php/li_carrays_runme.php +++ b/Examples/test-suite/php/li_carrays_runme.php @@ -1,16 +1,16 @@ setitem(5, $d->getitem(0) + 3); check::equal($d->getitem(0) + $d->getitem(5), 17., "7+10==17"); check::done(); -?> diff --git a/Examples/test-suite/php/li_factory_runme.php b/Examples/test-suite/php/li_factory_runme.php index 982d7b1fd..18545fec7 100644 --- a/Examples/test-suite/php/li_factory_runme.php +++ b/Examples/test-suite/php/li_factory_runme.php @@ -1,13 +1,12 @@ width(); check::equal($w, 1.0, "w failed"); +$point = Geometry::create(Geometry::SHAPELESS); +check::equal($point, NULL, "NULL failed"); + check::done(); -?> diff --git a/Examples/test-suite/php/li_std_string_runme.php b/Examples/test-suite/php/li_std_string_runme.php index 04ee3fc86..680b7ce98 100644 --- a/Examples/test-suite/php/li_std_string_runme.php +++ b/Examples/test-suite/php/li_std_string_runme.php @@ -1,11 +1,34 @@ ConstMemberString, "const member string", "ConstMembe check::equal(Structure::StaticMemberString2(), "static member string 2", "StaticMemberString2 test 1"); Structure::StaticMemberString2($s); check::equal(Structure::StaticMemberString2(), $s, "StaticMemberString2 test 2"); -// below broken ? -//check::equal(Structure::ConstStaticMemberString(), "const static member string", "ConstStaticMemberString test"); +check::equal(Structure::ConstStaticMemberString(), "const static member string", "ConstStaticMemberString test"); // This used to give "Undefined variable: r" li_std_string::test_const_reference_returning_void("foo"); check::done(); -?> diff --git a/Examples/test-suite/php/li_std_vector_member_var_runme.php b/Examples/test-suite/php/li_std_vector_member_var_runme.php index 238350352..32ce484fc 100644 --- a/Examples/test-suite/php/li_std_vector_member_var_runme.php +++ b/Examples/test-suite/php/li_std_vector_member_var_runme.php @@ -1,7 +1,6 @@ start_t->x, 4, "S::x != 4"); check::equal($T->length, 7, "T::length != 7"); check::done(); -?> diff --git a/Examples/test-suite/php/long_long_runme.php b/Examples/test-suite/php/long_long_runme.php new file mode 100644 index 000000000..544a59c18 --- /dev/null +++ b/Examples/test-suite/php/long_long_runme.php @@ -0,0 +1,65 @@ +makeMore(); check::equal(get_class($bar), "Foo", "regular failed"); +check::equal(Foo::fooCount(), 2, "2 Foo objects expected"); +$foo = null; +check::equal(Foo::fooCount(), 1, "1 Foo object expected"); +$bar = null; +check::equal(Foo::fooCount(), 0, "no Foo objects expected"); check::done(); -?> diff --git a/Examples/test-suite/php/newobject2_runme.php b/Examples/test-suite/php/newobject2_runme.php new file mode 100644 index 000000000..f20a6a4f9 --- /dev/null +++ b/Examples/test-suite/php/newobject2_runme.php @@ -0,0 +1,17 @@ +create(7, -1), "create(7, -1) should be NULL"); check::isnull($factory->create(0, -1), "create(0, -1) should be NULL"); check::isnull($factory->create("bad", -1), "create(\"bad\", -1) should be NULL"); -?> +check::done(); diff --git a/Examples/test-suite/php/overload_bool_runme.php b/Examples/test-suite/php/overload_bool_runme.php new file mode 100644 index 000000000..e477330ef --- /dev/null +++ b/Examples/test-suite/php/overload_bool_runme.php @@ -0,0 +1,42 @@ +hip(false), 701, "Test 1 failed"); + +check::equal($p->hip($pInt), 702, "Test 2 failed"); + +# Reverse the order for the above +check::equal($p->hop($pInt), 805, "Test 3 failed"); + +check::equal($p->hop(false), 801, "Test 4 failed"); + +# Few more variations and order shuffled +check::equal($p->pop(false), 901, "Test 5 failed"); + +check::equal($p->pop($pInt), 904, "Test 6 failed"); + +check::equal($p->pop(), 905, "Test 7 failed"); + +# Overload on const only +check::equal($p->bop($pInt), 1001, "Test 8 failed"); + +check::equal($p->bip($pInt), 2002, "Test 9 failed"); + +# Globals +check::equal(muzak(false), 3001, "Test 10 failed"); + +check::equal(muzak($pInt), 3002, "Test 11 failed"); + +check::done(); diff --git a/Examples/test-suite/php/overload_copy_runme.php b/Examples/test-suite/php/overload_copy_runme.php new file mode 100644 index 000000000..893a715c5 --- /dev/null +++ b/Examples/test-suite/php/overload_copy_runme.php @@ -0,0 +1,13 @@ +test(3), 1, '$f->test(3)'); +check::equal($f->test("hello"), 2, '$f->test("hello")'); +check::equal($f->test(3.5, 2.5), 3, '$f->test(3.5, 2.5)'); +check::equal($f->test("hello", 20), 1020, '$f->test("hello", 20)'); +check::equal($f->test("hello", 20, 100), 120, '$f->test("hello", 20, 100)'); + +// C default args +check::equal($f->test($f), 30, '$f->test(f)'); +check::equal($f->test($f, 100), 120, '$f->test(f, 100)'); +check::equal($f->test($f, 100, 200), 300, '$f->test(f, 100, 200)'); + +check::done(); diff --git a/Examples/test-suite/php/overload_extend_c_runme.php b/Examples/test-suite/php/overload_extend_c_runme.php new file mode 100644 index 000000000..55f426c13 --- /dev/null +++ b/Examples/test-suite/php/overload_extend_c_runme.php @@ -0,0 +1,11 @@ +test(), 0, '$f->test()'); +check::equal($f->test(3), 1, '$f->test(3)'); +check::equal($f->test("hello"), 2, '$f->test("hello")'); +check::equal($f->test(3.0, 2.0), 5.0, '$f->test(3, 2)'); +check::equal($f->test(3.0), 1003.0, '$f->test(3.0)'); + +check::done(); diff --git a/Examples/test-suite/php/overload_extend_runme.php b/Examples/test-suite/php/overload_extend_runme.php new file mode 100644 index 000000000..89c0499eb --- /dev/null +++ b/Examples/test-suite/php/overload_extend_runme.php @@ -0,0 +1,11 @@ +test(), 0, '$f->test()'); +check::equal($f->test(3), 1, '$f->test(3)'); +check::equal($f->test("hello"), 2, '$f->test("hello")'); +check::equal($f->test(3.0, 2.0), 5.0, '$f->test(3.0, 2.0)'); +check::equal($f->test(3.0), 1003.0, '$f->test(3.0)'); + +check::done(); diff --git a/Examples/test-suite/php/overload_null_runme.php b/Examples/test-suite/php/overload_null_runme.php index 22824d4fb..7afafeacd 100644 --- a/Examples/test-suite/php/overload_null_runme.php +++ b/Examples/test-suite/php/overload_null_runme.php @@ -1,7 +1,6 @@ byval1cpr(null), "test 14"); check::equal(15, $o->byval2cpr(null), "test 15"); check::equal(16, $o->byval2cpr($x), "test 16"); -# forward class declaration -check::equal(17, $o->byval1forwardptr($x), "test 17"); -check::equal(18, $o->byval1forwardptr(null), "test 18"); +# fwd class declaration +check::equal(17, $o->byval1fwdptr($x), "test 17"); +check::equal(18, $o->byval1fwdptr(null), "test 18"); -check::equal(19, $o->byval2forwardptr(null), "test 19"); -check::equal(20, $o->byval2forwardptr($x), "test 20"); +check::equal(19, $o->byval2fwdptr(null), "test 19"); +check::equal(20, $o->byval2fwdptr($x), "test 20"); -check::equal(21, $o->byval1forwardref($x), "test 21"); +check::equal(21, $o->byval1fwdref($x), "test 21"); -check::equal(22, $o->byval2forwardref($x), "test 22"); +check::equal(22, $o->byval2fwdref($x), "test 22"); check::done(); -?> diff --git a/Examples/test-suite/php/overload_polymorphic_runme.php b/Examples/test-suite/php/overload_polymorphic_runme.php new file mode 100644 index 000000000..908988291 --- /dev/null +++ b/Examples/test-suite/php/overload_polymorphic_runme.php @@ -0,0 +1,12 @@ + diff --git a/Examples/test-suite/php/overload_return_type_runme.php b/Examples/test-suite/php/overload_return_type_runme.php index 4fa19d22a..f03a85d7f 100644 --- a/Examples/test-suite/php/overload_return_type_runme.php +++ b/Examples/test-suite/php/overload_return_type_runme.php @@ -1,7 +1,6 @@ foo(1), 0, ""); @@ -10,4 +9,4 @@ check::classname("A", $b->foo("test")); check::equal(overload_return_type::foo(), 1, "overload_return_type::foo() should be 1"); check::equal(overload_return_type::bar(), 1, "overload_return_type::bar() should be 1"); -?> +check::done(); diff --git a/Examples/test-suite/php/overload_simple_runme.php b/Examples/test-suite/php/overload_simple_runme.php new file mode 100644 index 000000000..949de9d98 --- /dev/null +++ b/Examples/test-suite/php/overload_simple_runme.php @@ -0,0 +1,195 @@ +foo(3), "foo:int", "Spam::foo:int"); + +check::equal($s->foo(3.0), "foo:double", "Spam::foo(double)"); + +check::equal($s->foo("hello"), "foo:char *", "Spam::foo:char *"); + +check::equal($s->foo($f), "foo:Foo *", "Spam::foo(Foo *)"); + +check::equal($s->foo($b), "foo:Bar *", "Spam::foo(Bar *)"); + +check::equal($s->foo($v), "foo:void *", "Spam::foo(void *)"); + +check::equal(Spam::bar(3), "bar:int", "Spam::bar(int)"); + +check::equal(Spam::bar(3.0), "bar:double", "Spam::bar(double)"); + +check::equal(Spam::bar("hello"), "bar:char *", "Spam::bar(char *)"); + +check::equal(Spam::bar($f), "bar:Foo *", "Spam::bar(Foo *)"); + +check::equal(Spam::bar($b), "bar:Bar *", "Spam::bar(Bar *)"); + +check::equal(Spam::bar($v), "bar:void *", "Spam::bar(void *)"); + +# Test constructors + +$s = new Spam(); +check::is_a($s, "spam"); + +check::equal($s->type, "none", "Spam()"); + +$s = new Spam(3); +check::is_a($s, "spam"); + +check::equal($s->type, "int", "Spam(int)"); + +$s = new Spam(3.0); +check::is_a($s, "spam"); +check::equal($s->type, "double", "Spam(double)"); + +$s = new Spam("hello"); +check::is_a($s, "spam"); +check::equal($s->type, "char *", "Spam(char *)"); + +$s = new Spam($f); +check::is_a($s, "spam"); +check::equal($s->type, "Foo *", "Spam(Foo *)"); + +$s = new Spam($b); +check::is_a($s, "spam"); +check::equal($s->type, "Bar *", "Spam(Bar *)"); + +$s = new Spam($v); +check::is_a($s, "spam"); +check::equal($s->type, "void *", "Spam(void *)"); + +# +# Combine dispatch +# + +check::equal(overload_simple::fid(3, 3.0), "fid:intdouble", "fid(int,double)"); + +check::equal(overload_simple::fid(3.0, 3), "fid:doubleint", "fid(double,int)"); + +check::equal(overload_simple::fid(3.0, 3.0), "fid:doubledouble", "fid(double,double)"); + +check::equal(overload_simple::fid(3, 3), "fid:intint", "fid(int,int)"); + +check::equal(false, overload_simple::fbool(false), "fbool(bool)"); +check::equal(true, overload_simple::fbool(true), "fbool(bool)"); +check::equal(2, overload_simple::fbool(2), "fbool(int)"); + +# int and object overload + +check::equal(overload_simple::int_object(1), 1, "int_object(1)"); +check::equal(overload_simple::int_object(0), 0, "int_object(0)"); +check::equal(overload_simple::int_object(NULL), 999, "int_object(Spam*)"); +check::equal(overload_simple::int_object($s), 999, "int_object(Spam*)"); + +function check($args, $want) { + if ($want === NULL) { + try { + eval("return Spam::bar($args);"); + check::fail("Expected exception"); + } catch (TypeError $e) { + check::equal(substr($e->getMessage(), 0, 35), "No matching function for overloaded", "Not the expected I expected"); + } + return; + } + check::equal(eval("return Spam::bar($args);"), "bar:$want", "bar($args) => $want"); +} + +# normal use patterns +check("11", 'int'); +check("11.0", 'double'); +check("'11'", 'char *'); +check("'11.0'", 'char *'); +check("-13", 'int'); +check("-13.0", 'double'); +check("'-13'", 'char *'); +check("'-13.0'", 'char *'); + +check("' '", 'char *'); +check("' 11 '", 'char *'); + +# Check TypeError is thrown when the wrong type is passed. +check("array()", NULL); +check("function(){}", NULL); +check("new stdClass()", NULL); +class NotASwigWrappedClass { }; +check("new NotASwigWrappedClass()", NULL); + +check::done(); diff --git a/Examples/test-suite/php/overload_subtype_runme.php b/Examples/test-suite/php/overload_subtype_runme.php new file mode 100644 index 000000000..f12025cf8 --- /dev/null +++ b/Examples/test-suite/php/overload_subtype_runme.php @@ -0,0 +1,11 @@ +foo(1); + + +check::done(); diff --git a/Examples/test-suite/php/overload_template_runme.php b/Examples/test-suite/php/overload_template_runme.php new file mode 100644 index 000000000..7aa19f693 --- /dev/null +++ b/Examples/test-suite/php/overload_template_runme.php @@ -0,0 +1,110 @@ +foo(1); + + +check::done(); diff --git a/Examples/test-suite/php/php_iterator_runme.php b/Examples/test-suite/php/php_iterator_runme.php index fd645ccb2..76b4757fc 100644 --- a/Examples/test-suite/php/php_iterator_runme.php +++ b/Examples/test-suite/php/php_iterator_runme.php @@ -1,9 +1,9 @@ $v) { check::equal($s, '(0=>2)(1=>3)(2=>4)', 'Simple iteration failed'); check::done(); -?> diff --git a/Examples/test-suite/php/php_pragma_runme.php b/Examples/test-suite/php/php_pragma_runme.php index c76cfc9b5..cf297701d 100644 --- a/Examples/test-suite/php/php_pragma_runme.php +++ b/Examples/test-suite/php/php_pragma_runme.php @@ -1,11 +1,14 @@ getVersion(),"1.5==version(php_pragma)"); check::done(); - -?> diff --git a/Examples/test-suite/php/pointer_reference_runme.php b/Examples/test-suite/php/pointer_reference_runme.php index 52946177e..a8a511271 100644 --- a/Examples/test-suite/php/pointer_reference_runme.php +++ b/Examples/test-suite/php/pointer_reference_runme.php @@ -1,7 +1,6 @@ value, 10, "pointer_reference::get() failed"); @@ -15,4 +14,3 @@ check::equal(pointer_reference::overloading(1), 111, "overload test 1 failed"); check::equal(pointer_reference::overloading($ss), 222, "overload test 2 failed"); check::done(); -?> diff --git a/Examples/test-suite/php/prefix_runme.php b/Examples/test-suite/php/prefix_runme.php index fcf7c66f6..9f83df1e1 100644 --- a/Examples/test-suite/php/prefix_runme.php +++ b/Examples/test-suite/php/prefix_runme.php @@ -1,18 +1,18 @@ get_self(); +Project::self(new ProjectBar()); + check::done(); -?> diff --git a/Examples/test-suite/php/preproc_constants_c_runme.php b/Examples/test-suite/php/preproc_constants_c_runme.php index 20868dcc0..688da52f6 100644 --- a/Examples/test-suite/php/preproc_constants_c_runme.php +++ b/Examples/test-suite/php/preproc_constants_c_runme.php @@ -1,7 +1,6 @@ +check::done(); diff --git a/Examples/test-suite/php/preproc_constants_runme.php b/Examples/test-suite/php/preproc_constants_runme.php index bd216c269..80f1a9a59 100644 --- a/Examples/test-suite/php/preproc_constants_runme.php +++ b/Examples/test-suite/php/preproc_constants_runme.php @@ -1,7 +1,6 @@ +check::done(); diff --git a/Examples/test-suite/php/primitive_ref_runme.php b/Examples/test-suite/php/primitive_ref_runme.php index 263a28074..9b281cf50 100644 --- a/Examples/test-suite/php/primitive_ref_runme.php +++ b/Examples/test-suite/php/primitive_ref_runme.php @@ -1,7 +1,6 @@ diff --git a/Examples/test-suite/php/rename_scope_runme.php b/Examples/test-suite/php/rename_scope_runme.php index df620d796..e1db4f59c 100644 --- a/Examples/test-suite/php/rename_scope_runme.php +++ b/Examples/test-suite/php/rename_scope_runme.php @@ -1,7 +1,6 @@ diff --git a/Examples/test-suite/php/skel.php b/Examples/test-suite/php/skel.php index 780a999ed..7fdebc7d6 100644 --- a/Examples/test-suite/php/skel.php +++ b/Examples/test-suite/php/skel.php @@ -2,14 +2,12 @@ // Sample test file require "tests.php"; -require "____.php"; // No new functions check::functions(array()); // No new classes check::classes(array()); -// now new vars +// No new vars check::globals(array()); check::done(); -?> diff --git a/Examples/test-suite/php/smart_pointer_rename_runme.php b/Examples/test-suite/php/smart_pointer_rename_runme.php index 26692dde5..094860386 100644 --- a/Examples/test-suite/php/smart_pointer_rename_runme.php +++ b/Examples/test-suite/php/smart_pointer_rename_runme.php @@ -1,7 +1,6 @@ test(),"bar->test"); check::classname("foo",$bar->__deref__()); check::done(); -?> diff --git a/Examples/test-suite/php/swig_exception_runme.php b/Examples/test-suite/php/swig_exception_runme.php index 76641996e..c218890e4 100644 --- a/Examples/test-suite/php/swig_exception_runme.php +++ b/Examples/test-suite/php/swig_exception_runme.php @@ -1,6 +1,5 @@ +check::done(); diff --git a/Examples/test-suite/php/sym_runme.php b/Examples/test-suite/php/sym_runme.php index 127d28fd9..7e8f914c1 100644 --- a/Examples/test-suite/php/sym_runme.php +++ b/Examples/test-suite/php/sym_runme.php @@ -1,13 +1,12 @@ jam(),"flam-jam","flam()->jam==flam-jam"); check::equal($flam->jar(),"flam-jar","flam()->jar==flam-jar"); check::done(); -?> diff --git a/Examples/test-suite/php/template_arg_typename_runme.php b/Examples/test-suite/php/template_arg_typename_runme.php index e609240e7..c7fcbbd9d 100644 --- a/Examples/test-suite/php/template_arg_typename_runme.php +++ b/Examples/test-suite/php/template_arg_typename_runme.php @@ -1,7 +1,6 @@ diff --git a/Examples/test-suite/php/template_construct_runme.php b/Examples/test-suite/php/template_construct_runme.php index b227d9fec..d09bc4d37 100644 --- a/Examples/test-suite/php/template_construct_runme.php +++ b/Examples/test-suite/php/template_construct_runme.php @@ -1,11 +1,9 @@ diff --git a/Examples/test-suite/php/tests.php b/Examples/test-suite/php/tests.php index 20fa1ed98..cec6e581f 100644 --- a/Examples/test-suite/php/tests.php +++ b/Examples/test-suite/php/tests.php @@ -1,86 +1,24 @@ getClassNames(), + function ($e) { return !preg_match('/^SWIG\\\\/', $e); })); foreach($classes as $class) { if (! class_exists($class)) $missing[]=$class; else unset($extra[$class]); @@ -164,15 +103,16 @@ class check { if (! is_array($functions)) $functions=array($functions); $message=array(); $missing=array(); - $extra=array_flip(check::get_extra_functions()); - + $extra = self::$_extension->getFunctions(); foreach ($functions as $func) { if (! function_exists($func)) $missing[]=$func; else unset($extra[$func]); } + $extra = array_filter(array_keys($extra), + function ($e) { return !preg_match('/_[gs]et$/', $e); }); if ($missing) $message[]=sprintf("Functions missing: %s",join(",",$missing)); if ($message) return check::fail(join("\n ",$message)); - if ($extra) $message[]=sprintf("These extra functions are defined: %s",join(",",array_keys($extra))); + if ($extra) $message[]=sprintf("These extra functions are defined: %s",join(",",$extra)); if ($message) return check::warn(join("\n ",$message)); return TRUE; } @@ -181,19 +121,19 @@ class check { if (! is_array($globals)) $globals=array($globals); $message=array(); $missing=array(); - $extra=array_flip(check::get_extra_globals()); + $extra = self::$_extension->getFunctions(); foreach ($globals as $glob) { - if (self::GETSET) { - if (! isset($extra[$glob])) $missing[]=$glob; - else unset($extra[$glob]); - } else { - if (! isset($GLOBALS[$glob])) $missing[]=$glob; - else unset($extra[$glob]); + if (! function_exists($glob . "_get") && ! function_exists($glob . "_set")) $missing[]=$glob; + else { + unset($extra[$glob . "_get"]); + unset($extra[$glob . "_set"]); } } + $extra = array_filter(array_keys($extra), + function ($e) { return preg_match('/_[gs]et$/', $e); }); if ($missing) $message[]=sprintf("Globals missing: %s",join(",",$missing)); if ($message) return check::fail(join("\n ",$message)); - if ($extra) $message[]=sprintf("These extra globals are defined: %s",join(",",array_keys($extra))); + if ($extra) $message[]=sprintf("These extra globals are defined: %s",join(",",$extra)); if ($message) return check::warn(join("\n ",$message)); return TRUE; @@ -210,24 +150,13 @@ class check { return TRUE; } - static function resource($a,$b,$message) { - $resource=trim(check::var_dump($a)); - if (! preg_match("/^resource\([0-9]+\) of type \($b\)/i", $resource)) - return check::fail($message); + static function equivalent($a,$b,$message) { + if (! ($a==$b)) return check::fail($message . ": '$a'!='$b'"); return TRUE; } static function isnull($a,$message) { - $value=trim(check::var_dump($a)); - return check::equal($value,"NULL",$message); - } - - static function var_dump($arg) { - ob_start(); - var_dump($arg); - $result=ob_get_contents(); - ob_end_clean(); - return $result; + return check::equal($a,NULL,$message); } static function fail($pattern) { @@ -246,4 +175,5 @@ class check { # print $_SERVER[argv][0]." ok\n"; } } -?> + +check::init(); diff --git a/Examples/test-suite/php/threads_exception_runme.php b/Examples/test-suite/php/threads_exception_runme.php index 80717eb88..21313aead 100644 --- a/Examples/test-suite/php/threads_exception_runme.php +++ b/Examples/test-suite/php/threads_exception_runme.php @@ -1,14 +1,13 @@ diff --git a/Examples/test-suite/php/typemap_ns_using_runme.php b/Examples/test-suite/php/typemap_ns_using_runme.php index 6a599f008..e15427856 100644 --- a/Examples/test-suite/php/typemap_ns_using_runme.php +++ b/Examples/test-suite/php/typemap_ns_using_runme.php @@ -1,9 +1,8 @@ diff --git a/Examples/test-suite/php/using1_runme.php b/Examples/test-suite/php/using1_runme.php index 51841bc78..e15427856 100644 --- a/Examples/test-suite/php/using1_runme.php +++ b/Examples/test-suite/php/using1_runme.php @@ -1,9 +1,8 @@ diff --git a/Examples/test-suite/php/using2_runme.php b/Examples/test-suite/php/using2_runme.php index 391a98f52..e15427856 100644 --- a/Examples/test-suite/php/using2_runme.php +++ b/Examples/test-suite/php/using2_runme.php @@ -1,9 +1,8 @@ diff --git a/Examples/test-suite/php/valuewrapper_base_runme.php b/Examples/test-suite/php/valuewrapper_base_runme.php index 6a1abdbd2..3f4c38e5b 100644 --- a/Examples/test-suite/php/valuewrapper_base_runme.php +++ b/Examples/test-suite/php/valuewrapper_base_runme.php @@ -1,13 +1,11 @@ diff --git a/Examples/test-suite/php/virtual_vs_nonvirtual_base_runme.php b/Examples/test-suite/php/virtual_vs_nonvirtual_base_runme.php index 0d4aa3d5f..8d8d40560 100644 --- a/Examples/test-suite/php/virtual_vs_nonvirtual_base_runme.php +++ b/Examples/test-suite/php/virtual_vs_nonvirtual_base_runme.php @@ -1,11 +1,10 @@ -getInner()->get(), $fail->getInner()->get(), "should both be 10"); -?> +check::done(); diff --git a/Examples/test-suite/php/wrapmacro_runme.php b/Examples/test-suite/php/wrapmacro_runme.php index f32da990e..18b2ef1e1 100644 --- a/Examples/test-suite/php/wrapmacro_runme.php +++ b/Examples/test-suite/php/wrapmacro_runme.php @@ -1,12 +1,10 @@ diff --git a/Examples/test-suite/php_namewarn_rename.i b/Examples/test-suite/php_namewarn_rename.i index d84e2196f..d70cad770 100644 --- a/Examples/test-suite/php_namewarn_rename.i +++ b/Examples/test-suite/php_namewarn_rename.i @@ -5,6 +5,10 @@ %warnfilter(SWIGWARN_PARSE_KEYWORD) stdClass; %warnfilter(SWIGWARN_PARSE_KEYWORD) directory; %warnfilter(SWIGWARN_PARSE_KEYWORD) Hello::empty(); +%warnfilter(SWIGWARN_PARSE_KEYWORD) null; +%warnfilter(SWIGWARN_PARSE_KEYWORD) True; +%warnfilter(SWIGWARN_PARSE_KEYWORD) FALSE; +%warnfilter(SWIGWARN_PARSE_KEYWORD) ns::readonly; #endif %ignore prev::operator++; @@ -36,4 +40,28 @@ prev operator++(int) { return *this; } }; + class null + { + }; + + class True + { + }; + + class FALSE + { + }; + + // PHP 8.1 made `readonly` a keyword, but (unlike any other keyword it seems) + // it may still be used as a function name. + namespace ns { + class readonly { }; + } + + class readonly_should_be_ok_as_method { + public: + bool readonly() const { return true; } + }; + + bool readonly() { return false; } %} diff --git a/Examples/test-suite/pike/Makefile.in b/Examples/test-suite/pike/Makefile.in deleted file mode 100644 index 6e1bdfbff..000000000 --- a/Examples/test-suite/pike/Makefile.in +++ /dev/null @@ -1,49 +0,0 @@ -####################################################################### -# Makefile for Pike test-suite -####################################################################### - -LANGUAGE = pike -PIKE = pike -SCRIPTSUFFIX = _runme.pike - -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ -top_builddir = @top_builddir@ - -include $(srcdir)/../common.mk - -# Overridden variables here -# none! - -# Custom tests - tests with additional commandline options -# none! - -# Rules for the different types of tests -%.cpptest: - $(setup) - +$(swig_and_compile_cpp) - $(run_testcase) - -%.ctest: - $(setup) - +$(swig_and_compile_c) - $(run_testcase) - -%.multicpptest: - $(setup) - +$(swig_and_compile_multi_cpp) - $(run_testcase) - -# Runs the testcase. A testcase is only run if -# a file is found which has _runme.pike appended after the testcase name. -run_testcase = \ - if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(PIKE) $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ - fi - -# Clean: remove the generated .pike file -%.clean: - @rm -f $*.pike; - -clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' pike_clean diff --git a/Examples/test-suite/prefix.i b/Examples/test-suite/prefix.i index b0cb31205..ca9e4c442 100644 --- a/Examples/test-suite/prefix.i +++ b/Examples/test-suite/prefix.i @@ -11,4 +11,20 @@ public: } }; +// This failed in git pre 4.1.0 - the calls to the parent class' magic __get, +// __set and __isset methods weren't getting the prefix. +class Bar : public Foo { +public: + Bar *get_self() { + return this; + } +}; + +// This failed in git pre 4.1.0 with PHP 8.x because we weren't adding the +// prefix to class names in type declarations. Error was at extension load +// time: +// +// Fatal error: Bar must be registered before ProjectBar in Unknown on line 0 +Bar* self(Bar* bar) { return bar->get_self(); } + %} diff --git a/Examples/test-suite/preproc.i b/Examples/test-suite/preproc.i index 215fdd0ef..dff6dbca1 100644 --- a/Examples/test-suite/preproc.i +++ b/Examples/test-suite/preproc.i @@ -11,13 +11,29 @@ #pragma SWIG nowarn=890 /* lots of Go name conflicts */ #pragma SWIG nowarn=206 /* Unexpected tokens after #endif directive. */ +/* Regression test: in SWIG < 4.1.0 this triggered the two #error cases. + * Github issue #1384 + */ +#if "" != "" +#endif +#if 1 && (!0) +// Should go here +#else +# error BUG +#endif +#if ((("" == ""))) || (1 && (!1)) +// Should go here +#else +# error BUG +#endif + %{ #if defined(__clang__) -//Suppress: warning: use of logical '&&' with constant operand [-Wconstant-logical-operand] +/*Suppress: warning: use of logical '&&' with constant operand [-Wconstant-logical-operand]*/ #pragma clang diagnostic ignored "-Wconstant-logical-operand" #endif #if defined(_MSC_VER) - #pragma warning(disable: 4003) // not enough actual parameters for macro 'FOO2' + #pragma warning(disable: 4003) /* not enough actual parameters for macro 'FOO2' */ #endif %} @@ -72,14 +88,14 @@ extern "C" TYPEMAP_LIST_VECTOR_INPUT_OUTPUT(boolean) -// preproc_3 +/* preproc_3 */ #define Sum( A, B, \ C) \ A + B + C -// preproc_4 +/* preproc_4 */ %{ int hello0() { @@ -102,33 +118,30 @@ TYPEMAP_LIST_VECTOR_INPUT_OUTPUT(boolean) #define HELLO_TYPE(A, B) ARITH_RTYPE(A, ARITH_RTYPE(A,B)) -// -// These two work fine -// int hello0(); ARITH_RTYPE(double,int) hello1(); -// -// This doesn't work with 1.3.17+ ( but it was ok in 1.3.16 ) -// it gets expanded as (using -E) -// -// ARITH_RTYPE(double,int) hello2(); -// +/* + This doesn't work with 1.3.17+ ( but it was ok in 1.3.16 ) + it gets expanded as (using -E) + + ARITH_RTYPE(double,int) hello2(); +*/ HELLO_TYPE(double,int) hello2(); #define min(x,y) ((x) < (y)) ? (x) : (y) int f(int min); -// preproc_5 +/* preproc_5 */ -%warnfilter(SWIGWARN_PARSE_REDEFINED) A5; // Ruby, wrong constant name -%warnfilter(SWIGWARN_RUBY_WRONG_NAME) a5; // Ruby, wrong constant name -%warnfilter(SWIGWARN_RUBY_WRONG_NAME) b5; // Ruby, wrong constant name -%warnfilter(SWIGWARN_RUBY_WRONG_NAME) c5; // Ruby, wrong constant name -%warnfilter(SWIGWARN_RUBY_WRONG_NAME) d5; // Ruby, wrong constant name +%warnfilter(SWIGWARN_PARSE_REDEFINED) A5; /* Ruby, wrong constant name */ +%warnfilter(SWIGWARN_RUBY_WRONG_NAME) a5; /* Ruby, wrong constant name */ +%warnfilter(SWIGWARN_RUBY_WRONG_NAME) b5; /* Ruby, wrong constant name */ +%warnfilter(SWIGWARN_RUBY_WRONG_NAME) c5; /* Ruby, wrong constant name */ +%warnfilter(SWIGWARN_RUBY_WRONG_NAME) d5; /* Ruby, wrong constant name */ -// Various preprocessor bits of nastiness. +/* Various preprocessor bits of nastiness. */ /* Test argument name substitution */ @@ -138,7 +151,7 @@ int f(int min); %constant char *a5 = foo(hello,world); %constant int b5 = bar(3,4); -// Wrap your brain around this one ;-) +/* Wrap your brain around this one ;-) */ %{ #define cat(x,y) x ## y @@ -168,7 +181,7 @@ NAME 42 #define C4"Hello" -// preproc_6 +/* preproc_6 */ %warnfilter(SWIGWARN_PARSE_REDEFINED) A6; /* Ruby, wrong constant name */ %warnfilter(SWIGWARN_RUBY_WRONG_NAME) a6; /* Ruby, wrong constant name */ @@ -206,7 +219,7 @@ NAME 42 MACRO2(int) -// cpp_macro_noarg. Tests to make sure macros with no arguments work right. +/* cpp_macro_noarg. Tests to make sure macros with no arguments work right. */ #define MACROWITHARG(x) something(x) typedef int MACROWITHARG; @@ -298,11 +311,6 @@ inline const char* mangle_macro ## #@__VA_ARGS__ () { /* chiao */ #endif; -#ifdef SWIGCHICKEN -/* define is a scheme keyword (and thus an invalid variable name), so SWIG warns about it */ -%warnfilter(SWIGWARN_PARSE_KEYWORD) define; -#endif - #ifdef SWIGRUBY %rename(ddefined) defined; #endif @@ -378,8 +386,11 @@ int methodX(int x); int methodX(int x) { return x+100; } %} -// Comma in macro - https://github.com/swig/swig/issues/974 (for /* */) -// and https://github.com/swig/swig/pull/1166 (for //) +/* + Comma in macro - https://github.com/swig/swig/issues/974 (for C comments) + and https://github.com/swig/swig/pull/1166 (for //) + Also see preproc_cpp.i +*/ %inline %{ #define swig__attribute__(x) #define TCX_PACKED(d) d swig__attribute__ ((__packed__)) @@ -397,21 +408,9 @@ TCX_PACKED (typedef struct tcxMessageBugImpl }) tcxMessageBug; -TCX_PACKED (typedef struct tcxMessageTestImpl2 -{ - int mHeader; ///< comment -}) tcxMessageTest2; - - -TCX_PACKED (typedef struct tcxMessageBugImpl2 -{ - int mBid; ///< Bid price and size, check PresentMap if available in message -}) tcxMessageBug2; - - %} -// Regression tests for https://github.com/swig/swig/pull/1111 +/* Regression tests for https://github.com/swig/swig/pull/1111 */ %{ static int foo_func(int x) { return x; } static int foo_func2() { return 0; } @@ -427,22 +426,22 @@ static int baz_func(int a, int b, int c) { return a + b - c; } #define FOOVAR(...) foo_func(__VA_ARGS__) #define BARVAR(...) bar_func(__VA_ARGS__) #define BAZVAR(...) baz_func(__VA_ARGS__) -// This has probably always worked, but make sure that the fix to accept -// an empty X doesn't cause this case to be incorrectly expanded: +/* This has probably always worked, but make sure that the fix to accept + an empty X doesn't cause this case to be incorrectly expanded:*/ const int FOO = 7; -// BAR was incorrectly expanded here, causing: -// Error: Syntax error in input(1). +/* BAR was incorrectly expanded here, causing: + Error: Syntax error in input(1). */ const int BAR = 6; -// This has probably always worked, but make sure that the fix to accept -// an empty X doesn't stop a non-empty X from working: +/* This has probably always worked, but make sure that the fix to accept + an empty X doesn't stop a non-empty X from working: */ FOO(int x) -// FOO() didn't used to get expanded here, causing: -// Syntax error in input(1). +/* FOO() didn't used to get expanded here, causing: + Syntax error in input(1). */ FOO2() -// Check BAR2() still gets expanded here. +/* Check BAR2() still gets expanded here. */ BAR2() { - // Regression test - this used to fail with: - // Error: Macro 'BAZ' expects 3 arguments + /* Regression test - this used to fail with: + Error: Macro 'BAZ' expects 3 arguments */ BAZ(,2,3); BARVAR(); FOOVAR(1); diff --git a/Examples/test-suite/preproc_constants.i b/Examples/test-suite/preproc_constants.i index 3050baa06..3873d2608 100644 --- a/Examples/test-suite/preproc_constants.i +++ b/Examples/test-suite/preproc_constants.i @@ -65,17 +65,15 @@ #define EXPR_MULTIPLY 0xFF * 2 #define EXPR_DIVIDE 0xFF / 2 -//FIXME #define EXPR_MOD 0xFF % 2 +#define EXPR_MOD 0xFF % 2 #define EXPR_PLUS 0xFF + 2 #define EXPR_MINUS 0xFF + 2 #define EXPR_LSHIFT 0xFF << 2 #define EXPR_RSHIFT 0xFF >> 2 -/* FIXME -#define EXPR_LT 0xFF < 255 -#define EXPR_GT 0xFF > 255 -*/ +#define EXPR_LT (0xFF < 255) +#define EXPR_GT (0xFF > 255) #define EXPR_LTE 0xFF <= 255 #define EXPR_GTE 0xFF >= 255 #define EXPR_INEQUALITY 0xFF != 255 diff --git a/Examples/test-suite/preproc_cpp.i b/Examples/test-suite/preproc_cpp.i new file mode 100644 index 000000000..c81f9a74f --- /dev/null +++ b/Examples/test-suite/preproc_cpp.i @@ -0,0 +1,36 @@ +%module preproc_cpp + + +// Comma in macro - https://github.com/swig/swig/issues/974 (for /* */) +// and https://github.com/swig/swig/pull/1166 (for //) +// Also see preproc.i +%inline %{ +#define swig__attribute__(x) +#define TCX_PACKED(d) d swig__attribute__ ((__packed__)) + + +TCX_PACKED (typedef struct tcxMessageTestImpl +{ + int mHeader; /**< comment */ +}) tcxMessageTest; + + +TCX_PACKED (typedef struct tcxMessageBugImpl +{ + int mBid; /**< Bid price and size, check PresentMap if available in message */ +}) tcxMessageBug; + + +TCX_PACKED (typedef struct tcxMessageTestImpl2 +{ + int mHeader; ///< comment +}) tcxMessageTest2; + + +TCX_PACKED (typedef struct tcxMessageBugImpl2 +{ + int mBid; ///< Bid price and size, check PresentMap if available in message +}) tcxMessageBug2; + + +%} diff --git a/Examples/test-suite/private_assign.i b/Examples/test-suite/private_assign.i index acc4d0bc9..d9ba70cf4 100644 --- a/Examples/test-suite/private_assign.i +++ b/Examples/test-suite/private_assign.i @@ -14,6 +14,8 @@ return *this; } public: + Foo() { } + Foo(const Foo &f) { } // copy ctor can still be public, however. void bar() { } }; diff --git a/Examples/test-suite/python/Makefile.in b/Examples/test-suite/python/Makefile.in index 4c0507cbb..57f72d512 100644 --- a/Examples/test-suite/python/Makefile.in +++ b/Examples/test-suite/python/Makefile.in @@ -10,20 +10,10 @@ endif LANGUAGE = python PYTHON = $(PYBIN) +SCRIPTSUFFIX = _runme.py PYCODESTYLE = @PYCODESTYLE@ PYCODESTYLE_FLAGS = --ignore=E252,E30,E402,E501,E731,E741,W291,W391 -#*_runme.py for Python 2.x, *_runme3.py for Python 3.x -PY2SCRIPTSUFFIX = _runme.py -PY3SCRIPTSUFFIX = _runme3.py -PY2TO3 = @PY2TO3@ -x import - -ifeq (,$(PY3)) - SCRIPTSUFFIX = $(PY2SCRIPTSUFFIX) -else - SCRIPTSUFFIX = $(PY3SCRIPTSUFFIX) -endif - srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ @@ -58,12 +48,14 @@ CPP_TEST_CASES += \ li_std_wstring_inherit \ primitive_types \ python_abstractbase \ + python_annotations_c \ python_append \ python_builtin \ python_destructor_exception \ python_director \ python_docstring \ python_extranative \ + python_flatstaticmethod \ python_moduleimport \ python_overload_simple_cast \ python_pickle \ @@ -85,6 +77,7 @@ CPP11_TEST_CASES = \ cpp11_shared_ptr_const \ cpp11_shared_ptr_nullptr_in_containers \ cpp11_shared_ptr_overload \ + cpp11_shared_ptr_template_upcast \ cpp11_shared_ptr_upcast \ cpp11_std_unordered_map \ cpp11_std_unordered_multimap \ @@ -92,59 +85,43 @@ CPP11_TEST_CASES = \ cpp11_std_unordered_set \ C_TEST_CASES += \ + ccomplextest \ file_test \ li_cstring \ li_cwstring \ python_nondynamic \ python_varargs_typemap \ -# -# This test only works with modern C compilers -# -#C_TEST_CASES += \ -# complextest - include $(srcdir)/../common.mk # Overridden variables here -SCRIPTDIR = . LIBS = -L. VALGRIND_OPT += --suppressions=pythonswig.supp # Custom tests - tests with additional commandline options -# none! +#python_flatstaticmethod.cpptest: SWIGOPT += -flatstaticmethod # Rules for the different types of tests %.cpptest: - +$(convert_testcase) $(setup) +$(swig_and_compile_cpp) $(check_pep8) $(run_testcase) %.ctest: - +$(convert_testcase) $(setup) +$(swig_and_compile_c) $(check_pep8) $(run_testcase) %.multicpptest: - +$(convert_testcase) $(setup) +$(swig_and_compile_multi_cpp) $(check_pep8_multi_cpp) $(run_testcase) - -# Runs the testcase. A testcase is only run if -# a file is found which has _runme.py (or _runme3.py for Python 3) appended after the testcase name. - -py_runme = $(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) -py2_runme = $(SCRIPTPREFIX)$*$(PY2SCRIPTSUFFIX) -py3_runme = $(SCRIPTPREFIX)$*$(PY3SCRIPTSUFFIX) - +# Python code style checking ifneq (,$(PYCODESTYLE)) check_pep8 = $(COMPILETOOL) $(PYCODESTYLE) $(PYCODESTYLE_FLAGS) $(SCRIPTPREFIX)$*.py @@ -154,77 +131,24 @@ check_pep8_multi_cpp = \ done endif -run_python = env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH PYTHONPATH=.:$(srcdir):$$PYTHONPATH $(RUNTOOL) $(PYTHON) $(py_runme) - +# Runs the testcase. A testcase is only run if +# a file is found which has _runme.py appended after the testcase name. run_testcase = \ - if [ -f $(SCRIPTDIR)/$(py_runme) ]; then \ - $(run_python);\ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH PYTHONPATH=.:$(srcdir):$$PYTHONPATH $(RUNTOOL) $(PYTHON) $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ fi -# Grab runme file ready for running: copied for out of source tree builds, and/or run 2to3 -# Note terminal (double colon) rules creating runme files to fix possible infinite recursion, -# see https://github.com/swig/swig/pull/688 -ifeq ($(SCRIPTDIR),$(srcdir)) - # in source tree build - ifeq (,$(PY3)) - convert_testcase = - else - convert_testcase = \ - if [ -f $(srcdir)/$(py2_runme) ]; then \ - $(MAKE) $(SCRIPTDIR)/$(py_runme); \ - fi - -# For converting python 2 tests into Python 3 tests -$(SCRIPTDIR)/$(SCRIPTPREFIX)%$(SCRIPTSUFFIX):: $(srcdir)/$(SCRIPTPREFIX)%$(PY2SCRIPTSUFFIX) - cp $< $@ - $(PY2TO3) -w $@ >/dev/null 2>&1 - - endif -else - # out of source tree build - ifeq (,$(PY3)) - convert_testcase = \ - if [ -f $(srcdir)/$(py2_runme) ]; then \ - $(MAKE) $(SCRIPTDIR)/$(py_runme); \ - fi - -$(SCRIPTDIR)/$(SCRIPTPREFIX)%$(SCRIPTSUFFIX):: $(srcdir)/$(SCRIPTPREFIX)%$(PY2SCRIPTSUFFIX) - cp $< $@ - - else - convert_testcase = \ - if [ -f $(srcdir)/$(py2_runme) ]; then \ - $(MAKE) $(SCRIPTDIR)/$(py_runme); \ - elif [ -f $(srcdir)/$(py3_runme) ]; then \ - $(MAKE) $(SCRIPTDIR)/$(py3_runme); \ - fi - -# For when there is a _runme3.py instead of a _runme.py, ie a Python 3 only run test -$(SCRIPTDIR)/$(SCRIPTPREFIX)%$(SCRIPTSUFFIX):: $(srcdir)/$(SCRIPTPREFIX)%$(PY3SCRIPTSUFFIX) - cp $< $@ - -# For converting python 2 tests into Python 3 tests -$(SCRIPTDIR)/$(SCRIPTPREFIX)%$(SCRIPTSUFFIX):: $(srcdir)/$(SCRIPTPREFIX)%$(PY2SCRIPTSUFFIX) - cp $< $@ - $(PY2TO3) -w $@ >/dev/null 2>&1 - - endif - -endif - # Clean: remove the generated .py file -# We only remove the _runme3.py if it is generated by 2to3 from a _runme.py. %.clean: @rm -f $*.py - @if test -f $(srcdir)/$(py2_runme); then rm -f $(SCRIPTDIR)/$(py3_runme) $(SCRIPTDIR)/$(py3_runme).bak; fi - @if test "x$(SCRIPTDIR)" != "x$(srcdir)"; then rm -f $(SCRIPTDIR)/$(py_runme); fi clean: $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' python_clean - rm -f hugemod.h hugemod_a.i hugemod_b.i hugemod_a.py hugemod_b.py hugemod_runme.py rm -f clientdata_prop_a.py clientdata_prop_b.py import_stl_a.py import_stl_b.py + rm -f hugemod.h hugemod_a.i hugemod_b.i hugemod_a.py hugemod_b.py hugemod_runme.py rm -f imports_a.py imports_b.py mod_a.py mod_b.py multi_import_a.py - rm -f multi_import_b.py packageoption_a.py packageoption_b.py packageoption_c.py + rm -f multi_import_b.py multi_import_d.py packageoption_a.py packageoption_b.py packageoption_c.py + rm -f template_typedef_cplx2.py hugemod_runme = hugemod$(SCRIPTPREFIX) diff --git a/Examples/test-suite/python/README b/Examples/test-suite/python/README index 71db759b5..84992ed05 100644 --- a/Examples/test-suite/python/README +++ b/Examples/test-suite/python/README @@ -1,8 +1,8 @@ See ../README for common README file. -Any testcases which have _runme.py (or _runme3.py for Python 3) appended after the testcase name will be detected and run. +Any testcases which have _runme.py appended after the testcase name will be detected and run. -If you intend to write a testcase for both Python 2.x and 3.x, do *not* directly put the _runme3.py in this directory. Just write Python 2.x's _runme.py testcase and it will be automatically converted to Python 3 code during test. +The _runme.py files needs to work for both Python 2.x and 3.x. You can run make with PY3=y to run test case with Python 3.x, eg. $ make voidtest.cpptest PY3=y diff --git a/Examples/test-suite/python/abstract_basecast_runme.py b/Examples/test-suite/python/abstract_basecast_runme.py new file mode 100644 index 000000000..4a3f4a9e1 --- /dev/null +++ b/Examples/test-suite/python/abstract_basecast_runme.py @@ -0,0 +1,15 @@ +from abstract_basecast import * + +def check(flag): + if not flag: + raise RuntimeError("Test failed") + +derived = DerivedClass() +derived.g() +check(isinstance(derived, BaseClass)) +check(isinstance(derived, DerivedClass)) + +base = derived.f() +base.g() +check(isinstance(base, BaseClass)) +check(not isinstance(base, DerivedClass)) diff --git a/Examples/test-suite/python/argcargvtest_runme.py b/Examples/test-suite/python/argcargvtest_runme.py index b0345746f..eb57f79ea 100644 --- a/Examples/test-suite/python/argcargvtest_runme.py +++ b/Examples/test-suite/python/argcargvtest_runme.py @@ -6,7 +6,6 @@ if mainc(largs) != 3: targs = ("hi", "hola") if mainv(targs, 1) != "hola": - print(mainv(targs, 1)) raise RuntimeError("bad main typemap") targs = ("hi", "hola") diff --git a/Examples/test-suite/python/array_member_runme.py b/Examples/test-suite/python/array_member_runme.py index de6e0f3e7..2708a6f37 100644 --- a/Examples/test-suite/python/array_member_runme.py +++ b/Examples/test-suite/python/array_member_runme.py @@ -5,7 +5,7 @@ f.data = cvar.global_data for i in range(0, 8): if get_value(f.data, i) != get_value(cvar.global_data, i): - raise RuntimeError, "Bad array assignment" + raise RuntimeError("Bad array assignment") for i in range(0, 8): @@ -15,4 +15,4 @@ cvar.global_data = f.data for i in range(0, 8): if get_value(f.data, i) != get_value(cvar.global_data, i): - raise RuntimeError, "Bad array assignment" + raise RuntimeError("Bad array assignment") diff --git a/Examples/test-suite/python/autodoc_runme.py b/Examples/test-suite/python/autodoc_runme.py index 7bc918644..960458584 100644 --- a/Examples/test-suite/python/autodoc_runme.py +++ b/Examples/test-suite/python/autodoc_runme.py @@ -65,14 +65,10 @@ check(inspect.getdoc(A.func0static), "func0static(e, arg2, hello, f=2) -> int") check(inspect.getdoc(_autodoc.A_func0static), "A_func0static(e, arg2, hello, f=2) -> int") -check(inspect.getdoc(A_func0static), - "A_func0static(e, arg2, hello, f=2) -> int") check(inspect.getdoc(A.func1static), "func1static(A e, short arg2, Tuple hello, double f=2) -> int") check(inspect.getdoc(_autodoc.A_func1static), "A_func1static(A e, short arg2, Tuple hello, double f=2) -> int") -check(inspect.getdoc(A_func1static), - "A_func1static(A e, short arg2, Tuple hello, double f=2) -> int") check(inspect.getdoc(A.func2static), "func2static(e, arg2, hello, f=2) -> int\n" "\n" @@ -91,15 +87,6 @@ check(inspect.getdoc(_autodoc.A_func2static), "arg2: short\n" "hello: int tuple[2]\n" "f: double") -check(inspect.getdoc(A_func2static), - "A_func2static(e, arg2, hello, f=2) -> int\n" - "\n" - "Parameters\n" - "----------\n" - "e: A *\n" - "arg2: short\n" - "hello: int tuple[2]\n" - "f: double") check(inspect.getdoc(A.func3static), "func3static(A e, short arg2, Tuple hello, double f=2) -> int\n" "\n" @@ -118,15 +105,6 @@ check(inspect.getdoc(_autodoc.A_func3static), "arg2: short\n" "hello: int tuple[2]\n" "f: double") -check(inspect.getdoc(A_func3static), - "A_func3static(A e, short arg2, Tuple hello, double f=2) -> int\n" - "\n" - "Parameters\n" - "----------\n" - "e: A *\n" - "arg2: short\n" - "hello: int tuple[2]\n" - "f: double") check(inspect.getdoc(A.variable_a), "variable_a" diff --git a/Examples/test-suite/python/callback_runme.py b/Examples/test-suite/python/callback_runme.py index de8a372f6..dbf957cbb 100644 --- a/Examples/test-suite/python/callback_runme.py +++ b/Examples/test-suite/python/callback_runme.py @@ -1,10 +1,14 @@ import _callback from callback import * +# callbacks are implemented by modifying docstrings, useful for debugging: +# print("A_bar doc: {}".format(A_bar.__doc__)) +# print("A.bar doc: {}".format(A.bar.__doc__)) + if foo(2) != 2: raise RuntimeError -if A_bar(2) != 4: +if A.bar(2) != 4: raise RuntimeError if foobar(3, _callback.foo) != foo(3): @@ -13,11 +17,7 @@ if foobar(3, _callback.foo) != foo(3): if foobar(3, foo) != foo(3): raise RuntimeError -# Needs some more work for -builtin -# if foobar(3, A.bar) != A.bar(3): -# raise RuntimeError - -if foobar(3, A_bar) != A_bar(3): +if foobar(3, A.bar) != A.bar(3): raise RuntimeError if foobar(3, foof) != foof(3): diff --git a/Examples/test-suite/python/ccomplextest_runme.py b/Examples/test-suite/python/ccomplextest_runme.py new file mode 100644 index 000000000..63a663f50 --- /dev/null +++ b/Examples/test-suite/python/ccomplextest_runme.py @@ -0,0 +1,22 @@ +import ccomplextest + +a = complex(-1, 2) + +if ccomplextest.has_c99_complex(): + if ccomplextest.Conj(a) != a.conjugate(): + raise RuntimeError("bad complex mapping") + + if ccomplextest.Conjf(a) != a.conjugate(): + raise RuntimeError("bad complex mapping") + + if ccomplextest.Conj2(a) != a.conjugate(): + raise RuntimeError("bad complex mapping") + + if ccomplextest.Conjf2(a) != a.conjugate(): + raise RuntimeError("bad complex mapping") + + if ccomplextest.Conj3(a) != a.conjugate(): + raise RuntimeError("bad complex mapping") + + if ccomplextest.Conjf3(a) != a.conjugate(): + raise RuntimeError("bad complex mapping") diff --git a/Examples/test-suite/python/char_binary_runme.py b/Examples/test-suite/python/char_binary_runme.py index 0425fe1c9..39c0b2447 100644 --- a/Examples/test-suite/python/char_binary_runme.py +++ b/Examples/test-suite/python/char_binary_runme.py @@ -2,16 +2,14 @@ from char_binary import * t = Test() if t.strlen("hile") != 4: - print t.strlen("hile") - raise RuntimeError, "bad multi-arg typemap" + raise RuntimeError("bad multi-arg typemap {}".format(t.strlen("hile"))) if t.ustrlen("hile") != 4: - print t.ustrlen("hile") - raise RuntimeError, "bad multi-arg typemap" + raise RuntimeError("bad multi-arg typemap {}".format(t.ustrlen("hile"))) if t.strlen("hil\0") != 4: - raise RuntimeError, "bad multi-arg typemap" + raise RuntimeError("bad multi-arg typemap") if t.ustrlen("hil\0") != 4: - raise RuntimeError, "bad multi-arg typemap" + raise RuntimeError("bad multi-arg typemap") # # creating a raw char* @@ -25,18 +23,17 @@ pchar_setitem(pc, 4, 0) if t.strlen(pc) != 4: - raise RuntimeError, "bad multi-arg typemap" + raise RuntimeError("bad multi-arg typemap") if t.ustrlen(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" + raise RuntimeError("bad pointer case {}".format(cvar.var_pchar)) cvar.var_namet = pc # 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/complextest_runme.py b/Examples/test-suite/python/complextest_runme.py index 5cfc7ccab..1b9ad6629 100644 --- a/Examples/test-suite/python/complextest_runme.py +++ b/Examples/test-suite/python/complextest_runme.py @@ -3,17 +3,16 @@ import complextest 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") if complextest.Conj2(a) != a.conjugate(): - raise RuntimeError, "bad complex mapping" + raise RuntimeError("bad complex mapping") if complextest.Conjf2(a) != a.conjugate(): - raise RuntimeError, "bad complex mapping" - + raise RuntimeError("bad complex mapping") v = (complex(1, 2), complex(2, 3), complex(4, 3), 1) @@ -27,4 +26,4 @@ p = complextest.ComplexPair() p.z1 = complex(0, 1) p.z2 = complex(0, -1) if complextest.Conj(p.z2) != p.z1: - raise RuntimeError, "bad complex mapping" + raise RuntimeError("bad complex mapping") diff --git a/Examples/test-suite/python/constover_runme.py b/Examples/test-suite/python/constover_runme.py index 2d28a55cc..0c03967f6 100644 --- a/Examples/test-suite/python/constover_runme.py +++ b/Examples/test-suite/python/constover_runme.py @@ -4,33 +4,26 @@ error = 0 p = constover.test("test") if p != "test": - print "test failed!" - error = 1 + raise RuntimeError("test failed!") p = constover.test_pconst("test") if p != "test_pconst": - print "test_pconst failed!" - error = 1 + raise RuntimeError("test_pconst failed!") f = constover.Foo() p = f.test("test") if p != "test": - print "member-test failed!" - error = 1 + raise RuntimeError("member-test failed!") p = f.test_pconst("test") if p != "test_pconst": - print "member-test_pconst failed!" - error = 1 + raise RuntimeError("member-test_pconst failed!") p = f.test_constm("test") if p != "test_constmethod": - print "member-test_constm failed!" - error = 1 + raise RuntimeError("member-test_constm failed!") p = f.test_pconstm("test") if p != "test_pconstmethod": - print "member-test_pconstm failed!" - error = 1 + raise RuntimeError("member-test_pconstm failed!") -sys.exit(error) diff --git a/Examples/test-suite/python/contract_runme.py b/Examples/test-suite/python/contract_runme.py index cd75a51d2..3194b6ac7 100644 --- a/Examples/test-suite/python/contract_runme.py +++ b/Examples/test-suite/python/contract_runme.py @@ -2,141 +2,141 @@ import contract contract.test_preassert(1, 2) try: - contract.test_preassert(-1) - print "Failed! Preassertions are broken" -except: + contract.test_preassert(-1, 3) + raise Exception("Failed! Preassertions are broken") +except RuntimeError: pass contract.test_postassert(3) try: contract.test_postassert(-3) - print "Failed! Postassertions are broken" -except: + raise Exception("Failed! Postassertions are broken") +except RuntimeError: pass contract.test_prepost(2, 3) contract.test_prepost(5, -4) try: contract.test_prepost(-3, 4) - print "Failed! Preassertions are broken" -except: + raise Exception("Failed! Preassertions are broken") +except RuntimeError: pass try: contract.test_prepost(4, -10) - print "Failed! Postassertions are broken" + raise Exception("Failed! Postassertions are broken") -except: +except RuntimeError: pass f = contract.Foo() f.test_preassert(4, 5) try: f.test_preassert(-2, 3) - print "Failed! Method preassertion." -except: + raise Exception("Failed! Method preassertion.") +except RuntimeError: pass f.test_postassert(4) try: f.test_postassert(-4) - print "Failed! Method postassertion" -except: + raise Exception("Failed! Method postassertion") +except RuntimeError: pass f.test_prepost(3, 4) f.test_prepost(4, -3) try: f.test_prepost(-4, 2) - print "Failed! Method preassertion." -except: + raise Exception("Failed! Method preassertion.") +except RuntimeError: pass try: f.test_prepost(4, -10) - print "Failed! Method postassertion." -except: + raise Exception("Failed! Method postassertion.") +except RuntimeError: 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" -except: + contract.Foo.stest_prepost(-4, 2) + raise Exception("Failed! Static method preassertion") +except RuntimeError: pass try: - contract.Foo_stest_prepost(4, -10) - print "Failed! Static method posteassertion" -except: + contract.Foo.stest_prepost(4, -10) + raise Exception("Failed! Static method posteassertion") +except RuntimeError: pass b = contract.Bar() try: b.test_prepost(2, -4) - print "Failed! Inherited preassertion." -except: + raise Exception("Failed! Inherited preassertion.") +except RuntimeError: pass d = contract.D() try: d.foo(-1, 1, 1, 1, 1) - print "Failed! Inherited preassertion (D)." -except: + raise Exception("Failed! Inherited preassertion (D).") +except RuntimeError: pass try: d.foo(1, -1, 1, 1, 1) - print "Failed! Inherited preassertion (D)." -except: + raise Exception("Failed! Inherited preassertion (D).") +except RuntimeError: pass try: d.foo(1, 1, -1, 1, 1) - print "Failed! Inherited preassertion (D)." -except: + raise Exception("Failed! Inherited preassertion (D).") +except RuntimeError: pass try: d.foo(1, 1, 1, -1, 1) - print "Failed! Inherited preassertion (D)." -except: + raise Exception("Failed! Inherited preassertion (D).") +except RuntimeError: pass try: d.foo(1, 1, 1, 1, -1) - print "Failed! Inherited preassertion (D)." -except: + raise Exception("Failed! Inherited preassertion (D).") +except RuntimeError: pass try: d.bar(-1, 1, 1, 1, 1) - print "Failed! Inherited preassertion (D)." -except: + raise Exception("Failed! Inherited preassertion (D).") +except RuntimeError: pass try: d.bar(1, -1, 1, 1, 1) - print "Failed! Inherited preassertion (D)." -except: + raise Exception("Failed! Inherited preassertion (D).") +except RuntimeError: pass try: d.bar(1, 1, -1, 1, 1) - print "Failed! Inherited preassertion (D)." -except: + raise Exception("Failed! Inherited preassertion (D).") +except RuntimeError: pass try: d.bar(1, 1, 1, -1, 1) - print "Failed! Inherited preassertion (D)." -except: + raise Exception("Failed! Inherited preassertion (D).") +except RuntimeError: pass try: d.bar(1, 1, 1, 1, -1) - print "Failed! Inherited preassertion (D)." -except: + raise Exception("Failed! Inherited preassertion (D).") +except RuntimeError: pass # Namespace my = contract.myClass(1) try: my = contract.myClass(0) - print "Failed! constructor preassertion" -except: + raise Exception("Failed! constructor preassertion") +except RuntimeError: 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 cc7b5cd91..e46a4772f 100644 --- a/Examples/test-suite/python/cpp11_alternate_function_syntax_runme.py +++ b/Examples/test-suite/python/cpp11_alternate_function_syntax_runme.py @@ -4,20 +4,20 @@ a = cpp11_alternate_function_syntax.SomeStruct() 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) 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.") res = a.addAlternateConst(4, 5) if res != 9: - raise RuntimeError, ("SomeStruct::addAlternateConst(4,5) returns ", res, " should be 9.") + raise RuntimeError("SomeStruct::addAlternateConst(4,5) returns ", res, " should be 9.") res = a.addAlternateNoExcept(4, 5) if res != 9: - raise RuntimeError, ("SomeStruct::addAlternateNoExcept(4,5) returns ", res, " should be 9.") + raise RuntimeError("SomeStruct::addAlternateNoExcept(4,5) returns ", res, " should be 9.") res = a.addAlternateConstNoExcept(4, 5) if res != 9: - raise RuntimeError, ("SomeStruct::addAlternateConstNoExcept(4,5) returns ", res, " should be 9.") + raise RuntimeError("SomeStruct::addAlternateConstNoExcept(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 1650d9004..a18f334dc 100644 --- a/Examples/test-suite/python/cpp11_decltype_runme.py +++ b/Examples/test-suite/python/cpp11_decltype_runme.py @@ -3,16 +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_hash_tables_runme.py b/Examples/test-suite/python/cpp11_hash_tables_runme.py index 7b772ff9a..3e7be49d0 100644 --- a/Examples/test-suite/python/cpp11_hash_tables_runme.py +++ b/Examples/test-suite/python/cpp11_hash_tables_runme.py @@ -10,14 +10,14 @@ for x in [cpp11_hash_tables.MapIntInt({1:7}), cpp11_hash_tables.UnorderedMultiMapIntInt({1:7}) ]: - swig_assert_equal([(k, v) for k, v in x.iteritems()], [(1, 7)]) - swig_assert_equal(x.keys(), [1]) - swig_assert_equal(x.values(), [7]) - swig_assert_equal(x.items(), [(1, 7)]) + swig_assert_equal([(k, v) for k, v in x.items()], [(1, 7)]) + swig_assert_equal(list(x.keys()), [1]) + swig_assert_equal(list(x.values()), [7]) + swig_assert_equal(list(x.items()), [(1, 7)]) swig_assert_equal([k for k in x], [1]) - swig_assert_equal([i for i in x.iterkeys()], [1]) - swig_assert_equal([i for i in x.itervalues()], [7]) - swig_assert_equal([i for i in x.iteritems()], [(1, 7)]) + swig_assert_equal([i for i in x.keys()], [1]) + swig_assert_equal([i for i in x.values()], [7]) + swig_assert_equal([i for i in x.items()], [(1, 7)]) swig_assert_equal(x[1], 7) swig_assert_equal(2 in x, False) @@ -33,7 +33,7 @@ for x in [cpp11_hash_tables.MapIntInt({1:7}), for x in [cpp11_hash_tables.MultiMapIntInt({1:7}), cpp11_hash_tables.UnorderedMultiMapIntInt({1:7})]: x[1] = 9 - swig_assert_equal(sorted([v for k, v in x.iteritems()]), [7, 9]) + swig_assert_equal(sorted([v for k, v in x.items()]), [7, 9]) swig_assert_equal(len(x), 2) for x in [cpp11_hash_tables.SetInt([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 54a8fe0eb..c39760344 100644 --- a/Examples/test-suite/python/cpp11_null_pointer_constant_runme.py +++ b/Examples/test-suite/python/cpp11_null_pointer_constant_runme.py @@ -3,15 +3,15 @@ import cpp11_null_pointer_constant a = cpp11_null_pointer_constant.A() if a._myA != None: - raise RuntimeError, ( + 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, ( + 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 6a587b860..90e450f8b 100644 --- a/Examples/test-suite/python/cpp11_raw_string_literals_runme.py +++ b/Examples/test-suite/python/cpp11_raw_string_literals_runme.py @@ -34,19 +34,19 @@ if cvar.aa != "Wide string": 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) def check(got, expected): diff --git a/Examples/test-suite/python/cpp11_result_of_runme.py b/Examples/test-suite/python/cpp11_result_of_runme.py index 4469efd81..691d2a2d8 100644 --- a/Examples/test-suite/python/cpp11_result_of_runme.py +++ b/Examples/test-suite/python/cpp11_result_of_runme.py @@ -2,10 +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 c1cd3bf26..85d64a581 100644 --- a/Examples/test-suite/python/cpp11_rvalue_reference_runme.py +++ b/Examples/test-suite/python/cpp11_rvalue_reference_runme.py @@ -4,24 +4,24 @@ a = cpp11_rvalue_reference.A() a.setAcopy(5) if a.getAcopy() != 5: - raise RunTimeError, ("int A::getAcopy() value is ", + 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( + 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( + 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( + raise RunTimeError("after A::setAmove(): int A::getAcopy() value is ", a.getAcopy( ), " should be 5") diff --git a/Examples/test-suite/python/cpp11_std_array_runme.py b/Examples/test-suite/python/cpp11_std_array_runme.py index e5e7373dd..9e11a3e5b 100644 --- a/Examples/test-suite/python/cpp11_std_array_runme.py +++ b/Examples/test-suite/python/cpp11_std_array_runme.py @@ -3,7 +3,7 @@ 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): @@ -26,8 +26,8 @@ def steps_exception(swigarray, i, j, step): a = swigarray[i::step] else: a = swigarray[i:j:step] - raise RuntimeError, "swigarray[" + str(i) + ":" + str(j) + ":" + str(step) + "] missed steps exception for " + str(list(swigarray)) - except ValueError, e: + raise RuntimeError("swigarray[" + str(i) + ":" + str(j) + ":" + str(step) + "] missed steps exception for " + str(list(swigarray))) + except ValueError as e: # print("exception: {}".format(e)) pass @@ -43,16 +43,16 @@ def del_exception(swigarray, i, j, step): del swigarray[i::step] else: del swigarray[i:j:step] - raise RuntimeError, "swigarray[" + str(i) + ":" + str(j) + ":" + str(step) + "] missed del exception for " + str(list(swigarray)) - except ValueError, e: + raise RuntimeError("swigarray[" + str(i) + ":" + str(j) + ":" + str(step) + "] missed del exception for " + str(list(swigarray))) + except ValueError as e: # print("exception: {}".format(e)) pass def setslice_exception(swigarray, newval): try: swigarray[::] = newval - raise RuntimeError, "swigarray[::] = " + str(newval) + " missed set exception for swigarray:" + str(list(swigarray)) - except TypeError, e: + raise RuntimeError("swigarray[::] = " + str(newval) + " missed set exception for swigarray:" + str(list(swigarray))) + except TypeError as e: # print("exception: {}".format(e)) pass diff --git a/Examples/test-suite/python/cpp11_template_explicit_runme.py b/Examples/test-suite/python/cpp11_template_explicit_runme.py new file mode 100644 index 000000000..dacfb74c8 --- /dev/null +++ b/Examples/test-suite/python/cpp11_template_explicit_runme.py @@ -0,0 +1,15 @@ +import cpp11_template_explicit + +def swig_assert_isinstance(a, b): + if not isinstance(a, b): + raise RuntimeError(str(a) + " not an instance of " + str(b)) + +# Call variants of the same templated function +t1 = cpp11_template_explicit.my_templated_function_int (1,1.0) +t2 = cpp11_template_explicit.my_templated_function_A (2,2.0) +t3 = cpp11_template_explicit.my_templated_function_TemperInt(3,3.0) + +# Check return types +swig_assert_isinstance(t1,int) +swig_assert_isinstance(t2,cpp11_template_explicit.A) +swig_assert_isinstance(t3,cpp11_template_explicit.TemperInt) diff --git a/Examples/test-suite/python/cpp11_uniform_initialization_runme.py b/Examples/test-suite/python/cpp11_uniform_initialization_runme.py index ecb468ccb..b01557a6f 100644 --- a/Examples/test-suite/python/cpp11_uniform_initialization_runme.py +++ b/Examples/test-suite/python/cpp11_uniform_initialization_runme.py @@ -9,13 +9,13 @@ if var2.getX() != 2: 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 + raise RuntimeError(m.vi) if m.more1([-1, 1, 2]) != 2: - raise RuntimeError, m.vi + raise RuntimeError(m.vi) if m.more1() != 10: raise RuntimeError diff --git a/Examples/test-suite/python/cpp_enum_runme.py b/Examples/test-suite/python/cpp_enum_runme.py index 5f1e91c97..910d378e4 100644 --- a/Examples/test-suite/python/cpp_enum_runme.py +++ b/Examples/test-suite/python/cpp_enum_runme.py @@ -3,21 +3,17 @@ import cpp_enum f = cpp_enum.Foo() if f.hola != f.Hello: - print f.hola - raise RuntimeError + raise RuntimeError("f.hola: {}".format(f.hola)) f.hola = f.Hi if f.hola != f.Hi: - print f.hola - raise RuntimeError + raise RuntimeError("f.hola: {}".format(f.hola)) f.hola = f.Hello if f.hola != f.Hello: - print f.hola - raise RuntimeError + raise RuntimeError("f.hola: {}".format(f.hola)) cpp_enum.cvar.hi = cpp_enum.Hello if cpp_enum.cvar.hi != cpp_enum.Hello: - print cpp_enum.cvar.hi - raise RuntimeError + raise RuntimeError("cpp_enum.cvar.hi: {}".format(cpp_enum.cvar.hi)) diff --git a/Examples/test-suite/python/default_args_runme.py b/Examples/test-suite/python/default_args_runme.py index 14ef8c594..b8077cc28 100644 --- a/Examples/test-suite/python/default_args_runme.py +++ b/Examples/test-suite/python/default_args_runme.py @@ -12,7 +12,7 @@ def run(module_name): de.accelerate() de.accelerate(default_args.EnumClass.SLOW) - if default_args.Statics_staticMethod() != 60: + if default_args.Statics.staticMethod() != 60: raise RuntimeError if default_args.cfunc1(1) != 2: @@ -108,48 +108,34 @@ def run(module_name): if Klass_inc().val != 0: raise RuntimeError("Klass::inc failed") - tricky_failure = False tricky = default_args.TrickyInPython() if tricky.value_m1(10) != -1: - print "trickyvalue_m1 failed" - tricky_failure = True + raise RuntimeError("trickyvalue_m1 failed") if tricky.value_m1(10, 10) != 10: - print "trickyvalue_m1 failed" - tricky_failure = True + raise RuntimeError("trickyvalue_m1 failed") if tricky.value_0xabcdef(10) != 0xabcdef: - print "trickyvalue_0xabcdef failed" - tricky_failure = True + raise RuntimeError("trickyvalue_0xabcdef failed") if tricky.value_0644(10) != 420: - print "trickyvalue_0644 failed" - tricky_failure = True + raise RuntimeError("trickyvalue_0644 failed") if tricky.value_perm(10) != 420: - print "trickyvalue_perm failed" - tricky_failure = True + raise RuntimeError("trickyvalue_perm failed") if tricky.value_m01(10) != -1: - print "trickyvalue_m01 failed" - tricky_failure = True + raise RuntimeError("trickyvalue_m01 failed") if not tricky.booltest2(): - print "booltest2 failed" - tricky_failure = True + raise RuntimeError("booltest2 failed") if tricky.max_32bit_int1() != 0x7FFFFFFF: - print "max_32bit_int1 failed" - tricky_failure = True + raise RuntimeError("max_32bit_int1 failed") if tricky.min_32bit_int1() != -2147483648: - print "min_32bit_int1 failed" - tricky_failure = True + raise RuntimeError("min_32bit_int1 failed") if tricky.max_32bit_int2() != 0x7FFFFFFF: - print "max_32bit_int2 failed" - tricky_failure = True + raise RuntimeError("max_32bit_int2 failed") tricky.too_big_32bit_int1() tricky.too_small_32bit_int1() tricky.too_big_32bit_int2() tricky.too_small_32bit_int2() - if tricky_failure: - raise RuntimeError - default_args.seek() default_args.seek(10) diff --git a/Examples/test-suite/python/default_constructor_runme.py b/Examples/test-suite/python/default_constructor_runme.py index 1e877adda..2943dc960 100644 --- a/Examples/test-suite/python/default_constructor_runme.py +++ b/Examples/test-suite/python/default_constructor_runme.py @@ -16,24 +16,24 @@ dc.delete_AA(aa) try: b = dc.new_B() - print "Whoa. new_BB created." -except: + raise RuntimeError("Whoa. new_BB created.") +except TypeError: pass del_b = dc.delete_B try: bb = dc.new_BB() - print "Whoa. new_BB created." -except: + raise RuntimeError("Whoa. new_BB created.") +except AttributeError: pass del_bb = dc.delete_BB try: c = dc.new_C() - print "Whoa. new_C created." -except: + raise RuntimeError("Whoa. new_C created.") +except AttributeError: pass del_c = dc.delete_C @@ -43,24 +43,24 @@ dc.delete_CC(cc) try: d = dc.new_D() - print "Whoa. new_D created" -except: + raise RuntimeError("Whoa. new_D created") +except AttributeError: pass del_d = dc.delete_D try: dd = dc.new_DD() - print "Whoa. new_DD created" -except: + raise RuntimeError("Whoa. new_DD created") +except AttributeError: pass dd = dc.delete_DD try: ad = dc.new_AD() - print "Whoa. new_AD created" -except: + raise RuntimeError("Whoa. new_AD created") +except AttributeError: pass del_ad = dc.delete_AD @@ -73,8 +73,8 @@ dc.delete_EE(ee) try: eb = dc.new_EB() - print "Whoa. new_EB created" -except: + raise RuntimeError("Whoa. new_EB created") +except AttributeError: pass del_eb = dc.delete_EB @@ -83,7 +83,7 @@ f = dc.new_F() try: del_f = dc.delete_F - print "Whoa. delete_F created" + raise RuntimeError("Whoa. delete_F created") except AttributeError: pass @@ -93,7 +93,7 @@ g = dc.new_G() try: del_g = dc.delete_G - print "Whoa. delete_G created" + raise RuntimeError("Whoa. delete_G created") except AttributeError: pass diff --git a/Examples/test-suite/python/director_abstract_runme.py b/Examples/test-suite/python/director_abstract_runme.py index 333b75fe5..fbc54808e 100644 --- a/Examples/test-suite/python/director_abstract_runme.py +++ b/Examples/test-suite/python/director_abstract_runme.py @@ -13,10 +13,10 @@ class MyFoo(director_abstract.Foo): 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): @@ -37,7 +37,7 @@ class MyExample3(director_abstract.Example3_i): return b me1 = MyExample1() -if director_abstract.Example1_get_color(me1, 1, 2, 3) != 1: +if director_abstract.Example1.get_color(me1, 1, 2, 3) != 1: raise RuntimeError me2 = MyExample2(1, 2) diff --git a/Examples/test-suite/python/director_alternating_runme.py b/Examples/test-suite/python/director_alternating_runme.py index a93ffec34..dc85351b5 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 6564c95a2..2d07c3ad5 100644 --- a/Examples/test-suite/python/director_basic_runme.py +++ b/Examples/test-suite/python/director_basic_runme.py @@ -10,18 +10,18 @@ class PyFoo(director_basic.Foo): 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) @@ -44,8 +44,8 @@ b = director_basic.Bar(3) d = director_basic.MyClass() c = PyClass() -cc = director_basic.MyClass_get_self(c) -dd = director_basic.MyClass_get_self(d) +cc = director_basic.MyClass.get_self(c) +dd = director_basic.MyClass.get_self(d) bc = cc.cmethod(b) bd = dd.cmethod(b) @@ -86,8 +86,8 @@ for i in range(0, 100): pymult = PyMulti() -p1 = director_basic.Foo_get_self(pymult) -p2 = director_basic.MyClass_get_self(pymult) +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_comparison_operators_runme.py b/Examples/test-suite/python/director_comparison_operators_runme.py new file mode 100644 index 000000000..e9bf9438d --- /dev/null +++ b/Examples/test-suite/python/director_comparison_operators_runme.py @@ -0,0 +1,11 @@ +import director_comparison_operators + + +class PyFoo(director_comparison_operators.Foo): + pass + + +a = PyFoo() + +if a.test() != "a=1,b=2": + raise RuntimeError(a.test()) diff --git a/Examples/test-suite/python/director_detect_runme.py b/Examples/test-suite/python/director_detect_runme.py index 345051982..b9c73eb45 100644 --- a/Examples/test-suite/python/director_detect_runme.py +++ b/Examples/test-suite/python/director_detect_runme.py @@ -35,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_exception_runme.py b/Examples/test-suite/python/director_exception_runme.py index 06856f30a..458983c6a 100644 --- a/Examples/test-suite/python/director_exception_runme.py +++ b/Examples/test-suite/python/director_exception_runme.py @@ -10,7 +10,7 @@ class MyException(Exception): class MyFoo(Foo): def ping(self): - raise NotImplementedError, "MyFoo::ping() EXCEPTION" + raise NotImplementedError("MyFoo::ping() EXCEPTION") class MyFoo2(Foo): @@ -28,74 +28,58 @@ class MyFoo3(Foo): class MyFoo4(Foo): def ping(self, *args): - print(type("bad", "call")) # throws TypeError message: type() takes 1 or 3 arguments + t = type("bad", "call") # throws TypeError message: type() takes 1 or 3 arguments return "Foo4.ping" # Check that the NotImplementedError raised by MyFoo.ping() is returned by # MyFoo.pong(). -ok = 0 a = MyFoo() b = launder(a) try: b.pong() -except NotImplementedError, e: - if str(e) == "MyFoo::ping() EXCEPTION": - ok = 1 - else: - print "Unexpected error message: %s" % str(e) -except: + raise RuntimeError("Exception was not thrown") +except NotImplementedError as e: + if not str(e) == "MyFoo::ping() EXCEPTION": + raise RuntimeError("Unexpected error message: %s" % str(e)) +except TypeError: pass -if not ok: - raise RuntimeError # Check that the director returns the appropriate TypeError if the return type # is wrong. -ok = 0 a = MyFoo2() b = launder(a) try: b.pong() -except TypeError, e: + raise RuntimeError("Exception was not thrown") +except TypeError as e: # fastdispatch mode adds on Additional Information to the exception message - just check the main exception message exists - if str(e).startswith("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 + if not str(e).startswith("SWIG director type mismatch in output value of type 'std::string'"): + raise RuntimeError("Unexpected error message: %s" % str(e)) # Check that the director can return an exception which requires two arguments # to the constructor, without mangling it. -ok = 0 a = MyFoo3() b = launder(a) try: b.pong() -except MyException, e: - if e.msg == "foobar": - ok = 1 - else: - print "Unexpected error message: %s" % str(e) -if not ok: - raise RuntimeError + raise RuntimeError("Exception was not thrown") +except MyException as e: + if e.msg != "foobar": + raise RuntimeError("Unexpected error message: %s" % str(e)) # Check that the director returns the appropriate TypeError thrown in a director method -ok = 0 a = MyFoo4() b = launder(a) try: b.pong() + raise RuntimeError("Exception was not thrown") except TypeError as e: - if str(e).startswith("type() takes 1 or 3 arguments"): - ok = 1 - else: - print "Unexpected error message: %s" % str(e) -if not ok: - raise RuntimeError + if not str(e).startswith("type() takes 1 or 3 arguments"): + raise RuntimeError("Unexpected error message: %s" % str(e)) # This is expected to fail with -builtin option diff --git a/Examples/test-suite/python/director_extend_runme.py b/Examples/test-suite/python/director_extend_runme.py index a5aad8245..870443d1f 100644 --- a/Examples/test-suite/python/director_extend_runme.py +++ b/Examples/test-suite/python/director_extend_runme.py @@ -17,6 +17,6 @@ class MyObject(SpObject): 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_frob_runme.py b/Examples/test-suite/python/director_frob_runme.py index 0ef4ad900..6c8fcad06 100644 --- a/Examples/test-suite/python/director_frob_runme.py +++ b/Examples/test-suite/python/director_frob_runme.py @@ -4,4 +4,4 @@ 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_nested_runme.py b/Examples/test-suite/python/director_nested_runme.py index f3d973630..24216f9dd 100644 --- a/Examples/test-suite/python/director_nested_runme.py +++ b/Examples/test-suite/python/director_nested_runme.py @@ -14,7 +14,7 @@ class A(FooBar_int): 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): @@ -34,7 +34,7 @@ class B(FooBar_int): 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): @@ -54,7 +54,7 @@ class C(FooBar_int): pass cc = C() -c = FooBar_int_get_self(cc) +c = FooBar_int.get_self(cc) c.advance() if c.get_name() != "FooBar::get_name hello": diff --git a/Examples/test-suite/python/director_profile_runme.py b/Examples/test-suite/python/director_profile_runme.py index 035007c61..7c269c3f7 100644 --- a/Examples/test-suite/python/director_profile_runme.py +++ b/Examples/test-suite/python/director_profile_runme.py @@ -38,4 +38,4 @@ while i: a = fi(a) # 20 i -= 1 -print a +print("a: {}".format(a)) diff --git a/Examples/test-suite/python/director_property_runme.py b/Examples/test-suite/python/director_property_runme.py index 5d713c27f..2fa41968c 100644 --- a/Examples/test-suite/python/director_property_runme.py +++ b/Examples/test-suite/python/director_property_runme.py @@ -14,6 +14,43 @@ foo.setA("BLABLA") if foo.getA() != "BLABLA": raise RuntimeError +# test property addition in PyFoo +if foo.a != "BLABLA": + raise RuntimeError + foo.a = "BIBI" if foo.a != "BIBI": raise RuntimeError +if foo.getA() != "BIBI": + raise RuntimeError + + + +class MyFoo(director_property.Foo): + def setA(self, a): + director_property.Foo.setA(self, a + " set from MyFoo") + def setAByRef(self, a): + director_property.Foo.setA(self, a + " setAByRef from MyFoo") + +a = MyFoo() +if (a.getA() != ""): + raise RuntimeError("Test failed") +a.setA("Hello") +if (a.getA() != "Hello set from MyFoo"): + raise RuntimeError("Test failed") +a.setAByRef("Hello") +if (a.getA() != "Hello setAByRef from MyFoo"): + raise RuntimeError("Test failed") +del a + +a_original = MyFoo() +a = director_property.Foo.get_self(a_original) +if (a.getA() != ""): + raise RuntimeError("Test failed") +a.setA("Hello") +if (a.getA() != "Hello set from MyFoo"): + raise RuntimeError("Test failed") +a.setAByRef("Hello") +if (a.getA() != "Hello setAByRef from MyFoo"): + raise RuntimeError("Test failed") +del a diff --git a/Examples/test-suite/python/director_protected_runme.py b/Examples/test-suite/python/director_protected_runme.py index c3118a7c0..94eab69a6 100644 --- a/Examples/test-suite/python/director_protected_runme.py +++ b/Examples/test-suite/python/director_protected_runme.py @@ -35,7 +35,7 @@ try: raise RuntimeError pass except: - raise RuntimeError, "bad FooBar::used" + raise RuntimeError("bad FooBar::used") try: s = fb2.used() @@ -43,7 +43,7 @@ try: raise RuntimeError pass except: - raise RuntimeError, "bad FooBar2::used" + raise RuntimeError("bad FooBar2::used") try: s = b.pong() @@ -51,7 +51,7 @@ try: raise RuntimeError pass except: - raise RuntimeError, "bad Bar::pong" + raise RuntimeError("bad Bar::pong") try: s = f.pong() @@ -59,7 +59,7 @@ try: raise RuntimeError pass except: - raise RuntimeError, " bad Foo::pong" + raise RuntimeError(" bad Foo::pong") try: s = fb.pong() @@ -67,7 +67,7 @@ try: raise RuntimeError pass except: - raise RuntimeError, " bad FooBar::pong" + raise RuntimeError(" bad FooBar::pong") protected = 1 try: @@ -76,7 +76,7 @@ try: except: pass if not protected: - raise RuntimeError, "Foo::ping is protected" + raise RuntimeError("Foo::ping is protected") protected = 1 try: @@ -85,7 +85,7 @@ try: except: pass if not protected: - raise RuntimeError, "Foo::ping is protected" + raise RuntimeError("Foo::ping is protected") protected = 1 @@ -95,7 +95,7 @@ try: except: pass if not protected: - raise RuntimeError, "FooBar::pang is protected" + raise RuntimeError("FooBar::pang is protected") protected = 1 @@ -105,7 +105,7 @@ try: except: pass if not protected: - raise RuntimeError, "Bar::cheer is protected" + raise RuntimeError("Bar::cheer is protected") protected = 1 try: @@ -114,19 +114,19 @@ try: except: 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_smartptr_runme.py b/Examples/test-suite/python/director_smartptr_runme.py index 23e22d0fb..b4cbafe32 100644 --- a/Examples/test-suite/python/director_smartptr_runme.py +++ b/Examples/test-suite/python/director_smartptr_runme.py @@ -31,7 +31,7 @@ class director_smartptr_MyBarFooDerived(FooDerived): def check(got, expected): if (got != expected): - raise RuntimeError, "Failed, got: " + got + " expected: " + expected + raise RuntimeError("Failed, got: " + got + " expected: " + expected) fooBar = FooBar() diff --git a/Examples/test-suite/python/director_string_runme.py b/Examples/test-suite/python/director_string_runme.py index dcd47d647..c6d4c8121 100644 --- a/Examples/test-suite/python/director_string_runme.py +++ b/Examples/test-suite/python/director_string_runme.py @@ -18,12 +18,10 @@ b = B("hello") b.get(0) if b.get_first() != "hello world!": - print b.get_first() - raise RuntimeError + raise RuntimeError("b.get_first(): {}".format(b.get_first())) b.call_process_func() if b.smem != "hello": - print smem - raise RuntimeError + raise RuntimeError("smem: {}".format(smem)) diff --git a/Examples/test-suite/python/director_thread_runme.py b/Examples/test-suite/python/director_thread_runme.py index 4fcf3bfd1..21a8ce1b0 100644 --- a/Examples/test-suite/python/director_thread_runme.py +++ b/Examples/test-suite/python/director_thread_runme.py @@ -14,7 +14,6 @@ d = Derived() d.run() if d.val >= 0: - print d.val - raise RuntimeError + raise RuntimeError("d.val: {}".format(d.val)) d.stop() diff --git a/Examples/test-suite/python/director_unroll_runme.py b/Examples/test-suite/python/director_unroll_runme.py index 60bc05585..ea602d8e2 100644 --- a/Examples/test-suite/python/director_unroll_runme.py +++ b/Examples/test-suite/python/director_unroll_runme.py @@ -16,5 +16,4 @@ c = b.get() if not (a.this == c.this): - print a, c - raise RuntimeError + raise RuntimeError("{} {}".format(a, c)) diff --git a/Examples/test-suite/python/director_wstring_runme.py b/Examples/test-suite/python/director_wstring_runme.py index b7929c0d2..5facc1f1d 100644 --- a/Examples/test-suite/python/director_wstring_runme.py +++ b/Examples/test-suite/python/director_wstring_runme.py @@ -7,22 +7,20 @@ class B(A): A.__init__(self, string) def get_first(self): - return A.get_first(self) + u" world!" + return A.get_first(self) + " world!" def process_text(self, s): self.smem = s -b = B(u"hello") +b = B("hello") b.get(0) -if b.get_first() != u"hello world!": - print b.get_first() - raise RuntimeError +if b.get_first() != "hello world!": + raise RuntimeError("b.get_first(): {}".format(b.get_first())) b.call_process_func() -if b.smem != u"hello": - print smem - raise RuntimeError +if b.smem != "hello": + raise RuntimeError("smem: {}".format(smem)) diff --git a/Examples/test-suite/python/dynamic_cast_runme.py b/Examples/test-suite/python/dynamic_cast_runme.py index 59e86d34c..ae080833b 100644 --- a/Examples/test-suite/python/dynamic_cast_runme.py +++ b/Examples/test-suite/python/dynamic_cast_runme.py @@ -8,4 +8,4 @@ y = b.blah() a = dynamic_cast.do_test(y) if a != "Bar::test": - print "Failed!!" + raise RuntimeError("Failed!!") diff --git a/Examples/test-suite/python/exception_order_runme.py b/Examples/test-suite/python/exception_order_runme.py index c53521e3e..5c1529999 100644 --- a/Examples/test-suite/python/exception_order_runme.py +++ b/Examples/test-suite/python/exception_order_runme.py @@ -9,36 +9,35 @@ a = A() try: a.foo() -except E1, e: +except E1 as e: pass except: - raise RuntimeError, "bad exception order" + raise RuntimeError("bad exception order") try: a.bar() -except E2, e: +except E2 as e: pass except: - raise RuntimeError, "bad exception order" + raise RuntimeError("bad exception order") try: a.foobar() -except RuntimeError, e: +except RuntimeError as e: if e.args[0] != "postcatch unknown": - print "bad exception order", - raise RuntimeError, e.args + raise RuntimeError("bad exception order {}".format(e.args)) try: a.barfoo(1) -except E1, e: +except E1 as e: pass except: - raise RuntimeError, "bad exception order" + raise RuntimeError("bad exception order") try: a.barfoo(2) -except E2, e: +except E2 as e: pass except: - raise RuntimeError, "bad exception order" + raise RuntimeError("bad exception order") diff --git a/Examples/test-suite/python/extern_c_runme.py b/Examples/test-suite/python/extern_c_runme.py index 91a218a87..c30509d07 100644 --- a/Examples/test-suite/python/extern_c_runme.py +++ b/Examples/test-suite/python/extern_c_runme.py @@ -1,3 +1,10 @@ import extern_c +def check(flag): + if not flag: + raise RuntimeError("Test failed") + extern_c.RealFunction(2) +check(extern_c.cvar.int2 == 123) +check(extern_c.cvar.int3 == 456) +check(extern_c.cvar.int4 == 789) diff --git a/Examples/test-suite/python/fvirtual_runme.py b/Examples/test-suite/python/fvirtual_runme.py index 99f5dc6b0..fe211b441 100644 --- a/Examples/test-suite/python/fvirtual_runme.py +++ b/Examples/test-suite/python/fvirtual_runme.py @@ -5,4 +5,4 @@ n = Node() 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 f411261b6..4aab1b082 100644 --- a/Examples/test-suite/python/global_functions_runme.py +++ b/Examples/test-suite/python/global_functions_runme.py @@ -11,7 +11,7 @@ check(global_two(2, 2), 4) fail = True try: global_void(1) -except TypeError, e: +except TypeError as e: fail = False if fail: raise RuntimeError("argument count check failed") @@ -19,7 +19,7 @@ if fail: fail = True try: global_one() -except TypeError, e: +except TypeError as e: fail = False if fail: raise RuntimeError("argument count check failed") @@ -27,7 +27,7 @@ if fail: fail = True try: global_one(2, 2) -except TypeError, e: +except TypeError as e: fail = False if fail: @@ -36,7 +36,7 @@ if fail: fail = True try: global_two(1) -except TypeError, e: +except TypeError as e: fail = False if fail: @@ -45,7 +45,7 @@ if fail: fail = True try: global_two(3, 3, 3) -except TypeError, e: +except TypeError as e: fail = False if fail: diff --git a/Examples/test-suite/python/global_vars_runme.py b/Examples/test-suite/python/global_vars_runme.py index 3ef0b494f..015519ec8 100644 --- a/Examples/test-suite/python/global_vars_runme.py +++ b/Examples/test-suite/python/global_vars_runme.py @@ -20,7 +20,7 @@ if x != 9876: fail = True try: global_vars.cvar.notexist = "something" -except AttributeError, e: +except AttributeError as e: fail = False if fail: raise RuntimeError("AttributeError should have been thrown") @@ -28,7 +28,7 @@ if fail: fail = True try: g = global_vars.cvar.notexist -except AttributeError, e: +except AttributeError as e: fail = False if fail: raise RuntimeError("AttributeError should have been thrown") diff --git a/Examples/test-suite/python/ignore_parameter_runme.py b/Examples/test-suite/python/ignore_parameter_runme.py index 2b5c21235..0f40f96c8 100644 --- a/Examples/test-suite/python/ignore_parameter_runme.py +++ b/Examples/test-suite/python/ignore_parameter_runme.py @@ -16,6 +16,7 @@ check(car.astonmartin("foo", 1), 101) check(car.bugatti("bar", 2), 8.8) check(car.lamborghini(), 101) check(car.maseratti(289), 289) +check(car.audi(), 8.8) # Typemap overrides default argument MiniCooper(200, 0) MorrisMinor("baz", 0) diff --git a/Examples/test-suite/python/import_stl_runme.py b/Examples/test-suite/python/import_stl_runme.py index 69fe812b9..d0efbd083 100644 --- a/Examples/test-suite/python/import_stl_runme.py +++ b/Examples/test-suite/python/import_stl_runme.py @@ -3,4 +3,4 @@ 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 + raise RuntimeError(v_new) diff --git a/Examples/test-suite/python/inctest_runme.py b/Examples/test-suite/python/inctest_runme.py index fa3492932..c2746560d 100644 --- a/Examples/test-suite/python/inctest_runme.py +++ b/Examples/test-suite/python/inctest_runme.py @@ -1,31 +1,21 @@ import inctest -error = 0 try: a = inctest.A() except: - print "didn't find A" - print "therefore, I didn't include 'testdir/subdir1/hello.i'" - error = 1 + raise RuntimeError("didn't find A, therefore, I didn't include 'testdir/subdir1/hello.i'") pass try: b = inctest.B() except: - print "didn't find B" - print "therefore, I didn't include 'testdir/subdir2/hello.i'" - error = 1 + raise RuntimeError("didn't find B, therefore, I didn't include 'testdir/subdir2/hello.i'") pass -if error == 1: - raise RuntimeError - # Check the import in subdirectory worked if inctest.importtest1(5) != 15: - print "import test 1 failed" - raise RuntimeError + raise RuntimeError("import test 1 failed") if inctest.importtest2("black") != "white": - print "import test 2 failed" - raise RuntimeError + raise RuntimeError("import test 2 failed") diff --git a/Examples/test-suite/python/inherit_missing_runme.py b/Examples/test-suite/python/inherit_missing_runme.py index 044c166fb..57a245e44 100644 --- a/Examples/test-suite/python/inherit_missing_runme.py +++ b/Examples/test-suite/python/inherit_missing_runme.py @@ -6,14 +6,14 @@ c = inherit_missing.Spam() x = inherit_missing.do_blah(a) if x != "Foo::blah": - print "Whoa! Bad return", x + raise RuntimeError("Whoa! Bad return {}".format(x)) x = inherit_missing.do_blah(b) if x != "Bar::blah": - print "Whoa! Bad return", x + raise RuntimeError("Whoa! Bad return {}".format(x)) x = inherit_missing.do_blah(c) if x != "Spam::blah": - print "Whoa! Bad return", x + raise RuntimeError("Whoa! Bad return {}".format(x)) inherit_missing.delete_Foo(a) diff --git a/Examples/test-suite/python/inplaceadd_runme.py b/Examples/test-suite/python/inplaceadd_runme.py index 7f292cbb5..3d5a1fd40 100644 --- a/Examples/test-suite/python/inplaceadd_runme.py +++ b/Examples/test-suite/python/inplaceadd_runme.py @@ -3,8 +3,7 @@ a = inplaceadd.A(7) a += 5 if a.val != 12: - print a.val - raise RuntimeError + raise RuntimeError("a.val: {}".format(a.val)) a -= 5 if a.val != 7: diff --git a/Examples/test-suite/python/kwargs_feature_runme.py b/Examples/test-suite/python/kwargs_feature_runme.py index 31d49d221..677c9ebd8 100644 --- a/Examples/test-suite/python/kwargs_feature_runme.py +++ b/Examples/test-suite/python/kwargs_feature_runme.py @@ -15,13 +15,16 @@ f = Foo(b=2, a=1) if f.foo(b=1, a=2) != 3: raise RuntimeError -if Foo_statfoo(b=2) != 3: +if Foo.statfoo(b=2) != 3: + raise RuntimeError + +if Foo.statfoo_onearg(x=4) != 8: raise RuntimeError if f.efoo(b=2) != 3: raise RuntimeError -if Foo_sfoo(b=2) != 3: +if Foo.sfoo(b=2) != 3: raise RuntimeError @@ -31,13 +34,13 @@ b = BarInt(b=2, a=1) if b.bar(b=1, a=2) != 3: raise RuntimeError -if BarInt_statbar(b=2) != 3: +if BarInt.statbar(b=2) != 3: raise RuntimeError if b.ebar(b=2) != 3: raise RuntimeError -if BarInt_sbar(b=2) != 3: +if BarInt.sbar(b=2) != 3: raise RuntimeError @@ -122,3 +125,18 @@ try: raise RuntimeError("missed exception") except TypeError as e: pass + +# Varargs +f = VarargConstructor(fmt="Ciao") +f.vararg_method(fmt="Bonjour") +try: + f = VarargConstructor(nonexistent="Ciao") + raise RuntimeError("missed exception") +except TypeError as e: + pass + +try: + f.vararg_method(nonexistent="Bonjour") + raise RuntimeError("missed exception") +except TypeError as e: + pass diff --git a/Examples/test-suite/python/li_attribute_runme.py b/Examples/test-suite/python/li_attribute_runme.py index 80e793618..d26bf0b68 100644 --- a/Examples/test-suite/python/li_attribute_runme.py +++ b/Examples/test-suite/python/li_attribute_runme.py @@ -8,12 +8,10 @@ if aa.a != 1: raise RuntimeError aa.a = 3 if aa.a != 3: - print aa.a - raise RuntimeError + raise RuntimeError("aa.a: {}".format(aa.a)) if aa.b != 2: - print aa.b - raise RuntimeError + raise RuntimeError("aa.b: {}".format(aa.b)) aa.b = 5 if aa.b != 5: raise RuntimeError @@ -47,6 +45,9 @@ myClass = li_attribute.MyClass() myClass.Foo = myFoo if myClass.Foo.x != 8: raise RuntimeError +myClass.Foo2 = myFoo +if myClass.Foo2.x != 8: + raise RuntimeError # class/struct attribute with get/set methods using return/pass by value myClassVal = li_attribute.MyClassVal() @@ -77,7 +78,7 @@ if myStringyClass.ReadOnlyString != "changed string": try: x = myFoo.does_not_exist raise RuntimeError -except AttributeError, e: +except AttributeError as e: if str(e).find("does_not_exist") == -1: 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 d33b12309..f0a774995 100644 --- a/Examples/test-suite/python/li_attribute_template_runme.py +++ b/Examples/test-suite/python/li_attribute_template_runme.py @@ -7,8 +7,7 @@ chell = li_attribute_template.Cintint(1, 2, 3) def rassert(what, master): if what != master: - print what - raise RuntimeError + raise RuntimeError("what: {}".format(what)) # Testing primitive by value attribute rassert(chell.a, 1) diff --git a/Examples/test-suite/python/li_boost_shared_ptr_director_runme.py b/Examples/test-suite/python/li_boost_shared_ptr_director_runme.py index 52868eacc..b4382ca1e 100644 --- a/Examples/test-suite/python/li_boost_shared_ptr_director_runme.py +++ b/Examples/test-suite/python/li_boost_shared_ptr_director_runme.py @@ -1,5 +1,9 @@ from li_boost_shared_ptr_director import * +def swig_assert_equal(a, b): + if a != b: + raise RuntimeError(str(a) + " != " + str(b)) + class Derived(Base): def __init__(self, flag): self.return_none = flag @@ -59,22 +63,22 @@ class Derived(Base): a = Derived(False) b = Derived(True) -assert call_ret_c_shared_ptr(a) == 1 -assert call_ret_c_shared_ptr(b) == -1 -assert call_ret_c_by_value(a) == 1 +swig_assert_equal(call_ret_c_shared_ptr(a), 1) +swig_assert_equal(call_ret_c_shared_ptr(b), -1) +swig_assert_equal(call_ret_c_by_value(a), 1) -assert call_take_c_by_value(a) == 5 -assert call_take_c_by_ref(a) == 6 -assert call_take_c_by_pointer(a) == 7 -assert call_take_c_by_pointer_ref(a) == 8 -assert call_take_c_shared_ptr_by_value(a) == 9 -assert call_take_c_shared_ptr_by_ref(a) == 10 -assert call_take_c_shared_ptr_by_pointer(a) == 11 -assert call_take_c_shared_ptr_by_pointer_ref(a) == 12 +swig_assert_equal(call_take_c_by_value(a), 5) +swig_assert_equal(call_take_c_by_ref(a), 6) +swig_assert_equal(call_take_c_by_pointer(a), 7) +swig_assert_equal(call_take_c_by_pointer_ref(a), 8) +swig_assert_equal(call_take_c_shared_ptr_by_value(a), 9) +swig_assert_equal(call_take_c_shared_ptr_by_ref(a), 10) +swig_assert_equal(call_take_c_shared_ptr_by_pointer(a), 11) +swig_assert_equal(call_take_c_shared_ptr_by_pointer_ref(a), 12) -assert call_take_c_by_pointer_with_null(a) == -2 -assert call_take_c_by_pointer_ref_with_null(a) == -3 -assert call_take_c_shared_ptr_by_value_with_null(a) == -4 -assert call_take_c_shared_ptr_by_ref_with_null(a) == -5 -assert call_take_c_shared_ptr_by_pointer_with_null(a) == -6 -assert call_take_c_shared_ptr_by_pointer_ref_with_null(a) == -7 +swig_assert_equal(call_take_c_by_pointer_with_null(a), -2) +swig_assert_equal(call_take_c_by_pointer_ref_with_null(a), -3) +swig_assert_equal(call_take_c_shared_ptr_by_value_with_null(a), -4) +swig_assert_equal(call_take_c_shared_ptr_by_ref_with_null(a), -5) +swig_assert_equal(call_take_c_shared_ptr_by_pointer_with_null(a), -6) +swig_assert_equal(call_take_c_shared_ptr_by_pointer_ref_with_null(a), -7) 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 c960625ad..bde79fd61 100644 --- a/Examples/test-suite/python/li_boost_shared_ptr_runme.py +++ b/Examples/test-suite/python/li_boost_shared_ptr_runme.py @@ -10,7 +10,7 @@ class li_boost_shared_ptr_runme: def main(self): if (debug): - print "Started" + print("Started") li_boost_shared_ptr.cvar.debug_shared = debug @@ -20,7 +20,7 @@ class li_boost_shared_ptr_runme: self.runtest() # Expect 1 instance - the one global variable (GlobalValue) - if (li_boost_shared_ptr.Klass_getTotal_count() != 1): + if (li_boost_shared_ptr.Klass.getTotal_count() != 1): raise RuntimeError("Klass.total_count=%s" % li_boost_shared_ptr.Klass.getTotal_count()) @@ -32,7 +32,7 @@ class li_boost_shared_ptr_runme: "shared_ptr wrapper count=%s" % wrapper_count) if (debug): - print "Finished" + print("Finished") def runtest(self): # simple shared_ptr usage - created in C++ @@ -168,6 +168,19 @@ class li_boost_shared_ptr_runme: except ValueError: pass + # test null pointers emitted from C++ + k = li_boost_shared_ptr.sp_pointer_null() + if (li_boost_shared_ptr.smartpointertest(k) != None): + raise RuntimeError("return was not null") + + k = li_boost_shared_ptr.null_sp_pointer() + if (li_boost_shared_ptr.smartpointertest(k) != None): + raise RuntimeError("return was not null") + + k = li_boost_shared_ptr.sp_value_null() + if (li_boost_shared_ptr.smartpointertest(k) != None): + raise RuntimeError("return was not null") + # $owner k = li_boost_shared_ptr.pointerownertest() val = k.getValue() diff --git a/Examples/test-suite/python/li_cstring_runme.py b/Examples/test-suite/python/li_cstring_runme.py index b718f1352..d22fc261b 100644 --- a/Examples/test-suite/python/li_cstring_runme.py +++ b/Examples/test-suite/python/li_cstring_runme.py @@ -11,12 +11,10 @@ if test2() != " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ raise RuntimeError if test3("hello") != "hello-suffix": - print test3("hello") - raise RuntimeError + raise RuntimeError("test3(\"hello\")") if test4("hello") != "hello-suffix": - print test4("hello") - raise RuntimeError + raise RuntimeError("test4(\"hello\")") if test5(4) != "xxxx": raise RuntimeError diff --git a/Examples/test-suite/python/li_cwstring_runme.py b/Examples/test-suite/python/li_cwstring_runme.py index 5dd7b9b20..9216445c6 100644 --- a/Examples/test-suite/python/li_cwstring_runme.py +++ b/Examples/test-suite/python/li_cwstring_runme.py @@ -1,28 +1,28 @@ from li_cwstring import * -if count(u"ab\0ab\0ab\0", 0) != 3: +if count("ab\0ab\0ab\0", 0) != 3: raise RuntimeError -if test1() != u"Hello World": +if test1() != "Hello World": raise RuntimeError -if test2() != u" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_": +if test2() != " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_": raise RuntimeError -if test3("hello") != u"hello-suffix": +if test3("hello") != "hello-suffix": raise RuntimeError -if test4("hello") != u"hello-suffix": +if test4("hello") != "hello-suffix": raise RuntimeError -if test5(4) != u"xxxx": +if test5(4) != "xxxx": raise RuntimeError -if test6(10) != u"xxxxx": +if test6(10) != "xxxxx": raise RuntimeError -if test7() != u"Hello world!": +if test7() != "Hello world!": raise RuntimeError -if test8() != u" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_": +if test8() != " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_": raise RuntimeError diff --git a/Examples/test-suite/python/li_factory_runme.py b/Examples/test-suite/python/li_factory_runme.py index fb2c81e45..ce0e3caef 100644 --- a/Examples/test-suite/python/li_factory_runme.py +++ b/Examples/test-suite/python/li_factory_runme.py @@ -1,11 +1,11 @@ from li_factory import * -circle = Geometry_create(Geometry.CIRCLE) +circle = Geometry.create(Geometry.CIRCLE) r = circle.radius() if (r != 1.5): raise RuntimeError -point = Geometry_create(Geometry.POINT) +point = Geometry.create(Geometry.POINT) w = point.width() if (w != 1.0): raise RuntimeError diff --git a/Examples/test-suite/python/li_implicit_runme.py b/Examples/test-suite/python/li_implicit_runme.py index d8dd0fdcc..5d5c6caa0 100644 --- a/Examples/test-suite/python/li_implicit_runme.py +++ b/Examples/test-suite/python/li_implicit_runme.py @@ -9,8 +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 6d2479f87..d62224ff6 100644 --- a/Examples/test-suite/python/li_std_auto_ptr_runme.py +++ b/Examples/test-suite/python/li_std_auto_ptr_runme.py @@ -2,16 +2,16 @@ from li_std_auto_ptr import * k1 = makeKlassAutoPtr("first") k2 = makeKlassAutoPtr("second") -if Klass_getTotal_count() != 2: +if Klass.getTotal_count() != 2: raise "number of objects should be 2" del k1 -if Klass_getTotal_count() != 1: +if Klass.getTotal_count() != 1: raise "number of objects should be 1" if k2.getLabel() != "second": raise "wrong object label" del k2 -if Klass_getTotal_count() != 0: +if Klass.getTotal_count() != 0: raise "no objects should be left" 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 941838a5f..f346de220 100644 --- a/Examples/test-suite/python/li_std_containers_int_runme.py +++ b/Examples/test-suite/python/li_std_containers_int_runme.py @@ -6,7 +6,7 @@ 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): @@ -26,7 +26,7 @@ def compare_containers(pythonlist, swigvector, swiglist): def container_insert_step(i, j, step, newval): - ps = range(6) + ps = list(range(6)) iv = vector_int(ps) il = list_int(ps) @@ -43,9 +43,9 @@ def container_insert_step(i, j, step, newval): else: ps[i:j:step] = newval ps_error = None - except ValueError, e: + except ValueError as e: ps_error = e - except IndexError, e: + except IndexError as e: ps_error = e # std::vector @@ -61,9 +61,9 @@ def container_insert_step(i, j, step, newval): else: iv[i:j:step] = newval iv_error = None - except ValueError, e: + except ValueError as e: iv_error = e - except IndexError, e: + except IndexError as e: iv_error = e # std::list @@ -79,14 +79,14 @@ def container_insert_step(i, j, step, newval): else: il[i:j:step] = newval il_error = None - except ValueError, e: + except ValueError as e: il_error = e - except IndexError, e: + except IndexError as 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) + raise RuntimeError("ValueError exception not consistently thrown: " + \ + str(ps_error) + " " + str(iv_error) + " " + str(il_error)) compare_containers(ps, iv, il) @@ -94,7 +94,7 @@ def container_insert_step(i, j, step, newval): # 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) + ps = list(range(6)) iv = vector_int(ps) il = list_int(ps) @@ -111,9 +111,9 @@ def container_delete_step(i, j, step): else: del ps[i:j:step] ps_error = None - except ValueError, e: + except ValueError as e: ps_error = e - except IndexError, e: + except IndexError as e: ps_error = e # std::vector @@ -129,9 +129,9 @@ def container_delete_step(i, j, step): else: del iv[i:j:step] iv_error = None - except ValueError, e: + except ValueError as e: iv_error = e - except IndexError, e: + except IndexError as e: iv_error = e # std::list @@ -147,14 +147,14 @@ def container_delete_step(i, j, step): else: del il[i:j:step] il_error = None - except ValueError, e: + except ValueError as e: il_error = e - except IndexError, e: + except IndexError as 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) + raise RuntimeError("ValueError exception not consistently thrown: " + \ + str(ps_error) + " " + str(iv_error) + " " + str(il_error)) compare_containers(ps, iv, il) @@ -252,7 +252,7 @@ for start in [-102, -100, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 10 for step in range(-7, 7): container_delete_step(start, end, step) -ps = range(6) +ps = list(range(6)) iv = vector_int(ps) il = list_int(ps) del ps[:] diff --git a/Examples/test-suite/python/li_std_map_runme.py b/Examples/test-suite/python/li_std_map_runme.py index ac214dd45..765527ea4 100644 --- a/Examples/test-suite/python/li_std_map_runme.py +++ b/Examples/test-suite/python/li_std_map_runme.py @@ -25,8 +25,7 @@ for k in m: for k in m: if pm[k].this != m[k].this: - print pm[k], m[k] - raise RuntimeError + raise RuntimeError("Not equal {} {}".format(pm[k], m[k])) m = {} @@ -51,31 +50,31 @@ mii[1] = 2 if mii[1] != 2: raise RuntimeError -if mii.keys() != [1]: +if list(mii.keys()) != [1]: raise RuntimeError("keys") -if mii.values() != [2]: +if list(mii.values()) != [2]: raise RuntimeError("values") -if mii.items() != [(1, 2)]: +if list(mii.items()) != [(1, 2)]: raise RuntimeError("items") if [k for k in mii] != [1]: raise RuntimeError("iteration") -if [i for i in mii.iterkeys()] != [1]: +if [i for i in mii.keys()] != [1]: raise RuntimeError("iterkeys") -if [i for i in mii.itervalues()] != [2]: +if [i for i in mii.values()] != [2]: raise RuntimeError("itervalues") -if [i for i in mii.iteritems()] != [(1, 2)]: +if [i for i in mii.items()] != [(1, 2)]: raise RuntimeError("iteritems") slmap = li_std_map.StringLengthNumberMap() li_std_map.populate(slmap) -keys = " ".join([k for k in slmap.keys()]) +keys = " ".join([k for k in list(slmap.keys())]) if keys != "a aa zzz xxxx aaaaa": raise RuntimeError("Keys are wrong or in wrong order: " + keys) -values = " ".join([str(v) for v in slmap.values()]) +values = " ".join([str(v) for v in list(slmap.values())]) if values != "1 2 3 4 5": raise RuntimeError("Values are wrong or in wrong order: " + values) diff --git a/Examples/test-suite/python/li_std_pair_runme.py b/Examples/test-suite/python/li_std_pair_runme.py new file mode 100644 index 000000000..4150e5cc8 --- /dev/null +++ b/Examples/test-suite/python/li_std_pair_runme.py @@ -0,0 +1,47 @@ +from li_std_pair import * + +def check(flag): + if not flag: + raise RuntimeError("Check failed") + +intPair = makeIntPair(7, 6) +check(isinstance(intPair, tuple)) +check(len(intPair) == 2) +check(intPair[0] == 7) +check(intPair[1] == 6) + +intPairConstRef = makeIntPairConstRef(7, 6) +check(isinstance(intPairConstRef, tuple)) +check(intPairConstRef[0] == 7) +check(intPairConstRef[1] == 6) + +# +# Each of these should return a reference to a wrapped +# std::pair object (i.e. an IntPair instance). +# +intPairPtr = makeIntPairPtr(7, 6) +check(isinstance(intPairPtr, IntPair)) +check(intPairPtr[0] == 7) +check(intPairPtr[1] == 6) + +intPairRef = makeIntPairRef(7, 6) +check(isinstance(intPairRef, IntPair)) +check(intPairRef[0] == 7) +check(intPairRef[1] == 6) +# +# Now test various input typemaps. Each of the wrapped C++ functions +# (product1, product2 and product3) is expecting an argument of a +# different type (see li_std_pair.i). Typemaps should be in place to +# convert this tuple into the expected argument type. +# +check(product1(intPair) == 42) +check(product2(intPair) == 42) +# check(product3(intPair) == 42) # TODO, if desirable to match Ruby wrappers behaviour. Requires equivalent to typemap(in) std::pair* in Lib/ruby/std_pair.i and further fixes to stop recursive calls to swig::asptr which this testcase shows. Plus further changes for any type of sequence type (including other STL containers) to be accepted by all methods taking an STL container to match Ruby behaviour. + +# +# Similarly, each of the input typemaps should know what to do +# with an IntPair instance. +# +check(product1(intPairPtr) == 42) +check(product2(intPairPtr) == 42) +check(product3(intPairPtr) == 42) diff --git a/Examples/test-suite/python/li_std_set_runme.py b/Examples/test-suite/python/li_std_set_runme.py index 5e5b72442..34a1eb19c 100644 --- a/Examples/test-suite/python/li_std_set_runme.py +++ b/Examples/test-suite/python/li_std_set_runme.py @@ -14,11 +14,11 @@ if sum != "abc": raise RuntimeError i = s.__iter__() -if i.next() != "a": +if next(i) != "a": raise RuntimeError -if i.next() != "b": +if next(i) != "b": raise RuntimeError -if i.next() != "c": +if next(i) != "c": raise RuntimeError @@ -26,7 +26,7 @@ b = s.begin() e = s.end() sum = "" while (b != e): - sum = sum + b.next() + sum = sum + next(b) if sum != "abc": raise RuntimeError @@ -34,7 +34,7 @@ b = s.rbegin() e = s.rend() sum = "" while (b != e): - sum = sum + b.next() + sum = sum + next(b) if sum != "cba": raise RuntimeError @@ -47,25 +47,25 @@ si.append(2) si.append(3) i = si.__iter__() -if i.next() != 1: +if next(i) != 1: raise RuntimeError -if i.next() != 2: +if next(i) != 2: raise RuntimeError -if i.next() != 3: +if next(i) != 3: raise RuntimeError if si[0] != 1: raise RuntimeError i = s.begin() -i.next() +next(i) s.erase(i) b = s.begin() e = s.end() sum = "" while (b != e): - sum = sum + b.next() + sum = sum + next(b) if sum != "ac": 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 08c308856..a4526f07b 100644 --- a/Examples/test-suite/python/li_std_stream_runme.py +++ b/Examples/test-suite/python/li_std_stream_runme.py @@ -9,5 +9,4 @@ o << a << " " << 2345 << " " << 1.435 if o.str() != "A class 2345 1.435": - print "\"%s\"" % (o.str(),) - raise RuntimeError + raise RuntimeError("str failed: \"%s\"".format(o.str())) 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 087d92b19..96c64163d 100644 --- a/Examples/test-suite/python/li_std_string_extra_runme.py +++ b/Examples/test-suite/python/li_std_string_extra_runme.py @@ -4,17 +4,16 @@ 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" + raise RuntimeError("bad string mapping {} {}".format(x, li_std_string_extra.test_value(x))) 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") @@ -23,45 +22,43 @@ s = li_std_string_extra.string("he") s = s + "llo" if s != x: - print s, x - raise RuntimeError, "bad string mapping" + raise RuntimeError("bad string mapping {} {}".format(s, x)) 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" + raise RuntimeError("bad string mapping {}".format(a + b)) 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" + raise RuntimeError("bad string mapping") c = "hello" + b if c.find_last_of("l") != 9: - raise RuntimeError, "bad string mapping" + raise RuntimeError("bad string mapping") s = "hello world" @@ -69,33 +66,33 @@ 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") if li_std_string_extra.test_value_basic_overload(x) != x: - raise RuntimeError, "bad overload string" + raise RuntimeError("bad overload string") if li_std_string_extra.test_value_basic_overload(123) != "int": - raise RuntimeError, "bad overload int" + raise RuntimeError("bad overload int") try: li_std_string_extra.test_value_basic_overload([x]) - raise RuntimeError, "should throw TypeError" + raise RuntimeError("should throw TypeError") except TypeError as e: if str(e).find("Possible C/C++ prototypes are:") == -1: raise RuntimeError("Incorrect error message text:\n{}".format(e)) @@ -103,7 +100,7 @@ except TypeError as e: try: li_std_string_extra.test_value_basic_overload([123]) - raise RuntimeError, "should throw TypeError" + raise RuntimeError("should throw TypeError") except TypeError as e: if str(e).find("Possible C/C++ prototypes are:") == -1: raise RuntimeError("Incorrect error message text:\n{}".format(e)) @@ -112,30 +109,30 @@ except TypeError as e: # 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": 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 318d1bff6..587f20b37 100644 --- a/Examples/test-suite/python/li_std_vector_enum_runme.py +++ b/Examples/test-suite/python/li_std_vector_enum_runme.py @@ -14,7 +14,7 @@ check(ev.nums[2], 30) it = ev.nums.iterator() v = it.value() check(v, 10) -it.next() +next(it) v = it.value() check(v, 20) 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 59e729a27..40444552b 100644 --- a/Examples/test-suite/python/li_std_vector_extra_runme.py +++ b/Examples/test-suite/python/li_std_vector_extra_runme.py @@ -23,20 +23,20 @@ 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]) 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() @@ -47,7 +47,7 @@ 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" + raise RuntimeError("bad std::vector mapping") delete_ArrInt(ap) @@ -57,42 +57,42 @@ a = halfs([10, 8, 4, 3]) v = IntVector() 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)]) diff --git a/Examples/test-suite/python/li_std_wstream_runme.py b/Examples/test-suite/python/li_std_wstream_runme.py index 045645b61..0ecdddbf8 100644 --- a/Examples/test-suite/python/li_std_wstream_runme.py +++ b/Examples/test-suite/python/li_std_wstream_runme.py @@ -5,8 +5,7 @@ a = A() o = wostringstream() -o << a << u" " << 2345 << u" " << 1.435 << wends +o << a << " " << 2345 << " " << 1.435 << wends if o.str() != "A class 2345 1.435\0": - print "\"%s\"" % (o.str(),) - raise RuntimeError + raise RuntimeError("str failed: \"%s\"".format(o.str())) diff --git a/Examples/test-suite/python/li_std_wstring_inherit_runme.py b/Examples/test-suite/python/li_std_wstring_inherit_runme.py index 558914e7e..bd585890c 100644 --- a/Examples/test-suite/python/li_std_wstring_inherit_runme.py +++ b/Examples/test-suite/python/li_std_wstring_inherit_runme.py @@ -1,14 +1,13 @@ import li_std_wstring_inherit import sys -x = u"hello" +x = "hello" -s = li_std_wstring_inherit.wstring(u"he") -s = s + u"llo" +s = li_std_wstring_inherit.wstring("he") +s = s + "llo" if s != x: - print s, x - raise RuntimeError("bad string mapping") + raise RuntimeError("bad string mapping {} {}".format(s, x)) if s[1:4] != x[1:4]: raise RuntimeError("bad string mapping") @@ -34,12 +33,12 @@ if not li_std_wstring_inherit.is_python_builtin(): b = li_std_wstring_inherit.B("hi") -b.name = li_std_wstring_inherit.wstring(u"hello") +b.name = li_std_wstring_inherit.wstring("hello") if b.name != "hello": raise RuntimeError("bad string mapping") b.a = li_std_wstring_inherit.A("hello") -if b.a != u"hello": +if b.a != "hello": raise RuntimeError("bad string mapping") diff --git a/Examples/test-suite/python/li_std_wstring_runme.py b/Examples/test-suite/python/li_std_wstring_runme.py index c6210e2de..ca8dc3184 100644 --- a/Examples/test-suite/python/li_std_wstring_runme.py +++ b/Examples/test-suite/python/li_std_wstring_runme.py @@ -5,10 +5,10 @@ def check_equal(a, b): if a != b: raise RuntimeError("failed {} {}".format(a, b)) -h = u"h" +h = "h" check_equal(li_std_wstring.test_wcvalue(h), h) -x = u"abc" +x = "abc" check_equal(li_std_wstring.test_ccvalue(x), x) check_equal(li_std_wstring.test_cvalue(x), x) @@ -54,6 +54,12 @@ check_equal(li_std_wstring.test_value(x), x) check_equal(li_std_wstring.test_ccvalue(x), "abc") check_equal(li_std_wstring.test_wchar_overload(x), "abc") +ts = li_std_wstring.wchar_test_struct() +ts.wchar_t_member = h +check_equal(ts.wchar_t_member, h) +ts.wchar_t_ptr_member = s +check_equal(ts.wchar_t_ptr_member, s) + ################### Python specific # Byte strings only converted in Python 2 @@ -72,7 +78,7 @@ except TypeError: # Check surrogateescape if sys.version_info[0:2] > (3, 1): - x = u"h\udce9llo" # surrogate escaped representation of C char*: "h\xe9llo" + x = "h\udce9llo" # surrogate escaped representation of C char*: "h\xe9llo" if li_std_wstring.non_utf8_c_str() != x: raise RuntimeError("surrogateescape not working") if li_std_wstring.size_wstring(x) != 5 and len(x) != 5: diff --git a/Examples/test-suite/python/minherit_runme.py b/Examples/test-suite/python/minherit_runme.py index b7e7d019c..8638d2357 100644 --- a/Examples/test-suite/python/minherit_runme.py +++ b/Examples/test-suite/python/minherit_runme.py @@ -7,31 +7,31 @@ c = minherit.FooBar() d = minherit.Spam() if a.xget() != 1: - raise RuntimeError, "Bad attribute value" + 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 @@ -41,27 +41,27 @@ cc = minherit.toFooBarPtr(c) dd = minherit.toSpamPtr(d) if aa.xget() != 1: - raise RuntimeError, "Bad attribute value" + 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/multivalue_runme.py b/Examples/test-suite/python/multivalue_runme.py new file mode 100644 index 000000000..ba832724a --- /dev/null +++ b/Examples/test-suite/python/multivalue_runme.py @@ -0,0 +1,19 @@ +import multivalue + +q, r = multivalue.divide_l(37, 5); +if q != 7: + raise RuntimeError("Test divide_l quotient") +if r != 2: + raise RuntimeError("Test divide_l remainder") + +q, r = multivalue.divide_v(41, 7); +if q != 5: + raise RuntimeError("Test divide_v quotient") +if r != 6: + raise RuntimeError("Test divide_v remainder") + +q, r = multivalue.divide_l(91, 13); +if q != 7: + raise RuntimeError("Test divide_mv quotient") +if r != 0: + raise RuntimeError("Test divide_mv remainder") diff --git a/Examples/test-suite/python/name_warnings_runme.py b/Examples/test-suite/python/name_warnings_runme.py new file mode 100644 index 000000000..0387436e0 --- /dev/null +++ b/Examples/test-suite/python/name_warnings_runme.py @@ -0,0 +1,9 @@ +from name_warnings import * + +def check(flag): + if not flag: + raise RuntimeError("Test failed") + +four = double_an_int(2) +check(four == 4) + diff --git a/Examples/test-suite/python/namespace_class_runme.py b/Examples/test-suite/python/namespace_class_runme.py index aa5165562..9349f2430 100644 --- a/Examples/test-suite/python/namespace_class_runme.py +++ b/Examples/test-suite/python/namespace_class_runme.py @@ -7,7 +7,7 @@ except: error = 0 if (error): - raise RuntimeError, "Private1 is private" + raise RuntimeError("Private1 is private") try: p = Private2() @@ -16,7 +16,7 @@ except: error = 0 if (error): - raise RuntimeError, "Private2 is private" + raise RuntimeError("Private2 is private") EulerT3D.toFrame(1, 1, 1) diff --git a/Examples/test-suite/python/not_c_keywords_runme.py b/Examples/test-suite/python/not_c_keywords_runme.py new file mode 100644 index 000000000..7f0772407 --- /dev/null +++ b/Examples/test-suite/python/not_c_keywords_runme.py @@ -0,0 +1,7 @@ +from not_c_keywords import * + +cs = ComplexStruct() +cs.init() +if cs.complex != 123: + raise RuntimeError("complex not correct") +cs.complex = 456 diff --git a/Examples/test-suite/python/operator_overload_runme.py b/Examples/test-suite/python/operator_overload_runme.py index 31c49058e..cd565f619 100644 --- a/Examples/test-suite/python/operator_overload_runme.py +++ b/Examples/test-suite/python/operator_overload_runme.py @@ -1,7 +1,7 @@ from operator_overload import * # first check all the operators are implemented correctly from pure C++ code -Op_sanity_check() +Op.sanity_check() pop = Op(6)/Op(3) diff --git a/Examples/test-suite/python/overload_complicated_runme.py b/Examples/test-suite/python/overload_complicated_runme.py index 2593c4f16..8794da12b 100644 --- a/Examples/test-suite/python/overload_complicated_runme.py +++ b/Examples/test-suite/python/overload_complicated_runme.py @@ -10,38 +10,38 @@ p = Pop(pInt, False) # Check overloaded in const only and pointers/references which target # languages cannot disambiguate if p.hip(False) != 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(False) != 801: - raise RuntimeError, "Test 4 failed" + raise RuntimeError("Test 4 failed") # Few more variations and order shuffled if p.pop(False) != 901: - raise RuntimeError, "Test 5 failed" + raise RuntimeError("Test 5 failed") if p.pop(pInt) != 904: - 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) != 2002: - raise RuntimeError, "Test 9 failed" + raise RuntimeError("Test 9 failed") # Globals if muzak(False) != 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_null_runme.py b/Examples/test-suite/python/overload_null_runme.py index a34524255..4b69b5c8d 100644 --- a/Examples/test-suite/python/overload_null_runme.py +++ b/Examples/test-suite/python/overload_null_runme.py @@ -32,13 +32,13 @@ check(14, o.byval1cpr(None)) check(15, o.byval2cpr(None)) check(16, o.byval2cpr(x)) -# forward class declaration -check(17, o.byval1forwardptr(x)) -check(18, o.byval1forwardptr(None)) +# fwd class declaration +check(17, o.byval1fwdptr(x)) +check(18, o.byval1fwdptr(None)) -check(19, o.byval2forwardptr(None)) -check(20, o.byval2forwardptr(x)) +check(19, o.byval2fwdptr(None)) +check(20, o.byval2fwdptr(x)) -check(21, o.byval1forwardref(x)) +check(21, o.byval1fwdref(x)) -check(22, o.byval2forwardref(x)) +check(22, o.byval2fwdref(x)) diff --git a/Examples/test-suite/python/overload_simple_runme.py b/Examples/test-suite/python/overload_simple_runme.py index 6d72ec081..56763828d 100644 --- a/Examples/test-suite/python/overload_simple_runme.py +++ b/Examples/test-suite/python/overload_simple_runme.py @@ -1,95 +1,95 @@ from overload_simple import * if foo(3) != "foo:int": - raise RuntimeError, "foo(int)" + raise RuntimeError("foo(int)") if foo(3.0) != "foo:double": - raise RuntimeError, "foo(double)" + raise RuntimeError("foo(double)") if foo("hello") != "foo:char *": - raise RuntimeError, "foo(char *)" + raise RuntimeError("foo(char *)") f = Foo() b = Bar() if foo(f) != "foo:Foo *": - raise RuntimeError, "foo(Foo *)" + raise RuntimeError("foo(Foo *)") if foo(b) != "foo:Bar *": - raise RuntimeError, "foo(Bar *)" + raise RuntimeError("foo(Bar *)") v = malloc_void(32) if foo(v) != "foo:void *": - raise RuntimeError, "foo(void *)" + raise RuntimeError("foo(void *)") s = Spam() if s.foo(3) != "foo:int": - raise RuntimeError, "Spam::foo(int)" + raise RuntimeError("Spam::foo(int)") if s.foo(3.0) != "foo:double": - raise RuntimeError, "Spam::foo(double)" + raise RuntimeError("Spam::foo(double)") if s.foo("hello") != "foo:char *": - raise RuntimeError, "Spam::foo(char *)" + raise RuntimeError("Spam::foo(char *)") if s.foo(f) != "foo:Foo *": - raise RuntimeError, "Spam::foo(Foo *)" + raise RuntimeError("Spam::foo(Foo *)") if s.foo(b) != "foo:Bar *": - raise RuntimeError, "Spam::foo(Bar *)" + raise RuntimeError("Spam::foo(Bar *)") if s.foo(v) != "foo:void *": - raise RuntimeError, "Spam::foo(void *)" + raise RuntimeError("Spam::foo(void *)") -if Spam_bar(3) != "bar:int": - raise RuntimeError, "Spam::bar(int)" +if Spam.bar(3) != "bar:int": + raise RuntimeError("Spam::bar(int)") -if Spam_bar(3.0) != "bar:double": - raise RuntimeError, "Spam::bar(double)" +if Spam.bar(3.0) != "bar:double": + raise RuntimeError("Spam::bar(double)") -if Spam_bar("hello") != "bar:char *": - raise RuntimeError, "Spam::bar(char *)" +if Spam.bar("hello") != "bar:char *": + raise RuntimeError("Spam::bar(char *)") -if Spam_bar(f) != "bar:Foo *": - raise RuntimeError, "Spam::bar(Foo *)" +if Spam.bar(f) != "bar:Foo *": + raise RuntimeError("Spam::bar(Foo *)") -if Spam_bar(b) != "bar:Bar *": - raise RuntimeError, "Spam::bar(Bar *)" +if Spam.bar(b) != "bar:Bar *": + raise RuntimeError("Spam::bar(Bar *)") -if Spam_bar(v) != "bar:void *": - raise RuntimeError, "Spam::bar(void *)" +if Spam.bar(v) != "bar:void *": + raise RuntimeError("Spam::bar(void *)") # Test constructors s = Spam() if s.type != "none": - raise RuntimeError, "Spam()" + raise RuntimeError("Spam()") s = Spam(3) if s.type != "int": - raise RuntimeError, "Spam(int)" + raise RuntimeError("Spam(int)") s = Spam(3.4) if s.type != "double": - raise RuntimeError, "Spam(double)" + raise RuntimeError("Spam(double)") s = Spam("hello") if s.type != "char *": - raise RuntimeError, "Spam(char *)" + raise RuntimeError("Spam(char *)") s = Spam(f) if s.type != "Foo *": - raise RuntimeError, "Spam(Foo *)" + raise RuntimeError("Spam(Foo *)") s = Spam(b) if s.type != "Bar *": - raise RuntimeError, "Spam(Bar *)" + raise RuntimeError("Spam(Bar *)") s = Spam(v) if s.type != "void *": - raise RuntimeError, "Spam(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 3f32a5583..b02e62ff3 100644 --- a/Examples/test-suite/python/overload_subtype_runme.py +++ b/Examples/test-suite/python/overload_subtype_runme.py @@ -4,7 +4,7 @@ f = Foo() b = Bar() if spam(f) != 1: - raise RuntimeError, "foo" + raise RuntimeError("foo") if spam(b) != 2: - raise RuntimeError, "bar" + 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 ca3cac9b5..e4eb33288 100644 --- a/Examples/test-suite/python/overload_template_fast_runme.py +++ b/Examples/test-suite/python/overload_template_fast_runme.py @@ -7,74 +7,74 @@ 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 @@ -84,61 +84,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/overload_template_runme.py b/Examples/test-suite/python/overload_template_runme.py index 014ec71cb..8bd105add 100644 --- a/Examples/test-suite/python/overload_template_runme.py +++ b/Examples/test-suite/python/overload_template_runme.py @@ -6,74 +6,74 @@ 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,63 +83,63 @@ 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) +A.foo(1) b = B() b.foo(1) diff --git a/Examples/test-suite/python/pointer_reference_runme.py b/Examples/test-suite/python/pointer_reference_runme.py index b9b47881d..f12648696 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_cpp_runme.py b/Examples/test-suite/python/preproc_cpp_runme.py new file mode 100644 index 000000000..8c3e21237 --- /dev/null +++ b/Examples/test-suite/python/preproc_cpp_runme.py @@ -0,0 +1,4 @@ +import preproc_cpp + +t1 = preproc_cpp.tcxMessageTest() +t2 = preproc_cpp.tcxMessageBug() diff --git a/Examples/test-suite/python/primitive_types_runme.py b/Examples/test-suite/python/primitive_types_runme.py index 04588ddf2..7ed4b52d1 100644 --- a/Examples/test-suite/python/primitive_types_runme.py +++ b/Examples/test-suite/python/primitive_types_runme.py @@ -31,8 +31,7 @@ v_check() def pyerror(name, val, cte): - print "bad val/cte", name, val, cte - raise RuntimeError + raise RuntimeError("bad val/cte {} {} {}".format(name, val, cte)) pass if cvar.var_bool != cct_bool: @@ -173,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 @@ -228,63 +227,57 @@ t.v_check() # this value contains a '0' char! if def_namet != "hola": - print "bad namet", def_namet - raise RuntimeError + raise RuntimeError("bad namet {}".format(def_namet)) t.var_namet = def_namet if t.var_namet != def_namet: - print "bad namet", t.var_namet, def_namet - raise RuntimeError + raise RuntimeError("bad namet {} {}".format(t.var_namet, def_namet)) t.var_namet = "hola" if t.var_namet != "hola": - print "bad namet", t.var_namet - raise RuntimeError + raise RuntimeError("bad namet {}".format(t.var_namet)) t.var_namet = "hol" if t.var_namet != "hol": # if t.var_namet != "hol\0\0": - print "bad namet", t.var_namet - raise RuntimeError + raise RuntimeError("bad namet {}".format(t.var_namet)) 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 != "": - print "hola", "", cvar.var_namet - raise RuntimeError, "bad char '\0' case" + raise RuntimeError("bad char '\0' case hola {}".format(cvar.var_namet)) cvar.var_namet = "" # 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" + raise RuntimeError("bad char empty case %c" % (cvar.var_pchar[0],)) 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") # @@ -300,13 +293,12 @@ pchar_setitem(pc, 4, 0) cvar.var_pchar = pc if cvar.var_pchar != "hola": - print cvar.var_pchar - raise RuntimeError, "bad pointer case" + raise RuntimeError("bad pointer case {}".format(cvar.var_pchar)) cvar.var_namet = pc # if cvar.var_namet != "hola\0": if cvar.var_namet != "hola": - raise RuntimeError, "bad pointer case" + raise RuntimeError("bad pointer case") delete_pchar(pc) @@ -325,7 +317,7 @@ except OverflowError: error = 1 pass if error: - raise RuntimeError, "bad uchar typemap" + raise RuntimeError("bad uchar typemap") try: @@ -338,7 +330,7 @@ except TypeError: error = 1 pass if error: - raise RuntimeError, "bad char typemap" + raise RuntimeError("bad char typemap") try: error = 0 @@ -350,7 +342,7 @@ except OverflowError: error = 1 pass if error: - raise RuntimeError, "bad ushort typemap" + raise RuntimeError("bad ushort typemap") try: error = 0 @@ -362,7 +354,7 @@ except OverflowError: error = 1 pass if error: - raise RuntimeError, "bad uint typemap" + raise RuntimeError("bad uint typemap") try: error = 0 @@ -374,7 +366,7 @@ except OverflowError: error = 1 pass if error: - raise RuntimeError, "bad sizet typemap" + raise RuntimeError("bad sizet typemap") try: error = 0 @@ -386,7 +378,7 @@ except OverflowError: error = 1 pass if error: - raise RuntimeError, "bad ulong typemap" + raise RuntimeError("bad ulong typemap") # # @@ -400,43 +392,43 @@ except TypeError: 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" + 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" + raise RuntimeError("bad int typemap") s = char_foo(1, "hello") if s != "hello": - raise RuntimeError, "bad char* typemap" + raise RuntimeError("bad char* typemap") v = SetPos(1, 3) if v != 4: - raise RuntimeError, "bad int typemap" + raise RuntimeError("bad int typemap") # # Check the bounds for converting various types @@ -481,7 +473,7 @@ maxullong = 2 * maxllong + 1 # Make sure Python 2's sys.maxint is the same as the maxlong we calculated if sys.version_info[0] <= 2 and maxlong != sys.maxint: - raise RuntimeError, "sys.maxint is not the maximum value of a signed long" + raise RuntimeError("sys.maxint is not the maximum value of a signed long") def checkType(t, e, val, delta): """t = Test object, e = type name (e.g. ulong), val = max or min allowed value, delta = +1 for max, -1 for min""" @@ -511,7 +503,7 @@ def checkType(t, e, val, delta): except OverflowError: pass if error: - raise RuntimeError, "bad " + e + " typemap" + raise RuntimeError("bad " + e + " typemap") def checkFull(t, e, maxval, minval): """Check the maximum and minimum bounds for the type given by e""" @@ -543,17 +535,17 @@ def checkOverload(t, name, val, delta, prevval, limit): if val != prevval: # Make sure the most extreme value of this type gives the name of this type if t.ovr_str(val) != name: - raise RuntimeError, "bad " + name + " typemap" + raise RuntimeError("bad " + name + " typemap") # Make sure a more extreme value doesn't give the name of this type try: if t.ovr_str(val + delta) == name: - raise RuntimeError, "bad " + name + " typemap" + raise RuntimeError("bad " + name + " typemap") if val == limit: # Should raise TypeError here since this is the largest integral type - raise RuntimeError, "bad " + name + " typemap" + raise RuntimeError("bad " + name + " typemap") except TypeError: if val != limit: - raise RuntimeError, "bad " + name + " typemap" + raise RuntimeError("bad " + name + " typemap") # Check that overloading works: uchar > schar > ushort > short > uint > int > ulong > long > ullong > llong checkOverload(t, "uchar", maxuchar, +1, 0, maxullong) @@ -568,22 +560,22 @@ checkOverload(t, "long", minlong, -1, minint, minllong) checkOverload(t, "llong", minllong, -1, minlong, minllong) # Make sure that large ints can be converted to doubles properly -if val_double(sys.maxint + 1) != float(sys.maxint + 1): - raise RuntimeError, "bad double typemap" -if val_double(-sys.maxint - 2) != float(-sys.maxint - 2): - raise RuntimeError, "bad double typemap" +if val_double(sys.maxsize + 1) != float(sys.maxsize + 1): + raise RuntimeError("bad double typemap") +if val_double(-sys.maxsize - 2) != float(-sys.maxsize - 2): + raise RuntimeError("bad double typemap") # Check the minimum and maximum values that fit in ptrdiff_t and size_t def checkType(name, maxfunc, maxval, minfunc, minval, echofunc): if maxfunc() != maxval: - raise RuntimeError, "bad " + name + " typemap" + raise RuntimeError("bad " + name + " typemap") if minfunc() != minval: - raise RuntimeError, "bad " + name + " typemap" + raise RuntimeError("bad " + name + " typemap") if echofunc(maxval) != maxval: - raise RuntimeError, "bad " + name + " typemap" + raise RuntimeError("bad " + name + " typemap") if echofunc(minval) != minval: - raise RuntimeError, "bad " + name + " typemap" + raise RuntimeError("bad " + name + " typemap") error = 0 try: echofunc(maxval + 1) @@ -591,14 +583,14 @@ def checkType(name, maxfunc, maxval, minfunc, minval, echofunc): except OverflowError: pass if error == 1: - raise RuntimeError, "bad " + name + " typemap" + raise RuntimeError("bad " + name + " typemap") try: echofunc(minval - 1) error = 1 except OverflowError: pass if error == 1: - raise RuntimeError, "bad " + name + " typemap" + raise RuntimeError("bad " + name + " typemap") # sys.maxsize is the largest value supported by Py_ssize_t, which should be the same as ptrdiff_t if sys.version_info[0:2] >= (2, 6): diff --git a/Examples/test-suite/python/python_abstractbase_runme3.py b/Examples/test-suite/python/python_abstractbase_runme.py similarity index 100% rename from Examples/test-suite/python/python_abstractbase_runme3.py rename to Examples/test-suite/python/python_abstractbase_runme.py diff --git a/Examples/test-suite/python/python_annotations_c_runme.py b/Examples/test-suite/python/python_annotations_c_runme.py new file mode 100644 index 000000000..3110d8f83 --- /dev/null +++ b/Examples/test-suite/python/python_annotations_c_runme.py @@ -0,0 +1,31 @@ +import sys + +if sys.version_info[0:2] >= (3, 2): + from python_annotations_c import * + + # No __annotations__ support with -builtin or -fastproxy + annotations_supported = not(is_python_builtin() or is_python_fastproxy()) + + if annotations_supported: + anno = MakeShort.__annotations__ + if anno != {'x': 'int', 'return': 'Space::Template< short >'}: + raise RuntimeError("annotations mismatch: {}".format(anno)) + + anno = global_ints.__annotations__ + if anno != {'ri': 'int &', 't': 'TemplateShort', 'return': 'int *'}: + raise RuntimeError("annotations mismatch: {}".format(anno)) + + ts = MakeShort(10) + + anno = MakeShort.__annotations__ + if anno != {'x': 'int', 'return': 'Space::Template< short >'}: + raise RuntimeError("annotations mismatch: {}".format(anno)) + + anno = ts.mymethod.__annotations__ + if anno != {'arg2': 'int', 'tt': 'TemplateShort', 'return': 'void'}: + raise RuntimeError("annotations mismatch: {}".format(anno)) + + # No annotations + anno = no_annotations.__annotations__ + if anno != {}: + raise RuntimeError("annotations mismatch: {}".format(anno)) diff --git a/Examples/test-suite/python/python_builtin_runme.py b/Examples/test-suite/python/python_builtin_runme.py index 26e757ca7..8a42a2607 100644 --- a/Examples/test-suite/python/python_builtin_runme.py +++ b/Examples/test-suite/python/python_builtin_runme.py @@ -32,7 +32,7 @@ if is_python_builtin(): passed = False try: h = hash(ExceptionHashFunction()) - except RuntimeError, e: + except RuntimeError as e: passed = str(e).find("oops") != -1 pass diff --git a/Examples/test-suite/python/python_destructor_exception_runme.py b/Examples/test-suite/python/python_destructor_exception_runme.py index ee71ab33b..47659531b 100644 --- a/Examples/test-suite/python/python_destructor_exception_runme.py +++ b/Examples/test-suite/python/python_destructor_exception_runme.py @@ -1,7 +1,11 @@ import python_destructor_exception -from StringIO import StringIO import sys +if sys.version_info[0:2] < (3, 0): + import StringIO as io +else: + import io + def error_function(): python_destructor_exception.ClassWithThrowingDestructor().GetBlah() @@ -9,13 +13,13 @@ def runtest(): attributeErrorOccurred = False try: error_function() - except AttributeError, e: + except AttributeError: attributeErrorOccurred = True return attributeErrorOccurred def test1(): stderr_saved = sys.stderr - buffer = StringIO() + buffer = io.StringIO() attributeErrorOccurred = False try: # Suppress stderr while making this call to suppress the output shown by PyErr_WriteUnraisable diff --git a/Examples/test-suite/python/python_flatstaticmethod_runme.py b/Examples/test-suite/python/python_flatstaticmethod_runme.py new file mode 100644 index 000000000..f34670013 --- /dev/null +++ b/Examples/test-suite/python/python_flatstaticmethod_runme.py @@ -0,0 +1,85 @@ +from python_flatstaticmethod import * +import inspect + +# This testcase tests C++ class static functions when using legacy "flattened" +# staticmethod access, A_bar, as well as the normal staticmethod access, A.bar. + + +def check(got, expected): + if got != expected: + raise RuntimeError("\ngot :{}\nwant:{}\n".format(got, expected)) + +if A_bar(2) != 4: + raise RuntimeError + +if A.bar(2) != 4: + raise RuntimeError + +# %callback +if foobar(3, A_bar) != A_bar(3): + raise RuntimeError + +if foobar(3, A.bar) != A_bar(3): + raise RuntimeError + +# kwargs +if A_pub() != 1: + raise RuntimeError + +if A_pub(b=2) != 3: + raise RuntimeError + +if A_pub(b=10,a=20) != 30: + raise RuntimeError + +if A.pub() != 1: + raise RuntimeError + +if A.pub(b=2) != 3: + raise RuntimeError + +if A.pub(b=10,a=20) != 30: + raise RuntimeError + +check(inspect.getdoc(A_func0static), + "A_func0static(e, arg2, hello, f=2) -> int") +check(inspect.getdoc(A_func1static), + "A_func1static(A e, short arg2, Tuple hello, double f=2) -> int") + +# overloaded static functions +if A_over(3) != "over:int": + raise RuntimeError("A::over(int)") + +if A_over(3.0) != "over:double": + raise RuntimeError("A::over(double)") + +if A_over("hello") != "over:char *": + raise RuntimeError("A::over(char *)") + +if A.over(3) != "over:int": + raise RuntimeError("A::over(int)") + +if A.over(3.0) != "over:double": + raise RuntimeError("A::over(double)") + +if A.over("hello") != "over:char *": + raise RuntimeError("A::over(char *)") + +# default args +if A_defargs() != 30: + raise RuntimeError + +if A_defargs(1) != 21: + raise RuntimeError + +if A_defargs(1, 2) != 3: + raise RuntimeError + +if A.defargs() != 30: + raise RuntimeError + +if A.defargs(1) != 21: + raise RuntimeError + +if A.defargs(1, 2) != 3: + raise RuntimeError diff --git a/Examples/test-suite/python/python_nondynamic_runme.py b/Examples/test-suite/python/python_nondynamic_runme.py index fbb60ad36..870c70b3b 100644 --- a/Examples/test-suite/python/python_nondynamic_runme.py +++ b/Examples/test-suite/python/python_nondynamic_runme.py @@ -1,9 +1,5 @@ import python_nondynamic -def is_python_modern(): - """Return True if SWIG is generating Python code using -modern. Works only if %python_nondynamic has been used.""" - return hasattr(python_nondynamic, "_swig_setattr_nondynamic_class_variable") - def debug_print(s): show_debug = False if show_debug: @@ -51,9 +47,7 @@ if python_nondynamic.retrieve_A_b(bb) != 5: raise RuntimeError("b not set correc try: bb.c = 3 - print("bb.c = {}".format(bb.c)) - print("B.c = {}".format(B.c)) - raise RuntimeError("B.c class variable messes up nondynamic-ness of B") + raise RuntimeError("B.c class variable messes up nondynamic-ness of B bb.c={} B.c={}".format(bb.c, B.c)) except AttributeError as e: debug_print(e) pass @@ -68,7 +62,7 @@ except AttributeError as e: cc = python_nondynamic.C() cc.d = 3 -# An inconsistency between builtin and (non-builtin/modern). +# An inconsistency between builtin and non-builtin. # Class variables cannot be set on builtin types, like other Python builtins, eg list.classvar=111 fails if python_nondynamic.is_python_builtin(): try: @@ -80,8 +74,8 @@ if python_nondynamic.is_python_builtin(): else: python_nondynamic.C.classvar = 111 -if is_python_modern() and not python_nondynamic.is_python_builtin(): - # Not working with builtin or non-modern :( +if not python_nondynamic.is_python_builtin(): + # Not working with builtin :( try: B.a = 10 raise RuntimeError("B should not allow adding a class variable by setting it as an instance variable") @@ -99,9 +93,7 @@ if is_python_modern() and not python_nondynamic.is_python_builtin(): if not python_nondynamic.is_python_builtin(): try: bb.cc = 3 - print("bb.cc = {}".format(bb.cc)) - print("B.cc = {}".format(B.cc)) - raise RuntimeError("B.cc class variable messes up nondynamic-ness of B") + raise RuntimeError("B.cc class variable messes up nondynamic-ness of B bb.cc={} B.cc={}".format(bb.cc, B.cc)) except AttributeError as e: debug_print(e) pass 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 d4cb8a37a..2aee5bb53 100644 --- a/Examples/test-suite/python/python_overload_simple_cast_runme.py +++ b/Examples/test-suite/python/python_overload_simple_cast_runme.py @@ -9,6 +9,8 @@ class Ai: def __int__(self): return self.x + def __index__(self): + return self.x class Ad: @@ -30,136 +32,136 @@ except: good = 1 if not good: - raise RuntimeError, "fint(int)" + raise RuntimeError("fint(int)") if fint(ad) != "fint:int": - raise RuntimeError, "fint(int)" + raise RuntimeError("fint(int)") if fdouble(ad) != "fdouble:double": - raise RuntimeError, "fdouble(double)" + raise RuntimeError("fdouble(double)") if fint(ai) != "fint:int": - raise RuntimeError, "fint(int)" + raise RuntimeError("fint(int)") if fint(5.0) != "fint:int": - raise RuntimeError, "fint(int)" + raise RuntimeError("fint(int)") if fint(3) != "fint:int": - raise RuntimeError, "fint(int)" + raise RuntimeError("fint(int)") if fint(3.0) != "fint:int": - raise RuntimeError, "fint(int)" + raise RuntimeError("fint(int)") if fdouble(ad) != "fdouble:double": - raise RuntimeError, "fdouble(double)" + raise RuntimeError("fdouble(double)") if fdouble(3) != "fdouble:double": - raise RuntimeError, "fdouble(double)" + raise RuntimeError("fdouble(double)") if fdouble(3.0) != "fdouble:double": - raise RuntimeError, "fdouble(double)" + raise RuntimeError("fdouble(double)") if fid(3, 3.0) != "fid:intdouble": - raise RuntimeError, "fid:intdouble" + raise RuntimeError("fid:intdouble") if fid(3.0, 3) != "fid:doubleint": - raise RuntimeError, "fid:doubleint" + raise RuntimeError("fid:doubleint") if fid(ad, ai) != "fid:doubleint": - raise RuntimeError, "fid:doubleint" + raise RuntimeError("fid:doubleint") if fid(ai, ad) != "fid:intdouble": - raise RuntimeError, "fid:intdouble" + raise RuntimeError("fid:intdouble") if foo(3) != "foo:int": - raise RuntimeError, "foo(int)" + raise RuntimeError("foo(int)") if foo(3.0) != "foo:double": - raise RuntimeError, "foo(double)" + raise RuntimeError("foo(double)") if foo("hello") != "foo:char *": - raise RuntimeError, "foo(char *)" + raise RuntimeError("foo(char *)") f = Foo() b = Bar() if foo(f) != "foo:Foo *": - raise RuntimeError, "foo(Foo *)" + raise RuntimeError("foo(Foo *)") if foo(b) != "foo:Bar *": - raise RuntimeError, "foo(Bar *)" + raise RuntimeError("foo(Bar *)") v = malloc_void(32) if foo(v) != "foo:void *": - raise RuntimeError, "foo(void *)" + raise RuntimeError("foo(void *)") s = Spam() if s.foo(3) != "foo:int": - raise RuntimeError, "Spam::foo(int)" + raise RuntimeError("Spam::foo(int)") if s.foo(3.0) != "foo:double": - raise RuntimeError, "Spam::foo(double)" + raise RuntimeError("Spam::foo(double)") if s.foo("hello") != "foo:char *": - raise RuntimeError, "Spam::foo(char *)" + raise RuntimeError("Spam::foo(char *)") if s.foo(f) != "foo:Foo *": - raise RuntimeError, "Spam::foo(Foo *)" + raise RuntimeError("Spam::foo(Foo *)") if s.foo(b) != "foo:Bar *": - raise RuntimeError, "Spam::foo(Bar *)" + raise RuntimeError("Spam::foo(Bar *)") if s.foo(v) != "foo:void *": - raise RuntimeError, "Spam::foo(void *)" + raise RuntimeError("Spam::foo(void *)") -if Spam_bar(3) != "bar:int": - raise RuntimeError, "Spam::bar(int)" +if Spam.bar(3) != "bar:int": + raise RuntimeError("Spam::bar(int)") -if Spam_bar(3.0) != "bar:double": - raise RuntimeError, "Spam::bar(double)" +if Spam.bar(3.0) != "bar:double": + raise RuntimeError("Spam::bar(double)") -if Spam_bar("hello") != "bar:char *": - raise RuntimeError, "Spam::bar(char *)" +if Spam.bar("hello") != "bar:char *": + raise RuntimeError("Spam::bar(char *)") -if Spam_bar(f) != "bar:Foo *": - raise RuntimeError, "Spam::bar(Foo *)" +if Spam.bar(f) != "bar:Foo *": + raise RuntimeError("Spam::bar(Foo *)") -if Spam_bar(b) != "bar:Bar *": - raise RuntimeError, "Spam::bar(Bar *)" +if Spam.bar(b) != "bar:Bar *": + raise RuntimeError("Spam::bar(Bar *)") -if Spam_bar(v) != "bar:void *": - raise RuntimeError, "Spam::bar(void *)" +if Spam.bar(v) != "bar:void *": + raise RuntimeError("Spam::bar(void *)") # Test constructors s = Spam() if s.type != "none": - raise RuntimeError, "Spam()" + raise RuntimeError("Spam()") s = Spam(3) if s.type != "int": - raise RuntimeError, "Spam(int)" + raise RuntimeError("Spam(int)") s = Spam(3.4) if s.type != "double": - raise RuntimeError, "Spam(double)" + raise RuntimeError("Spam(double)") s = Spam("hello") if s.type != "char *": - raise RuntimeError, "Spam(char *)" + raise RuntimeError("Spam(char *)") s = Spam(f) if s.type != "Foo *": - raise RuntimeError, "Spam(Foo *)" + raise RuntimeError("Spam(Foo *)") s = Spam(b) if s.type != "Bar *": - raise RuntimeError, "Spam(Bar *)" + raise RuntimeError("Spam(Bar *)") s = Spam(v) if s.type != "void *": - raise RuntimeError, "Spam(void *)" + raise RuntimeError("Spam(void *)") # unsigned long long @@ -168,13 +170,13 @@ ullmaxd = 9007199254740992.0 ullmin = 0 ullmind = 0.0 if ull(ullmin) != ullmin: - raise RuntimeError, "ull(ullmin)" + raise RuntimeError("ull(ullmin)") if ull(ullmax) != ullmax: - raise RuntimeError, "ull(ullmax)" + raise RuntimeError("ull(ullmax)") if ull(ullmind) != ullmind: - raise RuntimeError, "ull(ullmind)" + raise RuntimeError("ull(ullmind)") if ull(ullmaxd) != ullmaxd: - raise RuntimeError, "ull(ullmaxd)" + raise RuntimeError("ull(ullmaxd)") # long long llmax = 9223372036854775807 # 0x7fffffffffffffff @@ -183,13 +185,13 @@ llmin = -9223372036854775808 llmaxd = 9007199254740992.0 llmind = -9007199254740992.0 if ll(llmin) != llmin: - raise RuntimeError, "ll(llmin)" + raise RuntimeError("ll(llmin)") if ll(llmax) != llmax: - raise RuntimeError, "ll(llmax)" + raise RuntimeError("ll(llmax)") if ll(llmind) != llmind: - raise RuntimeError, "ll(llmind)" + raise RuntimeError("ll(llmind)") if ll(llmaxd) != llmaxd: - raise RuntimeError, "ll(llmaxd)" + raise RuntimeError("ll(llmaxd)") free_void(v) diff --git a/Examples/test-suite/python/python_pickle_runme.py b/Examples/test-suite/python/python_pickle_runme.py index 27c67ae10..cbe425fa2 100644 --- a/Examples/test-suite/python/python_pickle_runme.py +++ b/Examples/test-suite/python/python_pickle_runme.py @@ -15,15 +15,15 @@ check(p) r = p.__reduce__() if python_pickle.cvar.debug: - print "__reduce__ returned:", r + print("__reduce__ returned: {}".format(r)) pickle_string = pickle.dumps(p) newp = pickle.loads(pickle_string) check(newp) # Not yet working... some crash and others are not producing a sensible "can't be pickled" error #nfp = python_pickle.NotForPickling("no no") -#print nfp.__reduce__() +#print("{}".format(nfp.__reduce__())) #pickle_string = pickle.dumps(nfp) -#print pickle_string +#print("{}".format(pickle_string)) #newp = pickle.loads(pickle_string) -#print newp.msg +#print("{}".format(newp.msg)) diff --git a/Examples/test-suite/python/python_pybuffer_runme.py b/Examples/test-suite/python/python_pybuffer_runme.py index 8ecdb523b..65079200b 100644 --- a/Examples/test-suite/python/python_pybuffer_runme.py +++ b/Examples/test-suite/python/python_pybuffer_runme.py @@ -17,13 +17,13 @@ if len(sys.argv) >= 2 and sys.argv[1] == "benchmark": a = bytearray(b"hello world") for i in range(k): python_pybuffer.title1(a) - print "Time used by bytearray:", time.time() - t + print("Time used by bytearray: {}".format(time.time() - t)) t = time.time() b = "hello world" for i in range(k): python_pybuffer.title2(b) - print "Time used by string:", time.time() - t + print("Time used by string: {}".format(time.time() - t)) else: # run the test case buf1 = bytearray(10) @@ -44,3 +44,27 @@ else: buf3 = bytearray(b"hello") python_pybuffer.title1(buf3) check(buf3 == b"Hello") + + try: + python_pybuffer.func1(1) + raise RuntimeError("should throw TypeError") + except TypeError as e: + check("(char *buf1, int len)" in str(e)) + + try: + python_pybuffer.func2(1) + raise RuntimeError("should throw TypeError") + except TypeError as e: + check("(char *buf2)" in str(e)) + + try: + python_pybuffer.func3(1) + raise RuntimeError("should throw TypeError") + except TypeError as e: + check("(const char *buf3, int len)" in str(e)) + + try: + python_pybuffer.func4(1) + raise RuntimeError("should throw TypeError") + except TypeError as e: + check("(const char *buf4)" in str(e)) diff --git a/Examples/test-suite/python/python_richcompare_runme.py b/Examples/test-suite/python/python_richcompare_runme.py index 724d1d73c..988a3f91f 100644 --- a/Examples/test-suite/python/python_richcompare_runme.py +++ b/Examples/test-suite/python/python_richcompare_runme.py @@ -114,22 +114,22 @@ else: try: res = base1 < 42 raise RuntimeError("Failed to throw") - except TypeError,e: + except TypeError as e: check_unorderable_types(e) try: res = base1 <= 42 raise RuntimeError("Failed to throw") - except TypeError,e: + except TypeError as e: check_unorderable_types(e) try: res = base1 > 42 raise RuntimeError("Failed to throw") - except TypeError,e: + except TypeError as e: check_unorderable_types(e) try: res = base1 >= 42 raise RuntimeError("Failed to throw") - except TypeError,e: + except TypeError as e: check_unorderable_types(e) # Check inequalities used for ordering diff --git a/Examples/test-suite/python/python_strict_unicode_runme.py b/Examples/test-suite/python/python_strict_unicode_runme.py index e7fae2556..79c768de1 100644 --- a/Examples/test-suite/python/python_strict_unicode_runme.py +++ b/Examples/test-suite/python/python_strict_unicode_runme.py @@ -1,8 +1,20 @@ import python_strict_unicode +import sys test_bytes = b"hello \x01world\x99" BYTES = b"BYTES" -test_unicode = u"h\udce9llo w\u00f6rld" + +if sys.version_info[0:2] < (3, 0): + # Python 3.0-3.2 results in a SyntaxError when using u"" string literals, so we use a + # convoluted unicode string construction using unicode() and unichr(). + # Conventional Python 2 syntax shown in comments. + test_unicode = unicode("h" + unichr(0xdce9) + "llo w" + unichr(0x00f6) + "rld") # u"h\udce9llo w\u00f6rld" + UNICODE = unicode("UNICODE") + type_unicode_string = type(UNICODE) +else: + test_unicode = "h\udce9llo w\u00f6rld" + UNICODE = "UNICODE" + type_unicode_string = type(UNICODE) # Test that byte string inputs and outputs work as expected bdbl = python_strict_unicode.double_str(test_bytes) @@ -20,12 +32,12 @@ if type(bout) != type(BYTES): udbl = python_strict_unicode.double_wstr(test_unicode) if udbl != test_unicode + test_unicode: raise RuntimeError("Failed to double wide string") -if type(udbl) != type(u""): +if type(udbl) != type_unicode_string: raise RuntimeError("Wrong type output for wide string") uout = python_strict_unicode.same_wstr(test_unicode) if uout != test_unicode: raise RuntimeError("Failed to copy wchar_t*") -if type(uout) != type(u""): +if type(uout) != type_unicode_string: raise RuntimeError("Wrong type output for wchar_t*") # Test that overloading is handled properly @@ -35,9 +47,9 @@ if bovr != BYTES: if type(bovr) != type(BYTES): raise RuntimeError("Wrong type output from overload") uovr = python_strict_unicode.overload(test_unicode) -if uovr != u"UNICODE": +if uovr != UNICODE: raise RuntimeError("Failed to return unicode from overload") -if type(uovr) != type(u""): +if type(uovr) != type_unicode_string: raise RuntimeERror("Wrong type output from overload") # Test that bytes aren't accepted as wide strings and unicode isn't accepted as narrow strings diff --git a/Examples/test-suite/python/refcount_runme.py b/Examples/test-suite/python/refcount_runme.py index 2cab6a77e..5bea25fa1 100644 --- a/Examples/test-suite/python/refcount_runme.py +++ b/Examples/test-suite/python/refcount_runme.py @@ -5,7 +5,7 @@ from refcount import * a = A3() b1 = B(a) -b2 = B_create(a) +b2 = B.create(a) if a.ref_count() != 3: @@ -13,7 +13,7 @@ if a.ref_count() != 3: rca = b2.get_rca() -b3 = B_create(rca) +b3 = B.create(rca) if a.ref_count() != 5: raise RuntimeError("Count = %d" % a.ref_count()) @@ -38,7 +38,7 @@ b5 = global_create(a) if b5.ref_count() != 1: raise RuntimeError -b6 = Factory_create(a) +b6 = Factory.create(a) if b6.ref_count() != 1: raise RuntimeError diff --git a/Examples/test-suite/python/return_const_value_runme.py b/Examples/test-suite/python/return_const_value_runme.py index ff3bd5f02..8cbac125c 100644 --- a/Examples/test-suite/python/return_const_value_runme.py +++ b/Examples/test-suite/python/return_const_value_runme.py @@ -1,12 +1,10 @@ import return_const_value import sys -p = return_const_value.Foo_ptr_getPtr() +p = return_const_value.Foo_ptr.getPtr() if (p.getVal() != 17): - print "Runtime test1 failed. p.getVal()=", p.getVal() - sys.exit(1) + raise RuntimeError("Runtime test1 failed. p.getVal()={}".format(p.getVal())) -p = return_const_value.Foo_ptr_getConstPtr() +p = return_const_value.Foo_ptr.getConstPtr() if (p.getVal() != 17): - print "Runtime test2 failed. p.getVal()=", p.getVal() - sys.exit(1) + raise RuntimeError("Runtime test2 failed. p.getVal()={}".format(p.getVal())) diff --git a/Examples/test-suite/python/smart_pointer_member_runme.py b/Examples/test-suite/python/smart_pointer_member_runme.py index d2ed87e79..9758b0ba4 100644 --- a/Examples/test-suite/python/smart_pointer_member_runme.py +++ b/Examples/test-suite/python/smart_pointer_member_runme.py @@ -11,9 +11,7 @@ b = Bar(f) b.y = 2 if f.y != 2: - print f.y - print b.y - raise RuntimeError + raise RuntimeError("Failed {} {}".format(f.y, b.y)) if b.x != f.x: 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 69704c4ef..8cd9f11f3 100644 --- a/Examples/test-suite/python/smart_pointer_not_runme.py +++ b/Examples/test-suite/python/smart_pointer_not_runme.py @@ -7,36 +7,36 @@ g = Grok(f) try: x = b.x - print "Error! b.x" -except: + raise RuntimeError("Error! b.x") +except AttributeError: pass try: x = s.x - print "Error! s.x" -except: + raise RuntimeError("Error! s.x") +except AttributeError: pass try: x = g.x - print "Error! g.x" -except: + raise RuntimeError("Error! g.x") +except AttributeError: pass try: x = b.getx() - print "Error! b.getx()" -except: + raise RuntimeError("Error! b.getx()") +except AttributeError: pass try: x = s.getx() - print "Error! s.getx()" -except: + raise RuntimeError("Error! s.getx()") +except AttributeError: pass try: x = g.getx() - print "Error! g.getx()" -except: + raise RuntimeError("Error! g.getx()") +except AttributeError: pass diff --git a/Examples/test-suite/python/std_containers_runme.py b/Examples/test-suite/python/std_containers_runme.py index 7404cd5f4..820c8f454 100644 --- a/Examples/test-suite/python/std_containers_runme.py +++ b/Examples/test-suite/python/std_containers_runme.py @@ -7,34 +7,33 @@ 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" + raise RuntimeError("bad cident") p = (1, 2) if p != std_containers.pident(p): - raise RuntimeError, "bad pident" + raise RuntimeError("bad pident") 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" + 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" + 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" + raise RuntimeError("bad getslice {} {}".format(v[0:3][1], vu[0:3][1])) m = ((1, 2, 3), (2, 3), (3, 4)) @@ -43,20 +42,20 @@ 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" + raise RuntimeError("bad getslice") 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" + 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 = {} @@ -67,7 +66,7 @@ map["3"] = 2 imap = std_containers.mapident(map) for k in map: if map[k] != imap[k]: - raise RuntimeError, "bad map" + raise RuntimeError("bad map") # Test __contains__ (required for 'x in y' to work) if not imap.__contains__("hello"): diff --git a/Examples/test-suite/python/struct_value_runme.py b/Examples/test-suite/python/struct_value_runme.py index aa3ece38c..9fe5c815c 100644 --- a/Examples/test-suite/python/struct_value_runme.py +++ b/Examples/test-suite/python/struct_value_runme.py @@ -17,7 +17,7 @@ b.added = 123 if b.added != 123: raise RuntimeError("Wrong attribute value") -if not b.__dict__.has_key("added"): +if "added" not in b.__dict__: raise RuntimeError("Missing added attribute in __dict__") @@ -28,7 +28,7 @@ class PyBar(struct_value.Bar): struct_value.Bar.__init__(self) pybar = PyBar() -if not pybar.__dict__.has_key("extra"): +if "extra" not in pybar.__dict__: 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 de232f580..e28e187c9 100644 --- a/Examples/test-suite/python/swigobject_runme.py +++ b/Examples/test-suite/python/swigobject_runme.py @@ -1,5 +1,5 @@ - from swigobject import * +import sys a = A() @@ -11,7 +11,11 @@ if a1.this != a2.this: raise RuntimeError -lthis = long(a.this) +if sys.version_info[0:2] < (3, 0): + lthis = long(a.this) +else: + lthis = int(a.this) + # match pointer value, but deal with leading zeros on 8/16 bit systems and # different C++ compilers interpretation of %p xstr1 = "%016X" % (lthis,) @@ -23,13 +27,17 @@ xstr2 = str.lstrip(xstr2, "0") xstr2 = str.upper(xstr2) if xstr1 != xstr2: - print xstr1, xstr2 - raise RuntimeError + raise RuntimeError("Not equal failed {} {}".format(xstr1, xstr2)) s = str(a.this) r = repr(a.this) v1 = v_ptr(a) v2 = v_ptr(a) -if long(v1) != long(v2): - raise RuntimeError + +if sys.version_info[0:2] < (3, 0): + if long(v1) != long(v2): + raise RuntimeError +else: + if int(v1) != int(v2): + raise RuntimeError diff --git a/Examples/test-suite/python/template_classes_runme.py b/Examples/test-suite/python/template_classes_runme.py index 38b2d7a62..1bd133975 100644 --- a/Examples/test-suite/python/template_classes_runme.py +++ b/Examples/test-suite/python/template_classes_runme.py @@ -13,7 +13,7 @@ RectangleInt.static_onearg(1) fail = True try: rectangle.setPoint() -except TypeError, e: +except TypeError as e: fail = False if fail: raise RuntimeError("argument count check failed") @@ -22,7 +22,7 @@ if fail: fail = True try: rectangle.getPoint(0) -except TypeError, e: +except TypeError as e: fail = False if fail: raise RuntimeError("argument count check failed") @@ -30,7 +30,7 @@ if fail: fail = True try: RectangleInt.static_noargs(0) -except TypeError, e: +except TypeError as e: fail = False if fail: raise RuntimeError("argument count check failed") @@ -38,7 +38,7 @@ if fail: fail = True try: RectangleInt.static_onearg() -except TypeError, e: +except TypeError as 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 91b1e0e8c..e9ef00f99 100644 --- a/Examples/test-suite/python/template_default_arg_runme.py +++ b/Examples/test-suite/python/template_default_arg_runme.py @@ -7,25 +7,25 @@ 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() x = template_default_arg.X_longlong(20.0) -x = template_default_arg.X_longlong(20.0, 200L) +x = template_default_arg.X_longlong(20.0, 200) x = template_default_arg.X_int() @@ -54,40 +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_static_runme.py b/Examples/test-suite/python/template_static_runme.py index c87a52439..84da28438 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 * -Foo_bar_double(1) +Foo.bar_double(1) diff --git a/Examples/test-suite/python/template_template_parameters_runme.py b/Examples/test-suite/python/template_template_parameters_runme.py new file mode 100644 index 000000000..4b0e27d9c --- /dev/null +++ b/Examples/test-suite/python/template_template_parameters_runme.py @@ -0,0 +1,30 @@ +from template_template_parameters import * + +# Test first part +listBool = ListFastBool() +listBool.item = True +x_boolean = listBool.allotype +if listBool.item != True: + raise RuntimeError("Failed") + +listDouble = ListDefaultDouble() +listDouble.item = 10.2 +x_double = listDouble.allotype +if listDouble.item != 10.2: + raise RuntimeError("Failed") + +# Test second part +floatTestStruct = FloatTestStruct() +floatContainer2 = floatTestStruct.x +floatContainer2.x = 8.1 +intTestStruct = IntTestStruct() +intContainer1 = intTestStruct.x +intContainer1.x = 91 +if intContainer1.x != 91: + raise RuntimeError("Failed") +if intTestStruct.x.x != 91: + raise RuntimeError("Failed") +intTestStructReturned = TestStructContainer1Method(intTestStruct) +if intTestStructReturned.x.x != 101: + raise RuntimeError("Failed") + diff --git a/Examples/test-suite/python/template_typedef_cplx2_runme.py b/Examples/test-suite/python/template_typedef_cplx2_runme.py index 161bd51fc..23f19efb9 100644 --- a/Examples/test-suite/python/template_typedef_cplx2_runme.py +++ b/Examples/test-suite/python/template_typedef_cplx2_runme.py @@ -8,25 +8,21 @@ try: d = make_Identity_double() a = d.this except: - print d, "is not an instance" - raise RuntimeError + raise RuntimeError("{} is not an instance".format(d)) s = "%s" % d if str.find(s, "ArithUnaryFunction") == -1: - print d, "is not an ArithUnaryFunction" - raise RuntimeError + raise RuntimeError("{} is not an ArithUnaryFunction".format(d)) try: e = make_Multiplies_double_double_double_double(d, d) a = e.this except: - print e, "is not an instance" - raise RuntimeError + raise RuntimeError("{} is not an instance".format(e)) s = "%s" % e if str.find(s, "ArithUnaryFunction") == -1: - print e, "is not an ArithUnaryFunction" - raise RuntimeError + raise RuntimeError("{} is not an ArithUnaryFunction".format(e)) # @@ -37,25 +33,21 @@ try: c = make_Identity_complex() a = c.this except: - print c, "is not an instance" - raise RuntimeError + raise RuntimeError("{} is not an instance".format(c)) s = "%s" % c if str.find(s, "ArithUnaryFunction") == -1: - print c, "is not an ArithUnaryFunction" - raise RuntimeError + raise RuntimeError("{} is not an ArithUnaryFunction".format(c)) try: f = make_Multiplies_complex_complex_complex_complex(c, c) a = f.this except: - print f, "is not an instance" - raise RuntimeError + raise RuntimeError("{} is not an instance".format(f)) s = "%s" % f if str.find(s, "ArithUnaryFunction") == -1: - print f, "is not an ArithUnaryFunction" - raise RuntimeError + raise RuntimeError("{} is not an ArithUnaryFunction".format(f)) # # Mix case @@ -65,29 +57,24 @@ try: g = make_Multiplies_double_double_complex_complex(d, c) a = g.this except: - print g, "is not an instance" - raise RuntimeError + raise RuntimeError("{} is not an instance".format(g)) s = "%s" % g if str.find(s, "ArithUnaryFunction") == -1: - print g, "is not an ArithUnaryFunction" - raise RuntimeError + raise RuntimeError("{} is not an ArithUnaryFunction".format(g)) try: h = make_Multiplies_complex_complex_double_double(c, d) a = h.this except: - print h, "is not an instance" - raise RuntimeError + raise RuntimeError("{} is not an instance".format(h)) s = "%s" % h if str.find(s, "ArithUnaryFunction") == -1: - print h, "is not an ArithUnaryFunction" - raise RuntimeError + raise RuntimeError("{} is not an ArithUnaryFunction".format(h)) try: a = g.get_value() except: - print g, "has not get_value() method" - raise RuntimeError + raise RuntimeError("{}, has not get_value() method".format(g)) diff --git a/Examples/test-suite/python/template_typedef_cplx_runme.py b/Examples/test-suite/python/template_typedef_cplx_runme.py index 1846739eb..69d5642d6 100644 --- a/Examples/test-suite/python/template_typedef_cplx_runme.py +++ b/Examples/test-suite/python/template_typedef_cplx_runme.py @@ -8,25 +8,21 @@ try: d = make_Identity_double() a = d.this except: - print d, "is not an instance" - raise RuntimeError + raise RuntimeError("{} is not an instance".format(d)) s = "%s" % d if str.find(s, "ArithUnaryFunction") == -1: - print d, "is not an ArithUnaryFunction" - raise RuntimeError + raise RuntimeError("{} is not an ArithUnaryFunction".format(d)) try: e = make_Multiplies_double_double_double_double(d, d) a = e.this except: - print e, "is not an instance" - raise RuntimeError + raise RuntimeError("{} is not an instance".format(e)) s = "%s" % e if str.find(s, "ArithUnaryFunction") == -1: - print e, "is not an ArithUnaryFunction" - raise RuntimeError + raise RuntimeError("{} is not an ArithUnaryFunction".format(e)) # @@ -37,25 +33,21 @@ try: c = make_Identity_complex() a = c.this except: - print c, "is not an instance" - raise RuntimeError + raise RuntimeError("{} is not an instance".format(c)) s = "%s" % c if str.find(s, "ArithUnaryFunction") == -1: - print c, "is not an ArithUnaryFunction" - raise RuntimeError + raise RuntimeError("{} is not an ArithUnaryFunction".format(c)) try: f = make_Multiplies_complex_complex_complex_complex(c, c) a = f.this except: - print f, "is not an instance" - raise RuntimeError + raise RuntimeError("{} is not an instance".format(f)) s = "%s" % f if str.find(s, "ArithUnaryFunction") == -1: - print f, "is not an ArithUnaryFunction" - raise RuntimeError + raise RuntimeError("{} is not an ArithUnaryFunction".format(f)) # # Mix case @@ -65,23 +57,19 @@ try: g = make_Multiplies_double_double_complex_complex(d, c) a = g.this except: - print g, "is not an instance" - raise RuntimeError + raise RuntimeError("{} is not an instance".format(g)) s = "%s" % g if str.find(s, "ArithUnaryFunction") == -1: - print g, "is not an ArithUnaryFunction" - raise RuntimeError + raise RuntimeError("{} is not an ArithUnaryFunction".format(g)) try: h = make_Multiplies_complex_complex_double_double(c, d) a = h.this except: - print h, "is not an instance" - raise RuntimeError + raise RuntimeError("{} is not an instance".format(h)) s = "%s" % h if str.find(s, "ArithUnaryFunction") == -1: - print h, "is not an ArithUnaryFunction" - raise RuntimeError + raise RuntimeError("{} is not an ArithUnaryFunction".format(h)) diff --git a/Examples/test-suite/python/template_typedef_runme.py b/Examples/test-suite/python/template_typedef_runme.py index 16695bada..5723e4f59 100644 --- a/Examples/test-suite/python/template_typedef_runme.py +++ b/Examples/test-suite/python/template_typedef_runme.py @@ -14,22 +14,19 @@ try: e = make_Multiplies_float_float_float_float(d, d) a = e.this except: - print e, "is not an instance" - raise RuntimeError + raise RuntimeError("{} is not an instance".format(e)) try: f = make_Multiplies_reald_reald_reald_reald(c, c) a = f.this except: - print f, "is not an instance" - raise RuntimeError + raise RuntimeError("{} is not an instance".format(f)) try: g = make_Multiplies_float_float_reald_reald(d, c) a = g.this except: - print g, "is not an instance" - raise RuntimeError + raise RuntimeError("{} is not an instance".format(g)) # the old large format diff --git a/Examples/test-suite/python/template_typemaps_typedef2_runme.py b/Examples/test-suite/python/template_typemaps_typedef2_runme.py index 258f44366..da26a9f76 100644 --- a/Examples/test-suite/python/template_typemaps_typedef2_runme.py +++ b/Examples/test-suite/python/template_typemaps_typedef2_runme.py @@ -5,7 +5,7 @@ m1 = MultimapIntA() dummy_pair = m1.make_dummy_pair() val = m1.typemap_test(dummy_pair).val if val != 1234: - raise RuntimeError, "typemaps not working" + raise RuntimeError("typemaps not working") m2 = MultimapAInt() @@ -13,24 +13,24 @@ m2 = MultimapAInt() #dummy_pair = m2.make_dummy_pair() #val = m2.typemap_test(dummy_pair) -# print val +# print("{}".format(val)) # if val != 4321: # raise RuntimeError, "typemaps not working" if typedef_test1(dummy_pair).val != 1234: - raise RuntimeError, "typedef_test1 not working" + raise RuntimeError("typedef_test1 not working") if typedef_test2(dummy_pair).val != 1234: - raise RuntimeError, "typedef_test2 not working" + raise RuntimeError("typedef_test2 not working") if typedef_test3(dummy_pair).val != 1234: - raise RuntimeError, "typedef_test3 not working" + raise RuntimeError("typedef_test3 not working") if typedef_test4(dummy_pair).val != 1234: - raise RuntimeError, "typedef_test4 not working" + raise RuntimeError("typedef_test4 not working") if typedef_test5(dummy_pair).val != 1234: - raise RuntimeError, "typedef_test5 not working" + raise RuntimeError("typedef_test5 not working") if typedef_test6(dummy_pair).val != 1234: - raise RuntimeError, "typedef_test6 not working" + 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 1ca3f835c..a5209b71f 100644 --- a/Examples/test-suite/python/template_typemaps_typedef_runme.py +++ b/Examples/test-suite/python/template_typemaps_typedef_runme.py @@ -5,7 +5,7 @@ m1 = MultimapIntA() dummy_pair = m1.make_dummy_pair() val = m1.typemap_test(dummy_pair).val if val != 1234: - raise RuntimeError, "typemaps not working" + raise RuntimeError("typemaps not working") m2 = MultimapAInt() @@ -13,24 +13,24 @@ m2 = MultimapAInt() #dummy_pair = m2.make_dummy_pair() #val = m2.typemap_test(dummy_pair) -# print val +# print("{}".format(val)) # if val != 4321: # raise RuntimeError, "typemaps not working" if typedef_test1(dummy_pair).val != 1234: - raise RuntimeError, "typedef_test1 not working" + raise RuntimeError("typedef_test1 not working") if typedef_test2(dummy_pair).val != 1234: - raise RuntimeError, "typedef_test2 not working" + raise RuntimeError("typedef_test2 not working") if typedef_test3(dummy_pair).val != 1234: - raise RuntimeError, "typedef_test3 not working" + raise RuntimeError("typedef_test3 not working") if typedef_test4(dummy_pair).val != 1234: - raise RuntimeError, "typedef_test4 not working" + raise RuntimeError("typedef_test4 not working") if typedef_test5(dummy_pair).val != 1234: - raise RuntimeError, "typedef_test5 not working" + raise RuntimeError("typedef_test5 not working") if typedef_test6(dummy_pair).val != 1234: - raise RuntimeError, "typedef_test6 not working" + 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 056bd849b..e3f6299e7 100644 --- a/Examples/test-suite/python/threads_exception_runme.py +++ b/Examples/test-suite/python/threads_exception_runme.py @@ -3,18 +3,18 @@ import threads_exception t = threads_exception.Test() try: t.unknown() -except RuntimeError, e: +except RuntimeError as e: pass try: t.simple() -except RuntimeError, e: +except RuntimeError as e: if e.args[0] != 37: raise RuntimeError try: t.message() -except RuntimeError, e: +except RuntimeError as e: if e.args[0] != "I died.": raise RuntimeError @@ -23,18 +23,18 @@ except RuntimeError, e: if not threads_exception.is_python_builtin(): try: t.hosed() - except threads_exception.Exc, e: + except threads_exception.Exc as e: code = e.code if code != 42: - raise RuntimeError, "bad... code: %d" % code + raise RuntimeError("bad... code: %d" % code) msg = e.msg if msg != "Hosed": - raise RuntimeError, "bad... msg: '%s' len: %d" % (msg, len(msg)) + raise RuntimeError("bad... msg: '%s' len: %d" % (msg, len(msg))) for i in range(1, 4): try: t.multi(i) - except RuntimeError, e: + except RuntimeError as e: pass - except threads_exception.Exc, e: + except threads_exception.Exc as e: pass diff --git a/Examples/test-suite/python/typedef_inherit_runme.py b/Examples/test-suite/python/typedef_inherit_runme.py index 6b7f2d872..3c552ec65 100644 --- a/Examples/test-suite/python/typedef_inherit_runme.py +++ b/Examples/test-suite/python/typedef_inherit_runme.py @@ -5,19 +5,19 @@ b = typedef_inherit.Bar() x = typedef_inherit.do_blah(a) if x != "Foo::blah": - print "Whoa! Bad return", x + raise RuntimeError("Whoa! Bad return {}".format(x)) x = typedef_inherit.do_blah(b) if x != "Bar::blah": - print "Whoa! Bad return", x + raise RuntimeError("Whoa! Bad return {}".format(x)) c = typedef_inherit.Spam() d = typedef_inherit.Grok() x = typedef_inherit.do_blah2(c) if x != "Spam::blah": - print "Whoa! Bad return", x + raise RuntimeError("Whoa! Bad return {}".format(x)) x = typedef_inherit.do_blah2(d) if x != "Grok::blah": - print "Whoa! Bad return", x + raise RuntimeError("Whoa! Bad return {}".format(x)) diff --git a/Examples/test-suite/python/typedef_scope_runme.py b/Examples/test-suite/python/typedef_scope_runme.py index edd3e9f3a..0294c4a07 100644 --- a/Examples/test-suite/python/typedef_scope_runme.py +++ b/Examples/test-suite/python/typedef_scope_runme.py @@ -3,8 +3,8 @@ import typedef_scope b = typedef_scope.Bar() x = b.test1(42, "hello") if x != 42: - print "Failed!!" + raise RuntimeError("Failed!!") x = b.test2(42, "hello") if x != "hello": - print "Failed!!" + raise RuntimeError("Failed!!") diff --git a/Examples/test-suite/python/typemap_arrays_runme.py b/Examples/test-suite/python/typemap_arrays_runme.py index ea0f08d6b..7bc45f908 100644 --- a/Examples/test-suite/python/typemap_arrays_runme.py +++ b/Examples/test-suite/python/typemap_arrays_runme.py @@ -1,4 +1,4 @@ from typemap_arrays import * if sumA(None) != 60: - raise RuntimeError, "Sum is wrong" + raise RuntimeError("Sum is wrong") diff --git a/Examples/test-suite/python/typemap_out_optimal_runme.py b/Examples/test-suite/python/typemap_out_optimal_runme.py index c7a34308e..c325ece55 100644 --- a/Examples/test-suite/python/typemap_out_optimal_runme.py +++ b/Examples/test-suite/python/typemap_out_optimal_runme.py @@ -1,4 +1,4 @@ from typemap_out_optimal import * cvar.XX_debug = False -x = XX_create() +x = XX.create() diff --git a/Examples/test-suite/python/typename_runme.py b/Examples/test-suite/python/typename_runme.py index aac936fde..a4f76fc36 100644 --- a/Examples/test-suite/python/typename_runme.py +++ b/Examples/test-suite/python/typename_runme.py @@ -4,8 +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, float): + 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, int): + raise RuntimeError("Wrong return type (IntType)!") diff --git a/Examples/test-suite/python/unicode_strings_runme.py b/Examples/test-suite/python/unicode_strings_runme.py index 4e661f00e..57bd7abca 100644 --- a/Examples/test-suite/python/unicode_strings_runme.py +++ b/Examples/test-suite/python/unicode_strings_runme.py @@ -2,12 +2,8 @@ import sys import unicode_strings -# The 'u' string prefix isn't valid in Python 3.0 - 3.2 and is redundant -# in 3.3+. Since this file is run through 2to3 before testing, though, -# mark this as a unicode string in 2.x so it'll become a str in 3.x. -test_string = u"h\udce9llo w\u00f6rld" - if sys.version_info[0:2] >= (3, 1): + test_string = "h\udce9llo w\u00f6rld" if unicode_strings.non_utf8_c_str() != test_string: raise ValueError("Test comparison mismatch") if unicode_strings.non_utf8_std_string() != test_string: @@ -19,19 +15,24 @@ def check(s1, s2): # Testing SWIG_PYTHON_2_UNICODE flag which allows unicode strings to be passed to C if sys.version_info[0:2] < (3, 0): + # Python 3.0-3.2 results in a SyntaxError when using u"" string literals, so we use a + # convoluted unicode string construction using unicode() and unichr(). + # Conventional Python 2 syntax shown in comments. check(unicode_strings.charstring("hello1"), "hello1") - check(unicode_strings.charstring(str(u"hello2")), "hello2") - check(unicode_strings.charstring(u"hello3"), "hello3") - check(unicode_strings.charstring(unicode("hello4")), "hello4") - unicode_strings.charstring(u"hell\xb05") - unicode_strings.charstring(u"hell\u00f66") - -low_surrogate_string = u"\udcff" -try: + check(unicode_strings.charstring(str(unicode("hello2"))), "hello2") # u"hello2" + check(unicode_strings.charstring(unicode("hello3")), "hello3") # u"hello3" + check(unicode_strings.charstring(str("hello4")), "hello4") + unicode_strings.charstring(unicode("hell" + unichr(0xb0) + "5")) # u"hell\xb05" + unicode_strings.charstring(unicode("hell" + unichr(0x00f6) +"6")) # u"hell\u00f66" + low_surrogate_string = unichr(0xdcff) # u"\udcff" unicode_strings.instring(low_surrogate_string) - # Will succeed with Python 2 -except TypeError, e: - # Python 3 will fail the PyUnicode_AsUTF8String conversion resulting in a TypeError. - # The real error is actually: - # UnicodeEncodeError: 'utf-8' codec can't encode character '\udcff' in position 0: surrogates not allowed - pass +else: + low_surrogate_string = "\udcff" + try: + unicode_strings.instring(low_surrogate_string) + raise RuntimeError("Exception should have been thrown") + except TypeError as e: + # Python 3 will fail the PyUnicode_AsUTF8String conversion resulting in a TypeError. + # The real error is actually: + # UnicodeEncodeError: 'utf-8' codec can't encode character '\udcff' in position 0: surrogates not allowed + pass diff --git a/Examples/test-suite/python/unions_runme.py b/Examples/test-suite/python/unions_runme.py index 387a048c8..5a3ee3b5c 100644 --- a/Examples/test-suite/python/unions_runme.py +++ b/Examples/test-suite/python/unions_runme.py @@ -3,7 +3,6 @@ # union embedded within a struct can be set and read correctly. import unions -import sys import string # Create new instances of SmallStruct and BigStruct for later use @@ -23,28 +22,23 @@ eut.number = 1 eut.uni.small = small Jill1 = eut.uni.small.jill if (Jill1 != 200): - print "Runtime test1 failed. eut.uni.small.jill=", Jill1 - sys.exit(1) + raise RuntimeError("Runtime test1 failed. eut.uni.small.jill={}".format(Jill1)) Num1 = eut.number if (Num1 != 1): - print "Runtime test2 failed. eut.number=", Num1 - sys.exit(1) + raise RuntimeError("Runtime test2 failed. eut.number=".format(Num1)) # Secondly check the BigStruct in EmbeddedUnionTest eut.number = 2 eut.uni.big = big Jack1 = eut.uni.big.jack if (Jack1 != 300): - print "Runtime test3 failed. eut.uni.big.jack=", Jack1 - sys.exit(1) + raise RuntimeError("Runtime test3 failed. eut.uni.big.jack={}".format(Jack1)) Jill2 = eut.uni.big.smallstruct.jill if (Jill2 != 200): - print "Runtime test4 failed. eut.uni.big.smallstruct.jill=", Jill2 - sys.exit(1) + raise RuntimeError("Runtime test4 failed. eut.uni.big.smallstruct.jill={}".format(Jill2)) Num2 = eut.number if (Num2 != 2): - print "Runtime test5 failed. eut.number=", Num2 - sys.exit(1) + raise RuntimeError("Runtime test5 failed. eut.number={}".format(Num2)) diff --git a/Examples/test-suite/python/using_composition_runme.py b/Examples/test-suite/python/using_composition_runme.py index c4f339095..67f72bc2f 100644 --- a/Examples/test-suite/python/using_composition_runme.py +++ b/Examples/test-suite/python/using_composition_runme.py @@ -2,32 +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 038a1686a..7e0912926 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)" + raise RuntimeError("blah(int,int)") if f.blah(3.5, 7.5) != (3.5 + 7.5): - raise RuntimeError, "blah(double,double)" + 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 4fd595968..ccdeece8d 100644 --- a/Examples/test-suite/python/using_inherit_runme.py +++ b/Examples/test-suite/python/using_inherit_runme.py @@ -2,47 +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/using_member_runme.py b/Examples/test-suite/python/using_member_runme.py new file mode 100644 index 000000000..a0ea64888 --- /dev/null +++ b/Examples/test-suite/python/using_member_runme.py @@ -0,0 +1,24 @@ +from using_member import * + +def swig_assert_equal(a, b): + if a != b: + raise RuntimeError(str(a) + " != " + str(b)) + +b = B() +swig_assert_equal(b.get(int(1)), 10) +swig_assert_equal(b.get(float(1)), 20) + +bb = BB() +swig_assert_equal(bb.greater(int(1)), 0) +swig_assert_equal(bb.greater(float(1)), 1) +swig_assert_equal(bb.great(True), 2) + +cc = CC() +swig_assert_equal(cc.greater(int(10)), 0) +swig_assert_equal(cc.greater(float(10)), 1) +swig_assert_equal(cc.greater(True), 20) + +dd = DD() +swig_assert_equal(dd.greater(int(10)), 0) +swig_assert_equal(dd.greater(float(10)), 1) +swig_assert_equal(dd.greaterstill(True), 30) diff --git a/Examples/test-suite/python/using_private_runme.py b/Examples/test-suite/python/using_private_runme.py index 00c9a8d25..9e0a15f12 100644 --- a/Examples/test-suite/python/using_private_runme.py +++ b/Examples/test-suite/python/using_private_runme.py @@ -4,10 +4,10 @@ f = FooBar() f.x = 3 if f.blah(4) != 4: - raise RuntimeError, "blah(int)" + raise RuntimeError("blah(int)") if f.defaulted() != -1: - raise RuntimeError, "defaulted()" + raise RuntimeError("defaulted()") if f.defaulted(222) != 222: - raise RuntimeError, "defaulted(222)" + raise RuntimeError("defaulted(222)") diff --git a/Examples/test-suite/python/using_protected_runme.py b/Examples/test-suite/python/using_protected_runme.py index 525a1cde4..dd477237e 100644 --- a/Examples/test-suite/python/using_protected_runme.py +++ b/Examples/test-suite/python/using_protected_runme.py @@ -4,4 +4,4 @@ f = FooBar() f.x = 3 if f.blah(4) != 4: - raise RuntimeError, "blah(int)" + raise RuntimeError("blah(int)") diff --git a/Examples/test-suite/python/varargs_overload_runme.py b/Examples/test-suite/python/varargs_overload_runme.py index 6f5a70222..ffa763450 100644 --- a/Examples/test-suite/python/varargs_overload_runme.py +++ b/Examples/test-suite/python/varargs_overload_runme.py @@ -1,62 +1,62 @@ import varargs_overload if varargs_overload.vararg_over1("Hello") != "Hello": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") if varargs_overload.vararg_over1(2) != "2": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") if varargs_overload.vararg_over2("Hello") != "Hello": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") if varargs_overload.vararg_over2(2, 2.2) != "2 2.2": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") if varargs_overload.vararg_over3("Hello") != "Hello": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") if varargs_overload.vararg_over3(2, 2.2, "hey") != "2 2.2 hey": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") if varargs_overload.vararg_over4("Hello") != "Hello": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") if varargs_overload.vararg_over4(123) != "123": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") if varargs_overload.vararg_over4("Hello", 123) != "Hello": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") # Same as above but non-vararg function declared first if varargs_overload.vararg_over6("Hello") != "Hello": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") if varargs_overload.vararg_over6(2) != "2": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") if varargs_overload.vararg_over7("Hello") != "Hello": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") if varargs_overload.vararg_over7(2, 2.2) != "2 2.2": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") if varargs_overload.vararg_over8("Hello") != "Hello": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") if varargs_overload.vararg_over8(2, 2.2, "hey") != "2 2.2 hey": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") if varargs_overload.vararg_over9("Hello") != "Hello": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") if varargs_overload.vararg_over9(123) != "123": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") if varargs_overload.vararg_over9("Hello", 123) != "Hello": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") diff --git a/Examples/test-suite/python/varargs_runme.py b/Examples/test-suite/python/varargs_runme.py index 277ea757a..13f85a75f 100644 --- a/Examples/test-suite/python/varargs_runme.py +++ b/Examples/test-suite/python/varargs_runme.py @@ -1,31 +1,35 @@ import varargs if varargs.test("Hello") != "Hello": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") + +vc = varargs.VarargConstructor("Hey there") +if vc.str != "Hey there": + raise RuntimeError("Failed") f = varargs.Foo("Greetings") if f.str != "Greetings": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") if f.test("Hello") != "Hello": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") if varargs.test_def("Hello", 1) != "Hello": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") if varargs.test_def("Hello") != "Hello": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") ### if varargs.test_plenty("Hello") != "Hello": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") if varargs.test_plenty("Hello", 1) != "Hello": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") if varargs.test_plenty("Hello", 1, 2) != "Hello": - raise RuntimeError, "Failed" + raise RuntimeError("Failed") try: varargs.test_plenty("Hello", 1, 2, 3) diff --git a/Examples/test-suite/python/virtual_derivation_runme.py b/Examples/test-suite/python/virtual_derivation_runme.py index 68546c6eb..21014bd02 100644 --- a/Examples/test-suite/python/virtual_derivation_runme.py +++ b/Examples/test-suite/python/virtual_derivation_runme.py @@ -4,4 +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 0df6271ef..6708b6f99 100644 --- a/Examples/test-suite/python/virtual_poly_runme.py +++ b/Examples/test-suite/python/virtual_poly_runme.py @@ -29,10 +29,10 @@ if d.get() != dr.get(): # # 'narrowing' also works # -ddc = virtual_poly.NDouble_narrow(d.nnumber()) +ddc = virtual_poly.NDouble.narrow(d.nnumber()) if d.get() != ddc.get(): raise RuntimeError -dic = virtual_poly.NInt_narrow(i.nnumber()) +dic = virtual_poly.NInt.narrow(i.nnumber()) if i.get() != dic.get(): raise RuntimeError diff --git a/Examples/test-suite/python/voidtest_runme.py b/Examples/test-suite/python/voidtest_runme.py index b16cacf00..dd25b4c25 100644 --- a/Examples/test-suite/python/voidtest_runme.py +++ b/Examples/test-suite/python/voidtest_runme.py @@ -4,7 +4,7 @@ voidtest.globalfunc() f = voidtest.Foo() f.memberfunc() -voidtest.Foo_staticmemberfunc() +voidtest.Foo.staticmemberfunc() def fvoid(): diff --git a/Examples/test-suite/python_annotations_c.i b/Examples/test-suite/python_annotations_c.i new file mode 100644 index 000000000..8ecf4c6b0 --- /dev/null +++ b/Examples/test-suite/python_annotations_c.i @@ -0,0 +1,40 @@ +%module python_annotations_c + +// Tests the C/C++ annotations that were automatically added by using -py3 before swig-4.1.0 +// In swig-4.1.0 and later, the feature below is needed as annotations are no longer generated with -py3 +%feature("python:annotations", "c") mymethod; +%feature("python:annotations", "c") makeT; +%feature("python:annotations", "c") global_ints; + +%inline %{ +namespace Space { +template +struct Template { + void mymethod(int, Template* tt) {} +}; +} +template +Space::Template makeT(int x) { + return Space::Template(); +}; +int *global_ints(int &ri, Space::Template t) { return &ri; } +int *global_overloaded(int &ri) { return &ri; } +int *global_overloaded() { return NULL; } +int *no_annotations(int &ri, const char *c) { return NULL; } +%} +%template(TemplateShort) Space::Template; +%template(MakeShort) makeT; + +%inline %{ +#ifdef SWIGPYTHON_BUILTIN +int is_python_builtin() { return 1; } +#else +int is_python_builtin() { return 0; } +#endif + +#if defined SWIGPYTHON_FASTPROXY +int is_python_fastproxy() { return 1; } +#else +int is_python_fastproxy() { return 0; } +#endif +%} diff --git a/Examples/test-suite/python_flatstaticmethod.i b/Examples/test-suite/python_flatstaticmethod.i new file mode 100644 index 000000000..c0de7d298 --- /dev/null +++ b/Examples/test-suite/python_flatstaticmethod.i @@ -0,0 +1,36 @@ +%module python_flatstaticmethod + +// This testcase tests C++ class static functions when using legacy "flattened" +// staticmethod access, A_bar, as well as the normal staticmethod access, A.bar. + +%callback(1) A::bar; +%feature("kwargs") A::pub; +%feature("autodoc","0") A::func0static; // names +%feature("autodoc","1") A::func1static; // names + types +// special typemap and its docs +%typemap(in) (int c, int d) "$1 = 0; $2 = 0;"; +%typemap(doc,name="hello",type="Tuple") (int c, int d) "hello: int tuple[2]"; + +%inline %{ + struct A { + static int bar(int a) { + return 2*a; + } + static int pub(int a = 1, int b = 0) { + return a + b; + } + static int func0static(A *e, short, int c, int d, double f = 2) { return 0; } + static int func1static(A *e, short, int c, int d, double f = 2) { return 0; } + + static const char *over(int) { return "over:int"; } + static const char *over(double) { return "over:double"; } + static const char *over(char *) { return "over:char *"; } + + static int defargs(int xx = 10, int yy = 20) { return xx + yy; } + }; + + extern "C" int foobar(int a, int (*pf)(int a)) { + return pf(a); + } +%} + diff --git a/Examples/test-suite/r/Makefile.in b/Examples/test-suite/r/Makefile.in index 98835b958..33e9d90da 100644 --- a/Examples/test-suite/r/Makefile.in +++ b/Examples/test-suite/r/Makefile.in @@ -18,7 +18,6 @@ C_TEST_CASES += \ CPP_TEST_CASES += \ r_double_delete \ - r_memory_leak \ r_overload_array \ r_sexp \ r_overload_comma \ diff --git a/Examples/test-suite/r/r_memory_leak_runme.R b/Examples/test-suite/r/exception_memory_leak_runme.R similarity index 77% rename from Examples/test-suite/r/r_memory_leak_runme.R rename to Examples/test-suite/r/exception_memory_leak_runme.R index ef6533aef..1f770420a 100644 --- a/Examples/test-suite/r/r_memory_leak_runme.R +++ b/Examples/test-suite/r/exception_memory_leak_runme.R @@ -1,8 +1,8 @@ clargs <- commandArgs(trailing=TRUE) source(file.path(clargs[1], "unittest.R")) -dyn.load(paste("r_memory_leak", .Platform$dynlib.ext, sep="")) -source("r_memory_leak.R") +dyn.load(paste("exception_memory_leak", .Platform$dynlib.ext, sep="")) +source("exception_memory_leak.R") cacheMetaData(1) a <- Foo(); @@ -13,6 +13,7 @@ unittest(Foo_get_count(), 2); # Normal behaviour invisible(trigger_internal_swig_exception("no problem", a)); unittest(Foo_get_count(), 2); +unittest(Foo_get_freearg_count(), 1); # SWIG exception introduced result <- tryCatch({ trigger_internal_swig_exception("null", b); @@ -24,3 +25,4 @@ result <- tryCatch({ unittest(1,1); }) unittest(Foo_get_count(), 2); +unittest(Foo_get_freearg_count(), 2); diff --git a/Examples/test-suite/r/namespace_struct_runme.R b/Examples/test-suite/r/namespace_struct_runme.R new file mode 100644 index 000000000..f84ef3054 --- /dev/null +++ b/Examples/test-suite/r/namespace_struct_runme.R @@ -0,0 +1,11 @@ +clargs <- commandArgs(trailing=TRUE) +source(file.path(clargs[1], "unittest.R")) + +dyn.load(paste("namespace_struct", .Platform$dynlib.ext, sep="")) +source("namespace_struct.R") +cacheMetaData(1) + +xy = Y() +xy$x = as.integer(2) +xy$y = as.integer(4) +copyToR(xy) diff --git a/Examples/test-suite/r/overload_null_runme.R b/Examples/test-suite/r/overload_null_runme.R index d187a1fbb..13dc0c609 100644 --- a/Examples/test-suite/r/overload_null_runme.R +++ b/Examples/test-suite/r/overload_null_runme.R @@ -34,16 +34,16 @@ unittest(12, o$byconstref2(x)) #unittest(15, o$byval2cpr(NULL)) #unittest(16, o$byval2cpr(x)) -# forward class declaration -unittest(17, o$byval1forwardptr(x)) -unittest(18, o$byval1forwardptr(NULL)) +# fwd class declaration +unittest(17, o$byval1fwdptr(x)) +unittest(18, o$byval1fwdptr(NULL)) -unittest(19, o$byval2forwardptr(NULL)) -unittest(20, o$byval2forwardptr(x)) +unittest(19, o$byval2fwdptr(NULL)) +unittest(20, o$byval2fwdptr(x)) -unittest(21, o$byval1forwardref(x)) +unittest(21, o$byval1fwdref(x)) -unittest(22, o$byval2forwardref(x)) +unittest(22, o$byval2fwdref(x)) q(save="no") diff --git a/Examples/test-suite/register_par.i b/Examples/test-suite/register_par.i index 643841455..3be1c7ea0 100644 --- a/Examples/test-suite/register_par.i +++ b/Examples/test-suite/register_par.i @@ -4,6 +4,18 @@ struct swig_tree; %} +%{ +#if defined(__cplusplus) +#if __cplusplus >= 201703L +/* +Fix for languages that compile C tests as C++: + error: ISO C++17 does not allow ‘register’ storage class specifier [-Werror=register] +*/ +#define register +#endif +#endif +%} + // bug # 924413 %inline { void clear_tree_flags(register struct swig_tree *tp, register int i) {} diff --git a/Examples/test-suite/rename_camel.i b/Examples/test-suite/rename_camel.i index 970bb9215..0f4ae11a1 100644 --- a/Examples/test-suite/rename_camel.i +++ b/Examples/test-suite/rename_camel.i @@ -20,18 +20,14 @@ } -%define SedCmd "%(command:sed -e 's/\([a-z]\)/\U\\1/' -e 's/\(_\)\([a-z]\)/\U\\2/g' <<<)s" %enddef - %rename(CamelCase1) camel_case_1; -%rename(SedCmd) camel_case_2; +%rename("%(camelcase)s") camel_case_2; %rename("%(ctitle)s") camel_case_3; %rename("%(utitle)s") CamelCase_5; -%define awk_cmd "%(command:awk '/^i/{print toupper($1)}' <<<)s" %enddef - -%rename(awk_cmd) ""; +%rename("%(regex:/\\(.*i.*\\)/\\U\\1/)s") ""; %rename("%(title)s",regexmatch$parentNode$type="enum .*") ""; diff --git a/Examples/test-suite/rname.i b/Examples/test-suite/rname.i index 09d6e3e3b..b7cf5d22b 100644 --- a/Examples/test-suite/rname.i +++ b/Examples/test-suite/rname.i @@ -22,7 +22,7 @@ %rename (newname) Space::Base::oldname(double d) const; /* Rename derived class method only */ -%rename (Xfunc) Space::Derived::fn(Base baseValue, Base* basePtr, Base& baseRef); +%rename (Xfunc) Space::Derived::fn1(Base baseValue, Base* basePtr, Base& baseRef); %inline %{ class Bar { @@ -43,14 +43,14 @@ class Base { public: Base(){}; virtual ~Base(){}; - void fn(Base baseValue, Base* basePtr, Base& baseRef){} + void fn1(Base baseValue, Base* basePtr, Base& baseRef){} virtual const char * oldname(double d) const { return "Base"; } }; class Derived : public Base { public: Derived(){} ~Derived(){} - void fn(Base baseValue, Base* basePtr, Base& baseRef){} + void fn1(Base baseValue, Base* basePtr, Base& baseRef){} virtual const char * oldname(double d) const { return "Derived"; } }; } diff --git a/Examples/test-suite/ruby/Makefile.in b/Examples/test-suite/ruby/Makefile.in index 2c59029ec..f982eca1f 100644 --- a/Examples/test-suite/ruby/Makefile.in +++ b/Examples/test-suite/ruby/Makefile.in @@ -84,6 +84,8 @@ ruby_naming.cpptest: SWIGOPT += -autorename run_testcase = \ if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(RUBY) $(RUBYFLAGS) -I$(srcdir):. $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + elif [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*.so ] ; then \ + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(RUBY) $(RUBYFLAGS) -I$(srcdir):. -r$(SCRIPTDIR)/$(SCRIPTPREFIX)$*.so -e '' ; \ fi # Clean diff --git a/Examples/test-suite/ruby/constant_directive_runme.rb b/Examples/test-suite/ruby/constant_directive_runme.rb new file mode 100644 index 000000000..ae6cf4fb3 --- /dev/null +++ b/Examples/test-suite/ruby/constant_directive_runme.rb @@ -0,0 +1,16 @@ +#!/usr/bin/env ruby +# +# This test implementation is directly derived from its Python counterpart. +# + +require 'swig_assert' +require 'constant_directive' + +swig_assert("Constant_directive::TYPE1_CONSTANT1.is_a?(Constant_directive::Type1)", binding) +swig_assert("Constant_directive::getType1Instance().is_a?(Constant_directive::Type1)", binding) + +swig_assert_equal('Constant_directive::TYPE1_CONSTANT1.val', '1', binding) +swig_assert_equal('Constant_directive::TYPE1_CONSTANT2.val', '2', binding) +swig_assert_equal('Constant_directive::TYPE1_CONSTANT3.val', '3', binding) +swig_assert_equal('Constant_directive::TYPE1CONST_CONSTANT1.val', '1', binding) +swig_assert_equal('Constant_directive::TYPE1CPTR_CONSTANT1.val', '1', binding) diff --git a/Examples/test-suite/ruby/contract_runme.rb b/Examples/test-suite/ruby/contract_runme.rb new file mode 100644 index 000000000..df7fd3d8f --- /dev/null +++ b/Examples/test-suite/ruby/contract_runme.rb @@ -0,0 +1,69 @@ +#!/usr/bin/env ruby +# +# This test implementation is directly derived from its Python counterpart. +# + +require 'swig_assert' +require 'contract' + +def swig_assert_runtime_error(msg, type, &block) + begin + yield(block) + raise SwigRubyError.new("#{msg} failed") + rescue RuntimeError => e + reason = e.to_s + if reason =~ /\bcontract violation\b/i && reason =~ /\b#{type}\b/i + # OK + else + raise e + end + end +end + +Contract::test_preassert(1, 2) +swig_assert_runtime_error("Preassertions", "require") { Contract::test_preassert(-1, 3) } + +Contract::test_postassert(3) +swig_assert_runtime_error("Postassertions", "ensure") { Contract::test_postassert(-3) } + +Contract::test_prepost(2, 3) +Contract::test_prepost(5, -4) +swig_assert_runtime_error("Preassertions", "require") { Contract::test_prepost(-3, 4) } +swig_assert_runtime_error("Postassertions", "ensure") { Contract::test_prepost(4, -10) } + +f = Contract::Foo.new +f.test_preassert(4, 5) +swig_assert_runtime_error("Method preassertion", "require") { f.test_preassert(-2, 3) } + +f.test_postassert(4) +swig_assert_runtime_error("Method postassertion", "ensure") { f.test_postassert(-4) } + +f.test_prepost(3, 4) +f.test_prepost(4, -3) +swig_assert_runtime_error("Method preassertion", "require") { f.test_prepost(-4, 2) } +swig_assert_runtime_error("Method postassertion", "ensure") { f.test_prepost(4, -10) } + +Contract::Foo.stest_prepost(4, 0) +swig_assert_runtime_error("Static method preassertion", "require") { Contract::Foo.stest_prepost(-4, 2) } +swig_assert_runtime_error("Static method postassertion", "ensure") { Contract::Foo.stest_prepost(4, -10) } + +b = Contract::Bar.new +swig_assert_runtime_error("Inherited preassertion", "require") { b.test_prepost(2, -4) } + +d = Contract::D.new +swig_assert_runtime_error("Inherited preassertion (D)", "require") { d.foo(-1, 1, 1, 1, 1) } +swig_assert_runtime_error("Inherited preassertion (D)", "require") { d.foo(1, -1, 1, 1, 1) } +swig_assert_runtime_error("Inherited preassertion (D)", "require") { d.foo(1, 1, -1, 1, 1) } +swig_assert_runtime_error("Inherited preassertion (D)", "require") { d.foo(1, 1, 1, -1, 1) } +swig_assert_runtime_error("Inherited preassertion (D)", "require") { d.foo(1, 1, 1, 1, -1) } + +swig_assert_runtime_error("Inherited preassertion (D)", "require") { d.bar(-1, 1, 1, 1, 1) } +swig_assert_runtime_error("Inherited preassertion (D)", "require") { d.bar(1, -1, 1, 1, 1) } +swig_assert_runtime_error("Inherited preassertion (D)", "require") { d.bar(1, 1, -1, 1, 1) } +swig_assert_runtime_error("Inherited preassertion (D)", "require") { d.bar(1, 1, 1, -1, 1) } +swig_assert_runtime_error("Inherited preassertion (D)", "require") { d.bar(1, 1, 1, 1, -1) } + +# namespace +Contract::MyClass.new(1) +swig_assert_runtime_error("Constructor preassertion", "require") { Contract::MyClass.new(0) } + diff --git a/Examples/test-suite/ruby/cpp11_alias_nested_template_scoping_runme.rb b/Examples/test-suite/ruby/cpp11_alias_nested_template_scoping_runme.rb new file mode 100644 index 000000000..c6e2b8559 --- /dev/null +++ b/Examples/test-suite/ruby/cpp11_alias_nested_template_scoping_runme.rb @@ -0,0 +1,23 @@ +#!/usr/bin/env ruby +# +# This test implementation is directly derived from its Java counterpart. +# + +require 'swig_assert' +require 'cpp11_alias_nested_template_scoping' + +ys = Cpp11_alias_nested_template_scoping::Yshort.new +val = ys.create1 +val = ys.create2 +val = ys.create3 +val = ys.create4 +val = ys.create5 +val = ys.create6 +val = ys.create7 + +val = ys.create13 + +val = ys.create15 +val = ys.create16 +val = ys.create17 + diff --git a/Examples/test-suite/ruby/cpp17_nested_namespaces_runme.rb b/Examples/test-suite/ruby/cpp17_nested_namespaces_runme.rb new file mode 100644 index 000000000..e9e841179 --- /dev/null +++ b/Examples/test-suite/ruby/cpp17_nested_namespaces_runme.rb @@ -0,0 +1,24 @@ +#!/usr/bin/env ruby +# +# This test implementation is directly derived from its Java counterpart. +# + +require 'cpp17_nested_namespaces' + +Cpp17_nested_namespaces::A1Struct.new.A1Method +Cpp17_nested_namespaces::B1Struct.new.B1Method +Cpp17_nested_namespaces::C1Struct.new.C1Method + +Cpp17_nested_namespaces.createA1Struct().A1Method +Cpp17_nested_namespaces.createB1Struct().B1Method +Cpp17_nested_namespaces.createC1Struct().C1Method + +Cpp17_nested_namespaces::B2Struct.new.B2Method +Cpp17_nested_namespaces::C2Struct.new.C2Method +Cpp17_nested_namespaces.createB2Struct().B2Method +Cpp17_nested_namespaces.createC2Struct().C2Method + +Cpp17_nested_namespaces::B3Struct.new.B3Method +Cpp17_nested_namespaces::C3Struct.new.C3Method +Cpp17_nested_namespaces.createB3Struct().B3Method +Cpp17_nested_namespaces.createC3Struct().C3Method diff --git a/Examples/test-suite/ruby/cpp_enum_runme.rb b/Examples/test-suite/ruby/cpp_enum_runme.rb new file mode 100644 index 000000000..0a395e0e0 --- /dev/null +++ b/Examples/test-suite/ruby/cpp_enum_runme.rb @@ -0,0 +1,19 @@ +#!/usr/bin/env ruby +# +# This test implementation is directly derived from its Python counterpart. +# + +require 'swig_assert' +require 'cpp_enum' + +f = Cpp_enum::Foo.new +swig_assert_equal('f.hola', 'Cpp_enum::Foo::Hello', binding) + +f.hola = Cpp_enum::Foo::Hi +swig_assert_equal('f.hola', 'Cpp_enum::Foo::Hi', binding) + +f.hola = Cpp_enum::Foo::Hello +swig_assert_equal('f.hola', 'Cpp_enum::Foo::Hello', binding) + +Cpp_enum::hi = Cpp_enum::Hello +swig_assert_equal('Cpp_enum::hi', 'Cpp_enum::Hello', binding) diff --git a/Examples/test-suite/ruby/cpp_static_runme.rb b/Examples/test-suite/ruby/cpp_static_runme.rb new file mode 100644 index 000000000..85bdb7028 --- /dev/null +++ b/Examples/test-suite/ruby/cpp_static_runme.rb @@ -0,0 +1,26 @@ +#!/usr/bin/env ruby +# +# This test implementation is derived from its Python counterpart. +# + +require 'swig_assert' +require 'cpp_static' + +Cpp_static::StaticFunctionTest.static_func() +Cpp_static::StaticFunctionTest.static_func_2(1) +Cpp_static::StaticFunctionTest.static_func_3(1, 2) + +swig_assert_equal("Cpp_static::StaticMemberTest.static_int", "99", binding) +Cpp_static::StaticMemberTest.static_int = 10 +swig_assert_equal("Cpp_static::StaticMemberTest.static_int", "10", binding) + +swig_assert_equal("Cpp_static::StaticBase.statty", "11", binding) +swig_assert_equal("Cpp_static::StaticBase.grab_statty_base", "11", binding) +swig_assert_equal("Cpp_static::StaticDerived.statty", "111", binding) +swig_assert_equal("Cpp_static::StaticDerived.grab_statty_derived", "111", binding) +Cpp_static::StaticBase.statty = 22 +Cpp_static::StaticDerived.statty = 222 +swig_assert_equal("Cpp_static::StaticBase.statty", "22", binding) +swig_assert_equal("Cpp_static::StaticBase.grab_statty_base", "22", binding) +swig_assert_equal("Cpp_static::StaticDerived.statty", "222", binding) +swig_assert_equal("Cpp_static::StaticDerived.grab_statty_derived", "222", binding) diff --git a/Examples/test-suite/ruby/enums_runme.rb b/Examples/test-suite/ruby/enums_runme.rb index cafac25fa..274d59568 100644 --- a/Examples/test-suite/ruby/enums_runme.rb +++ b/Examples/test-suite/ruby/enums_runme.rb @@ -25,10 +25,7 @@ Enums::BAR1 == 0 Enums::BAR2 == 1 EOF -# -# @bug: -# -# swig_assert_each_line( < e + # due to missing import_fragments_a + exception_file = e.respond_to?(:path) ? e.path : e.to_s.sub(/.* -- /, '') +end + +swig_assert(exception_file == "import_fragments_a", + msg: "Loading should have failed due to missing 'import_fragments_a'") + diff --git a/Examples/test-suite/ruby/li_std_functors_runme.rb b/Examples/test-suite/ruby/li_std_functors_runme.rb index 5623d49f0..a2a7c6f3d 100644 --- a/Examples/test-suite/ruby/li_std_functors_runme.rb +++ b/Examples/test-suite/ruby/li_std_functors_runme.rb @@ -63,7 +63,9 @@ def test yield method(:_map), Li_std_functors::Map end -# these should fail and not segfault +# these should fail and not segfault but currently do segfault with Ruby 2.6 +# in GitHub Actions environment +if RUBY_VERSION != '2.6.6' begin Li_std_functors::Set.new('sd') rescue @@ -72,5 +74,4 @@ end test do |proc, container| proc.call(container) end - - +end diff --git a/Examples/test-suite/ruby/li_std_wstring_runme.rb b/Examples/test-suite/ruby/li_std_wstring_runme.rb index 4922d8d90..170f80ebf 100644 --- a/Examples/test-suite/ruby/li_std_wstring_runme.rb +++ b/Examples/test-suite/ruby/li_std_wstring_runme.rb @@ -50,3 +50,10 @@ x = "abc\0def" swig_assert_equal("Li_std_wstring.test_value(x)", "x", binding) swig_assert_equal("Li_std_wstring.test_ccvalue(x)", '"abc"', binding) swig_assert_equal("Li_std_wstring.test_wchar_overload(x)", '"abc"', binding) + +ts = Li_std_wstring::Wchar_test_struct.new +ts.wchar_t_member = h +swig_assert_equal("ts.wchar_t_member", "h", binding) +ts.wchar_t_ptr_member = s +swig_assert_equal("ts.wchar_t_ptr_member", "s", binding) + diff --git a/Examples/test-suite/ruby/multiple_inheritance_abstract_runme.rb b/Examples/test-suite/ruby/multiple_inheritance_abstract_runme.rb new file mode 100644 index 000000000..01e9e6e4e --- /dev/null +++ b/Examples/test-suite/ruby/multiple_inheritance_abstract_runme.rb @@ -0,0 +1,243 @@ +#!/usr/bin/env ruby +# +# This test implementation is directly derived from its Java counterpart. +# + +require 'swig_assert' +require 'multiple_inheritance_abstract' + +# Test base class as a parameter in Ruby + +def jcbase1b(cb1) + cb1.cbase1y +end + +def jabase1(ab1) + ab1.abase1 +end + +def jcbase2(cb2) + cb2.cbase2 +end + +# test Derived1 +d1 = Multiple_inheritance_abstract::Derived1.new +swig_assert_equal('d1.cbase1y', '3', binding, 'Derived1::cbase1y() failed') +swig_assert_equal('d1.cbase2', '4', binding, 'Derived1::cbase2() failed') + +# test Derived2 +d2 = Multiple_inheritance_abstract::Derived2.new +swig_assert_equal('d2.cbase1y', '6', binding, 'Derived2::cbase1y() failed') +swig_assert_equal('d2.abase1', '5', binding, 'Derived2::cbase1y() failed') + +# test Derived3 +d3 = Multiple_inheritance_abstract::Derived3.new +swig_assert_equal('d3.cbase1y', '7', binding, 'Derived3::cbase1y() failed') +swig_assert_equal('d3.cbase2', '8', binding, 'Derived3::cbase2() failed') +swig_assert_equal('d3.abase1', '9', binding, 'Derived3::abase1() failed') + +# test Bottom1 +b1 = Multiple_inheritance_abstract::Bottom1.new +swig_assert_equal('b1.cbase1y', '103', binding, 'Bottom1::cbase1y() failed') +swig_assert_equal('b1.cbase2', '104', binding, 'Bottom1::cbase2() failed') + +# test Bottom2 +b2 = Multiple_inheritance_abstract::Bottom2.new +swig_assert_equal('b2.cbase1y', '206', binding, 'Bottom2::cbase1y() failed') +swig_assert_equal('b2.abase1', '205', binding, 'Bottom2::abase1() failed') + +# test Bottom3 +b3 = Multiple_inheritance_abstract::Bottom3.new +swig_assert_equal('b3.cbase1y', '307', binding, 'Bottom3::cbase1y() failed') +swig_assert_equal('b3.cbase2', '308', binding, 'Bottom3::cbase2() failed') +swig_assert_equal('b3.abase1', '309', binding, 'Bottom3::abase1() failed') + +# test interfaces from C++ classes +cb1 = Multiple_inheritance_abstract::CBase1.new +cb2 = Multiple_inheritance_abstract::CBase2.new +swig_assert_equal('cb1.cbase1y', '1', binding, 'CBase1::cbase1y() failed') +swig_assert_equal('cb2.cbase2', '2', binding, 'CBase2::cbase2() failed') + +# test nspace class as return value +ab1 = d3.cloneit +swig_assert_equal('ab1.abase1', '9', binding, 'Derived3::abase1() through ABase1 failed') + +# test concrete base class as return value +cb6 = d2.cloneit +cb7 = d1.cloneit +swig_assert_equal('cb6.cbase1y', '6', binding, 'Derived2::cbase1y() through CBase1 failed') +swig_assert_equal('cb7.cbase2', '4', binding, 'Derived1:cbase2() through ABase1 failed') + +# test multi inheritance +cb3 = Multiple_inheritance_abstract::Derived1.new +cb4 = Multiple_inheritance_abstract::Derived3.new +cb5 = Multiple_inheritance_abstract::Derived3.new +ab6 = Multiple_inheritance_abstract::Derived2.new +swig_assert_equal('cb3.cbase1y', '3', binding, 'Derived1::cbase1y() through CBase1 failed') +swig_assert_equal('cb4.cbase1y', '7', binding, 'Derived3::cbase1y() through CBase1 failed') +swig_assert_equal('cb5.cbase2', '8', binding, 'Derived3::cbase2() through CBase2 failed') +swig_assert_equal('ab6.abase1', '5', binding, 'Derived2::abase1() through ABase1 failed') + +# test base classes as parameter in Ruby +swig_assert_equal('jcbase1b(d1)', '3', binding, 'jcbase1b() through Derived1 as parameter failed') +swig_assert_equal('jcbase1b(d2)', '6', binding, 'jcbase1b() through Derived2 as parameter failed') +swig_assert_equal('jcbase1b(d3)', '7', binding, 'jcbase1b() through Derived3 as parameter failed') +swig_assert_equal('jcbase2(d1)', '4', binding, 'jcbase2() through Derived1 as parameter failed') +swig_assert_equal('jcbase2(d3)', '8', binding, 'jcbase2() through Derived3 as parameter failed') +swig_assert_equal('jabase1(d2)', '5', binding, 'jabase1() through Derived2 as parameter failed') +swig_assert_equal('jabase1(d3)', '9', binding, 'jabase1() through Derived3 as parameter failed') + +# value parameters +# test CBase1 CBase2 as parameters (note slicing for Derived and Bottom classes) +swig_assert_equal('Multiple_inheritance_abstract::InputValCBase1(d1)', '1', binding, 'InputValCBase1(), Derived1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputValCBase1(d2)', '1', binding, 'InputValCBase1(), Derived2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputValCBase1(d3)', '1', binding, 'InputValCBase1(), Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputValCBase2(d3)', '2', binding, 'InputValCBase2(), Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputValCBase2(d1)', '2', binding, 'InputValCBase2(), Derived1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputValCBase1(cb1)', '1', binding, 'InputValCBase1(), CBase1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputValCBase2(cb2)', '2', binding, 'InputValCBase2(), CBase2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputValCBase1(b1)', '1', binding, 'InputValCBase1(), Bottom1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputValCBase1(b2)', '1', binding, 'InputValCBase1(), Bottom2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputValCBase1(b3)', '1', binding, 'InputValCBase1(), Bottom3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputValCBase2(b3)', '2', binding, 'InputValCBase2(), Bottom3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputValCBase2(b1)', '2', binding, 'InputValCBase2(), Bottom1 as a parameter failed') + +# pointer parameters +# test ABase1 as a parameter +swig_assert_equal('Multiple_inheritance_abstract::InputPtrABase1(d2)', '5', binding, 'InputPtrABase1() through Derived2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputPtrABase1(d3)', '9', binding, 'InputPtrABase1() through Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputPtrABase1(b2)', '205', binding, 'InputPtrABase1() through Bottom2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputPtrABase1(b3)', '309', binding, 'InputPtrABase1() through Bottom3 as a parameter failed') + +# test CBase1 CBase2 as parameters +swig_assert_equal('Multiple_inheritance_abstract::InputPtrCBase1(d1)', '3', binding, 'InputPtrCBase1(), Derived1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputPtrCBase1(d2)', '6', binding, 'InputPtrCBase1(), Derived2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputPtrCBase1(d3)', '7', binding, 'InputPtrCBase1(), Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputPtrCBase2(d3)', '8', binding, 'InputPtrCBase2(), Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputPtrCBase2(d1)', '4', binding, 'InputPtrCBase2(), Derived1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputPtrCBase1(cb1)', '1', binding, 'InputPtrCBase1(), CBase1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputPtrCBase2(cb2)', '2', binding, 'InputPtrCBase2(), CBase2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputPtrCBase1(b1)', '103', binding, 'InputPtrCBase1(), Bottom1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputPtrCBase1(b2)', '206', binding, 'InputPtrCBase1(), Bottom2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputPtrCBase1(b3)', '307', binding, 'InputPtrCBase1(), Bottom3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputPtrCBase2(b3)', '308', binding, 'InputPtrCBase2(), Bottom3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputPtrCBase2(b1)', '104', binding, 'InputPtrCBase2(), Bottom1 as a parameter failed') + +# reference parameters +# test ABase1 as a parameter +swig_assert_equal('Multiple_inheritance_abstract::InputRefABase1(d2)', '5', binding, 'InputRefABase1() through Derived2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputRefABase1(d3)', '9', binding, 'InputRefABase1() through Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputRefABase1(b2)', '205', binding, 'InputRefABase1() through Bottom2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputRefABase1(b3)', '309', binding, 'InputRefABase1() through Bottom3 as a parameter failed') + +# test CBase1 CBase2 as parameters +swig_assert_equal('Multiple_inheritance_abstract::InputRefCBase1(d1)', '3', binding, 'InputRefCBase1(), Derived1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputRefCBase1(d2)', '6', binding, 'InputRefCBase1(), Derived2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputRefCBase1(d3)', '7', binding, 'InputRefCBase1(), Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputRefCBase2(d3)', '8', binding, 'InputRefCBase2(), Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputRefCBase2(d1)', '4', binding, 'InputRefCBase2(), Derived1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputRefCBase1(cb1)', '1', binding, 'InputRefCBase1(), CBase1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputRefCBase2(cb2)', '2', binding, 'InputRefCBase2(), CBase2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputRefCBase1(b1)', '103', binding, 'InputRefCBase1(), Bottom1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputRefCBase1(b2)', '206', binding, 'InputRefCBase1(), Bottom2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputRefCBase1(b3)', '307', binding, 'InputRefCBase1(), Bottom3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputRefCBase2(b3)', '308', binding, 'InputRefCBase2(), Bottom3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputRefCBase2(b1)', '104', binding, 'InputRefCBase2(), Bottom1 as a parameter failed') + +# const reference pointer parameters +# test ABase1 as a parameter +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefABase1(d2)', '5', binding, 'InputCPtrRefABase1() through Derived2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefABase1(d3)', '9', binding, 'InputCPtrRefABase1() through Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefABase1(b2)', '205', binding, 'InputCPtrRefABase1() through Bottom2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefABase1(b3)', '309', binding, 'InputCPtrRefABase1() through Bottom3 as a parameter failed') + +# test CBase1 CBase2 as parameters +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefCBase1(d1)', '3', binding, 'InputCPtrRefCBase1(), Derived1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefCBase1(d2)', '6', binding, 'InputCPtrRefCBase1(), Derived2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefCBase1(d3)', '7', binding, 'InputCPtrRefCBase1(), Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefCBase2(d3)', '8', binding, 'InputCPtrRefCBase2(), Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefCBase2(d1)', '4', binding, 'InputCPtrRefCBase2(), Derived1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefCBase1(cb1)', '1', binding, 'InputCPtrRefCBase1(), CBase1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefCBase2(cb2)', '2', binding, 'InputCPtrRefCBase2(), CBase2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefCBase1(b1)', '103', binding, 'InputCPtrRefCBase1(), Bottom1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefCBase1(b2)', '206', binding, 'InputCPtrRefCBase1(), Bottom2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefCBase1(b3)', '307', binding, 'InputCPtrRefCBase1(), Bottom3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefCBase2(b3)', '308', binding, 'InputCPtrRefCBase2(), Bottom3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefCBase2(b1)', '104', binding, 'InputCPtrRefCBase2(), Bottom1 as a parameter failed') + +# derived classes as parameters +swig_assert_equal('Multiple_inheritance_abstract::InputValDerived1(d1)', '3+4', binding, 'InputValDerived1() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputValDerived2(d2)', '6+5', binding, 'InputValDerived2() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputValDerived3(d3)', '7+8+9', binding, 'InputValDerived3() failed') + +swig_assert_equal('Multiple_inheritance_abstract::InputRefDerived1(d1)', '3+4', binding, 'InputRefDerived1() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputRefDerived2(d2)', '6+5', binding, 'InputRefDerived2() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputRefDerived3(d3)', '7+8+9', binding, 'InputRefDerived3() failed') + +swig_assert_equal('Multiple_inheritance_abstract::InputPtrDerived1(d1)', '3+4', binding, 'InputPtrDerived1() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputPtrDerived2(d2)', '6+5', binding, 'InputPtrDerived2() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputPtrDerived3(d3)', '7+8+9', binding, 'InputPtrDerived3() failed') + +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefDerived1(d1)', '3+4', binding, 'InputCPtrRefDerived1() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefDerived2(d2)', '6+5', binding, 'InputCPtrRefDerived2() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefDerived3(d3)', '7+8+9', binding, 'InputCPtrRefDerived3() failed') + +# bottom classes as Derived parameters +swig_assert_equal('Multiple_inheritance_abstract::InputValDerived1(b1)', '3+4', binding, 'InputValDerived1() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputValDerived2(b2)', '6+5', binding, 'InputValDerived2() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputValDerived3(b3)', '7+8+9', binding, 'InputValDerived3() failed') + +swig_assert_equal('Multiple_inheritance_abstract::InputRefDerived1(b1)', '103+104', binding, 'InputRefDerived1() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputRefDerived2(b2)', '206+205', binding, 'InputRefDerived2() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputRefDerived3(b3)', '307+308+309', binding, 'InputRefDerived3() failed') + +swig_assert_equal('Multiple_inheritance_abstract::InputPtrDerived1(b1)', '103+104', binding, 'InputPtrDerived1() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputPtrDerived2(b2)', '206+205', binding, 'InputPtrDerived2() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputPtrDerived3(b3)', '307+308+309', binding, 'InputPtrDerived3() failed') + +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefDerived1(b1)', '103+104', binding, 'InputCPtrRefDerived1() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefDerived2(b2)', '206+205', binding, 'InputCPtrRefDerived2() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefDerived3(b3)', '307+308+309', binding, 'InputCPtrRefDerived3() failed') + +# bottom classes as Bottom parameters +swig_assert_equal('Multiple_inheritance_abstract::InputValBottom1(b1)', '103+104', binding, 'InputValBottom1() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputValBottom2(b2)', '206+205', binding, 'InputValBottom2() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputValBottom3(b3)', '307+308+309', binding, 'InputValBottom3() failed') + +swig_assert_equal('Multiple_inheritance_abstract::InputRefBottom1(b1)', '103+104', binding, 'InputRefBottom1() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputRefBottom2(b2)', '206+205', binding, 'InputRefBottom2() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputRefBottom3(b3)', '307+308+309', binding, 'InputRefBottom3() failed') + +swig_assert_equal('Multiple_inheritance_abstract::InputPtrBottom1(b1)', '103+104', binding, 'InputPtrBottom1() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputPtrBottom2(b2)', '206+205', binding, 'InputPtrBottom2() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputPtrBottom3(b3)', '307+308+309', binding, 'InputPtrBottom3() failed') + +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefBottom1(b1)', '103+104', binding, 'InputCPtrRefBottom1() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefBottom2(b2)', '206+205', binding, 'InputCPtrRefBottom2() failed') +swig_assert_equal('Multiple_inheritance_abstract::InputCPtrRefBottom3(b3)', '307+308+309', binding, 'InputCPtrRefBottom3() failed') + +# return pointers +swig_assert_equal('Multiple_inheritance_abstract::MakePtrDerived1_CBase1().cbase1y', '3', binding, 'MakePtrDerived1_CBase1 failed') +swig_assert_equal('Multiple_inheritance_abstract::MakePtrDerived1_CBase2().cbase2', '4', binding, 'MakePtrDerived1_CBase2 failed') +swig_assert_equal('Multiple_inheritance_abstract::MakePtrDerived2_CBase1().cbase1y', '6', binding, 'MakePtrDerived2_CBase1 failed') +swig_assert_equal('Multiple_inheritance_abstract::MakePtrDerived2_ABase1().abase1', '5', binding, 'MakePtrDerived2_ABase1 failed') +swig_assert_equal('Multiple_inheritance_abstract::MakePtrDerived3_ABase1().abase1', '9', binding, 'MakePtrDerived3_ABase1 failed') +swig_assert_equal('Multiple_inheritance_abstract::MakePtrDerived3_CBase1().cbase1y', '7', binding, 'MakePtrDerived3_CBase1 failed') +swig_assert_equal('Multiple_inheritance_abstract::MakePtrDerived3_CBase2().cbase2', '8', binding, 'MakePtrDerived3_CBase2 failed') + +# return references +swig_assert_equal('Multiple_inheritance_abstract::MakeRefDerived1_CBase1().cbase1y', '3', binding, 'MakeRefDerived1_CBase1 failed') +swig_assert_equal('Multiple_inheritance_abstract::MakeRefDerived1_CBase2().cbase2', '4', binding, 'MakeRefDerived1_CBase2 failed') +swig_assert_equal('Multiple_inheritance_abstract::MakeRefDerived2_CBase1().cbase1y', '6', binding, 'MakeRefDerived2_CBase1 failed') +swig_assert_equal('Multiple_inheritance_abstract::MakeRefDerived2_ABase1().abase1', '5', binding, 'MakeRefDerived2_ABase1 failed') +swig_assert_equal('Multiple_inheritance_abstract::MakeRefDerived3_ABase1().abase1', '9', binding, 'MakeRefDerived3_ABase1 failed') +swig_assert_equal('Multiple_inheritance_abstract::MakeRefDerived3_CBase1().cbase1y', '7', binding, 'MakeRefDerived3_CBase1 failed') +swig_assert_equal('Multiple_inheritance_abstract::MakeRefDerived3_CBase2().cbase2', '8', binding, 'MakeRefDerived3_CBase2 failed') + +# return by value (sliced objects) +swig_assert_equal('Multiple_inheritance_abstract::MakeValDerived1_CBase1().cbase1y', '1', binding, 'MakeValDerived1_CBase1 failed') +swig_assert_equal('Multiple_inheritance_abstract::MakeValDerived1_CBase2().cbase2', '2', binding, 'MakeValDerived1_CBase2 failed') +swig_assert_equal('Multiple_inheritance_abstract::MakeValDerived2_CBase1().cbase1y', '1', binding, 'MakeValDerived2_CBase1 failed') +swig_assert_equal('Multiple_inheritance_abstract::MakeValDerived3_CBase1().cbase1y', '1', binding, 'MakeValDerived3_CBase1 failed') +swig_assert_equal('Multiple_inheritance_abstract::MakeValDerived3_CBase2().cbase2', '2', binding, 'MakeValDerived3_CBase2 failed') + diff --git a/Examples/test-suite/ruby/multiple_inheritance_nspace_runme.rb b/Examples/test-suite/ruby/multiple_inheritance_nspace_runme.rb new file mode 100644 index 000000000..fb28a0f83 --- /dev/null +++ b/Examples/test-suite/ruby/multiple_inheritance_nspace_runme.rb @@ -0,0 +1,243 @@ +#!/usr/bin/env ruby +# +# This test implementation is directly derived from its Java counterpart. +# + +require 'swig_assert' +require 'multiple_inheritance_nspace' + +# Test base class as a parameter in Ruby + +def jcbase1b(cb1) + cb1.cbase1y +end + +def jabase1(ab1) + ab1.abase1 +end + +def jcbase2(cb2) + cb2.cbase2 +end + +# test Derived1 +d1 = Multiple_inheritance_nspace::Derived1.new +swig_assert_equal('d1.cbase1y', '3', binding, 'Derived1::cbase1y() failed') +swig_assert_equal('d1.cbase2', '4', binding, 'Derived1::cbase2() failed') + +# test Derived2 +d2 = Multiple_inheritance_nspace::Derived2.new +swig_assert_equal('d2.cbase1y', '6', binding, 'Derived2::cbase1y() failed') +swig_assert_equal('d2.abase1', '5', binding, 'Derived2::cbase1y() failed') + +# test Derived3 +d3 = Multiple_inheritance_nspace::Derived3.new +swig_assert_equal('d3.cbase1y', '7', binding, 'Derived3::cbase1y() failed') +swig_assert_equal('d3.cbase2', '8', binding, 'Derived3::cbase2() failed') +swig_assert_equal('d3.abase1', '9', binding, 'Derived3::abase1() failed') + +# test Bottom1 +b1 = Multiple_inheritance_nspace::Bottom1.new +swig_assert_equal('b1.cbase1y', '103', binding, 'Bottom1::cbase1y() failed') +swig_assert_equal('b1.cbase2', '104', binding, 'Bottom1::cbase2() failed') + +# test Bottom2 +b2 = Multiple_inheritance_nspace::Bottom2.new +swig_assert_equal('b2.cbase1y', '206', binding, 'Bottom2::cbase1y() failed') +swig_assert_equal('b2.abase1', '205', binding, 'Bottom2::abase1() failed') + +# test Bottom3 +b3 = Multiple_inheritance_nspace::Bottom3.new +swig_assert_equal('b3.cbase1y', '307', binding, 'Bottom3::cbase1y() failed') +swig_assert_equal('b3.cbase2', '308', binding, 'Bottom3::cbase2() failed') +swig_assert_equal('b3.abase1', '309', binding, 'Bottom3::abase1() failed') + +# test interfaces from C++ classes +cb1 = Multiple_inheritance_nspace::CBase1.new +cb2 = Multiple_inheritance_nspace::CBase2.new +swig_assert_equal('cb1.cbase1y', '1', binding, 'CBase1::cbase1y() failed') +swig_assert_equal('cb2.cbase2', '2', binding, 'CBase2::cbase2() failed') + +# test nspace class as return value +ab1 = d3.cloneit +swig_assert_equal('ab1.abase1', '9', binding, 'Derived3::abase1() through ABase1 failed') + +# test concrete base class as return value +cb6 = d2.cloneit +cb7 = d1.cloneit +swig_assert_equal('cb6.cbase1y', '6', binding, 'Derived2::cbase1y() through CBase1 failed') +swig_assert_equal('cb7.cbase2', '4', binding, 'Derived1:cbase2() through ABase1 failed') + +# test multi inheritance +cb3 = Multiple_inheritance_nspace::Derived1.new +cb4 = Multiple_inheritance_nspace::Derived3.new +cb5 = Multiple_inheritance_nspace::Derived3.new +ab6 = Multiple_inheritance_nspace::Derived2.new +swig_assert_equal('cb3.cbase1y', '3', binding, 'Derived1::cbase1y() through CBase1 failed') +swig_assert_equal('cb4.cbase1y', '7', binding, 'Derived3::cbase1y() through CBase1 failed') +swig_assert_equal('cb5.cbase2', '8', binding, 'Derived3::cbase2() through CBase2 failed') +swig_assert_equal('ab6.abase1', '5', binding, 'Derived2::abase1() through ABase1 failed') + +# test base classes as parameter in Ruby +swig_assert_equal('jcbase1b(d1)', '3', binding, 'jcbase1b() through Derived1 as parameter failed') +swig_assert_equal('jcbase1b(d2)', '6', binding, 'jcbase1b() through Derived2 as parameter failed') +swig_assert_equal('jcbase1b(d3)', '7', binding, 'jcbase1b() through Derived3 as parameter failed') +swig_assert_equal('jcbase2(d1)', '4', binding, 'jcbase2() through Derived1 as parameter failed') +swig_assert_equal('jcbase2(d3)', '8', binding, 'jcbase2() through Derived3 as parameter failed') +swig_assert_equal('jabase1(d2)', '5', binding, 'jabase1() through Derived2 as parameter failed') +swig_assert_equal('jabase1(d3)', '9', binding, 'jabase1() through Derived3 as parameter failed') + +# value parameters +# test CBase1 CBase2 as parameters (note slicing for Derived and Bottom classes) +swig_assert_equal('Multiple_inheritance_nspace::InputValCBase1(d1)', '1', binding, 'InputValCBase1(), Derived1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputValCBase1(d2)', '1', binding, 'InputValCBase1(), Derived2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputValCBase1(d3)', '1', binding, 'InputValCBase1(), Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputValCBase2(d3)', '2', binding, 'InputValCBase2(), Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputValCBase2(d1)', '2', binding, 'InputValCBase2(), Derived1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputValCBase1(cb1)', '1', binding, 'InputValCBase1(), CBase1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputValCBase2(cb2)', '2', binding, 'InputValCBase2(), CBase2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputValCBase1(b1)', '1', binding, 'InputValCBase1(), Bottom1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputValCBase1(b2)', '1', binding, 'InputValCBase1(), Bottom2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputValCBase1(b3)', '1', binding, 'InputValCBase1(), Bottom3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputValCBase2(b3)', '2', binding, 'InputValCBase2(), Bottom3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputValCBase2(b1)', '2', binding, 'InputValCBase2(), Bottom1 as a parameter failed') + +# pointer parameters +# test ABase1 as a parameter +swig_assert_equal('Multiple_inheritance_nspace::InputPtrABase1(d2)', '5', binding, 'InputPtrABase1() through Derived2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputPtrABase1(d3)', '9', binding, 'InputPtrABase1() through Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputPtrABase1(b2)', '205', binding, 'InputPtrABase1() through Bottom2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputPtrABase1(b3)', '309', binding, 'InputPtrABase1() through Bottom3 as a parameter failed') + +# test CBase1 CBase2 as parameters +swig_assert_equal('Multiple_inheritance_nspace::InputPtrCBase1(d1)', '3', binding, 'InputPtrCBase1(), Derived1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputPtrCBase1(d2)', '6', binding, 'InputPtrCBase1(), Derived2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputPtrCBase1(d3)', '7', binding, 'InputPtrCBase1(), Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputPtrCBase2(d3)', '8', binding, 'InputPtrCBase2(), Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputPtrCBase2(d1)', '4', binding, 'InputPtrCBase2(), Derived1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputPtrCBase1(cb1)', '1', binding, 'InputPtrCBase1(), CBase1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputPtrCBase2(cb2)', '2', binding, 'InputPtrCBase2(), CBase2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputPtrCBase1(b1)', '103', binding, 'InputPtrCBase1(), Bottom1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputPtrCBase1(b2)', '206', binding, 'InputPtrCBase1(), Bottom2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputPtrCBase1(b3)', '307', binding, 'InputPtrCBase1(), Bottom3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputPtrCBase2(b3)', '308', binding, 'InputPtrCBase2(), Bottom3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputPtrCBase2(b1)', '104', binding, 'InputPtrCBase2(), Bottom1 as a parameter failed') + +# reference parameters +# test ABase1 as a parameter +swig_assert_equal('Multiple_inheritance_nspace::InputRefABase1(d2)', '5', binding, 'InputRefABase1() through Derived2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputRefABase1(d3)', '9', binding, 'InputRefABase1() through Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputRefABase1(b2)', '205', binding, 'InputRefABase1() through Bottom2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputRefABase1(b3)', '309', binding, 'InputRefABase1() through Bottom3 as a parameter failed') + +# test CBase1 CBase2 as parameters +swig_assert_equal('Multiple_inheritance_nspace::InputRefCBase1(d1)', '3', binding, 'InputRefCBase1(), Derived1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputRefCBase1(d2)', '6', binding, 'InputRefCBase1(), Derived2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputRefCBase1(d3)', '7', binding, 'InputRefCBase1(), Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputRefCBase2(d3)', '8', binding, 'InputRefCBase2(), Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputRefCBase2(d1)', '4', binding, 'InputRefCBase2(), Derived1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputRefCBase1(cb1)', '1', binding, 'InputRefCBase1(), CBase1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputRefCBase2(cb2)', '2', binding, 'InputRefCBase2(), CBase2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputRefCBase1(b1)', '103', binding, 'InputRefCBase1(), Bottom1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputRefCBase1(b2)', '206', binding, 'InputRefCBase1(), Bottom2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputRefCBase1(b3)', '307', binding, 'InputRefCBase1(), Bottom3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputRefCBase2(b3)', '308', binding, 'InputRefCBase2(), Bottom3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputRefCBase2(b1)', '104', binding, 'InputRefCBase2(), Bottom1 as a parameter failed') + +# const reference pointer parameters +# test ABase1 as a parameter +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefABase1(d2)', '5', binding, 'InputCPtrRefABase1() through Derived2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefABase1(d3)', '9', binding, 'InputCPtrRefABase1() through Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefABase1(b2)', '205', binding, 'InputCPtrRefABase1() through Bottom2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefABase1(b3)', '309', binding, 'InputCPtrRefABase1() through Bottom3 as a parameter failed') + +# test CBase1 CBase2 as parameters +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefCBase1(d1)', '3', binding, 'InputCPtrRefCBase1(), Derived1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefCBase1(d2)', '6', binding, 'InputCPtrRefCBase1(), Derived2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefCBase1(d3)', '7', binding, 'InputCPtrRefCBase1(), Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefCBase2(d3)', '8', binding, 'InputCPtrRefCBase2(), Derived3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefCBase2(d1)', '4', binding, 'InputCPtrRefCBase2(), Derived1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefCBase1(cb1)', '1', binding, 'InputCPtrRefCBase1(), CBase1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefCBase2(cb2)', '2', binding, 'InputCPtrRefCBase2(), CBase2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefCBase1(b1)', '103', binding, 'InputCPtrRefCBase1(), Bottom1 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefCBase1(b2)', '206', binding, 'InputCPtrRefCBase1(), Bottom2 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefCBase1(b3)', '307', binding, 'InputCPtrRefCBase1(), Bottom3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefCBase2(b3)', '308', binding, 'InputCPtrRefCBase2(), Bottom3 as a parameter failed') +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefCBase2(b1)', '104', binding, 'InputCPtrRefCBase2(), Bottom1 as a parameter failed') + +# derived classes as parameters +swig_assert_equal('Multiple_inheritance_nspace::InputValDerived1(d1)', '3+4', binding, 'InputValDerived1() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputValDerived2(d2)', '6+5', binding, 'InputValDerived2() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputValDerived3(d3)', '7+8+9', binding, 'InputValDerived3() failed') + +swig_assert_equal('Multiple_inheritance_nspace::InputRefDerived1(d1)', '3+4', binding, 'InputRefDerived1() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputRefDerived2(d2)', '6+5', binding, 'InputRefDerived2() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputRefDerived3(d3)', '7+8+9', binding, 'InputRefDerived3() failed') + +swig_assert_equal('Multiple_inheritance_nspace::InputPtrDerived1(d1)', '3+4', binding, 'InputPtrDerived1() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputPtrDerived2(d2)', '6+5', binding, 'InputPtrDerived2() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputPtrDerived3(d3)', '7+8+9', binding, 'InputPtrDerived3() failed') + +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefDerived1(d1)', '3+4', binding, 'InputCPtrRefDerived1() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefDerived2(d2)', '6+5', binding, 'InputCPtrRefDerived2() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefDerived3(d3)', '7+8+9', binding, 'InputCPtrRefDerived3() failed') + +# bottom classes as Derived parameters +swig_assert_equal('Multiple_inheritance_nspace::InputValDerived1(b1)', '3+4', binding, 'InputValDerived1() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputValDerived2(b2)', '6+5', binding, 'InputValDerived2() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputValDerived3(b3)', '7+8+9', binding, 'InputValDerived3() failed') + +swig_assert_equal('Multiple_inheritance_nspace::InputRefDerived1(b1)', '103+104', binding, 'InputRefDerived1() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputRefDerived2(b2)', '206+205', binding, 'InputRefDerived2() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputRefDerived3(b3)', '307+308+309', binding, 'InputRefDerived3() failed') + +swig_assert_equal('Multiple_inheritance_nspace::InputPtrDerived1(b1)', '103+104', binding, 'InputPtrDerived1() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputPtrDerived2(b2)', '206+205', binding, 'InputPtrDerived2() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputPtrDerived3(b3)', '307+308+309', binding, 'InputPtrDerived3() failed') + +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefDerived1(b1)', '103+104', binding, 'InputCPtrRefDerived1() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefDerived2(b2)', '206+205', binding, 'InputCPtrRefDerived2() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefDerived3(b3)', '307+308+309', binding, 'InputCPtrRefDerived3() failed') + +# bottom classes as Bottom parameters +swig_assert_equal('Multiple_inheritance_nspace::InputValBottom1(b1)', '103+104', binding, 'InputValBottom1() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputValBottom2(b2)', '206+205', binding, 'InputValBottom2() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputValBottom3(b3)', '307+308+309', binding, 'InputValBottom3() failed') + +swig_assert_equal('Multiple_inheritance_nspace::InputRefBottom1(b1)', '103+104', binding, 'InputRefBottom1() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputRefBottom2(b2)', '206+205', binding, 'InputRefBottom2() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputRefBottom3(b3)', '307+308+309', binding, 'InputRefBottom3() failed') + +swig_assert_equal('Multiple_inheritance_nspace::InputPtrBottom1(b1)', '103+104', binding, 'InputPtrBottom1() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputPtrBottom2(b2)', '206+205', binding, 'InputPtrBottom2() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputPtrBottom3(b3)', '307+308+309', binding, 'InputPtrBottom3() failed') + +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefBottom1(b1)', '103+104', binding, 'InputCPtrRefBottom1() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefBottom2(b2)', '206+205', binding, 'InputCPtrRefBottom2() failed') +swig_assert_equal('Multiple_inheritance_nspace::InputCPtrRefBottom3(b3)', '307+308+309', binding, 'InputCPtrRefBottom3() failed') + +# return pointers +swig_assert_equal('Multiple_inheritance_nspace::MakePtrDerived1_CBase1().cbase1y', '3', binding, 'MakePtrDerived1_CBase1 failed') +swig_assert_equal('Multiple_inheritance_nspace::MakePtrDerived1_CBase2().cbase2', '4', binding, 'MakePtrDerived1_CBase2 failed') +swig_assert_equal('Multiple_inheritance_nspace::MakePtrDerived2_CBase1().cbase1y', '6', binding, 'MakePtrDerived2_CBase1 failed') +swig_assert_equal('Multiple_inheritance_nspace::MakePtrDerived2_ABase1().abase1', '5', binding, 'MakePtrDerived2_ABase1 failed') +swig_assert_equal('Multiple_inheritance_nspace::MakePtrDerived3_ABase1().abase1', '9', binding, 'MakePtrDerived3_ABase1 failed') +swig_assert_equal('Multiple_inheritance_nspace::MakePtrDerived3_CBase1().cbase1y', '7', binding, 'MakePtrDerived3_CBase1 failed') +swig_assert_equal('Multiple_inheritance_nspace::MakePtrDerived3_CBase2().cbase2', '8', binding, 'MakePtrDerived3_CBase2 failed') + +# return references +swig_assert_equal('Multiple_inheritance_nspace::MakeRefDerived1_CBase1().cbase1y', '3', binding, 'MakeRefDerived1_CBase1 failed') +swig_assert_equal('Multiple_inheritance_nspace::MakeRefDerived1_CBase2().cbase2', '4', binding, 'MakeRefDerived1_CBase2 failed') +swig_assert_equal('Multiple_inheritance_nspace::MakeRefDerived2_CBase1().cbase1y', '6', binding, 'MakeRefDerived2_CBase1 failed') +swig_assert_equal('Multiple_inheritance_nspace::MakeRefDerived2_ABase1().abase1', '5', binding, 'MakeRefDerived2_ABase1 failed') +swig_assert_equal('Multiple_inheritance_nspace::MakeRefDerived3_ABase1().abase1', '9', binding, 'MakeRefDerived3_ABase1 failed') +swig_assert_equal('Multiple_inheritance_nspace::MakeRefDerived3_CBase1().cbase1y', '7', binding, 'MakeRefDerived3_CBase1 failed') +swig_assert_equal('Multiple_inheritance_nspace::MakeRefDerived3_CBase2().cbase2', '8', binding, 'MakeRefDerived3_CBase2 failed') + +# return by value (sliced objects) +swig_assert_equal('Multiple_inheritance_nspace::MakeValDerived1_CBase1().cbase1y', '1', binding, 'MakeValDerived1_CBase1 failed') +swig_assert_equal('Multiple_inheritance_nspace::MakeValDerived1_CBase2().cbase2', '2', binding, 'MakeValDerived1_CBase2 failed') +swig_assert_equal('Multiple_inheritance_nspace::MakeValDerived2_CBase1().cbase1y', '1', binding, 'MakeValDerived2_CBase1 failed') +swig_assert_equal('Multiple_inheritance_nspace::MakeValDerived3_CBase1().cbase1y', '1', binding, 'MakeValDerived3_CBase1 failed') +swig_assert_equal('Multiple_inheritance_nspace::MakeValDerived3_CBase2().cbase2', '2', binding, 'MakeValDerived3_CBase2 failed') + diff --git a/Examples/test-suite/ruby/namespace_chase_runme.rb b/Examples/test-suite/ruby/namespace_chase_runme.rb new file mode 100644 index 000000000..c5f227dfd --- /dev/null +++ b/Examples/test-suite/ruby/namespace_chase_runme.rb @@ -0,0 +1,14 @@ +#!/usr/bin/env ruby +# +# This test implementation is directly derived from its Java counterpart. +# + +require 'swig_assert' +require 'namespace_chase' + +s1a = Namespace_chase::Struct1A.new +s1b = Namespace_chase::Struct1B.new +s1c = Namespace_chase::Struct1C.new + +Namespace_chase.sss3a(s1a, s1b, s1c) +Namespace_chase.sss3b(s1a, s1b, s1c) diff --git a/Examples/test-suite/ruby/namespace_class_runme.rb b/Examples/test-suite/ruby/namespace_class_runme.rb new file mode 100644 index 000000000..fd9345814 --- /dev/null +++ b/Examples/test-suite/ruby/namespace_class_runme.rb @@ -0,0 +1,40 @@ +#!/usr/bin/env ruby +# +# This test implementation is directly derived from its Python counterpart. +# + +require 'swig_assert' +require 'namespace_class' + +begin + p = Namespace_class::Private1.new + raise SwigRubyError.new("Private1 is private") +rescue NameError => e + # OK +end + +begin + p = Namespace_class::Private2.new + raise SwigRubyError.new("Private2 is private") +rescue NameError => e + # OK +end + +Namespace_class::EulerT3D.toFrame(1, 1, 1) + +b = Namespace_class::BooT_i.new +b = Namespace_class::BooT_H.new + + +f = Namespace_class::FooT_i.new +f.quack(1) + +f = Namespace_class::FooT_d.new +f.moo(1) + +f = Namespace_class::FooT_H.new +f.foo(Namespace_class::Hi) + +f_type = f.class.to_s +swig_assert_equal('f_type', '"Namespace_class::FooT_H"', binding) + diff --git a/Examples/test-suite/ruby/namespace_forward_declaration_runme.rb b/Examples/test-suite/ruby/namespace_forward_declaration_runme.rb new file mode 100644 index 000000000..0e6b50eb8 --- /dev/null +++ b/Examples/test-suite/ruby/namespace_forward_declaration_runme.rb @@ -0,0 +1,16 @@ +#!/usr/bin/env ruby +# +# This test implementation is directly derived from its Java counterpart. +# + +require 'swig_assert' +require 'namespace_forward_declaration' + +xxx = Namespace_forward_declaration::XXX.new +Namespace_forward_declaration.testXXX1(xxx) +Namespace_forward_declaration.testXXX2(xxx) +Namespace_forward_declaration.testXXX3(xxx) +yyy = Namespace_forward_declaration::YYY.new +Namespace_forward_declaration.testYYY1(yyy) +Namespace_forward_declaration.testYYY2(yyy) +Namespace_forward_declaration.testYYY3(yyy) diff --git a/Examples/test-suite/ruby/namespace_virtual_method_runme.rb b/Examples/test-suite/ruby/namespace_virtual_method_runme.rb new file mode 100644 index 000000000..54e4a7a21 --- /dev/null +++ b/Examples/test-suite/ruby/namespace_virtual_method_runme.rb @@ -0,0 +1,8 @@ +#!/usr/bin/env ruby +# +# This test implementation is directly derived from its Python counterpart. +# + +require 'namespace_virtual_method' + +x = Namespace_virtual_method::Spam.new diff --git a/Examples/test-suite/ruby/nested_class_runme.rb b/Examples/test-suite/ruby/nested_class_runme.rb new file mode 100644 index 000000000..2cf3bf96a --- /dev/null +++ b/Examples/test-suite/ruby/nested_class_runme.rb @@ -0,0 +1,54 @@ +#!/usr/bin/env ruby +# +# This test implementation is directly derived from its Java counterpart. +# + +require 'swig_assert' +require 'nested_class' + +outer = Nested_class::Outer.new +is1 = outer.makeInnerStruct1 +ic1 = outer.makeInnerClass1 +iu1 = outer.makeInnerUnion1 + +is2 = outer.makeInnerStruct2 +ic2 = outer.makeInnerClass2 +iu2 = outer.makeInnerUnion2 + +ic4 = outer.makeInnerClass4Typedef +is4 = outer.makeInnerStruct4Typedef +iu4 = outer.makeInnerUnion4Typedef + +ic5 = outer.makeInnerClass5 +is5 = outer.makeInnerStruct5 +iu5 = outer.makeInnerUnion5 + +ic5 = outer.makeInnerClass5Typedef +is5 = outer.makeInnerStruct5Typedef +iu5 = outer.makeInnerUnion5Typedef + +im1 = outer.MultipleInstance1 +im2 = outer.MultipleInstance2 +im3 = outer.MultipleInstance3 +im4 = outer.MultipleInstance4 + +im1 = outer.MultipleDerivedInstance1 +im2 = outer.MultipleDerivedInstance2 +im3 = outer.MultipleDerivedInstance3 +im4 = outer.MultipleDerivedInstance4 + +im1 = outer.MultipleDerivedInstance1 +im2 = outer.MultipleDerivedInstance2 +im3 = outer.MultipleDerivedInstance3 +im4 = outer.MultipleDerivedInstance4 + +mat1 = outer.makeInnerMultipleAnonTypedef1 +mat2 = outer.makeInnerMultipleAnonTypedef2 +mat3 = outer.makeInnerMultipleAnonTypedef3 + +mnt = outer.makeInnerMultipleNamedTypedef +mnt1 = outer.makeInnerMultipleNamedTypedef1 +mnt2 = outer.makeInnerMultipleNamedTypedef2 +mnt3 = outer.makeInnerMultipleNamedTypedef3 + +isn = outer.makeInnerSameName diff --git a/Examples/test-suite/ruby/nested_directors_runme.rb b/Examples/test-suite/ruby/nested_directors_runme.rb new file mode 100644 index 000000000..b2020b3d4 --- /dev/null +++ b/Examples/test-suite/ruby/nested_directors_runme.rb @@ -0,0 +1,29 @@ +#!/usr/bin/env ruby +# +# This test implementation is directly derived from its C# counterpart. +# + +require 'swig_assert' +require 'nested_directors' + +# nested classes not yet supported +#class CNested < Nested_directors::Base::Nest +# def GetValue +# true +# end +#end + +class CSub < Nested_directors::Sub + def GetValue + super + end + def Test + GetValue() + end +end + +#n = CNested.new +#swig_assert('n.GetValue()', binding) + +s = CSub.new +swig_assert('s.Test()', binding) diff --git a/Examples/test-suite/ruby/nested_in_template_runme.rb b/Examples/test-suite/ruby/nested_in_template_runme.rb new file mode 100644 index 000000000..4d3b721a1 --- /dev/null +++ b/Examples/test-suite/ruby/nested_in_template_runme.rb @@ -0,0 +1,11 @@ +#!/usr/bin/env ruby +# +# This test implementation is directly derived from its Python counterpart. +# + +require 'swig_assert' +require 'nested_in_template' + + +cd = Nested_in_template::ConcreteDerived.new(88) +swig_assert_equal('cd.m_value', '88', binding, 'ConcreteDerived not created correctly') diff --git a/Examples/test-suite/ruby/nested_scope_flat_runme.rb b/Examples/test-suite/ruby/nested_scope_flat_runme.rb new file mode 100644 index 000000000..bd7ee7c91 --- /dev/null +++ b/Examples/test-suite/ruby/nested_scope_flat_runme.rb @@ -0,0 +1,25 @@ +#!/usr/bin/env ruby +# +# Check the availability of expected classes and their member variables. +# + +require 'swig_assert' +require 'nested_scope_flat' + +Nested_scope_flat::Global_.new +Nested_scope_flat::Outer1.new +nested2 = Nested_scope_flat::Nested2.new +nested2.data = 42 +swig_assert_equal("nested2.data", "42", binding) +Nested_scope_flat::Klass.new + +Nested_scope_flat::Abstract_int +cannot_instantiate = false +begin + Nested_scope_flat::Abstract_int.new +rescue TypeError + cannot_instantiate = true +end +swig_assert_simple(cannot_instantiate) + +Nested_scope_flat::Real.new.Method() diff --git a/Examples/test-suite/ruby/nested_template_base_runme.rb b/Examples/test-suite/ruby/nested_template_base_runme.rb new file mode 100644 index 000000000..a4f293365 --- /dev/null +++ b/Examples/test-suite/ruby/nested_template_base_runme.rb @@ -0,0 +1,16 @@ +#!/usr/bin/env ruby +# +# This test implementation is directly derived from its Python counterpart. +# + +require 'swig_assert' +require 'nested_template_base' + +ois = Nested_template_base::InnerS.new(123) +oic = Nested_template_base::InnerC.new + +# Check base method is available +swig_assert_equal('oic.outer(ois).val', '123', binding, 'Wrong value calling outer') + +# Check non-derived class using base class +swig_assert_equal('oic.innerc().outer(ois).val', '123', binding, 'Wrong value calling innerc') diff --git a/Examples/test-suite/ruby/nested_workaround_runme.rb b/Examples/test-suite/ruby/nested_workaround_runme.rb new file mode 100644 index 000000000..645bdd321 --- /dev/null +++ b/Examples/test-suite/ruby/nested_workaround_runme.rb @@ -0,0 +1,21 @@ +#!/usr/bin/env ruby +# +# This test implementation is derived from its Java counterpart. +# + +require 'swig_assert' +require 'nested_workaround' + +begin + inner = Nested_workaround::Inner.new(5) + outer = Nested_workaround::Outer.new + newInner = outer.doubleInnerValue(inner) + swig_assert_equal("newInner.getValue", "10", binding) +end + +begin + outer = Nested_workaround::Outer.new + inner = outer.createInner(3) + newInner = outer.doubleInnerValue(inner) + swig_assert_equal("outer.getInnerValue(newInner)", "6", binding) +end diff --git a/Examples/test-suite/ruby/overload_null_runme.rb b/Examples/test-suite/ruby/overload_null_runme.rb index eabea5e40..e84851a88 100644 --- a/Examples/test-suite/ruby/overload_null_runme.rb +++ b/Examples/test-suite/ruby/overload_null_runme.rb @@ -40,13 +40,13 @@ swig_assert(14 == o.byval1cpr(nil)) swig_assert(15 == o.byval2cpr(nil)) swig_assert(16 == o.byval2cpr(x)) -# forward class declaration -swig_assert(17 == o.byval1forwardptr(x)) -swig_assert(18 == o.byval1forwardptr(nil)) +# fwd class declaration +swig_assert(17 == o.byval1fwdptr(x)) +swig_assert(18 == o.byval1fwdptr(nil)) -swig_assert(19 == o.byval2forwardptr(nil)) -swig_assert(20 == o.byval2forwardptr(x)) +swig_assert(19 == o.byval2fwdptr(nil)) +swig_assert(20 == o.byval2fwdptr(x)) -swig_assert(21 == o.byval1forwardref(x)) +swig_assert(21 == o.byval1fwdref(x)) -swig_assert(22 == o.byval2forwardref(x)) +swig_assert(22 == o.byval2fwdref(x)) diff --git a/Examples/test-suite/ruby/preproc_runme.rb b/Examples/test-suite/ruby/preproc_runme.rb new file mode 100644 index 000000000..4b4a9157d --- /dev/null +++ b/Examples/test-suite/ruby/preproc_runme.rb @@ -0,0 +1,40 @@ +#!/usr/bin/env ruby +# +# This test implementation is directly derived from its Python counterpart. +# + +require 'swig_assert' + +# This extension to the Warning class is intended for suppressing expected +# Ruby warning messages about invalid or redefined Ruby constants - basically +# the equivalent of %warnfilter(SWIGWARN_RUBY_WRONG_NAME) but for the moment +# the wrapper library is loaded by the Ruby interpreter. +# Note: This only works for Ruby 2.4 and later +if Object.const_defined?(:Warning) && Warning.respond_to?(:warn) + module CustomWarningFilter + def warn(*args) + msg = args[0] + if msg =~ /[Aa]lready initialized constant Preproc::A[56]/ || + msg =~ /invalid name .?__GMP_HAVE_/ + # ignore + else + super + end + end + end + Warning.extend CustomWarningFilter +end + +require 'preproc' + +swig_assert_equal('Preproc::endif', '1', binding) +swig_assert_equal('Preproc::define', '1', binding) +swig_assert_equal('Preproc::ddefined', '1', binding) + +swig_assert_equal('2 * Preproc::One', 'Preproc::Two', binding) + +swig_assert_equal('Preproc::methodX(99)', '199', binding) + +t1 = Preproc::TcxMessageTest +t2 = Preproc::TcxMessageBug + diff --git a/Examples/test-suite/ruby/ruby_naming_bugs_runme.rb b/Examples/test-suite/ruby/ruby_naming_bugs_runme.rb new file mode 100644 index 000000000..49311352d --- /dev/null +++ b/Examples/test-suite/ruby/ruby_naming_bugs_runme.rb @@ -0,0 +1,16 @@ +#!/usr/bin/env ruby +# +# Regression tests for Ruby naming bugs +# + +require 'swig_assert' + +require 'ruby_naming_bugs' + +# Prior to SWIG 4.1.0 the "Cool_" here was overzealously removed +# while trying to remove a class name prefix, so this method would be +# named "somethingFast" in Ruby instead. +c = Ruby_naming_bugs::Cool.new() +if c.somethingCool_Fast != 42 + raise RuntimeError, "Incorrect value for somethingCool_Fast" +end diff --git a/Examples/test-suite/ruby/template_nested_flat_runme.rb b/Examples/test-suite/ruby/template_nested_flat_runme.rb new file mode 100644 index 000000000..5d0907f80 --- /dev/null +++ b/Examples/test-suite/ruby/template_nested_flat_runme.rb @@ -0,0 +1,23 @@ +#!/usr/bin/env ruby +# +# This test implementation is directly derived from its Java counterpart. +# + +require 'swig_assert' +require 'template_nested_flat' + +Template_nested_flat::T_NormalTemplateNormalClass.new.tmethod(Template_nested_flat::NormalClass.new) +Template_nested_flat::OuterClass.new.T_OuterTMethodNormalClass(Template_nested_flat::NormalClass.new) + +tf = Template_nested_flat::TemplateFuncs.new +swig_assert_equal("tf.T_TemplateFuncs1Int(-10)", "-10", binding) +swig_assert_equal("tf.T_TemplateFuncs2Double(-12.3)", "-12.3", binding) + +tn = Template_nested_flat::T_NestedOuterTemplateDouble.new +swig_assert_equal("tn.hohum(-12.3)", "-12.3", binding) + +inner1 = Template_nested_flat::OuterClass.new.useInner1(Template_nested_flat::T_OuterClassInner1Int.new) +inner2 = Template_nested_flat::T_OuterClassInner2NormalClass.new +inner2.embeddedVar = 2 +inner22 = Template_nested_flat::OuterClass.new.useInner2Again(inner2) +inner3 = Template_nested_flat::T_OuterClassInner1Double.new diff --git a/Examples/test-suite/ruby/template_static_runme.rb b/Examples/test-suite/ruby/template_static_runme.rb new file mode 100644 index 000000000..83c40e177 --- /dev/null +++ b/Examples/test-suite/ruby/template_static_runme.rb @@ -0,0 +1,12 @@ +#!/usr/bin/env ruby +# +# This test implementation is directly derived from its Python counterpart. +# + +require 'template_static' + +Template_static::Foo_i.test +Template_static::Foo_d.test +Template_static::Foo::test +Template_static::Foo::bar_double(1) + diff --git a/Examples/test-suite/ruby_naming_bugs.i b/Examples/test-suite/ruby_naming_bugs.i new file mode 100644 index 000000000..6449addf1 --- /dev/null +++ b/Examples/test-suite/ruby_naming_bugs.i @@ -0,0 +1,9 @@ +%module ruby_naming_bugs + +%inline %{ + // Prior to SWIG 4.1.0 the "Cool_" here was overzealously removed while + // trying to remove a class name prefix. + struct Cool { + int somethingCool_Fast() { return 42; } + }; +%} diff --git a/Examples/test-suite/schemerunme/li_typemaps.scm b/Examples/test-suite/schemerunme/li_typemaps.scm index 161e803bb..a24bbdaf0 100644 --- a/Examples/test-suite/schemerunme/li_typemaps.scm +++ b/Examples/test-suite/schemerunme/li_typemaps.scm @@ -24,8 +24,8 @@ ;(check "ulonglong" 6432 =) ;; The checking of inoutr-int2 and out-foo is done in the individual -;; language runme scripts, since chicken returns multiple values -;; and must be checked with call-with-values, while guile just returns a list +;; language runme scripts, since how multiple values are returned +;; differs between scheme variants. ;(call-with-values (lambda () (inoutr-int2 3 -2)) ; (lambda (a b) diff --git a/Examples/test-suite/schemerunme/li_typemaps_proxy.scm b/Examples/test-suite/schemerunme/li_typemaps_proxy.scm index f61d4fee5..07bb8556f 100644 --- a/Examples/test-suite/schemerunme/li_typemaps_proxy.scm +++ b/Examples/test-suite/schemerunme/li_typemaps_proxy.scm @@ -24,8 +24,8 @@ (check "ulonglong" 6432 =) ;; The checking of inoutr-int2 and out-foo is done in the individual -;; language runme scripts, since chicken returns multiple values -;; and must be checked with call-with-values, while guile just returns a list +;; language runme scripts, since how multiple values are returned +;; differs between scheme variants. ;(call-with-values (lambda () (inoutr-int2 3 -2)) ; (lambda (a b) diff --git a/Examples/test-suite/scilab/allprotected_runme.sci b/Examples/test-suite/scilab/allprotected_runme.sci index 7bc74fac0..b76bd7c89 100644 --- a/Examples/test-suite/scilab/allprotected_runme.sci +++ b/Examples/test-suite/scilab/allprotected_runme.sci @@ -21,10 +21,10 @@ checkequal(PubBase_virtualMethod(pubBase), "PublicBase", "PubBase_virtualMethod( class = PubBase_instanceMethod(pubBase, klass); checkequal(Klass_getName(class), "allprotected_klass", "Klass_getName(PubBase_instanceMethod(pubBase, klass))"); -class = PubBase_instanceOverload(pubBase, klass); +class = PubBase_instanceOverloaded(pubBase, klass); checkequal(Klass_getName(class), "allprotected_klass", "Klass_getName(PubBase_instanceOverloaded(pubBase, klass))"); -class = PubBase_instanceOverload(pubBase, klass, "allprotected_klass2"); +class = PubBase_instanceOverloaded(pubBase, klass, "allprotected_klass2"); checkequal(Klass_getName(class), "allprotected_klass2", "Klass_getName(PubBase_instanceOverloaded(pubBase, klass, ""allprotected_klass2""))"); class = PubBase_staticMethod(klass); @@ -40,12 +40,22 @@ checkequal(Klass_getName(class), "allprotected_klass3", "Klass_getName(PubBase_s checkequal(PubBase_EnumVal1_get(), 0, "PubBase_EnumVal1_get()"); checkequal(PubBase_EnumVal2_get(), 1, "(PubBase_EnumVal2_get()"); +v=getversion("scilab"); +if v(1) < 6 then + PubBase_instanceMemb_set(pubBase, 12); + checkequal(PubBase_instanceMemb_get(pubBase), 12, "PubBase_instanceMemb_get(pubBase)"); +else + PubBase_instanceMemberVariable_set(pubBase, 12); + checkequal(PubBase_instanceMemberVariable_get(pubBase), 12, "PubBase_instanceMemberVariable_get(pubBase)"); +end -PubBase_instanceMemb_set(pubBase, 12); -checkequal(PubBase_instanceMemb_get(pubBase), 12, "PubBase_instanceMemb_get(pubBase)"); - -checkequal(PubBase_staticConstM_get(), 20, "PubBase_staticConstM_get()"); -checkequal(PubBase_staticMember_get(), 10, "PubBase_staticMember_get()") +if v(1) < 6 then + checkequal(PubBase_staticConstM_get(), 20, "PubBase_staticConstMemberVariable_get()"); + checkequal(PubBase_staticMember_get(), 10, "PubBase_staticMemberVariable_get()") +else + checkequal(PubBase_staticConstMemberVariable_get(), 20, "PubBase_staticConstMemberVariable_get()"); + checkequal(PubBase_staticMemberVariable_get(), 10, "PubBase_staticMemberVariable_get()") +end PubBase_stringMember_set(pubBase, "dummy"); checkequal(PubBase_stringMember_get(pubBase), "dummy", "PubBase_stringMember_get()"); diff --git a/Examples/test-suite/scilab/li_std_except_runme.sci b/Examples/test-suite/scilab/li_std_except_runme.sci index 3b6522f45..272f03261 100644 --- a/Examples/test-suite/scilab/li_std_except_runme.sci +++ b/Examples/test-suite/scilab/li_std_except_runme.sci @@ -14,7 +14,7 @@ checkException('Test_throw_domain_error(t)', 20009, 'ValueError: oops'); checkException('Test_throw_exception(t)', 20010, 'SystemError: std::exception'); -checkException('Test_throw_invalid_argum(t)', 20009, 'ValueError: oops'); +checkException('Test_throw_invalid_argument(t)', 20009, 'ValueError: oops'); checkException('Test_throw_length_error(t)', 20004, 'IndexError: oops'); @@ -22,7 +22,7 @@ checkException('Test_throw_logic_error(t)', 20003, 'RuntimeError: oops'); checkException('Test_throw_out_of_range(t)', 20004, 'IndexError: oops'); -checkException('Test_throw_overflow_erro(t)', 20007, 'OverflowError: oops'); +checkException('Test_throw_overflow_error(t)', 20007, 'OverflowError: oops'); checkException('Test_throw_range_error(t)', 20007, 'OverflowError: oops'); diff --git a/Examples/test-suite/scilab/li_std_string_extra_runme.sci b/Examples/test-suite/scilab/li_std_string_extra_runme.sci index b96b07e84..c4f254425 100644 --- a/Examples/test-suite/scilab/li_std_string_extra_runme.sci +++ b/Examples/test-suite/scilab/li_std_string_extra_runme.sci @@ -42,8 +42,12 @@ checkequal(Structure_StaticStr2_get(), "static member string 2", "Structure_Stat Structure_StaticStr2_set(s); checkequal(Structure_StaticStr2_get(), s, "Structure_StaticStr2_get()"); -checkequal(Structure_ConstStati_get(), "const static member string", "Structure_ConstStaticStr_get()"); - +v = getversion("scilab"); +if v(1) < 6 then + checkequal(Structure_ConstStati_get(), "const static member string", "Structure_ConstStati_get()"); +else + checkequal(Structure_ConstStaticStr_get(), "const static member string", "Structure_ConstStaticStr_get()"); +end checkequal(stdstring_empty(), "", "stdstring_empty()"); checkequal(c_empty(), "", "c_empty()"); diff --git a/Examples/test-suite/scilab/overload_null_runme.sci b/Examples/test-suite/scilab/overload_null_runme.sci index e3939ac5c..72a2b7ea6 100644 --- a/Examples/test-suite/scilab/overload_null_runme.sci +++ b/Examples/test-suite/scilab/overload_null_runme.sci @@ -30,16 +30,16 @@ checkequal(14, Overload_byval1cpr(o, NULL), "test 14"); checkequal(15, Overload_byval2cpr(o, NULL), "test 15"); checkequal(16, Overload_byval2cpr(o, x), "test 16"); -// forward class declaration -checkequal(17, Overload_byval1forwardptr(o, x), "test 17"); -checkequal(18, Overload_byval1forwardptr(o, NULL), "test 18"); +// fwd class declaration +checkequal(17, Overload_byval1fwdptr(o, x), "test 17"); +checkequal(18, Overload_byval1fwdptr(o, NULL), "test 18"); -checkequal(19, Overload_byval2forwardptr(o, NULL), "test 19"); -checkequal(20, Overload_byval2forwardptr(o, x), "test 20"); +checkequal(19, Overload_byval2fwdptr(o, NULL), "test 19"); +checkequal(20, Overload_byval2fwdptr(o, x), "test 20"); -checkequal(21, Overload_byval1forwardref(o, x), "test 21"); +checkequal(21, Overload_byval1fwdref(o, x), "test 21"); -checkequal(22, Overload_byval2forwardref(o, x), "test 22"); +checkequal(22, Overload_byval2fwdref(o, x), "test 22"); exec("swigtest.quit", -1); diff --git a/Examples/test-suite/scilab/preproc_constants_runme.sci b/Examples/test-suite/scilab/preproc_constants_runme.sci index d3d0a4b56..3dc1433af 100644 --- a/Examples/test-suite/scilab/preproc_constants_runme.sci +++ b/Examples/test-suite/scilab/preproc_constants_runme.sci @@ -24,7 +24,7 @@ endfunction test_global(); -// Test assignement in enums +// Test assignment in enums checkequal(kValue_get(), 4, "kValue"); exec("swigtest.quit", -1); diff --git a/Examples/test-suite/scilab/scilab_identifier_name_runme.sci b/Examples/test-suite/scilab/scilab_identifier_name_runme.sci index 9a4f3cc08..1665ec91a 100644 --- a/Examples/test-suite/scilab/scilab_identifier_name_runme.sci +++ b/Examples/test-suite/scilab/scilab_identifier_name_runme.sci @@ -1,29 +1,46 @@ exec("swigtest.start", -1); +v = getversion("scilab"); -// Test truncating variables, constants, functions identifier names +// Test truncating variables, constants, functions identifier names in Scilab 5 // not truncated gvar_identifier_name_set(-101); checkequal(gvar_identifier_name_get(), -101, "gvar_identifier_name_get()"); checkequal(CONS_IDENTIFIER_NAME_get(), -11, "CONS_IDENTIFIER_NAME_get()"); checkequal(function_identifier_name(), -21, "function_identifier_name()"); -// truncated +// truncated in Scilab 5 +if v(1) < 6 then too_long_gvar_identi_set(101); checkequal(too_long_gvar_identi_get(), 101, "too_long_variable_id_get()"); -checkequal(TOO_LONG_CONST_IDENT_get(), 11, "TOO_LONG_CONST_IDENT_get()"); -checkequal(too_long_function_identi(), 21, "too_long_function_identi()"); +checkequal(TOO_LONG_CONST_IDENT_get(), 11, "TOO_LONG_CONST_IDENTIFIER_NAME_1_get"); +checkequal(too_long_function_identi(), 21, "too_long_function_identifier_name_1()"); +else +too_long_gvar_identifier_name_1_set(101); +checkequal(too_long_gvar_identifier_name_1_get(), 101, "too_long_variable_id_get()"); +checkequal(TOO_LONG_CONST_IDENTIFIER_NAME_1_get(), 11, "TOO_LONG_CONST_IDENTIFIER_NAME_1_get"); +checkequal(too_long_function_identifier_name_1(), 21, "too_long_function_identifier_name_1()"); +end // Test truncating when %scilabconst mode is activated -checkequal(SC_CONST_IDENTIFIER_NAME, int32(-12), "SC_TOO_LONG_IDENTIF"); -checkequal(SC_TOO_LONG_CONST_IDENTI, int32(14), "SC_TOO_LONG_IDENTIF"); +checkequal(SC_CONST_IDENTIFIER_NAME, int32(-12), "SC_CONST_IDENTIFIER_NAME"); +if v(1) < 6 then +checkequal(SC_TOO_LONG_CONST_IDENTI, int32(14), "SC_TOO_LONG_CONST_IDENTIFIER_NAME_2"); +else +checkequal(SC_TOO_LONG_CONST_IDENTIFIER_NAME_2, int32(14), "SC_TOO_LONG_CONST_IDENTIFIER_NAME_2"); +end // Test truncating in the case of struct st = new_st(); st_m_identifier_name_set(st, 15); checkequal(st_m_identifier_name_get(st), 15, "st_m_identifier_name_get(st)"); +if v(1) < 6 then st_too_long_member_i_set(st, 25); -checkequal(st_too_long_member_i_get(st), 25, "st_too_long_member_i_get(st)"); +checkequal(st_too_long_member_i_get(st), 25, "st_too_long_member_identifier_name_get(st)"); +else +st_too_long_member_identifier_name_set(st, 25); +checkequal(st_too_long_member_identifier_name_get(st), 25, "st_too_long_member_identifier_name_get(st)"); +end delete_st(st); exec("swigtest.quit", -1); diff --git a/Examples/test-suite/scilab/swigtest.start b/Examples/test-suite/scilab/swigtest.start index e4347bd90..161337115 100644 --- a/Examples/test-suite/scilab/swigtest.start +++ b/Examples/test-suite/scilab/swigtest.start @@ -2,6 +2,8 @@ lines(0); warning('off'); ilib_verbose(0); +ver = getversion('scilab'); + // Get test name (used in swigtest.quit file) [units, typ, names] = file(1); swigtestname = strsubst(fileparts(names, "fname"), "_runme", ""); @@ -23,7 +25,12 @@ end // Module initialization try - moduleInit = sprintf("%s_Init()", swigtestname); + if ver(1) < 6 then + entry = stripblanks(part(swigtestname, 1:24-5)); + else + entry = swigtestname; + end + moduleInit = sprintf("%s_Init()", entry); execstr(moduleInit); catch mfprintf(0, "*** MODULE INIT FAILED ***\n"); diff --git a/Examples/test-suite/scilab_identifier_name.i b/Examples/test-suite/scilab_identifier_name.i index 94dde47e0..4e5a574e9 100644 --- a/Examples/test-suite/scilab_identifier_name.i +++ b/Examples/test-suite/scilab_identifier_name.i @@ -7,7 +7,7 @@ // Test truncating variables, constants, functions identifier names %inline %{ -// these identifier names wont be truncated +// these identifier names won't be truncated int gvar_identifier_name = -1; #define CONS_IDENTIFIER_NAME -11 int function_identifier_name() { return -21; }; diff --git a/Examples/test-suite/sizet.i b/Examples/test-suite/sizet.i index 537914155..6b70f680d 100644 --- a/Examples/test-suite/sizet.i +++ b/Examples/test-suite/sizet.i @@ -3,9 +3,7 @@ #include %} -#ifndef SWIGCHICKEN %include "std_common.i" -#endif %inline { diff --git a/Examples/test-suite/smart_pointer_const_overload.i b/Examples/test-suite/smart_pointer_const_overload.i index 75a137b73..526bcc9bd 100644 --- a/Examples/test-suite/smart_pointer_const_overload.i +++ b/Examples/test-suite/smart_pointer_const_overload.i @@ -3,6 +3,10 @@ %warnfilter(SWIGWARN_LANG_OVERLOAD_IGNORED) Bar::operator->; // Overloaded method Bar::operator ->() ignored %warnfilter(SWIGWARN_LANG_OVERLOAD_IGNORED) Bar2::operator->; // Overloaded method Bar2::operator ->() ignored +%{ +#include +%} + %inline %{ int CONST_ACCESS = 1; int MUTABLE_ACCESS = 2; diff --git a/Examples/test-suite/smart_pointer_inherit.i b/Examples/test-suite/smart_pointer_inherit.i index 52df5a92b..26987a5ac 100644 --- a/Examples/test-suite/smart_pointer_inherit.i +++ b/Examples/test-suite/smart_pointer_inherit.i @@ -70,7 +70,10 @@ class ItkVectorContainerUILSNUS2 : public std::vector< ItkLevelSetNodeUS2 > { class ItkVectorContainerUILSNUS2_Pointer { public: - ItkVectorContainerUILSNUS2 * operator->() const { return 0; } + ItkVectorContainerUILSNUS2 * operator->() const { + static ItkVectorContainerUILSNUS2 instance; + return &instance; + } }; %} diff --git a/Examples/test-suite/special_variable_macros.i b/Examples/test-suite/special_variable_macros.i index ca2edaa98..98d108b6b 100644 --- a/Examples/test-suite/special_variable_macros.i +++ b/Examples/test-suite/special_variable_macros.i @@ -9,6 +9,8 @@ #if defined(_MSC_VER) #pragma warning(disable: 4996) // 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup. See online help for details. #endif +#include +#include %} %ignore Name::operator=; diff --git a/Examples/test-suite/string_simple.i b/Examples/test-suite/string_simple.i index 537daa570..55cb950b0 100644 --- a/Examples/test-suite/string_simple.i +++ b/Examples/test-suite/string_simple.i @@ -3,6 +3,7 @@ %newobject copy_str; %inline %{ +#include #include const char* copy_str(const char* str) { size_t len = strlen(str); diff --git a/Examples/test-suite/tcl/imports_runme.tcl b/Examples/test-suite/tcl/imports_runme.tcl index 6b2e77bde..bf2fc8cba 100644 --- a/Examples/test-suite/tcl/imports_runme.tcl +++ b/Examples/test-suite/tcl/imports_runme.tcl @@ -15,8 +15,8 @@ import set x [new_B] A_hello $x -if [ catch { $x nonexistant } ] { +if [ catch { $x nonexistent } ] { } else { - puts stderr "nonexistant method did not throw exception\n" + puts stderr "nonexistent method did not throw exception\n" exit 1 } diff --git a/Examples/test-suite/tcl/li_std_vector_runme.tcl b/Examples/test-suite/tcl/li_std_vector_runme.tcl new file mode 100644 index 000000000..743565d95 --- /dev/null +++ b/Examples/test-suite/tcl/li_std_vector_runme.tcl @@ -0,0 +1,15 @@ + +if [ catch { load ./li_std_vector[info sharedlibextension] li_std_vector} err_msg ] { + puts stderr "Could not load shared object:\n$err_msg" +} + +# Regression test for bug fixed in SWIG 4.1.0. +if {[sum []] != 0} { error "bad vector sum" } + +IntPtrVector v 6 +if {[v empty] != 0} { error "bad std::vector::empty()" } +if {[v size] != 6} { error "bad std::vector::size()" } +# Test that calling get succeeds +v get 0 +v pop +if {[v size] != 5} { error "bad std::vector::size()" } diff --git a/Examples/test-suite/tcl/overload_null_runme.tcl b/Examples/test-suite/tcl/overload_null_runme.tcl index 3716612ab..075d6046c 100644 --- a/Examples/test-suite/tcl/overload_null_runme.tcl +++ b/Examples/test-suite/tcl/overload_null_runme.tcl @@ -40,13 +40,13 @@ check "testX" 14 [$o byval1cpr "NULL"] check "testX" 15 [$o byval2cpr "NULL"] check "testX" 16 [$o byval2cpr $x] -# forward class declaration -check "testX" 17 [$o byval1forwardptr $x] -check "testX" 18 [$o byval1forwardptr "NULL"] +# fwd class declaration +check "testX" 17 [$o byval1fwdptr $x] +check "testX" 18 [$o byval1fwdptr "NULL"] -check "testX" 19 [$o byval2forwardptr "NULL"] -check "testX" 20 [$o byval2forwardptr $x] +check "testX" 19 [$o byval2fwdptr "NULL"] +check "testX" 20 [$o byval2fwdptr $x] -check "testX" 21 [$o byval1forwardref $x] +check "testX" 21 [$o byval1fwdref $x] -check "testX" 22 [$o byval2forwardref $x] +check "testX" 22 [$o byval2fwdref $x] diff --git a/Examples/test-suite/template_arg_replace.i b/Examples/test-suite/template_arg_replace.i index 25274c9ab..d887c2661 100644 --- a/Examples/test-suite/template_arg_replace.i +++ b/Examples/test-suite/template_arg_replace.i @@ -6,7 +6,7 @@ template class test_Matrix { public: - void Func(const test_Matrix &m) { }; + void Func(const test_Matrix &m) { } }; %} diff --git a/Examples/test-suite/template_default.i b/Examples/test-suite/template_default.i index d771ef09e..83ffd5427 100644 --- a/Examples/test-suite/template_default.i +++ b/Examples/test-suite/template_default.i @@ -196,7 +196,6 @@ namespace ns1 { %} -#ifndef SWIGCHICKEN %include std_vector.i %{ @@ -211,6 +210,3 @@ void q(double = 0) {} %constant void (*Bf)(std::vector *p = 0) = g; %constant void (*Cf)(double = 0) = q; - - -#endif diff --git a/Examples/test-suite/template_default_vw.i b/Examples/test-suite/template_default_vw.i index 429ed301e..ed207125c 100644 --- a/Examples/test-suite/template_default_vw.i +++ b/Examples/test-suite/template_default_vw.i @@ -13,7 +13,7 @@ public: typedef Handle hSomeClass; class AnotherClass { public: - void someFunc( hSomeClass a = hSomeClass() ) { }; + void someFunc( hSomeClass a = hSomeClass() ) { } }; %} diff --git a/Examples/test-suite/template_nested.i b/Examples/test-suite/template_nested.i index 67668fb1a..941ec9e3a 100644 --- a/Examples/test-suite/template_nested.i +++ b/Examples/test-suite/template_nested.i @@ -1,11 +1,11 @@ %module template_nested -#if !defined(SWIGCSHARP) && !defined(SWIGJAVA) -%feature ("flatnested"); -#endif - // Test nested templates - that is template classes and template methods within a class. +#if !defined(SWIGCSHARP) && !defined(SWIGJAVA) +#pragma SWIG nowarn=SWIGWARN_PARSE_NAMED_NESTED_CLASS +#endif + namespace ns { template struct ForwardTemplate; } diff --git a/Examples/test-suite/template_nested_flat.i b/Examples/test-suite/template_nested_flat.i new file mode 100644 index 000000000..3c1d8bfef --- /dev/null +++ b/Examples/test-suite/template_nested_flat.i @@ -0,0 +1,7 @@ +%module template_nested_flat + +// Test nested templates ("flatnested" version of template_nested.i) + +%feature ("flatnested"); + +%include "template_nested.i" diff --git a/Examples/test-suite/template_static.i b/Examples/test-suite/template_static.i index bbca99490..dafb9ca5c 100644 --- a/Examples/test-suite/template_static.i +++ b/Examples/test-suite/template_static.i @@ -19,6 +19,7 @@ template int foo::test = 0; namespace toto { class Foo { public: + static int test; template static double bar(int i) { return 1.0; @@ -28,6 +29,7 @@ namespace toto { int i; }; } +int toto::Foo::test = 5; %} %template(bar_double) toto::Foo::bar; diff --git a/Examples/test-suite/template_template_parameters.i b/Examples/test-suite/template_template_parameters.i index 89197229e..53b18b0b0 100644 --- a/Examples/test-suite/template_template_parameters.i +++ b/Examples/test-suite/template_template_parameters.i @@ -2,6 +2,9 @@ %inline %{ + +/* part 1 */ + namespace pfc { template class t_alloc> class array_t {}; template class alloc_fast { @@ -16,7 +19,7 @@ class list_tt : public list_impl_t > { public: t_item item; -// typename t_alloc::alloc_type allotype; // SWIG can't handle this yet + typename t_alloc::alloc_type allotype; // SWIG can handle this now void xx() { typename t_alloc::alloc_type atype; // this type is the same as t_item type atype = true; @@ -29,11 +32,42 @@ void TestInstantiations() { (void) myArrayInt; (void) myListImplInt; } + +/* part 2 */ + +template +struct Container1 { + T x; +}; +template +struct Container2 { + U x; +}; +template class TemplateTemplateT> +struct TestStruct { + TemplateTemplateT x; +}; + +TestStruct TestStructContainer1Method(TestStruct ts1) { + ts1.x.x += 10; + return ts1; +} + %} +/* part 1 */ %template(ListImplFastBool) list_impl_t >; %template(ListFastBool) list_tt; %template(ListImplFastDouble) list_impl_t >; %template(ListDefaultDouble) list_tt; +%template(BoolAllocFast) pfc::alloc_fast; +%template(DoubleAllocFast) pfc::alloc_fast; + +/* part 2 */ +%template(IntContainer1) Container1; +%template(FloatContainer2) Container2; +%template(IntTestStruct) TestStruct; +%template(FloatTestStruct) TestStruct; + diff --git a/Examples/test-suite/template_typedef_cplx2.h b/Examples/test-suite/template_typedef_cplx2.h index 17d065252..a6ee3c673 100644 --- a/Examples/test-suite/template_typedef_cplx2.h +++ b/Examples/test-suite/template_typedef_cplx2.h @@ -113,6 +113,8 @@ namespace vfncs { #ifndef SWIG // Initialize these static class members +// XXX Since this is a header file, the following creates the symbols in *each* SWIG _wrap.cxx file. Linking the resulting SWIG modules together may result in +// duplicate symbol link errors. const char* const arith_traits< double, double >::arg_type = "double"; const char* const arith_traits< double, double >::res_type = "double"; diff --git a/Examples/test-suite/testdir/inctest/subdir2/hello.i b/Examples/test-suite/testdir/inctest/subdir2/hello.i index ed172b1fd..e87b43759 100644 --- a/Examples/test-suite/testdir/inctest/subdir2/hello.i +++ b/Examples/test-suite/testdir/inctest/subdir2/hello.i @@ -3,6 +3,7 @@ %{ typedef char * TypedefString; +#include %} diff --git a/Examples/test-suite/threads.i b/Examples/test-suite/threads.i index 7c6b09be0..28c55945e 100644 --- a/Examples/test-suite/threads.i +++ b/Examples/test-suite/threads.i @@ -9,6 +9,7 @@ %inline %{ #include + #include struct Kerfuffle { std::string StdString(std::string str) { return str; diff --git a/Examples/test-suite/threads_exception.i b/Examples/test-suite/threads_exception.i index 4708633db..776e84231 100644 --- a/Examples/test-suite/threads_exception.i +++ b/Examples/test-suite/threads_exception.i @@ -13,6 +13,7 @@ %} %{ +#include struct A {}; %} diff --git a/Examples/test-suite/typedef_struct.i b/Examples/test-suite/typedef_struct.i index 185e81105..b9a670cf5 100644 --- a/Examples/test-suite/typedef_struct.i +++ b/Examples/test-suite/typedef_struct.i @@ -31,6 +31,7 @@ #define MS_NOOVERRIDE -1111 +#include %} diff --git a/Examples/test-suite/typemap_qualifier_strip.i b/Examples/test-suite/typemap_qualifier_strip.i index 9b9f24cd8..36d524dad 100644 --- a/Examples/test-suite/typemap_qualifier_strip.i +++ b/Examples/test-suite/typemap_qualifier_strip.i @@ -4,18 +4,18 @@ %typemap(freearg) int *const ptrConst "" %typemap(freearg) int const* constPtr "" -%typemap(in) int *ptr { - int temp = 1234; +%typemap(in) int *ptr (int temp) { + temp = 1234; $1 = &temp; } -%typemap(in) int *const ptrConst { - int temp = 5678; +%typemap(in) int *const ptrConst (int temp) { + temp = 5678; $1 = &temp; } -%typemap(in) int const* constPtr { - int temp = 3456; +%typemap(in) int const* constPtr (int temp) { + temp = 3456; $1 = &temp; } diff --git a/Examples/test-suite/typemap_various.i b/Examples/test-suite/typemap_various.i index 3436bac1c..d619aabaa 100644 --- a/Examples/test-suite/typemap_various.i +++ b/Examples/test-suite/typemap_various.i @@ -58,10 +58,18 @@ void CheckRetTypemapUsed() { /* hello */ delete[] result; } +%{ +#include +%} + %inline { class FFoo { public: - char * Bar(bool b) const { return (char *)"x"; } + char * Bar(bool b) const { + char *ret = new char[2]; + strcpy(ret, b ? "1" : "0"); + return ret; + } }; } diff --git a/Examples/test-suite/types_directive.i b/Examples/test-suite/types_directive.i index 26cb6aeeb..530c338ae 100644 --- a/Examples/test-suite/types_directive.i +++ b/Examples/test-suite/types_directive.i @@ -19,10 +19,11 @@ struct Date { }; struct Time1 { - Time1(unsigned int year, unsigned int month, unsigned int day, unsigned int seconds) : date(year, month, day), seconds(seconds) {} + Time1(unsigned int year, unsigned int month, unsigned int day, unsigned int seconds) : padding(), date(year, month, day), seconds(seconds) {} Date &dateFromTime() { return date; } + unsigned int padding; // so that memory layout is not the same as Date Date date; unsigned int seconds; }; diff --git a/Examples/test-suite/uffi/Makefile.in b/Examples/test-suite/uffi/Makefile.in deleted file mode 100644 index 5d6dc110c..000000000 --- a/Examples/test-suite/uffi/Makefile.in +++ /dev/null @@ -1,51 +0,0 @@ -####################################################################### -# Makefile for uffi test-suite -####################################################################### - -LANGUAGE = uffi -UFFI = @UFFIBIN@ -SCRIPTSUFFIX = _runme.lisp - -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ -top_builddir = @top_builddir@ - -include $(srcdir)/../common.mk - -# Overridden variables here -# no C++ tests for now -CPP_TEST_CASES = -#C_TEST_CASES += - -# Custom tests - tests with additional commandline options -# none! - -# Rules for the different types of tests -%.cpptest: - $(setup) - +$(swig_and_compile_cpp) - $(run_testcase) - -%.ctest: - $(setup) - +$(swig_and_compile_c) - $(run_testcase) - -%.multicpptest: - $(setup) - +$(swig_and_compile_multi_cpp) - $(run_testcase) - -# Runs the testcase. A testcase is only run if -# a file is found which has _runme.lisp appended after the testcase name. -run_testcase = \ - if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(UFFI) -batch -s $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ - fi - -# Clean: (does nothing, we dont generate extra uffi code) -%.clean: - @exit 0 - -clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' uffi_clean diff --git a/Examples/test-suite/using2.i b/Examples/test-suite/using2.i index 1f3dc46f5..1c471c1e5 100644 --- a/Examples/test-suite/using2.i +++ b/Examples/test-suite/using2.i @@ -1,6 +1,6 @@ %module using2 -%warnfilter(SWIGWARN_PARSE_USING_UNDEF); +%warnfilter(SWIGWARN_PARSE_USING_UNDEF) ::baz; using ::baz; diff --git a/Examples/test-suite/using_member.i b/Examples/test-suite/using_member.i new file mode 100644 index 000000000..6b4af2ea7 --- /dev/null +++ b/Examples/test-suite/using_member.i @@ -0,0 +1,70 @@ +%module using_member + +/* using declaration tests, including renaming */ +%warnfilter(SWIGWARN_LANG_USING_NAME_DIFFERENT) one::twotwo::threetwo::BB::great; + +%rename(greater) one::two::three::interface1::AA::great(int); +%rename(greater) one::two::three::interface1::AA::great(float); +%rename(greater) one::CC::great; +%rename(greater) one::DD::great; +%rename(greaterstill) one::DD::great(bool); + +%inline %{ +namespace interface1 +{ + struct A + { + int get(int) {return 10;} + }; +} +using interface1::A; + +struct B : public A +{ + using A::get; + int get(double) {return 20;} +}; + + +namespace one { + namespace two { + namespace three { + namespace interface1 + { + class AA + { + public: + int great(int) {return 0;} + int great(float) {return 1;} + }; + } + using interface1::AA; + } + } + namespace twotwo { + namespace threetwo { + class BB : public two::three::AA + { + public: + using two::three::AA::great; + int great(bool) {return 2;} + int jj() {return 3;} + }; + } + } + + class CC : public two::three::AA + { + public: + using two::three::AA::great; + int great(bool) {return 20;} + }; + + class DD : public two::three::AA + { + public: + using two::three::AA::great; + int great(bool) {return 30;} + }; +} +%} diff --git a/Examples/test-suite/valuewrapper_base.i b/Examples/test-suite/valuewrapper_base.i index 63471bbc8..5107a3c9b 100644 --- a/Examples/test-suite/valuewrapper_base.i +++ b/Examples/test-suite/valuewrapper_base.i @@ -12,7 +12,7 @@ template struct Interface_ : Base { - Interface_(const Base& b) { }; + Interface_(const Base& b) { } }; template diff --git a/Examples/test-suite/varargs.i b/Examples/test-suite/varargs.i index dd56cb073..c1aee229e 100644 --- a/Examples/test-suite/varargs.i +++ b/Examples/test-suite/varargs.i @@ -1,17 +1,35 @@ -// Tests SWIG's *default* handling of varargs (function varargs, not preprocessor varargs). +// Tests SWIG's handling of varargs (function varargs, not preprocessor varargs). // The default behavior is to simply ignore the varargs. %module varargs +// Default handling of varargs + +%{ +#include +%} + +%inline %{ +char *test(const char *fmt, ...) { + return (char *) fmt; +} + +struct VarargConstructor { + char *str; + VarargConstructor(const char *fmt, ...) { + str = new char[strlen(fmt) + 1]; + strcpy(str, fmt); + } +}; +%} + +// %varargs support + %varargs(int mode = 0) test_def; %varargs(int mode = 0) Foo::Foo; %varargs(int mode = 0) Foo::statictest(const char*fmt, ...); %varargs(2, int mode = 0) test_plenty(const char*fmt, ...); %inline %{ -char *test(const char *fmt, ...) { - return (char *) fmt; -} - const char *test_def(const char *fmt, ...) { return fmt; } @@ -40,5 +58,4 @@ public: const char *test_plenty(const char *fmt, ...) { return fmt; } - %} diff --git a/Examples/xml/example_apply.expected-xml b/Examples/xml/example_apply.expected-xml index 6118ef1f2..26cf5df2f 100644 --- a/Examples/xml/example_apply.expected-xml +++ b/Examples/xml/example_apply.expected-xml @@ -409,7 +409,7 @@ static void _ptrset(SV *_PTRVALUE, SV *value, int index, char *type) { } else if (strcmp(type,"char *") == 0) { char *c = SvPV(value,PL_na); char **ca = (char **) ptr; - if (ca[index]) free(ca[index]); + free(ca[index]); if (strcmp(c,"NULL") == 0) { ca[index] = 0; } else { @@ -500,8 +500,7 @@ void _ptrfree(SV *_PTRVALUE) { } } } - if (ptr) - free((char *) ptr); + free((char *) ptr); } diff --git a/Examples/xml/example_xml.expected-xml b/Examples/xml/example_xml.expected-xml index 4d08b206a..e13bcf24b 100644 --- a/Examples/xml/example_xml.expected-xml +++ b/Examples/xml/example_xml.expected-xml @@ -441,7 +441,7 @@ static void _ptrset(SV *_PTRVALUE, SV *value, int index, char *type) { } else if (strcmp(type,"char *") == 0) { char *c = SvPV(value,PL_na); char **ca = (char **) ptr; - if (ca[index]) free(ca[index]); + free(ca[index]); if (strcmp(c,"NULL") == 0) { ca[index] = 0; } else { @@ -532,8 +532,7 @@ void _ptrfree(SV *_PTRVALUE) { } } } - if (ptr) - free((char *) ptr); + free((char *) ptr); } diff --git a/Lib/allegrocl/allegrocl.swg b/Lib/allegrocl/allegrocl.swg deleted file mode 100644 index 524aa7c11..000000000 --- a/Lib/allegrocl/allegrocl.swg +++ /dev/null @@ -1,615 +0,0 @@ -/* Define a C preprocessor symbol that can be used in interface files - to distinguish between the SWIG language modules. */ - -#define SWIG_ALLEGRO_CL - -#define %ffargs(...) %feature("ffargs", "1", ##__VA_ARGS__) -%ffargs(strings_convert="t"); - -/* typemaps for argument and result type conversions. */ -%typemap(lin,numinputs=1) SWIGTYPE "(cl::let (($out $in))\n $body)"; - -%typemap(lout) bool, char, unsigned char, signed char, - short, signed short, unsigned short, - int, signed int, unsigned int, - long, signed long, unsigned long, - float, double, long double, char *, void *, - enum SWIGTYPE "(cl::setq ACL_ffresult $body)"; -%typemap(lout) void "$body"; -#ifdef __cplusplus -%typemap(lout) SWIGTYPE[ANY], SWIGTYPE *, SWIGTYPE &, SWIGTYPE && -%{ (cl:let* ((address $body) - (new-inst (cl:make-instance '$lclass :foreign-address address))) - (cl:when (cl:and $owner (cl:not (cl:zerop address))) - (excl:schedule-finalization new-inst #'$ldestructor)) - (cl:setq ACL_ffresult new-inst)) %} - -%typemap(lout) SWIGTYPE "(cl::let* ((address $body)\n (new-inst (cl::make-instance '$lclass :foreign-address address)))\n (cl::unless (cl::zerop address)\n (excl:schedule-finalization new-inst #'$ldestructor))\n (cl::setq ACL_ffresult new-inst))"; -#else -%typemap(lout) SWIGTYPE[ANY], SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE -%{ (cl:let* ((address $body) - (new-inst (cl:make-instance '$lclass :foreign-address address))) - (cl:setq ACL_ffresult new-inst)) %} -#endif - -%typemap(lisptype) bool, const bool "cl:boolean"; -%typemap(lisptype) char, const char "cl:character"; -%typemap(lisptype) unsigned char, const unsigned char "cl:integer"; -%typemap(lisptype) signed char, const signed char "cl:integer"; - -%typemap(ffitype) bool, const bool ":int"; -%typemap(ffitype) char, const char, - signed char, const signed char ":char"; -%typemap(ffitype) unsigned char, const unsigned char ":unsigned-char"; -%typemap(ffitype) short, const short, - signed short, const signed short ":short"; -%typemap(ffitype) unsigned short, const unsigned short ":unsigned-short"; -%typemap(ffitype) int, const int, signed int, const signed int ":int"; -%typemap(ffitype) unsigned int, const unsigned int ":unsigned-int"; -%typemap(ffitype) long, const long, signed long, const signed long ":long"; -%typemap(ffitype) unsigned long, const unsigned long ":unsigned-long"; -%typemap(ffitype) float, const float ":float"; -%typemap(ffitype) double, const double ":double"; -%typemap(ffitype) char *, const char *, signed char *, - const signed char *, signed char &, - const signed char & "(* :char)"; -%typemap(ffitype) unsigned char *, const unsigned char *, - unsigned char &, const unsigned char & "(* :unsigned-char)"; -%typemap(ffitype) short *, const short *, short &, - const short & "(* :short)"; -%typemap(ffitype) unsigned short *, const unsigned short *, - unsigned short &, const unsigned short & "(* :unsigned-short)"; -%typemap(ffitype) int *, const int *, int &, const int & "(* :int)"; -%typemap(ffitype) unsigned int *, const unsigned int *, - unsigned int &, const unsigned int & "(* :unsigned-int)"; -%typemap(ffitype) void * "(* :void)"; -%typemap(ffitype) void ":void"; -%typemap(ffitype) enum SWIGTYPE ":int"; -%typemap(ffitype) SWIGTYPE & "(* :void)"; -%typemap(ffitype) SWIGTYPE && "(* :void)"; - -/* const typemaps -idea: marshall all primitive c types to their respective lisp types -to maintain const corretness. For pointers/references, all bets -are off if you try to modify them. - -idea: add a constant-p slot to the base foreign-pointer class. For -constant pointer/references check this value when setting (around method?) -and error if a setf operation is performed on the address of this object. - -*/ - -/* -%exception %{ - try { - $action - } catch (...) { - return $null; - } -%} - -*/ - -// %typemap(throws) SWIGTYPE { -// (void)$1; -// SWIG_fail; -// } - -%typemap(ctype) bool, const bool "int"; -%typemap(ctype) char, unsigned char, signed char, - short, signed short, unsigned short, - int, signed int, unsigned int, - long, signed long, unsigned long, - float, double, long double, char *, void *, void, - enum SWIGTYPE, SWIGTYPE *, SWIGTYPE[], - SWIGTYPE[ANY], SWIGTYPE &, SWIGTYPE &&, const SWIGTYPE "$1_ltype"; -%typemap(ctype) SWIGTYPE "$&1_type"; - -%typemap(in) bool "$1 = (bool)$input;"; -%typemap(in) char, unsigned char, signed char, - short, signed short, unsigned short, - int, signed int, unsigned int, - long, signed long, unsigned long, - float, double, long double, char *, void *, void, - enum SWIGTYPE, SWIGTYPE *, SWIGTYPE[], - SWIGTYPE[ANY], SWIGTYPE &, SWIGTYPE && "$1 = $input;"; -%typemap(in) SWIGTYPE "$1 = *$input;"; - -/* We don't need to do any actual C-side typechecking, but need to - use the precedence values to choose which overloaded function - interfaces to generate when conflicts arise. */ - -/* predefined precedence values - -Symbolic Name Precedence Value ------------------------------- ------------------ -SWIG_TYPECHECK_POINTER 0 -SWIG_TYPECHECK_VOIDPTR 10 -SWIG_TYPECHECK_BOOL 15 -SWIG_TYPECHECK_UINT8 20 -SWIG_TYPECHECK_INT8 25 -SWIG_TYPECHECK_UINT16 30 -SWIG_TYPECHECK_INT16 35 -SWIG_TYPECHECK_UINT32 40 -SWIG_TYPECHECK_INT32 45 -SWIG_TYPECHECK_UINT64 50 -SWIG_TYPECHECK_INT64 55 -SWIG_TYPECHECK_UINT128 60 -SWIG_TYPECHECK_INT128 65 -SWIG_TYPECHECK_INTEGER 70 -SWIG_TYPECHECK_FLOAT 80 -SWIG_TYPECHECK_DOUBLE 90 -SWIG_TYPECHECK_COMPLEX 100 -SWIG_TYPECHECK_UNICHAR 110 -SWIG_TYPECHECK_UNISTRING 120 -SWIG_TYPECHECK_CHAR 130 -SWIG_TYPECHECK_STRING 140 -SWIG_TYPECHECK_BOOL_ARRAY 1015 -SWIG_TYPECHECK_INT8_ARRAY 1025 -SWIG_TYPECHECK_INT16_ARRAY 1035 -SWIG_TYPECHECK_INT32_ARRAY 1045 -SWIG_TYPECHECK_INT64_ARRAY 1055 -SWIG_TYPECHECK_INT128_ARRAY 1065 -SWIG_TYPECHECK_FLOAT_ARRAY 1080 -SWIG_TYPECHECK_DOUBLE_ARRAY 1090 -SWIG_TYPECHECK_CHAR_ARRAY 1130 -SWIG_TYPECHECK_STRING_ARRAY 1140 -*/ - -%typecheck(SWIG_TYPECHECK_BOOL) bool { $1 = 1; }; -%typecheck(SWIG_TYPECHECK_CHAR) char { $1 = 1; }; -%typecheck(SWIG_TYPECHECK_FLOAT) float { $1 = 1; }; -%typecheck(SWIG_TYPECHECK_DOUBLE) double { $1 = 1; }; -%typecheck(SWIG_TYPECHECK_STRING) char * { $1 = 1; }; -%typecheck(SWIG_TYPECHECK_INTEGER) - unsigned char, signed char, - short, signed short, unsigned short, - int, signed int, unsigned int, - long, signed long, unsigned long, - enum SWIGTYPE { $1 = 1; }; -%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, - SWIGTYPE[], SWIGTYPE[ANY], - SWIGTYPE { $1 = 1; }; - -/* This maps C/C++ types to Lisp classes for overload dispatch */ - -%typemap(lispclass) bool "t"; -%typemap(lispclass) char "cl:character"; -%typemap(lispclass) unsigned char, signed char, - short, signed short, unsigned short, - int, signed int, unsigned int, - long, signed long, unsigned long, - enum SWIGTYPE "cl:integer"; -%typemap(lispclass) float "cl:single-float"; -%typemap(lispclass) double "cl:double-float"; -%typemap(lispclass) char * "cl:string"; - -%typemap(out) void ""; -%typemap(out) bool "$result = (int)$1;"; -%typemap(out) char, unsigned char, signed char, - short, signed short, unsigned short, - int, signed int, unsigned int, - long, signed long, unsigned long, - float, double, long double, char *, void *, - enum SWIGTYPE, SWIGTYPE *, - SWIGTYPE[ANY], SWIGTYPE &, SWIGTYPE && "$result = $1;"; -#ifdef __cplusplus -%typemap(out) SWIGTYPE "$result = new $1_ltype($1);"; -#else -%typemap(out) SWIGTYPE { - $result = ($&1_ltype) malloc(sizeof($1_type)); - memmove($result, &$1, sizeof($1_type)); -} -#endif - -////////////////////////////////////////////////////////////// -// UCS-2 string conversion - -// should this be SWIG_TYPECHECK_CHAR? -%typecheck(SWIG_TYPECHECK_UNICHAR) wchar_t { $1 = 1; }; - -%typemap(in) wchar_t "$1 = $input;"; -%typemap(lin,numinputs=1) wchar_t "(cl::let (($out (cl:char-code $in)))\n $body)"; -%typemap(lin,numinputs=1) wchar_t * "(excl:with-native-string ($out $in -:external-format #+little-endian :fat-le #-little-endian :fat)\n -$body)" - -%typemap(out) wchar_t "$result = $1;"; -%typemap(lout) wchar_t "(cl::setq ACL_ffresult (cl::code-char $body))"; -%typemap(lout) wchar_t * "(cl::setq ACL_ffresult (excl:native-to-string $body -:external-format #+little-endian :fat-le #-little-endian :fat))"; - -%typemap(ffitype) wchar_t ":unsigned-short"; -%typemap(lisptype) wchar_t ""; -%typemap(ctype) wchar_t "wchar_t"; -%typemap(lispclass) wchar_t "cl:character"; -%typemap(lispclass) wchar_t * "cl:string"; -////////////////////////////////////////////////////////////// - -/* Array reference typemaps */ -%apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } -%apply SWIGTYPE && { SWIGTYPE ((&&)[ANY]) } - -/* const pointers */ -%apply SWIGTYPE * { SWIGTYPE *const } -%apply SWIGTYPE (CLASS::*) { SWIGTYPE (CLASS::*const) } -%apply SWIGTYPE & { SWIGTYPE (CLASS::*const&) } - -/* name conversion for overloaded operators. */ -#ifdef __cplusplus -%rename(__add__) *::operator+; -%rename(__pos__) *::operator+(); -%rename(__pos__) *::operator+() const; - -%rename(__sub__) *::operator-; -%rename(__neg__) *::operator-() const; -%rename(__neg__) *::operator-(); - -%rename(__mul__) *::operator*; -%rename(__deref__) *::operator*(); -%rename(__deref__) *::operator*() const; - -%rename(__div__) *::operator/; -%rename(__mod__) *::operator%; -%rename(__logxor__) *::operator^; -%rename(__logand__) *::operator&; -%rename(__logior__) *::operator|; -%rename(__lognot__) *::operator~(); -%rename(__lognot__) *::operator~() const; - -%rename(__not__) *::operator!(); -%rename(__not__) *::operator!() const; - -%rename(__assign__) *::operator=; - -%rename(__add_assign__) *::operator+=; -%rename(__sub_assign__) *::operator-=; -%rename(__mul_assign__) *::operator*=; -%rename(__div_assign__) *::operator/=; -%rename(__mod_assign__) *::operator%=; -%rename(__logxor_assign__) *::operator^=; -%rename(__logand_assign__) *::operator&=; -%rename(__logior_assign__) *::operator|=; - -%rename(__lshift__) *::operator<<; -%rename(__lshift_assign__) *::operator<<=; -%rename(__rshift__) *::operator>>; -%rename(__rshift_assign__) *::operator>>=; - -%rename(__eq__) *::operator==; -%rename(__ne__) *::operator!=; -%rename(__lt__) *::operator<; -%rename(__gt__) *::operator>; -%rename(__lte__) *::operator<=; -%rename(__gte__) *::operator>=; - -%rename(__and__) *::operator&&; -%rename(__or__) *::operator||; - -%rename(__preincr__) *::operator++(); -%rename(__postincr__) *::operator++(int); -%rename(__predecr__) *::operator--(); -%rename(__postdecr__) *::operator--(int); - -%rename(__comma__) *::operator,(); -%rename(__comma__) *::operator,() const; - -%rename(__member_ref__) *::operator->; -%rename(__member_func_ref__) *::operator->*; - -%rename(__funcall__) *::operator(); -%rename(__aref__) *::operator[]; - -%rename(__bool__) *::operator bool(); -%rename(__bool__) *::operator bool() const; -#endif - -%insert("lisphead") %{ -(eval-when (:compile-toplevel :load-toplevel :execute) - - ;; avoid compiling ef-templates at runtime - (excl:find-external-format :fat) - (excl:find-external-format :fat-le) - -;;; You can define your own identifier converter if you want. -;;; Use the -identifier-converter command line argument to -;;; specify its name. - -(eval-when (:compile-toplevel :load-toplevel :execute) - (cl::defparameter *swig-export-list* nil)) - -(cl::defconstant *void* :..void..) - -;; parsers to aid in finding SWIG definitions in files. -(cl::defun scm-p1 (form) - (let* ((info (cl::second form)) - (id (car info)) - (id-args (if (eq (cl::car form) 'swig-dispatcher) - (cl::cdr info) - (cl::cddr info)))) - (cl::apply *swig-identifier-converter* id - (cl::progn (cl::when (cl::eq (cl::car form) 'swig-dispatcher) - (cl::remf id-args :arities)) - id-args)))) - -(cl::defmacro defswig1 (name (&rest args) &body body) - `(cl::progn (cl::defmacro ,name ,args - ,@body) - (excl::define-simple-parser ,name scm-p1)) ) - -(cl::defmacro defswig2 (name (&rest args) &body body) - `(cl::progn (cl::defmacro ,name ,args - ,@body) - (excl::define-simple-parser ,name second))) - -(defun read-symbol-from-string (string) - (cl::multiple-value-bind (result position) - (cl::read-from-string string nil "eof" :preserve-whitespace t) - (cl::if (cl::and (cl::symbolp result) - (cl::eql position (cl::length string))) - result - (cl::multiple-value-bind (sym) - (cl::intern string) - sym)))) - -(cl::defun full-name (id type arity class) - ; We need some kind of a hack here to handle template classes - ; and other synonym types right. We need the original name. - (let*( (sym (read-symbol-from-string - (if (eq *swig-identifier-converter* 'identifier-convert-lispify) - (string-lispify id) - id))) - (sym-class (find-class sym nil)) - (id (cond ( (not sym-class) - id ) - ( (and sym-class - (not (eq (class-name sym-class) - sym))) - (class-name sym-class) ) - ( t - id ))) ) - (cl::case type - (:getter (cl::format nil "~@[~A_~]~A" class id)) - (:constructor (cl::format nil "new_~A~@[~A~]" id arity)) - (:destructor (cl::format nil "delete_~A" id)) - (:type (cl::format nil "ff_~A" id)) - (:slot id) - (:ff-operator (cl::format nil "ffi_~A" id)) - (otherwise (cl::format nil "~@[~A_~]~A~@[~A~]" - class id arity))))) - -(cl::defun identifier-convert-null (id &key type class arity) - (cl::if (cl::eq type :setter) - `(cl::setf ,(identifier-convert-null - id :type :getter :class class :arity arity)) - (read-symbol-from-string (full-name id type arity class)))) - -(cl::defun string-lispify (str) - (cl::let ( (cname (excl::replace-regexp str "_" "-")) - (lastcase :other) - newcase char res ) - (cl::dotimes (n (cl::length cname)) - (cl::setf char (cl::schar cname n)) - (excl::if* (cl::alpha-char-p char) - then - (cl::setf newcase (cl::if (cl::upper-case-p char) :upper :lower)) - (cl::when (cl::and (cl::eq lastcase :lower) - (cl::eq newcase :upper)) - ;; case change... add a dash - (cl::push #\- res) - (cl::setf newcase :other)) - (cl::push (cl::char-downcase char) res) - (cl::setf lastcase newcase) - else - (cl::push char res) - (cl::setf lastcase :other))) - (cl::coerce (cl::nreverse res) 'string))) - -(cl::defun identifier-convert-lispify (cname &key type class arity) - (cl::assert (cl::stringp cname)) - (cl::when (cl::eq type :setter) - (cl::return-from identifier-convert-lispify - `(cl::setf ,(identifier-convert-lispify - cname :type :getter :class class :arity arity)))) - (cl::setq cname (full-name cname type arity class)) - (cl::if (cl::eq type :constant) - (cl::setf cname (cl::format nil "*~A*" cname))) - (read-symbol-from-string (string-lispify cname))) - -(cl::defun id-convert-and-export (name &rest kwargs) - (cl::multiple-value-bind (symbol package) - (cl::apply *swig-identifier-converter* name kwargs) - (cl::let ((args (cl::list (cl::if (cl::consp symbol) - (cl::cadr symbol) symbol) - (cl::or package cl::*package*)))) - (cl::apply #'cl::export args) - (cl::pushnew args *swig-export-list*)) - symbol)) - -(cl::defmacro swig-insert-id (name namespace &key (type :type) class) - `(cl::let ((cl::*package* (cl::find-package ,(package-name-for-namespace namespace)))) - (id-convert-and-export ,name :type ,type :class ,class))) - -(defswig2 swig-defconstant (string value) - (cl::let ((symbol (id-convert-and-export string :type :constant))) - `(cl::eval-when (:compile-toplevel :load-toplevel :execute) - (cl::defconstant ,symbol ,value)))) - -(cl::defun maybe-reorder-args (funcname arglist) - ;; in the foreign setter function the new value will be the last argument - ;; in Lisp it needs to be the first - (cl::if (cl::consp funcname) - (cl::append (cl::last arglist) (cl::butlast arglist)) - arglist)) - -(cl::defun maybe-return-value (funcname arglist) - ;; setf functions should return the new value - (cl::when (cl::consp funcname) - `(,(cl::if (cl::consp (cl::car arglist)) - (cl::caar arglist) - (cl::car arglist))))) - -(cl::defun swig-anyvarargs-p (arglist) - (cl::member :SWIG__varargs_ arglist)) - -(defswig1 swig-defun ((name &optional (mangled-name name) - &key (type :operator) class arity) - arglist kwargs - &body body) - (cl::let* ((symbol (id-convert-and-export name :type type - :arity arity :class class)) - (mangle (excl::if* (cl::string-equal name mangled-name) - then (id-convert-and-export - (cl::cond - ((cl::eq type :setter) (cl::format nil "~A-set" name)) - ((cl::eq type :getter) (cl::format nil "~A-get" name)) - (t name)) - :type :ff-operator :arity arity :class class) - else (cl::intern mangled-name))) - (defun-args (maybe-reorder-args - symbol - (cl::mapcar #'cl::car (cl::and (cl::not (cl::equal arglist '(:void))) - (cl::loop as i in arglist - when (cl::eq (cl::car i) :p+) - collect (cl::cdr i)))))) - (ffargs (cl::if (cl::equal arglist '(:void)) - arglist - (cl::mapcar #'cl::cdr arglist))) - ) - (cl::when (swig-anyvarargs-p ffargs) - (cl::setq ffargs '())) - `(cl::eval-when (:compile-toplevel :load-toplevel :execute) - (excl::compiler-let ((*record-xref-info* nil)) - (ff:def-foreign-call (,mangle ,mangled-name) ,ffargs ,@kwargs)) - (cl::macrolet ((swig-ff-call (&rest args) - (cl::cons ',mangle args))) - (cl::defun ,symbol ,defun-args - ,@body - ,@(maybe-return-value symbol defun-args)))))) - -(defswig1 swig-defmethod ((name &optional (mangled-name name) - &key (type :operator) class arity) - ffargs kwargs - &body body) - (cl::let* ((symbol (id-convert-and-export name :type type - :arity arity :class class)) - (mangle (cl::intern mangled-name)) - (defmethod-args (maybe-reorder-args - symbol - (cl::unless (cl::equal ffargs '(:void)) - (cl::loop for (lisparg name dispatch) in ffargs - when (eq lisparg :p+) - collect `(,name ,dispatch))))) - (ffargs (cl::if (cl::equal ffargs '(:void)) - ffargs - (cl::loop for (nil name nil . ffi) in ffargs - collect `(,name ,@ffi))))) - `(cl::eval-when (:compile-toplevel :load-toplevel :execute) - (excl::compiler-let ((*record-xref-info* nil)) - (ff:def-foreign-call (,mangle ,mangled-name) ,ffargs ,@kwargs)) - (cl::macrolet ((swig-ff-call (&rest args) - (cl::cons ',mangle args))) - (cl::defmethod ,symbol ,defmethod-args - ,@body - ,@(maybe-return-value symbol defmethod-args)))))) - -(defswig1 swig-dispatcher ((name &key (type :operator) class arities)) - (cl::let ((symbol (id-convert-and-export name - :type type :class class))) - `(cl::eval-when (:compile-toplevel :load-toplevel :execute) - (cl::defun ,symbol (&rest args) - (cl::case (cl::length args) - ,@(cl::loop for arity in arities - for symbol-n = (id-convert-and-export name - :type type :class class :arity arity) - collect `(,arity (cl::apply #',symbol-n args))) - (t (cl::error "No applicable wrapper-methods for foreign call ~a with args ~a of classes ~a" ',symbol args (cl::mapcar #'(cl::lambda (x) (cl::class-name (cl::class-of x))) args))) - ))))) - -(defswig2 swig-def-foreign-stub (name) - (cl::let ((lsymbol (id-convert-and-export name :type :class)) - (symbol (id-convert-and-export name :type :type))) - `(cl::eval-when (:compile-toplevel :load-toplevel :execute) - (ff:def-foreign-type ,symbol (:class )) - (cl::defclass ,lsymbol (ff:foreign-pointer) ())))) - -(defswig2 swig-def-foreign-class (name supers &rest rest) - (cl::let ((lsymbol (id-convert-and-export name :type :class)) - (symbol (id-convert-and-export name :type :type))) - `(cl::eval-when (:compile-toplevel :load-toplevel :execute) - (ff:def-foreign-type ,symbol ,@rest) - (cl::defclass ,lsymbol ,supers - ((foreign-type :initform ',symbol :initarg :foreign-type - :accessor foreign-pointer-type)))))) - -(defswig2 swig-def-foreign-type (name &rest rest) - (cl::let ((symbol (id-convert-and-export name :type :type))) - `(cl::eval-when (:compile-toplevel :load-toplevel :execute) - (ff:def-foreign-type ,symbol ,@rest)))) - -(defswig2 swig-def-synonym-type (synonym of ff-synonym) - `(cl::eval-when (:compile-toplevel :load-toplevel :execute) - (cl::setf (cl::find-class ',synonym) (cl::find-class ',of)) - (ff:def-foreign-type ,ff-synonym (:struct )))) - -(cl::defun package-name-for-namespace (namespace) - (excl::list-to-delimited-string - (cl::cons *swig-module-name* - (cl::mapcar #'(cl::lambda (name) - (cl::string - (cl::funcall *swig-identifier-converter* - name - :type :namespace))) - namespace)) - ".")) - -(cl::defmacro swig-defpackage (namespace) - (cl::let* ((parent-namespaces (cl::maplist #'cl::reverse (cl::cdr (cl::reverse namespace)))) - (parent-strings (cl::mapcar #'package-name-for-namespace - parent-namespaces)) - (string (package-name-for-namespace namespace))) - `(cl::eval-when (:compile-toplevel :load-toplevel :execute) - (cl::defpackage ,string - (:use :swig :ff #+ignore '(:common-lisp :ff :excl) - ,@parent-strings ,*swig-module-name*) - (:import-from :cl :* :nil :t))))) - -(cl::defmacro swig-in-package (namespace) - `(cl::eval-when (:compile-toplevel :load-toplevel :execute) - (cl::in-package ,(package-name-for-namespace namespace)))) - -(defswig2 swig-defvar (name mangled-name &key type (ftype :unsigned-natural)) - (cl::let ((symbol (id-convert-and-export name :type type))) - `(cl::eval-when (:compile-toplevel :load-toplevel :execute) - (ff:def-foreign-variable (,symbol ,mangled-name) :type ,ftype)))) - -) ;; eval-when - -(cl::eval-when (:compile-toplevel :execute) - (cl::flet ((starts-with-p (str prefix) - (cl::and (cl::>= (cl::length str) (cl::length prefix)) - (cl::string= str prefix :end1 (cl::length prefix))))) - (cl::export (cl::loop for sym being each present-symbol of cl::*package* - when (cl::or (starts-with-p (cl::symbol-name sym) (cl::symbol-name :swig-)) - (starts-with-p (cl::symbol-name sym) (cl::symbol-name :identifier-convert-))) - collect sym)))) - -%} - -typedef void *__SWIGACL_FwdReference; - -%{ - -#ifdef __cplusplus -# define EXTERN extern "C" -#else -# define EXTERN extern -#endif - -#define EXPORT EXTERN SWIGEXPORT - -typedef void *__SWIGACL_FwdReference; - -#include -#include -%} diff --git a/Lib/allegrocl/inout_typemaps.i b/Lib/allegrocl/inout_typemaps.i deleted file mode 100644 index d8d61feed..000000000 --- a/Lib/allegrocl/inout_typemaps.i +++ /dev/null @@ -1,111 +0,0 @@ -/* inout_typemaps.i - - Support for INPUT, OUTPUT, and INOUT typemaps. OUTPUT variables are returned - as multiple values. - -*/ - - -/* Note that this macro automatically adds a pointer to the type passed in. - As a result, INOUT typemaps for char are for 'char *'. The definition - of typemaps for 'char' takes advantage of this, believing that it's more - likely to see an INOUT argument for strings, than a single char. */ -%define INOUT_TYPEMAP(type_, OUTresult_, INbind_) -// OUTPUT map. -%typemap(lin,numinputs=0) type_ *OUTPUT, type_ &OUTPUT -%{(cl::let (($out (ff:allocate-fobject '$*in_fftype :c))) - $body - OUTresult_ - (ff:free-fobject $out)) %} - -// INPUT map. -%typemap(in) type_ *INPUT, type_ &INPUT -%{ $1 = &$input; %} - -%typemap(ctype) type_ *INPUT, type_ &INPUT "$*1_ltype"; - - -// INOUT map. -// careful here. the input string is converted to a C string -// with length equal to the input string. This should be large -// enough to contain whatever OUTPUT value will be stored in it. -%typemap(lin,numinputs=1) type_ *INOUT, type_ &INOUT -%{(cl::let (($out (ff:allocate-fobject '$*in_fftype :c))) - INbind_ - $body - OUTresult_ - (ff:free-fobject $out)) %} - -%enddef - -// $in, $out, $lclass, -// $in_fftype, $*in_fftype - -INOUT_TYPEMAP(int, - (cl::push (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) ACL_result), - (cl::setf (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) $in)); -INOUT_TYPEMAP(short, - (cl::push (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) ACL_result), - (cl::setf (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) $in)); -INOUT_TYPEMAP(long, - (cl::push (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) ACL_result), - (cl::setf (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) $in)); -INOUT_TYPEMAP(unsigned int, - (cl::push (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) ACL_result), - (cl::setf (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) $in)); -INOUT_TYPEMAP(unsigned short, - (cl::push (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) ACL_result), - (cl::setf (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) $in)); -INOUT_TYPEMAP(unsigned long, - (cl::push (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) ACL_result), - (cl::setf (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) $in)); -// char * mapping for passing strings. didn't quite work -// INOUT_TYPEMAP(char, -// (cl::push (excl:native-to-string $out) ACL_result), -// (cl::setf (ff:fslot-value-typed (cl::quote $in_fftype) :c $out) -// (excl:string-to-native $in))) -INOUT_TYPEMAP(float, - (cl::push (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) ACL_result), - (cl::setf (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) $in)); -INOUT_TYPEMAP(double, - (cl::push (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) ACL_result), - (cl::setf (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) $in)); -INOUT_TYPEMAP(bool, - (cl::push (not (zerop (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out))) - ACL_result), - (cl::setf (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) (if $in 1 0))); - -%typemap(lisptype) bool *INPUT, bool &INPUT "boolean"; - -// long long support not yet complete -// INOUT_TYPEMAP(long long); -// INOUT_TYPEMAP(unsigned long long); - -// char *OUTPUT map. -// for this to work, swig needs to know how large an array to allocate. -// you can fake this by -// %typemap(ffitype) char *myarg "(:array :char 30)"; -// %apply char *OUTPUT { char *myarg }; -%typemap(lin,numinputs=0) char *OUTPUT, char &OUTPUT -%{(cl::let (($out (ff:allocate-fobject '$*in_fftype :c))) - $body - (cl::push (excl:native-to-string $out) ACL_result) - (ff:free-fobject $out)) %} - -// char *INPUT map. -%typemap(in) char *INPUT, char &INPUT -%{ $1 = &$input; %} -%typemap(ctype) char *INPUT, char &INPUT "$*1_ltype"; - -// char *INOUT map. -%typemap(lin,numinputs=1) char *INOUT, char &INOUT -%{(cl::let (($out (excl:string-to-native $in))) - $body - (cl::push (excl:native-to-string $out) ACL_result) - (ff:free-fobject $out)) %} - -// uncomment this if you want INOUT mappings for chars instead of strings. -// INOUT_TYPEMAP(char, -// (cl::push (code-char (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out)) -// ACL_result), -// (cl::setf (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) $in)); diff --git a/Lib/allegrocl/longlongs.i b/Lib/allegrocl/longlongs.i deleted file mode 100644 index a15adcdda..000000000 --- a/Lib/allegrocl/longlongs.i +++ /dev/null @@ -1,49 +0,0 @@ -/* ----------------------------------------------------------------------------- - * longlongs.i - * - * Typemap addition for support of 'long long' type and 'unsigned long long - * Makes use of swig-def-foreign-class, so this header should be loaded - * after allegrocl.swg and after any custom user identifier-conversion - * functions have been defined. - * ----------------------------------------------------------------------------- */ - -#ifdef Acl64Bit -%typemap(ctype) long long, unsigned long long "$1_ltype"; -%typemap(out) long long, unsigned long long "$result = $1;"; - -%typemap(ffitype) long long ":nat"; -%typemap(ffitype) unsigned long long ":unsigned-nat"; - -%typemap(lout) long long, unsigned long long " #+64bit (cl::setq ACL_ffresult $body)"; - -#else -%typemap(out) long long, unsigned long long "$result = &$1;"; -%typemap(ffitype) long long "(:struct (l1 :long) (l2 :long))"; - -%typemap(ffitype) unsigned long long "(:struct (l1 :unsigned-long) (l2 :unsigned-long))"; - -%typemap(lout) long long -" (cl::setq ACL_ffresult (make-instance '#.(swig-insert-id \"longlong\" () :type :class) - :foreign-address $body))"; - -%typemap(lout) unsigned long long -" (cl:setq ACL_ffresult (make-instance '#.(swig-insert-id \"ulonglong\" () :type :class) - :foreign-address $body))"; - -#endif - -%typemap(in) long long, unsigned long long "$1 = $input;"; - - -%insert("lisphead") %{ - -#-64bit -(swig-def-foreign-class "longlong" - (ff:foreign-pointer) - (:struct (l1 :long) (l2 :long))) - -#-64bit -(swig-def-foreign-class "ulonglong" - (ff:foreign-pointer) - (:struct (l1 :unsigned-long) (l2 :unsigned-long))) -%} diff --git a/Lib/allegrocl/std_list.i b/Lib/allegrocl/std_list.i deleted file mode 100644 index a3660c9f7..000000000 --- a/Lib/allegrocl/std_list.i +++ /dev/null @@ -1,230 +0,0 @@ -/* ----------------------------------------------------------------------------- - * std_list.i - * - * SWIG typemaps for std::list types - * - * To use, add: - * - * %include "std_list.i" - * - * to your interface file. You will also need to include a template directive - * for each instance of the list container you want to use in your application. - * e.g. - * - * %template (intlist) std::list; - * %template (floatlist) std::list; - * ----------------------------------------------------------------------------- */ - -%module std_list -%warnfilter(468) std::list; - -%{ -#include -#include -%} - - -namespace std{ - template class list - { - public: - typedef size_t size_type; - typedef ptrdiff_t difference_type; - typedef T value_type; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef T &iterator; - typedef const T& const_iterator; - - list(); - list(unsigned int size, const T& value = T()); - list(const list& other); - - void assign(unsigned int n, const T& value); - void swap(list &x); - - const_reference front(); - const_reference back(); - const_iterator begin(); - const_iterator end(); - - void resize(unsigned int n, T c = T()); - bool empty() const; - - void push_front(const T& INPUT); - void push_back(const T& INPUT); - - void pop_front(); - void pop_back(); - void clear(); - unsigned int size() const; - unsigned int max_size() const; - void resize(unsigned int n, const T& INPUT); - - void remove(const T& INPUT); - void unique(); - void reverse(); - void sort(); - - %extend - { - %typemap(lout) T &__getitem__ "(cl::setq ACL_ffresult (ff:fslot-value-typed '$*out_fftype :c $body))"; - %typemap(lout) T *__getitem__ "(cl::setq ACL_ffresult (make-instance '$lclass :foreign-address $body))"; - - const_reference __getitem__(int i) throw (std::out_of_range) - { - std::list::iterator first = self->begin(); - int size = int(self->size()); - if (i<0) i += size; - if (i>=0 && i::iterator first = self->begin(); - int size = int(self->size()); - if (i<0) i += size; - if (i>=0 && i::iterator first = self->begin(); - int size = int(self->size()); - if (i<0) i += size; - if (i>=0 && ierase(first); - } - else throw std::out_of_range("list index out of range"); - } - std::list __getslice__(int i,int j) - { - std::list::iterator first = self->begin(); - std::list::iterator end = self->end(); - - int size = int(self->size()); - if (i<0) i += size; - if (j<0) j += size; - if (i<0) i = 0; - if (j>size) j = size; - if (i>=j) i=j; - if (i>=0 && i=0) - { - for (int k=0;k tmp(j-i); - if (j>i) std::copy(first,end,tmp.begin()); - return tmp; - } - else throw std::out_of_range("list index out of range"); - } - void __delslice__(int i,int j) - { - std::list::iterator first = self->begin(); - std::list::iterator end = self->end(); - - int size = int(self->size()); - if (i<0) i += size; - if (j<0) j += size; - if (i<0) i = 0; - if (j>size) j = size; - - for (int k=0;kerase(first,end); - } - void __setslice__(int i,int j, const std::list& v) - { - std::list::iterator first = self->begin(); - std::list::iterator end = self->end(); - - int size = int(self->size()); - if (i<0) i += size; - if (j<0) j += size; - if (i<0) i = 0; - if (j>size) j = size; - - for (int k=0;kerase(first,end); - if (i+1 <= int(self->size())) - { - first = self->begin(); - for (int k=0;kinsert(first,v.begin(),v.end()); - } - else self->insert(self->end(),v.begin(),v.end()); - } - } - unsigned int __len__() - { - return self->size(); - } - bool __nonzero__() - { - return !(self->empty()); - } - void append(const T& INPUT) - { - self->push_back(INPUT); - } - void pop() - { - self->pop_back(); - } - } - }; -} - - - - - - diff --git a/Lib/allegrocl/std_string.i b/Lib/allegrocl/std_string.i deleted file mode 100644 index cbcd250a9..000000000 --- a/Lib/allegrocl/std_string.i +++ /dev/null @@ -1,209 +0,0 @@ -/* ----------------------------------------------------------------------------- - * std_string.i - * - * SWIG typemaps for std::string - * ----------------------------------------------------------------------------- */ - -// ------------------------------------------------------------------------ -// std::string is typemapped by value -// This can prevent exporting methods which return a string -// in order for the user to modify it. -// However, I think I'll wait until someone asks for it... -// ------------------------------------------------------------------------ - -// %include -%warnfilter(404) std::string; -%warnfilter(404) std::wstring; - -%{ -#include -%} - -// %include - -// %naturalvar std::string; -// %naturalvar std::wstring; - -namespace std { - typedef unsigned long size_t; - typedef signed long ptrdiff_t; - - template class basic_string { - public: - typedef charT *pointer; - typedef charT &reference; - typedef const charT &const_reference; - typedef size_t size_type; - typedef ptrdiff_t difference_type; - basic_string(); - basic_string( charT *str ); - size_type size(); - charT operator []( int pos ) const; - charT *c_str() const; - basic_string &operator = ( const basic_string &ws ); - basic_string &operator = ( const charT *str ); - basic_string &append( const basic_string &other ); - basic_string &append( const charT *str ); - void push_back( charT c ); - void clear(); - void reserve( size_type t ); - void resize( size_type n, charT c = charT() ); - int compare( const basic_string &other ) const; - int compare( const charT *str ) const; - basic_string &insert( size_type pos, - const basic_string &str ); - size_type find( const basic_string &other, int pos = 0 ) const; - size_type find( charT c, int pos = 0 ) const; - %extend { - bool operator == ( const basic_string &other ) const { - return self->compare( other ) == 0; - } - bool operator != ( const basic_string &other ) const { - return self->compare( other ) != 0; - } - bool operator < ( const basic_string &other ) const { - return self->compare( other ) == -1; - } - bool operator > ( const basic_string &other ) const { - return self->compare( other ) == 1; - } - bool operator <= ( const basic_string &other ) const { - return self->compare( other ) != 1; - } - bool operator >= ( const basic_string &other ) const { - return self->compare( other ) != -1; - } - - } - }; - - %template(string) basic_string; - %template(wstring) basic_string; - - %apply char * { string }; - %apply wchar_t * { wstring }; - - typedef basic_string string; - typedef basic_string wstring; - - // automatically convert constant std::strings to cl:strings - %typemap(ctype) string "char *"; - %typemap(in) string "$1.assign($input);"; - %typemap(out) string "$result = (char *)(&$1)->c_str();"; - %typemap(lisptype) string "cl:string"; - %typemap(lout) string "(cl::setq ACL_ffresult $body)"; - - %typemap(ctype) const string *"char *"; - %typemap(in) const string * "$1.assign($input);"; - %typemap(out) const string * "$result = (char *)($1)->c_str();"; - %typemap(lisptype) const string * "cl:string"; - %typemap(lout) const string * "(cl::setq ACL_ffresult $body)"; - - %typemap(ctype) wstring "wchar_t *"; - %typemap(in) wstring "$1.assign($input);"; - %typemap(out) wstring "$result = (wchar_t *)(&$1)->c_str();"; - %typemap(lisptype) wstring "cl:string"; - %typemap(lout) wstring "(cl::setq ACL_ffresult (excl:native-to-string $body -:external-format #+little-endian :fat-le #-little-endian :fat))"; - - %typemap(ctype) const wstring *"char *"; - %typemap(in) const wstring * "$1.assign($input);"; - %typemap(out) const wstring * "$result = (char *)($1)->c_str();"; - %typemap(lisptype) const wstring * "cl:string"; - %typemap(lout) const wstring * "(cl::setq ACL_ffresult $body)"; - - /* Overloading check */ -// %typemap(in) string { -// if (caml_ptr_check($input)) -// $1.assign((char *)caml_ptr_val($input,0), -// caml_string_len($input)); -// else -// SWIG_exception(SWIG_TypeError, "string expected"); -// } - -// %typemap(in) const string & ($*1_ltype temp) { -// if (caml_ptr_check($input)) { -// temp.assign((char *)caml_ptr_val($input,0), -// caml_string_len($input)); -// $1 = &temp; -// } else { -// SWIG_exception(SWIG_TypeError, "string expected"); -// } -// } - -// %typemap(in) string & ($*1_ltype temp) { -// if (caml_ptr_check($input)) { -// temp.assign((char *)caml_ptr_val($input,0), -// caml_string_len($input)); -// $1 = &temp; -// } else { -// SWIG_exception(SWIG_TypeError, "string expected"); -// } -// } - -// %typemap(in) string * ($*1_ltype *temp) { -// if (caml_ptr_check($input)) { -// temp = new $*1_ltype((char *)caml_ptr_val($input,0), -// caml_string_len($input)); -// $1 = temp; -// } else { -// SWIG_exception(SWIG_TypeError, "string expected"); -// } -// } - -// %typemap(free) string * ($*1_ltype *temp) { -// delete temp; -// } - -// %typemap(argout) string & { -// caml_list_append(swig_result,caml_val_string_len((*$1).c_str(), -// (*$1).size())); -// } - -// %typemap(directorout) string { -// $result.assign((char *)caml_ptr_val($input,0), -// caml_string_len($input)); -// } - -// %typemap(out) string { -// $result = caml_val_string_len($1.c_str(),$1.size()); -// } - -// %typemap(out) string * { -// $result = caml_val_string_len((*$1).c_str(),(*$1).size()); -// } -} - -// #ifdef ENABLE_CHARPTR_ARRAY -// char **c_charptr_array( const std::vector &str_v ); - -// %{ -// SWIGEXT char **c_charptr_array( const std::vector &str_v ) { -// char **out = new char *[str_v.size() + 1]; -// out[str_v.size()] = 0; -// for( int i = 0; i < str_v.size(); i++ ) { -// out[i] = (char *)str_v[i].c_str(); -// } -// return out; -// } -// %} -// #endif - -// #ifdef ENABLE_STRING_VECTOR -// %template (StringVector) std::vector; - -// %insert(ml) %{ -// (* Some STL convenience items *) - -// let string_array_to_vector sa = -// let nv = _new_StringVector C_void in -// array_to_vector nv (fun x -> C_string x) sa ; nv - -// let c_string_array ar = -// _c_charptr_array (string_array_to_vector ar) -// %} - -// %insert(mli) %{ -// val c_string_array: string array -> c_obj -// %} -// #endif diff --git a/Lib/allegrocl/typemaps.i b/Lib/allegrocl/typemaps.i deleted file mode 100644 index 293d1cd34..000000000 --- a/Lib/allegrocl/typemaps.i +++ /dev/null @@ -1,4 +0,0 @@ -/* Unused for Allegro CL module */ - -%include "inout_typemaps.i" -%include "longlongs.i" diff --git a/Lib/carrays.i b/Lib/carrays.i index 3a9c3cfee..0aa3eee89 100644 --- a/Lib/carrays.i +++ b/Lib/carrays.i @@ -5,6 +5,12 @@ * pointers as arrays. * ----------------------------------------------------------------------------- */ +#ifndef __cplusplus +// C uses free/calloc/malloc +%include "swigfragments.swg" +%fragment(""); +#endif + /* ----------------------------------------------------------------------------- * %array_functions(TYPE,NAME) * diff --git a/Lib/cdata.i b/Lib/cdata.i index f18ed4af5..8736de1c2 100644 --- a/Lib/cdata.i +++ b/Lib/cdata.i @@ -4,6 +4,8 @@ * SWIG library file containing macros for manipulating raw C data as strings. * ----------------------------------------------------------------------------- */ +%include + %{ typedef struct SWIGCDATA { char *data; @@ -21,7 +23,7 @@ typedef struct SWIGCDATA { } %typemap(in) (const void *indata, int inlen) = (char *STRING, int LENGTH); -#elif SWIGPHP7 +#elif SWIGPHP %typemap(out) SWIGCDATA { ZVAL_STRINGL($result, $1.data, $1.len); @@ -60,7 +62,7 @@ static jbyteArray SWIG_JavaArrayOutCDATA(JNIEnv *jenv, char *result, jsize sz) { /* ----------------------------------------------------------------------------- - * %cdata(TYPE [, NAME]) + * %cdata(TYPE [, NAME]) * * Convert raw C data to a binary string. * ----------------------------------------------------------------------------- */ @@ -99,6 +101,8 @@ SWIGCDATA cdata_##NAME(TYPE *ptr, int nelements); %cdata(void); +%fragment(""); + /* Memory move function. Due to multi-argument typemaps this appears to be wrapped as void memmove(void *data, const char *s); */ void memmove(void *data, const void *indata, int inlen); diff --git a/Lib/chicken/chicken.swg b/Lib/chicken/chicken.swg deleted file mode 100644 index 7df676754..000000000 --- a/Lib/chicken/chicken.swg +++ /dev/null @@ -1,809 +0,0 @@ -/* ----------------------------------------------------------------------------- - * chicken.swg - * - * CHICKEN configuration module. - * ----------------------------------------------------------------------------- */ - -/* chicken.h has to appear first. */ - -%insert(runtime) %{ -#include -#include -%} - -%insert(runtime) "swigrun.swg" // Common C API type-checking code -%insert(runtime) "swigerrors.swg" // SWIG errors -%insert(runtime) "chickenrun.swg" // CHICKEN run-time code - -/* ----------------------------------------------------------------------------- - * standard typemaps - * ----------------------------------------------------------------------------- */ - -/* - CHICKEN: C - ---------- - - fixnum: int, short, unsigned int, unsigned short, unsigned char, - signed char - - char: char - - bool: bool - - flonum: float, double, long, long long, unsigned long, unsigned long - long - */ - -/* --- Primitive types --- */ - -%define SIMPLE_TYPEMAP(type_, from_scheme, to_scheme, checker, convtype, storage_) - -%typemap(in) type_ -%{ if (!checker ($input)) { - swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument #$argnum is not of type 'type_'"); - } - $1 = ($1_ltype) from_scheme ($input); %} - -/* Const primitive references. Passed by value */ - -%typemap(in) const type_ & ($*1_ltype temp) -%{ if (!checker ($input)) { - swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument #$argnum is not of type 'type_'"); - } - temp = ($*1_ltype) from_scheme ($input); - $1 = &temp; %} - -/* --- Variable input --- */ -%typemap(varin) type_ -%{ if (!checker ($input)) { - swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Cannot use '$1_ltype' for variable '$name' of type 'type_'"); - } - $1 = ($1_ltype) from_scheme ($input); %} - -#if "storage_" == "0" - -%typemap(out) type_ -%{ - $result = to_scheme (convtype ($1)); -%} - -/* References to primitive types. Return by value */ - -%typemap(out) const type_ & -%{ - $result = to_scheme (convtype (*$1)); -%} - -/* --- Variable output --- */ -%typemap(varout) type_ -%{ - $result = to_scheme (convtype ($varname)); -%} - -%typemap(throws) type_ -%{ - SWIG_Chicken_ThrowException(to_scheme ( convtype ($1))); -%} - -#else - -%typemap(out) type_ -%{ - { - C_word *space = C_alloc(storage_); - $result = to_scheme (&space, convtype ($1)); - } -%} - -/* References to primitive types. Return by value */ - -%typemap(out) const type_ & -%{ - { - C_word *space = C_alloc(storage_); - $result = to_scheme (&space, convtype (*$1)); - } -%} - -/* --- Variable output --- */ -%typemap(varout) type_ -%{ - { - C_word *space = C_alloc(storage_); - $result = to_scheme (&space, convtype ($varname)); - } -%} - -%typemap(throws) type_ -%{ - { - C_word *space = C_alloc(storage_); - SWIG_Chicken_ThrowException(to_scheme (&space, convtype ($1))); - } -%} - -#endif - -/* --- Constants --- */ - -%typemap(constcode) type_ -"static const $1_type $result = $value;" - -%enddef - -SIMPLE_TYPEMAP(int, C_num_to_int, C_fix, C_swig_is_number, (int), 0); -//SIMPLE_TYPEMAP(enum SWIGTYPE, C_unfix, C_fix, C_swig_is_fixnum, (int), 0); -SIMPLE_TYPEMAP(short, C_num_to_int, C_fix, C_swig_is_number, (int), 0); -SIMPLE_TYPEMAP(long, C_num_to_long, C_long_to_num, C_swig_is_long, (long), C_SIZEOF_FLONUM); -SIMPLE_TYPEMAP(long long, C_num_to_long, C_long_to_num, C_swig_is_long, (long), C_SIZEOF_FLONUM); -SIMPLE_TYPEMAP(unsigned int, C_num_to_unsigned_int, C_unsigned_int_to_num, C_swig_is_number, (unsigned int), C_SIZEOF_FLONUM); -SIMPLE_TYPEMAP(unsigned short, C_num_to_unsigned_int, C_fix, C_swig_is_number, (unsigned int), 0); -SIMPLE_TYPEMAP(unsigned long, C_num_to_unsigned_long, C_unsigned_long_to_num, C_swig_is_long, (unsigned long), C_SIZEOF_FLONUM); -SIMPLE_TYPEMAP(unsigned long long, C_num_to_unsigned_long, C_unsigned_long_to_num, C_swig_is_long, (unsigned long), C_SIZEOF_FLONUM); -SIMPLE_TYPEMAP(unsigned char, C_character_code, C_make_character, C_swig_is_char, (unsigned int), 0); -SIMPLE_TYPEMAP(signed char, C_character_code, C_make_character, C_swig_is_char, (int), 0); -SIMPLE_TYPEMAP(char, C_character_code, C_make_character, C_swig_is_char, (char), 0); -SIMPLE_TYPEMAP(bool, C_truep, C_mk_bool, C_swig_is_bool, (bool), 0); -SIMPLE_TYPEMAP(float, C_c_double, C_flonum, C_swig_is_number, (double), C_SIZEOF_FLONUM); -SIMPLE_TYPEMAP(double, C_c_double, C_flonum, C_swig_is_number, (double), C_SIZEOF_FLONUM); - -/* enum SWIGTYPE */ -%apply int { enum SWIGTYPE }; -%apply const int& { const enum SWIGTYPE& }; -%apply const int& { const enum SWIGTYPE&& }; - -%typemap(varin) enum SWIGTYPE -{ - if (!C_swig_is_fixnum($input) && sizeof(int) != sizeof($1)) { - swig_barf(SWIG_BARF1_BAD_ARGUMENT_TYPE, "enum variable '$name' can not be set"); - } - *((int *)(void *)&$1) = C_unfix($input); -} - - -/* --- Input arguments --- */ - -/* Strings */ - -%typemap(in) char * -{ if ($input == C_SCHEME_FALSE) { - $1 = NULL; - } - else { - if (!C_swig_is_string ($input)) { - swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument #$argnum is not of type 'char *'"); - } - $1 = ($ltype) SWIG_MakeString ($input); - } -} - -%typemap(freearg) char * "if ($1 != NULL) { free ($1); }" - -/* Pointers, references, and arrays */ -%typemap(in,closcode="(slot-ref $input 'swig-this)") SWIGTYPE *, SWIGTYPE [], SWIGTYPE &, SWIGTYPE && { - $1 = ($1_ltype)SWIG_MustGetPtr($input, $descriptor, $argnum, $disown); -} - -%typemap(in,closcode="(slot-ref $input 'swig-this)") SWIGTYPE *DISOWN { - $1 = ($1_ltype)SWIG_MustGetPtr($input, $descriptor, $argnum, SWIG_POINTER_DISOWN); -} - -/* Void pointer. Accepts any kind of pointer */ -%typemap(in) void * { - $1 = ($1_ltype)SWIG_MustGetPtr($input, NULL, $argnum, 0); -} - -%typemap(varin,closcode="(slot-ref $input 'swig-this)") SWIGTYPE * { - $1 = ($1_ltype)SWIG_MustGetPtr($input, $descriptor, 1, SWIG_POINTER_DISOWN); -} - -%typemap(varin,closcode="(slot-ref $input 'swig-this)") SWIGTYPE & { - $1 = *(($1_ltype)SWIG_MustGetPtr($input, $descriptor, 1, 0)); -} - -%typemap(varin,closcode="(slot-ref $input 'swig-this)") SWIGTYPE && { - $1 = *(($1_ltype)SWIG_MustGetPtr($input, $descriptor, 1, 0)); -} - -%typemap(varin) SWIGTYPE [] { - SWIG_Chicken_Barf(SWIG_BARF1_BAD_ARGUMENT_TYPE, "Type error"); -} - -%typemap(varin) SWIGTYPE [ANY] { - void *temp; - int ii; - $1_basetype *b = 0; - temp = SWIG_MustGetPtr($input, $1_descriptor, 1, 0); - b = ($1_basetype *) $1; - for (ii = 0; ii < $1_size; ii++) b[ii] = *(($1_basetype *) temp + ii); -} - -%typemap(varin) void * { - $1 = SWIG_MustGetPtr($input, NULL, 1, 0); -} - -%typemap(out) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] { - C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER); - $result = SWIG_NewPointerObj($1, $descriptor, $owner); -} - -%typemap(out) SWIGTYPE *DYNAMIC, SWIGTYPE &DYNAMIC { - C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER); - swig_type_info *ty = SWIG_TypeDynamicCast($1_descriptor,(void **) &$1); - $result = SWIG_NewPointerObj($1, ty, $owner); -} - -%typemap(varout) SWIGTYPE *, SWIGTYPE [] { - C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER); - $result = SWIG_NewPointerObj($varname, $descriptor, 0); -} - -%typemap(varout) SWIGTYPE & { - C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER); - $result = SWIG_NewPointerObj((void *) &$varname, $1_descriptor, 0); -} - -%typemap(varout) SWIGTYPE && { - C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER); - $result = SWIG_NewPointerObj((void *) &$varname, $1_descriptor, 0); -} - -/* special typemaps for class pointers */ -%typemap(in) SWIGTYPE (CLASS::*) { - char err_msg[256]; - - if (C_swig_is_pair($input)) { - /* try and convert pointer object */ - void *result; - if (!SWIG_ConvertPtr(C_block_item($input,1), &result, $descriptor, 0)) { - C_word ptr = C_block_item($input,0); - if (C_swig_is_string(ptr)) { - SWIG_UnpackData(C_c_string(ptr), (void *) &$1, sizeof($type)); - } else { - snprintf(err_msg, sizeof(err_msg), "Type error in argument #%i: expected %s", $argnum, ($descriptor->str ? $descriptor->str : $descriptor->name)); - SWIG_Chicken_Barf(SWIG_BARF1_BAD_ARGUMENT_TYPE, err_msg); - } - } else { - snprintf(err_msg, sizeof(err_msg), "Type error in argument #%i: expected %s", $argnum, ($descriptor->str ? $descriptor->str : $descriptor->name)); - SWIG_Chicken_Barf(SWIG_BARF1_BAD_ARGUMENT_TYPE, err_msg); - } - } else { - snprintf(err_msg, sizeof(err_msg), "Type error in argument #%i: expected %s", $argnum, ($descriptor->str ? $descriptor->str : $descriptor->name)); - SWIG_Chicken_Barf(SWIG_BARF1_BAD_ARGUMENT_TYPE, err_msg); - } -} - -%typemap(out) SWIGTYPE (CLASS::*) { - size_t ptr_size = sizeof($type); - C_word *known_space = C_alloc(C_SIZEOF_PAIR + C_SIZEOF_STRING(2*ptr_size) + C_SIZEOF_SWIG_POINTER); - char *temp = (char *)malloc(2*ptr_size); - C_word ptr = SWIG_NewPointerObj((void *) known_space, $descriptor, 0); - - SWIG_PackData(temp, (void *) &$1, ptr_size); - $result = C_pair(&known_space, C_string(&known_space, 2*ptr_size, temp), ptr); - free(temp); -} - -%typemap(varin) SWIGTYPE (CLASS::*) { - char err_msg[256]; - - if (C_swig_is_pair($input)) { - /* try and convert pointer object */ - void *result; - if (!SWIG_ConvertPtr(C_block_item($input,1), &result, $descriptor, 0)) { - C_word ptr = C_block_item($input,0); - if (C_swig_is_string(ptr)) { - SWIG_UnpackData(C_c_string(ptr), (void *) &$1, sizeof($type)); - } else { - snprintf(err_msg, sizeof(err_msg), "Type error in argument #%i: expected %s", 1, ($descriptor->str ? $descriptor->str : $descriptor->name)); - SWIG_Chicken_Barf(SWIG_BARF1_BAD_ARGUMENT_TYPE, err_msg); - } - } else { - snprintf(err_msg, sizeof(err_msg), "Type error in argument #%i: expected %s", 1, ($descriptor->str ? $descriptor->str : $descriptor->name)); - SWIG_Chicken_Barf(SWIG_BARF1_BAD_ARGUMENT_TYPE, err_msg); - } - } else { - snprintf(err_msg, sizeof(err_msg), "Type error in argument #%i: expected %s", 1, ($descriptor->str ? $descriptor->str : $descriptor->name)); - SWIG_Chicken_Barf(SWIG_BARF1_BAD_ARGUMENT_TYPE, err_msg); - } -} - -%typemap(varout) SWIGTYPE (CLASS::*) { - size_t ptr_size = sizeof($type); - C_word *known_space = C_alloc(C_SIZEOF_PAIR + C_SIZEOF_STRING(2*ptr_size) + C_SIZEOF_SWIG_POINTER); - char *temp = (char *)malloc(2*ptr_size); - C_word ptr = SWIG_NewPointerObj((void *) known_space, $descriptor, 0); - - SWIG_PackData(temp, (void *) &$varname, ptr_size); - $result = C_pair(&known_space, C_string(&known_space, 2*ptr_size, temp), ptr); - free(temp); -} - - - -/* Pass-by-value */ - -%typemap(in,closcode="(slot-ref $input 'swig-this)") SWIGTYPE($&1_ltype argp) { - argp = ($&1_ltype)SWIG_MustGetPtr($input, $&1_descriptor, $argnum, 0); - $1 = *argp; -} - -%typemap(varin,closcode="(slot-ref $input 'swig-this)") SWIGTYPE { - $&1_ltype argp; - argp = ($&1_ltype)SWIG_MustGetPtr($input, $&1_descriptor, 1, 0); - $1 = *argp; -} - -%typemap(out) SWIGTYPE -#ifdef __cplusplus -{ - $&1_ltype resultptr; - C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER); - resultptr = new $1_ltype((const $1_ltype &) $1); - $result = SWIG_NewPointerObj(resultptr, $&1_descriptor, 1); -} -#else -{ - $&1_ltype resultptr; - C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER); - resultptr = ($&1_ltype) malloc(sizeof($1_type)); - memmove(resultptr, &$1, sizeof($1_type)); - $result = SWIG_NewPointerObj(resultptr, $&1_descriptor, 1); -} -#endif - -%typemap(varout) SWIGTYPE -#ifdef __cplusplus -{ - $&1_ltype resultptr; - C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER); - resultptr = new $1_ltype((const $1_ltype&) $1); - $result = SWIG_NewPointerObj(resultptr, $&1_descriptor, 0); -} -#else -{ - $&1_ltype resultptr; - C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER); - resultptr = ($&1_ltype) malloc(sizeof($1_type)); - memmove(resultptr, &$1, sizeof($1_type)); - $result = SWIG_NewPointerObj(resultptr, $&1_descriptor, 0); -} -#endif - -/* --- Output values --- */ - -/* Strings */ - -%typemap(out) - char * -{ char *s = (char*) $1; - if ($1 == NULL) { - $result = C_SCHEME_FALSE; - } - else { - int string_len = strlen ((char *) ($1)); - C_word *string_space = C_alloc (C_SIZEOF_STRING (string_len)); - $result = C_string (&string_space, string_len, s); - } -} - -%typemap(varout) - char * -{ char *s = (char*) $varname; - if ($varname == NULL) { - $result = C_SCHEME_FALSE; - } - else { - int string_len = strlen ($varname); - C_word *string_space = C_alloc (C_SIZEOF_STRING (string_len)); - $result = C_string (&string_space, string_len, s); - } -} - -%typemap(throws) char * -{ - if ($1 == NULL) { - SWIG_Chicken_ThrowException(C_SCHEME_FALSE); - } else { - int string_len = strlen($1); - C_word *string_space = C_alloc(C_SIZEOF_STRING(string_len)); - SWIG_Chicken_ThrowException(C_string(&string_space, string_len, (char *) $1)); - } -} - -/* Void */ -%typemap(out) void -%{ -$result = C_SCHEME_UNDEFINED; -%} - -/* Special typemap for character array return values */ - -%typemap(out) - char [ANY], const char [ANY] -%{ if ($1 == NULL) { - $result = C_SCHEME_FALSE; - } - else { - const int string_len = strlen ($1); - C_word *string_space = C_alloc (C_SIZEOF_STRING (string_len)); - $result = C_string (&string_space, string_len, $1); - } %} - -/* Primitive types--return by value */ - -/* --- Variable input --- */ - -/* A string */ -#ifdef __cplusplus -%typemap(varin) char * { - if ($input == C_SCHEME_FALSE) { - $1 = NULL; - } - else if (!C_swig_is_string ($input)) { - swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "C variable '$name ($1_ltype)'"); - } - else { - char *temp = C_c_string ($input); - int len = C_header_size ($input); - if ($1) delete [] $1; - $1 = ($type) new char[len+1]; - strncpy((char*)$1, temp, len); - ((char*)$1) [len] = 0; - } -} -%typemap(varin,warning="451:Setting const char * variable may leak memory") const char * { - if ($input == C_SCHEME_FALSE) { - $1 = NULL; - } - else if (!C_swig_is_string ($input)) { - swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "C variable '$name ($1_ltype)'"); - } - else { - char *temp = C_c_string ($input); - int len = C_header_size ($input); - $1 = ($type) new char[len+1]; - strncpy((char*)$1,temp,len); - ((char*)$1) [len] = 0; - } -} -#else -%typemap(varin) char * { - if ($input == C_SCHEME_FALSE) { - $1 = NULL; - } - else if (!C_swig_is_string ($input)) { - swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "C variable '$name ($1_ltype)'"); - } - else { - char *temp = C_c_string ($input); - int len = C_header_size ($input); - if ($1) free((char*) $1); - $1 = ($type) malloc(len+1); - strncpy((char*)$1,temp,len); - ((char*)$1) [len] = 0; - } -} -%typemap(varin,warning="451:Setting const char * variable may leak memory") const char * { - if ($input == C_SCHEME_FALSE) { - $1 = NULL; - } - else if (!C_swig_is_string ($input)) { - swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "C variable '$name ($1_ltype)'"); - } - else { - char *temp = C_c_string ($input); - int len = C_header_size ($input); - $1 = ($type) malloc(len+1); - strncpy((char*)$1,temp,len); - ((char*)$1) [len] = 0; - } -} -#endif - -%typemap(varin) char [] { - swig_barf(SWIG_BARF1_BAD_ARGUMENT_TYPE, "C/C++ variable '$name' is read-only"); -} - -/* Special case for string array variables */ -%typemap(varin) char [ANY] { - if ($input == C_SCHEME_FALSE) { - memset($1,0,$1_dim0*sizeof(char)); - } - else if (!C_swig_is_string ($input)) { - swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "C variable '$name ($1_ltype)'"); - } - else { - char *temp = C_c_string ($input); - strncpy($1,temp,$1_dim0*sizeof(char)); - } -} - -/* --- Variable output --- */ - -/* Void */ -%typemap(varout) void "$result = C_SCHEME_UNDEFINED;"; - -/* Special typemap for character array return values */ -%typemap(varout) char [ANY], const char [ANY] -%{ if ($varname == NULL) { - $result = C_SCHEME_FALSE; - } - else { - const int string_len = strlen ($varname); - C_word *string_space = C_alloc (C_SIZEOF_STRING (string_len)); - $result = C_string (&string_space, string_len, (char *) $varname); - } -%} - - -/* --- Constants --- */ - -%typemap(constcode) char * -"static const char *$result = $value;" - -%typemap(constcode) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] -"static const void *$result = (void*) $value;" - -/* ------------------------------------------------------------ - * String & length - * ------------------------------------------------------------ */ - -%typemap(in) (char *STRING, int LENGTH), (char *STRING, size_t LENGTH) { - if ($input == C_SCHEME_FALSE) { - swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Cannot use a null/#f string for a char*, int arguments"); - } - else if (C_swig_is_string ($input)) { - $1 = ($1_ltype) C_c_string ($input); - $2 = ($2_ltype) C_header_size ($input); - } - else { - swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument #$argnum is not of type 'string'"); - } -} - -/* ------------------------------------------------------------ - * CHICKEN types - * ------------------------------------------------------------ */ - -%typemap(in) C_word "$1 = $input;"; -%typemap(out) C_word "$result = $1;"; - -/* ------------------------------------------------------------ - * Typechecking rules - * ------------------------------------------------------------ */ - -%typecheck(SWIG_TYPECHECK_INTEGER) - bool, const bool & -{ - $1 = C_swig_is_bool ($input); -} - -%typecheck(SWIG_TYPECHECK_INTEGER) - int, short, - unsigned int, unsigned short, - signed char, unsigned char, - const int &, const short &, - const unsigned int &, const unsigned short &, - enum SWIGTYPE -{ - $1 = C_swig_is_fixnum ($input); -} - -%typecheck(SWIG_TYPECHECK_INTEGER) - long, - unsigned long, - long long, unsigned long long, - const long &, - const unsigned long &, - const long long &, const unsigned long long & -{ - $1 = (C_swig_is_bool ($input) || - C_swig_is_fixnum ($input) || - C_swig_is_flonum ($input)) ? 1 : 0; -} - -%typecheck(SWIG_TYPECHECK_DOUBLE) - float, double, - const float &, const double & -{ - $1 = C_swig_is_flonum ($input); -} - -%typecheck(SWIG_TYPECHECK_CHAR) char { - $1 = C_swig_is_string ($input); -} - -%typecheck(SWIG_TYPECHECK_STRING) char * { - $1 = C_swig_is_string ($input); -} - -%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE [] { - void *ptr; - $1 = !SWIG_ConvertPtr($input, &ptr, $1_descriptor, 0); -} - -%typecheck(SWIG_TYPECHECK_VOIDPTR) void * { - void *ptr; - $1 = !SWIG_ConvertPtr($input, &ptr, 0, 0); -} - -%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE & -{ - void *ptr = 0; - if (SWIG_ConvertPtr($input, &ptr, $descriptor, SWIG_POINTER_NO_NULL)) { - $1 = 0; - } else { - $1 = 1; - } -} - -%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE && -{ - void *ptr = 0; - if (SWIG_ConvertPtr($input, &ptr, $descriptor, SWIG_POINTER_NO_NULL)) { - $1 = 0; - } else { - $1 = 1; - } -} - -%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE -{ - void *ptr = 0; - if (SWIG_ConvertPtr($input, &ptr, $&descriptor, SWIG_POINTER_NO_NULL)) { - $1 = 0; - } else { - $1 = 1; - } -} - - -/* ------------------------------------------------------------ - * Exception handling - * ------------------------------------------------------------ */ - -/* ------------------------------------------------------------ - * --- Exception handling --- - * ------------------------------------------------------------ */ - -%typemap(throws) SWIGTYPE { - $<ype temp = new $ltype($1); - C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER); - C_word ptr = SWIG_NewPointerObj(temp, $&descriptor,1); - SWIG_Chicken_ThrowException(ptr); -} - -%typemap(throws) SWIGTYPE * { - C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER); - C_word ptr = SWIG_NewPointerObj((void *) $1, $descriptor, 0); - SWIG_Chicken_ThrowException(ptr); -} - -%typemap(throws) SWIGTYPE [ANY] { - C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER); - C_word ptr = SWIG_NewPointerObj((void *) $1, $descriptor, 0); - SWIG_Chicken_ThrowException(ptr); -} - -%typemap(throws) SWIGTYPE & { - C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER); - C_word ptr = SWIG_NewPointerObj((void *)&($1),$descriptor,0); - SWIG_Chicken_ThrowException(ptr); -} - -%typemap(throws) SWIGTYPE && { - C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER); - C_word ptr = SWIG_NewPointerObj((void *)&($1),$descriptor,0); - SWIG_Chicken_ThrowException(ptr); -} - -/* ------------------------------------------------------------ - * ANSI C typemaps - * ------------------------------------------------------------ */ - -%apply unsigned long { size_t }; - -/* ------------------------------------------------------------ - * Various - * ------------------------------------------------------------ */ - -/* Array reference typemaps */ -%apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } -%apply SWIGTYPE && { SWIGTYPE ((&&)[ANY]) } - -/* const pointers */ -%apply SWIGTYPE * { SWIGTYPE *const } -%apply SWIGTYPE (CLASS::*) { SWIGTYPE (CLASS::*const) } -%apply SWIGTYPE & { SWIGTYPE (CLASS::*const&) } - -/* ------------------------------------------------------------ - * Overloaded operator support - * ------------------------------------------------------------ */ - -#ifdef __cplusplus -%rename(__add__) *::operator+; -%rename(__pos__) *::operator+(); -%rename(__pos__) *::operator+() const; -%rename(__sub__) *::operator-; -%rename(__neg__) *::operator-(); -%rename(__neg__) *::operator-() const; -%rename(__mul__) *::operator*; -%rename(__div__) *::operator/; -%rename(__mod__) *::operator%; -%rename(__lshift__) *::operator<<; -%rename(__rshift__) *::operator>>; -%rename(__and__) *::operator&; -%rename(__or__) *::operator|; -%rename(__xor__) *::operator^; -%rename(__invert__) *::operator~; -%rename(__iadd__) *::operator+=; -%rename(__isub__) *::operator-=; -%rename(__imul__) *::operator*=; -%rename(__idiv__) *::operator/=; -%rename(__imod__) *::operator%=; -%rename(__ilshift__) *::operator<<=; -%rename(__irshift__) *::operator>>=; -%rename(__iand__) *::operator&=; -%rename(__ior__) *::operator|=; -%rename(__ixor__) *::operator^=; -%rename(__lt__) *::operator<; -%rename(__le__) *::operator<=; -%rename(__gt__) *::operator>; -%rename(__ge__) *::operator>=; -%rename(__eq__) *::operator==; -%rename(__ne__) *::operator!=; - -/* Special cases */ -%rename(__call__) *::operator(); - -#endif -/* Warnings for certain CHICKEN keywords */ -%include - -/* TinyCLOS <--> Low-level CHICKEN */ - -%typemap("clos_in") SIMPLE_CLOS_OBJECT * "(slot-ref $input (quote this))" -%typemap("clos_out") SIMPLE_CLOS_OBJECT * "(make $class (quote this) $1)" - -%insert(header) %{ -#ifdef __cplusplus -extern "C" { -#endif -/* Chicken initialization function */ -SWIGEXPORT void SWIG_init(C_word, C_word, C_word) C_noret; -#ifdef __cplusplus -} -#endif -%} - -%insert(closprefix) "swigclosprefix.scm" - -%insert(init) "swiginit.swg" - -%insert(init) %{ -/* CHICKEN initialization function */ -#ifdef __cplusplus -extern "C" { -#endif -SWIGEXPORT void SWIG_init(C_word argc, C_word closure, C_word continuation) { - int i; - C_word sym; - C_word tmp; - C_word *a; - C_word ret; - C_word *return_vec; - - SWIG_InitializeModule(0); - SWIG_PropagateClientData(); - ret = C_SCHEME_TRUE; - -#if $veclength - return_vec = C_alloc(C_SIZEOF_VECTOR($veclength)); - ret = (C_word) return_vec; - *(return_vec++) = C_VECTOR_TYPE | $veclength; -#endif - - a = C_alloc(2*$nummethods$symsize); - -%} diff --git a/Lib/chicken/chickenkw.swg b/Lib/chicken/chickenkw.swg deleted file mode 100644 index d2c26c74c..000000000 --- a/Lib/chicken/chickenkw.swg +++ /dev/null @@ -1,31 +0,0 @@ -#ifndef CHICKEN_CHICKENKW_SWG_ -#define CHICKEN_CHICKENKW_SWG_ - -/* Warnings for certain CHICKEN keywords. From Section 7.1.1 of - Revised^5 Report on the Algorithmic Language Scheme */ -#define CHICKENKW(x) %namewarn("314: '" #x "' is a R^5RS syntatic keyword") #x - -CHICKENKW(else); -CHICKENKW(=>); -CHICKENKW(define); -CHICKENKW(unquote); -CHICKENKW(unquote-splicing); -CHICKENKW(quote); -CHICKENKW(lambda); -CHICKENKW(if); -CHICKENKW(set!); -CHICKENKW(begin); -CHICKENKW(cond); -CHICKENKW(and); -CHICKENKW(or); -CHICKENKW(case); -CHICKENKW(let); -CHICKENKW(let*); -CHICKENKW(letrec); -CHICKENKW(do); -CHICKENKW(delay); -CHICKENKW(quasiquote); - -#undef CHICKENKW - -#endif //CHICKEN_CHICKENKW_SWG_ diff --git a/Lib/chicken/chickenrun.swg b/Lib/chicken/chickenrun.swg deleted file mode 100644 index bb14b4bc9..000000000 --- a/Lib/chicken/chickenrun.swg +++ /dev/null @@ -1,375 +0,0 @@ -/* ----------------------------------------------------------------------------- - * chickenrun.swg - * ----------------------------------------------------------------------------- */ - -#include -#include -#include -#include -#include -#if (defined(_MSC_VER) && (_MSC_VER < 1900)) || defined(__BORLANDC__) || defined(_WATCOM) -# ifndef snprintf -# define snprintf _snprintf -# endif -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#define SWIG_malloc(size) \ - malloc(size) -#define SWIG_free(mem) \ - free(mem) -#define SWIG_MakeString(c) \ - SWIG_Chicken_MakeString(c) -#define SWIG_ConvertPtr(s, result, type, flags) \ - SWIG_Chicken_ConvertPtr(s, result, type, flags) -#define SWIG_MustGetPtr(s, type, argnum, flags) \ - SWIG_Chicken_MustGetPtr(s, type, argnum, flags) -#define SWIG_NewPointerObj(ptr, type, owner) \ - SWIG_Chicken_NewPointerObj((void*)ptr, type, owner, &known_space) -#define swig_barf SWIG_Chicken_Barf -#define SWIG_ThrowException(val) SWIG_Chicken_ThrowException(val) - -#define SWIG_contract_assert(expr, message) if (!(expr)) { \ - SWIG_Chicken_Barf(SWIG_BARF1_CONTRACT_ASSERT, C_text(message)); } else - -/* Runtime API */ -#define SWIG_GetModule(clientdata) SWIG_Chicken_GetModule(clientdata) -#define SWIG_SetModule(clientdata, pointer) SWIG_Chicken_SetModule(pointer) - -#define C_swig_is_bool(x) C_truep (C_booleanp (x)) -#define C_swig_is_char(x) C_truep (C_charp (x)) -#define C_swig_is_fixnum(x) C_truep (C_fixnump (x)) -#define C_swig_is_flonum(x) (C_truep (C_blockp (x)) && C_truep (C_flonump (x))) -#define C_swig_is_string(x) (C_truep (C_blockp (x)) && C_truep (C_stringp (x))) -#define C_swig_is_vector(x) (C_truep (C_blockp (x)) && C_truep (C_vectorp (x))) -#define C_swig_is_list(x) (C_truep (C_i_listp (x))) -#define C_swig_is_pair(x) (C_truep (C_blockp(x)) && C_truep (C_pairp(x))) -#define C_swig_is_ptr(x) (C_truep (C_blockp (x)) && C_truep (C_pointerp (x))) -#define C_swig_is_swigpointer(x) (C_truep (C_blockp(x)) && C_truep (C_swigpointerp(x))) -#define C_swig_is_closurep(x) (C_truep (C_blockp(x)) && C_truep(C_closurep(x))) -#define C_swig_is_number(x) (C_swig_is_fixnum(x) || C_swig_is_flonum(x)) -#define C_swig_is_long(x) C_swig_is_number(x) - -#define C_swig_sizeof_closure(num) (num+1) - -#define SWIG_Chicken_SetupArgout { \ - C_word *a = C_alloc(C_swig_sizeof_closure(2)); \ - C_word *closure = a; \ - *(a++)=C_CLOSURE_TYPE|2; \ - *(a++)=(C_word)SWIG_Chicken_ApplyResults; \ - *(a++)=continuation; \ - continuation=(C_word)closure; \ -} - -#define SWIG_APPEND_VALUE(obj) { \ - C_word val = (C_word)(obj); \ - if (val != C_SCHEME_UNDEFINED) { \ - C_word *a = C_alloc(C_swig_sizeof_closure(3)); \ - C_word *closure = a; \ - *(a++)=C_CLOSURE_TYPE|3; \ - *(a++)=(C_word)SWIG_Chicken_MultiResultBuild; \ - *(a++)=(C_word)continuation; \ - *(a++)=val; \ - continuation=(C_word)closure; \ - } } - -#define SWIG_Chicken_FindCreateProxy(func,obj) \ - if (C_swig_is_swigpointer(obj)) { \ - swig_type_info *t = (swig_type_info *) C_block_item(obj, 1); \ - if (t && t->clientdata && ((swig_chicken_clientdata *)t->clientdata)->gc_proxy_create) { \ - func = CHICKEN_gc_root_ref( ((swig_chicken_clientdata *)t->clientdata)->gc_proxy_create); \ - } else { \ - func = C_SCHEME_FALSE; \ - } \ - } else { \ - func = C_SCHEME_FALSE; \ - } - - -enum { - SWIG_BARF1_BAD_ARGUMENT_TYPE /* 1 arg */, - SWIG_BARF1_ARGUMENT_NULL /* 1 arg */, - SWIG_BARF1_CONTRACT_ASSERT /* 1 arg */, -}; - -typedef C_word (*swig_chicken_destructor)(C_word,C_word,C_word,C_word); -typedef struct swig_chicken_clientdata { - void *gc_proxy_create; - swig_chicken_destructor destroy; -} swig_chicken_clientdata; - -static char * -SWIG_Chicken_MakeString(C_word str) { - char *ret; - size_t l; - - l = C_header_size(str); - ret = (char *) SWIG_malloc( (l + 1) * sizeof(char)); - if (!ret) return NULL; - - memcpy(ret, C_c_string(str), l); - ret[l] = '\0'; - return ret; -} - -static C_word SWIG_Chicken_LookupSymbol(char *name, C_SYMBOL_TABLE *stable) { - C_word *a = C_alloc(C_SIZEOF_STRING (strlen (name))); - C_word n = C_string2(&a, name); - C_word sym = C_find_symbol(n, stable); - if (C_truep(sym)) { - return C_symbol_value(sym); - } else { - return C_SCHEME_FALSE; - } -} - -/* Just a helper function. Do not export it */ -static void SWIG_Chicken_Panic (C_char *) C_noret; -static void SWIG_Chicken_Panic (C_char *msg) -{ - C_word *a = C_alloc (C_SIZEOF_STRING (strlen (msg))); - C_word scmmsg = C_string2 (&a, msg); - C_halt (scmmsg); - exit (5); /* should never get here */ -} - -static void -SWIG_Chicken_Barf(int code, C_char *msg, ...) C_noret; -static void -SWIG_Chicken_Barf(int code, C_char *msg, ...) -{ - char *errorhook = C_text("\003syserror-hook"); - C_word *a = C_alloc (C_SIZEOF_STRING (strlen (errorhook))); - C_word err = C_intern2 (&a, errorhook); - int c = -1; - int i, barfval; - va_list v; - - - C_temporary_stack = C_temporary_stack_bottom; - err = C_block_item(err, 0); - - if(C_immediatep (err)) - SWIG_Chicken_Panic (C_text ("`##sys#error-hook' is not defined")); - - switch (code) { - case SWIG_BARF1_BAD_ARGUMENT_TYPE: - barfval = C_BAD_ARGUMENT_TYPE_ERROR; - c = 1; - break; - case SWIG_BARF1_ARGUMENT_NULL: - barfval = C_BAD_ARGUMENT_TYPE_ERROR; - c = 1; - break; - case SWIG_BARF1_CONTRACT_ASSERT: - barfval = C_BAD_ARGUMENT_TYPE_ERROR; - c = 1; - break; - default: - SWIG_Chicken_Panic (C_text (msg)); - }; - - if(c > 0 && !C_immediatep (err)) { - C_save (C_fix (barfval)); - - i = c; - if (i) { - C_word *b = C_alloc (C_SIZEOF_STRING (strlen (msg))); - C_word scmmsg = C_string2 (&b, msg); - C_save (scmmsg); - i--; - } - - va_start (v, msg); - - while(i--) - C_save (va_arg (v, C_word)); - - va_end (v); - C_do_apply (c + 1, err, - C_SCHEME_UNDEFINED); /* <- no continuation is passed: - '##sys#error-hook' may not - return! */ - } - else if (msg) { - SWIG_Chicken_Panic (msg); - } - else { - SWIG_Chicken_Panic (C_text ("unspecified panic")); - } -} - -static void SWIG_Chicken_ThrowException(C_word value) C_noret; -static void SWIG_Chicken_ThrowException(C_word value) -{ - char *aborthook = C_text("\003sysabort"); - C_word *a = C_alloc(C_SIZEOF_STRING(strlen(aborthook))); - C_word abort = C_intern2(&a, aborthook); - - abort = C_block_item(abort, 0); - if (C_immediatep(abort)) - SWIG_Chicken_Panic(C_text("`##sys#abort' is not defined")); - - C_save(value); - C_do_apply(1, abort, C_SCHEME_UNDEFINED); -} - -static void -SWIG_Chicken_Finalizer(C_word argc, C_word closure, C_word continuation, C_word s) -{ - swig_type_info *type; - swig_chicken_clientdata *cdata; - - if (argc == 3 && s != C_SCHEME_FALSE && C_swig_is_swigpointer(s)) { - type = (swig_type_info *) C_block_item(s, 1); - if (type) { - cdata = (swig_chicken_clientdata *) type->clientdata; - if (cdata && cdata->destroy) { - /* this will not return, but will continue correctly */ - cdata->destroy(3,closure,continuation,s); - } - } - } - C_kontinue(continuation, C_SCHEME_UNDEFINED); -} -static C_word finalizer_obj[2] = {(C_word) (C_CLOSURE_TYPE|1), (C_word) SWIG_Chicken_Finalizer}; - -static C_word -SWIG_Chicken_NewPointerObj(void *ptr, swig_type_info *type, int owner, C_word **data) -{ - swig_chicken_clientdata *cdata = (swig_chicken_clientdata *) type->clientdata; - - if (ptr == NULL) - return C_SCHEME_FALSE; - else { - C_word cptr = C_swigmpointer(data, ptr, type); - /* add finalizer to object */ - #ifndef SWIG_CHICKEN_NO_COLLECTION - if (owner) - C_do_register_finalizer(cptr, (C_word) finalizer_obj); - #endif - - return cptr; - } -} - -/* Return 0 if successful. */ -static int -SWIG_Chicken_ConvertPtr(C_word s, void **result, swig_type_info *type, int flags) -{ - swig_cast_info *cast; - swig_type_info *from; - - if (s == C_SCHEME_FALSE) { - *result = NULL; - return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; - } else if (C_swig_is_swigpointer(s)) { - /* try and convert type */ - from = (swig_type_info *) C_block_item(s, 1); - if (!from) return 1; - if (type) { - cast = SWIG_TypeCheckStruct(from, type); - if (cast) { - int newmemory = 0; - *result = SWIG_TypeCast(cast, (void *) C_block_item(s, 0), &newmemory); - assert(!newmemory); /* newmemory handling not yet implemented */ - } else { - return 1; - } - } else { - *result = (void *) C_block_item(s, 0); - } - - /* check if we are disowning this object */ - if (flags & SWIG_POINTER_DISOWN) { - C_do_unregister_finalizer(s); - } - } else { - return 1; - } - - return 0; -} - -static SWIGINLINE void * -SWIG_Chicken_MustGetPtr (C_word s, swig_type_info *type, int argnum, int flags) -{ - void *result; - char err_msg[256]; - if (SWIG_Chicken_ConvertPtr(s, &result, type, flags)) { - /* type mismatch */ - snprintf(err_msg, sizeof(err_msg), "Type error in argument #%i: expected %s", argnum, (type->str ? type->str : type->name)); - SWIG_Chicken_Barf(SWIG_BARF1_BAD_ARGUMENT_TYPE, err_msg); - } - return result; -} - -static char *chicken_runtimevar_name = "type_pointer" SWIG_TYPE_TABLE_NAME; - -static swig_module_info * -SWIG_Chicken_GetModule(void *SWIGUNUSEDPARM(clientdata)) { - swig_module_info *ret = 0; - C_word sym; - - /* lookup the type pointer... it is stored in its own symbol table */ - C_SYMBOL_TABLE *stable = C_find_symbol_table("swig_runtime_data" SWIG_RUNTIME_VERSION); - if (stable != NULL) { - sym = SWIG_Chicken_LookupSymbol(chicken_runtimevar_name, stable); - if (C_truep(sym) && C_swig_is_ptr(sym)) { - ret = (swig_module_info *) C_block_item(sym, 0); - } - } - - return ret; -} - -static void -SWIG_Chicken_SetModule(swig_module_info *module) { - C_word *a; - C_SYMBOL_TABLE *stable; - C_word sym; - C_word pointer; - static C_word *space = 0; - - /* type pointer is stored in its own symbol table */ - stable = C_find_symbol_table("swig_runtime_data" SWIG_RUNTIME_VERSION); - if (stable == NULL) { - stable = C_new_symbol_table("swig_runtime_data" SWIG_RUNTIME_VERSION, 16); - } - - if (!space) { - space = (C_word *) C_malloc((C_SIZEOF_POINTER + C_SIZEOF_INTERNED_SYMBOL(C_strlen(chicken_runtimevar_name))) * sizeof(C_word)); - } - a = space; - pointer = C_mpointer(&a, (void *) module); - sym = C_intern_in(&a, C_strlen(chicken_runtimevar_name), chicken_runtimevar_name, stable); - C_set_block_item(sym, 0, pointer); -} - -static C_word SWIG_Chicken_MultiResultBuild(C_word num, C_word closure, C_word lst) { - C_word cont = C_block_item(closure,1); - C_word obj = C_block_item(closure,2); - C_word func; - - SWIG_Chicken_FindCreateProxy(func,obj); - - if (C_swig_is_closurep(func)) { - ((C_proc4)(void *)C_block_item(func, 0))(4,func,cont,obj,lst); - } else { - C_word *a = C_alloc(C_SIZEOF_PAIR); - C_kontinue(cont,C_pair(&a,obj,lst)); - } - return C_SCHEME_UNDEFINED; /* never reached */ -} - -static C_word SWIG_Chicken_ApplyResults(C_word num, C_word closure, C_word result) { - C_apply_values(3,C_SCHEME_UNDEFINED,C_block_item(closure,1),result); - return C_SCHEME_UNDEFINED; /* never reached */ -} - -#ifdef __cplusplus -} -#endif diff --git a/Lib/chicken/extra-install.list b/Lib/chicken/extra-install.list deleted file mode 100644 index 48721cee0..000000000 --- a/Lib/chicken/extra-install.list +++ /dev/null @@ -1,3 +0,0 @@ -swigclosprefix.scm -multi-generic.scm -tinyclos-multi-generic.patch diff --git a/Lib/chicken/multi-generic.scm b/Lib/chicken/multi-generic.scm deleted file mode 100644 index 9d2e31d34..000000000 --- a/Lib/chicken/multi-generic.scm +++ /dev/null @@ -1,152 +0,0 @@ -;; This file is no longer necessary with Chicken versions above 1.92 -;; -;; This file overrides two functions inside TinyCLOS to provide support -;; for multi-argument generics. There are many ways of linking this file -;; into your code... all that needs to happen is this file must be -;; executed after loading TinyCLOS but before any SWIG modules are loaded -;; -;; something like the following -;; (require 'tinyclos) -;; (load "multi-generic") -;; (declare (uses swigmod)) -;; -;; An alternative to loading this scheme code directly is to add a -;; (declare (unit multi-generic)) to the top of this file, and then -;; compile this into the final executable or something. Or compile -;; this into an extension. - -;; Lastly, to override TinyCLOS method creation, two functions are -;; overridden: see the end of this file for which two are overridden. -;; You might want to remove those two lines and then exert more control over -;; which functions are used when. - -;; Comments, bugs, suggestions: send either to chicken-users@nongnu.org or to -;; Most code copied from TinyCLOS - -(define (make - 'name "multi-generic" - 'direct-supers (list ) - 'direct-slots '())) - -(letrec ([applicable? - (lambda (c arg) - (memq c (class-cpl (class-of arg))))] - - [more-specific? - (lambda (c1 c2 arg) - (memq c2 (memq c1 (class-cpl (class-of arg)))))] - - [filter-in - (lambda (f l) - (if (null? l) - '() - (let ([h (##sys#slot l 0)] - [r (##sys#slot l 1)] ) - (if (f h) - (cons h (filter-in f r)) - (filter-in f r) ) ) ) )]) - -(add-method compute-apply-generic - (make-method (list ) - (lambda (call-next-method generic) - (lambda args - (let ([cam (let ([x (compute-apply-methods generic)] - [y ((compute-methods generic) args)] ) - (lambda (args) (x y args)) ) ] ) - (cam args) ) ) ) ) ) - - - -(add-method compute-methods - (make-method (list ) - (lambda (call-next-method generic) - (lambda (args) - (let ([applicable - (filter-in (lambda (method) - (let check-applicable ([list1 (method-specializers method)] - [list2 args]) - (cond ((null? list1) #t) - ((null? list2) #f) - (else - (and (applicable? (##sys#slot list1 0) (##sys#slot list2 0)) - (check-applicable (##sys#slot list1 1) (##sys#slot list2 1))))))) - (generic-methods generic) ) ] ) - (if (or (null? applicable) (null? (##sys#slot applicable 1))) - applicable - (let ([cmms (compute-method-more-specific? generic)]) - (sort applicable (lambda (m1 m2) (cmms m1 m2 args))) ) ) ) ) ) ) ) - -(add-method compute-method-more-specific? - (make-method (list ) - (lambda (call-next-method generic) - (lambda (m1 m2 args) - (let loop ((specls1 (method-specializers m1)) - (specls2 (method-specializers m2)) - (args args)) - (cond-expand - [unsafe - (let ((c1 (##sys#slot specls1 0)) - (c2 (##sys#slot specls2 0)) - (arg (##sys#slot args 0))) - (if (eq? c1 c2) - (loop (##sys#slot specls1 1) - (##sys#slot specls2 1) - (##sys#slot args 1)) - (more-specific? c1 c2 arg))) ] - [else - (cond ((and (null? specls1) (null? specls2)) - (##sys#error "two methods are equally specific" generic)) - ;((or (null? specls1) (null? specls2)) - ; (##sys#error "two methods have different number of specializers" generic)) - ((null? specls1) #f) - ((null? specls2) #t) - ((null? args) - (##sys#error "fewer arguments than specializers" generic)) - (else - (let ((c1 (##sys#slot specls1 0)) - (c2 (##sys#slot specls2 0)) - (arg (##sys#slot args 0))) - (if (eq? c1 c2) - (loop (##sys#slot specls1 1) - (##sys#slot specls2 1) - (##sys#slot args 1)) - (more-specific? c1 c2 arg)))) ) ] ) ) ) ) ) ) - -) ;; end of letrec - -(define multi-add-method - (lambda (generic method) - (slot-set! - generic - 'methods - (let filter-in-method ([methods (slot-ref generic 'methods)]) - (if (null? methods) - (list method) - (let ([l1 (length (method-specializers method))] - [l2 (length (method-specializers (##sys#slot methods 0)))]) - (cond ((> l1 l2) - (cons (##sys#slot methods 0) (filter-in-method (##sys#slot methods 1)))) - ((< l1 l2) - (cons method methods)) - (else - (let check-method ([ms1 (method-specializers method)] - [ms2 (method-specializers (##sys#slot methods 0))]) - (cond ((and (null? ms1) (null? ms2)) - (cons method (##sys#slot methods 1))) ;; skip the method already in the generic - ((eq? (##sys#slot ms1 0) (##sys#slot ms2 0)) - (check-method (##sys#slot ms1 1) (##sys#slot ms2 1))) - (else - (cons (##sys#slot methods 0) (filter-in-method (##sys#slot methods 1)))))))))))) - - (##sys#setslot (##sys#slot generic (- (##sys#size generic) 2)) 1 (compute-apply-generic generic)) )) - -(define (multi-add-global-method val sym specializers proc) - (let ((generic (if (procedure? val) val (make 'name (##sys#symbol->string sym))))) - (multi-add-method generic (make-method specializers proc)) - generic)) - -;; Might want to remove these, or perhaps do something like -;; (define old-add-method ##tinyclos#add-method) -;; and then you can switch between creating multi-generics and TinyCLOS generics. -(set! ##tinyclos#add-method multi-add-method) -(set! ##tinyclos#add-global-method multi-add-global-method) diff --git a/Lib/chicken/std_string.i b/Lib/chicken/std_string.i deleted file mode 100644 index fa77c1533..000000000 --- a/Lib/chicken/std_string.i +++ /dev/null @@ -1,96 +0,0 @@ -/* ----------------------------------------------------------------------------- - * std_string.i - * - * SWIG typemaps for std::string - * ----------------------------------------------------------------------------- */ - -%{ -#include -%} - -namespace std { - %naturalvar string; - - - %insert(closprefix) %{ (declare (hide )) %} - %nodefault string; - %rename("std-string") string; - class string { - public: - ~string() {} - }; - %extend string { - char *str; - } - %{ - #define std_string_str_get(s) ((char *)((s)->c_str())) - #define std_string_str_set(s,v) (s->assign((char *)(v))) - %} - - %typemap(typecheck) string = char *; - %typemap(typecheck) const string & = char *; - - %typemap(in) string (char * tempptr) { - if ($input == C_SCHEME_FALSE) { - $1.resize(0); - } else { - if (!C_swig_is_string ($input)) { - swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, - "Argument #$argnum is not a string"); - } - tempptr = SWIG_MakeString($input); - $1.assign(tempptr); - if (tempptr) SWIG_free(tempptr); - } - } - - %typemap(in) const string& ($*1_ltype temp, char *tempptr) { - - if ($input == C_SCHEME_FALSE) { - temp.resize(0); - $1 = &temp; - } else { - if (!C_swig_is_string ($input)) { - swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, - "Argument #$argnum is not a string"); - } - tempptr = SWIG_MakeString($input); - temp.assign(tempptr); - if (tempptr) SWIG_free(tempptr); - $1 = &temp; - } - } - - %typemap(out) string { - int size = $1.size(); - C_word *space = C_alloc (C_SIZEOF_STRING (size)); - $result = C_string (&space, size, (char *) $1.c_str()); - } - - %typemap(out) const string& { - int size = $1->size(); - C_word *space = C_alloc (C_SIZEOF_STRING (size)); - $result = C_string (&space, size, (char *) $1->c_str()); - } - - %typemap(varin) string { - if ($input == C_SCHEME_FALSE) { - $1.resize(0); - } else { - char *tempptr; - if (!C_swig_is_string ($input)) { - swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, - "Argument #$argnum is not a string"); - } - tempptr = SWIG_MakeString($input); - $1.assign(tempptr); - if (tempptr) SWIG_free(tempptr); - } - } - - %typemap(varout) string { - int size = $1.size(); - C_word *space = C_alloc (C_SIZEOF_STRING (size)); - $result = C_string (&space, size, (char *) $1.c_str()); - } -} diff --git a/Lib/chicken/swigclosprefix.scm b/Lib/chicken/swigclosprefix.scm deleted file mode 100644 index e4bd72b71..000000000 --- a/Lib/chicken/swigclosprefix.scm +++ /dev/null @@ -1,31 +0,0 @@ -(declare (hide swig-initialize)) - -(define (swig-initialize obj initargs create) - (slot-set! obj 'swig-this - (if (memq 'swig-this initargs) - (cadr initargs) - (let ((ret (apply create initargs))) - (if (instance? ret) - (slot-ref ret 'swig-this) - ret))))) - -(define-class () (void)) - -(define-method (compute-getter-and-setter (class ) slot allocator) - (if (not (memq ':swig-virtual slot)) - (call-next-method) - (let ((getter (let search-get ((lst slot)) - (if (null? lst) - #f - (if (eq? (car lst) ':swig-get) - (cadr lst) - (search-get (cdr lst)))))) - (setter (let search-set ((lst slot)) - (if (null? lst) - #f - (if (eq? (car lst) ':swig-set) - (cadr lst) - (search-set (cdr lst))))))) - (values - (lambda (o) (getter (slot-ref o 'swig-this))) - (lambda (o new) (setter (slot-ref o 'swig-this) new) new))))) diff --git a/Lib/chicken/tinyclos-multi-generic.patch b/Lib/chicken/tinyclos-multi-generic.patch deleted file mode 100644 index 2e585960e..000000000 --- a/Lib/chicken/tinyclos-multi-generic.patch +++ /dev/null @@ -1,150 +0,0 @@ -# This patch is against chicken 1.92, but it should work just fine -# with older versions of chicken. It adds support for mulit-argument -# generics, that is, generics now correctly handle adding methods -# with different lengths of specializer lists - -# This patch has been committed into the CHICKEN darcs repository, -# so chicken versions above 1.92 work fine. - -# Comments, bugs, suggestions send to chicken-users@nongnu.org - -# Patch written by John Lenz - ---- tinyclos.scm.old 2005-04-05 01:13:56.000000000 -0500 -+++ tinyclos.scm 2005-04-11 16:37:23.746181489 -0500 -@@ -37,8 +37,10 @@ - - (include "parameters") - -+(cond-expand [(not chicken-compile-shared) (declare (unit tinyclos))] -+ [else] ) -+ - (declare -- (unit tinyclos) - (uses extras) - (usual-integrations) - (fixnum) -@@ -234,7 +236,10 @@ - y = C_block_item(y, 1); - } - } -- return(C_block_item(v, i + 1)); -+ if (x == C_SCHEME_END_OF_LIST && y == C_SCHEME_END_OF_LIST) -+ return(C_block_item(v, i + 1)); -+ else -+ goto mismatch; - } - else if(free_index == -1) free_index = i; - mismatch: -@@ -438,7 +443,7 @@ - (define hash-arg-list - (foreign-lambda* unsigned-int ((scheme-object args) (scheme-object svector)) " - C_word tag, h, x; -- int n, i, j; -+ int n, i, j, len = 0; - for(i = 0; args != C_SCHEME_END_OF_LIST; args = C_block_item(args, 1)) { - x = C_block_item(args, 0); - if(C_immediatep(x)) { -@@ -481,8 +486,9 @@ - default: i += 255; - } - } -+ ++len; - } -- return(i & (C_METHOD_CACHE_SIZE - 1));") ) -+ return((i + len) & (C_METHOD_CACHE_SIZE - 1));") ) - - - ; -@@ -868,13 +874,27 @@ - (##tinyclos#slot-set! - generic - 'methods -- (cons method -- (filter-in -- (lambda (m) -- (let ([ms1 (method-specializers m)] -- [ms2 (method-specializers method)] ) -- (not (every2 (lambda (x y) (eq? x y)) ms1 ms2) ) ) ) -- (##tinyclos#slot-ref generic 'methods)))) -+ (let* ([ms1 (method-specializers method)] -+ [l1 (length ms1)] ) -+ (let filter-in-method ([methods (##tinyclos#slot-ref generic 'methods)]) -+ (if (null? methods) -+ (list method) -+ (let* ([mm (##sys#slot methods 0)] -+ [ms2 (method-specializers mm)] -+ [l2 (length ms2)]) -+ (cond ((> l1 l2) -+ (cons mm (filter-in-method (##sys#slot methods 1)))) -+ ((< l1 l2) -+ (cons method methods)) -+ (else -+ (let check-method ([ms1 ms1] -+ [ms2 ms2]) -+ (cond ((and (null? ms1) (null? ms2)) -+ (cons method (##sys#slot methods 1))) ;; skip the method already in the generic -+ ((eq? (##sys#slot ms1 0) (##sys#slot ms2 0)) -+ (check-method (##sys#slot ms1 1) (##sys#slot ms2 1))) -+ (else -+ (cons mm (filter-in-method (##sys#slot methods 1))))))))))))) - (if (memq generic generic-invocation-generics) - (set! method-cache-tag (vector)) - (%entity-cache-set! generic #f) ) -@@ -925,11 +945,13 @@ - (memq (car args) generic-invocation-generics)) - (let ([proc - (method-procedure -+ ; select the first method of one argument - (let lp ([lis (generic-methods generic)]) -- (let ([tail (##sys#slot lis 1)]) -- (if (null? tail) -- (##sys#slot lis 0) -- (lp tail)) ) ) ) ] ) -+ (if (null? lis) -+ (##sys#error "Unable to find original compute-apply-generic") -+ (if (= (length (method-specializers (##sys#slot lis 0))) 1) -+ (##sys#slot lis 0) -+ (lp (##sys#slot lis 1)))))) ] ) - (lambda (args) (apply proc #f args)) ) - (let ([x (compute-apply-methods generic)] - [y ((compute-methods generic) args)] ) -@@ -946,9 +968,13 @@ - (lambda (args) - (let ([applicable - (filter-in (lambda (method) -- (every2 applicable? -- (method-specializers method) -- args)) -+ (let check-applicable ([list1 (method-specializers method)] -+ [list2 args]) -+ (cond ((null? list1) #t) -+ ((null? list2) #f) -+ (else -+ (and (applicable? (##sys#slot list1 0) (##sys#slot list2 0)) -+ (check-applicable (##sys#slot list1 1) (##sys#slot list2 1))))))) - (generic-methods generic) ) ] ) - (if (or (null? applicable) (null? (##sys#slot applicable 1))) - applicable -@@ -975,8 +1001,10 @@ - [else - (cond ((and (null? specls1) (null? specls2)) - (##sys#error "two methods are equally specific" generic)) -- ((or (null? specls1) (null? specls2)) -- (##sys#error "two methods have different number of specializers" generic)) -+ ;((or (null? specls1) (null? specls2)) -+ ; (##sys#error "two methods have different number of specializers" generic)) -+ ((null? specls1) #f) -+ ((null? specls2) #t) - ((null? args) - (##sys#error "fewer arguments than specializers" generic)) - (else -@@ -1210,7 +1238,7 @@ - (define (make-primitive-class "structure")) - (define (make-primitive-class "procedure" )) - (define (make-primitive-class "end-of-file")) --(define (make-primitive-class "environment" )) ; (Benedikt insisted on this) -+(define (make-primitive-class "environment" )) - (define (make-primitive-class "hash-table" )) - (define (make-primitive-class "promise" )) - (define (make-primitive-class "queue" )) diff --git a/Lib/chicken/typemaps.i b/Lib/chicken/typemaps.i deleted file mode 100644 index fd587fd68..000000000 --- a/Lib/chicken/typemaps.i +++ /dev/null @@ -1,314 +0,0 @@ -/* ----------------------------------------------------------------------------- - * typemaps.i - * - * Pointer handling - * - * These mappings provide support for input/output arguments and - * common uses for C/C++ pointers. INOUT mappings allow for C/C++ - * pointer variables in addition to input/output arguments. - * ----------------------------------------------------------------------------- */ - -// INPUT typemaps. -// These remap a C pointer to be an "INPUT" value which is passed by value -// instead of reference. - -/* -The following methods can be applied to turn a pointer into a simple -"input" value. That is, instead of passing a pointer to an object, -you would use a real value instead. - - int *INPUT - short *INPUT - long *INPUT - long long *INPUT - unsigned int *INPUT - unsigned short *INPUT - unsigned long *INPUT - unsigned long long *INPUT - unsigned char *INPUT - char *INPUT - bool *INPUT - float *INPUT - double *INPUT - -To use these, suppose you had a C function like this : - - double fadd(double *a, double *b) { - return *a+*b; - } - -You could wrap it with SWIG as follows : - - %include - double fadd(double *INPUT, double *INPUT); - -or you can use the %apply directive : - - %include - %apply double *INPUT { double *a, double *b }; - double fadd(double *a, double *b); - -*/ - -// OUTPUT typemaps. These typemaps are used for parameters that -// are output only. The output value is appended to the result as -// a list element. - -/* -The following methods can be applied to turn a pointer into an "output" -value. When calling a function, no input value would be given for -a parameter, but an output value would be returned. In the case of -multiple output values, they are returned in the form of a Scheme list. - - int *OUTPUT - short *OUTPUT - long *OUTPUT - long long *OUTPUT - unsigned int *OUTPUT - unsigned short *OUTPUT - unsigned long *OUTPUT - unsigned long long *OUTPUT - unsigned char *OUTPUT - char *OUTPUT - bool *OUTPUT - float *OUTPUT - double *OUTPUT - -For example, suppose you were trying to wrap the modf() function in the -C math library which splits x into integral and fractional parts (and -returns the integer part in one of its parameters).K: - - double modf(double x, double *ip); - -You could wrap it with SWIG as follows : - - %include - double modf(double x, double *OUTPUT); - -or you can use the %apply directive : - - %include - %apply double *OUTPUT { double *ip }; - double modf(double x, double *ip); - -*/ - -//---------------------------------------------------------------------- -// -// T_OUTPUT typemap (and helper function) to return multiple argouts as -// a tuple instead of a list. -// -//---------------------------------------------------------------------- - -// Simple types - -%define INOUT_TYPEMAP(type_, from_scheme, to_scheme, checker, convtype, storage_) - -%typemap(in) type_ *INPUT($*1_ltype temp), type_ &INPUT($*1_ltype temp) -%{ if (!checker ($input)) { - swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument #$argnum is not of type 'type_'"); - } - temp = ($*1_ltype) from_scheme ($input); - $1 = &temp; %} - -%typemap(typecheck) type_ *INPUT = type_; -%typemap(typecheck) type_ &INPUT = type_; - -%typemap(in, numinputs=0) type_ *OUTPUT($*1_ltype temp), type_ &OUTPUT($*1_ltype temp) -" $1 = &temp;" - -#if "storage_" == "0" - -%typemap(argout) type_ *OUTPUT, type_ &OUTPUT -%{ - if ($1 == NULL) { - swig_barf (SWIG_BARF1_ARGUMENT_NULL, "Argument #$argnum must be non-null"); - } - SWIG_APPEND_VALUE(to_scheme (convtype (*$1))); -%} - -#else - -%typemap(argout) type_ *OUTPUT, type_ &OUTPUT -%{ - { - C_word *known_space = C_alloc(storage_); - if ($1 == NULL) { - swig_barf (SWIG_BARF1_ARGUMENT_NULL, "Variable '$1' must be non-null"); - } - SWIG_APPEND_VALUE(to_scheme (&known_space, convtype (*$1))); - } -%} - -#endif - -%enddef - -INOUT_TYPEMAP(int, C_num_to_int, C_fix, C_swig_is_number, (int), 0); -INOUT_TYPEMAP(enum SWIGTYPE, C_num_to_int, C_fix, C_swig_is_number, (int), 0); -INOUT_TYPEMAP(short, C_num_to_int, C_fix, C_swig_is_number, (int), 0); -INOUT_TYPEMAP(long, C_num_to_long, C_long_to_num, C_swig_is_long, (long), C_SIZEOF_FLONUM); -INOUT_TYPEMAP(long long, C_num_to_long, C_long_to_num, C_swig_is_long, (long), C_SIZEOF_FLONUM); -INOUT_TYPEMAP(unsigned int, C_num_to_unsigned_int, C_unsigned_int_to_num, C_swig_is_number, (int), C_SIZEOF_FLONUM); -INOUT_TYPEMAP(unsigned short, C_num_to_unsigned_int, C_fix, C_swig_is_number, (unsigned int), 0); -INOUT_TYPEMAP(unsigned long, C_num_to_unsigned_long, C_unsigned_long_to_num, C_swig_is_long, (unsigned long), C_SIZEOF_FLONUM); -INOUT_TYPEMAP(unsigned long long, C_num_to_unsigned_long, C_unsigned_long_to_num, C_swig_is_long, (unsigned long), C_SIZEOF_FLONUM); -INOUT_TYPEMAP(unsigned char, C_character_code, C_make_character, C_swig_is_char, (unsigned int), 0); -INOUT_TYPEMAP(signed char, C_character_code, C_make_character, C_swig_is_char, (int), 0); -INOUT_TYPEMAP(char, C_character_code, C_make_character, C_swig_is_char, (char), 0); -INOUT_TYPEMAP(bool, C_truep, C_mk_bool, C_swig_is_bool, (bool), 0); -INOUT_TYPEMAP(float, C_c_double, C_flonum, C_swig_is_number, (double), C_SIZEOF_FLONUM); -INOUT_TYPEMAP(double, C_c_double, C_flonum, C_swig_is_number, (double), C_SIZEOF_FLONUM); - -// INOUT -// Mappings for an argument that is both an input and output -// parameter - -/* -The following methods can be applied to make a function parameter both -an input and output value. This combines the behavior of both the -"INPUT" and "OUTPUT" methods described earlier. Output values are -returned in the form of a CHICKEN tuple. - - int *INOUT - short *INOUT - long *INOUT - long long *INOUT - unsigned int *INOUT - unsigned short *INOUT - unsigned long *INOUT - unsigned long long *INOUT - unsigned char *INOUT - char *INOUT - bool *INOUT - float *INOUT - double *INOUT - -For example, suppose you were trying to wrap the following function : - - void neg(double *x) { - *x = -(*x); - } - -You could wrap it with SWIG as follows : - - %include - void neg(double *INOUT); - -or you can use the %apply directive : - - %include - %apply double *INOUT { double *x }; - void neg(double *x); - -As well, you can wrap variables with : - - %include - %apply double *INOUT { double *y }; - extern double *y; - -Unlike C, this mapping does not directly modify the input value (since -this makes no sense in CHICKEN). Rather, the modified input value shows -up as the return value of the function. Thus, to apply this function -to a CHICKEN variable you might do this : - - x = neg(x) - -Note : previous versions of SWIG used the symbol 'BOTH' to mark -input/output arguments. This is still supported, but will be slowly -phased out in future releases. - -*/ - -%typemap(in) int *INOUT = int *INPUT; -%typemap(in) enum SWIGTYPE *INOUT = enum SWIGTYPE *INPUT; -%typemap(in) short *INOUT = short *INPUT; -%typemap(in) long *INOUT = long *INPUT; -%typemap(in) long long *INOUT = long long *INPUT; -%typemap(in) unsigned *INOUT = unsigned *INPUT; -%typemap(in) unsigned short *INOUT = unsigned short *INPUT; -%typemap(in) unsigned long *INOUT = unsigned long *INPUT; -%typemap(in) unsigned long long *INOUT = unsigned long long *INPUT; -%typemap(in) unsigned char *INOUT = unsigned char *INPUT; -%typemap(in) char *INOUT = char *INPUT; -%typemap(in) bool *INOUT = bool *INPUT; -%typemap(in) float *INOUT = float *INPUT; -%typemap(in) double *INOUT = double *INPUT; - -%typemap(in) int &INOUT = int &INPUT; -%typemap(in) enum SWIGTYPE &INOUT = enum SWIGTYPE &INPUT; -%typemap(in) short &INOUT = short &INPUT; -%typemap(in) long &INOUT = long &INPUT; -%typemap(in) long long &INOUT = long long &INPUT; -%typemap(in) unsigned &INOUT = unsigned &INPUT; -%typemap(in) unsigned short &INOUT = unsigned short &INPUT; -%typemap(in) unsigned long &INOUT = unsigned long &INPUT; -%typemap(in) unsigned long long &INOUT = unsigned long long &INPUT; -%typemap(in) unsigned char &INOUT = unsigned char &INPUT; -%typemap(in) char &INOUT = char &INPUT; -%typemap(in) bool &INOUT = bool &INPUT; -%typemap(in) float &INOUT = float &INPUT; -%typemap(in) double &INOUT = double &INPUT; - -%typemap(argout) int *INOUT = int *OUTPUT; -%typemap(argout) enum SWIGTYPE *INOUT = enum SWIGTYPE *OUTPUT; -%typemap(argout) short *INOUT = short *OUTPUT; -%typemap(argout) long *INOUT = long *OUTPUT; -%typemap(argout) long long *INOUT = long long *OUTPUT; -%typemap(argout) unsigned *INOUT = unsigned *OUTPUT; -%typemap(argout) unsigned short *INOUT = unsigned short *OUTPUT; -%typemap(argout) unsigned long *INOUT = unsigned long *OUTPUT; -%typemap(argout) unsigned long long *INOUT = unsigned long long *OUTPUT; -%typemap(argout) unsigned char *INOUT = unsigned char *OUTPUT; -%typemap(argout) bool *INOUT = bool *OUTPUT; -%typemap(argout) float *INOUT = float *OUTPUT; -%typemap(argout) double *INOUT = double *OUTPUT; - -%typemap(argout) int &INOUT = int &OUTPUT; -%typemap(argout) enum SWIGTYPE &INOUT = enum SWIGTYPE &OUTPUT; -%typemap(argout) short &INOUT = short &OUTPUT; -%typemap(argout) long &INOUT = long &OUTPUT; -%typemap(argout) long long &INOUT = long long &OUTPUT; -%typemap(argout) unsigned &INOUT = unsigned &OUTPUT; -%typemap(argout) unsigned short &INOUT = unsigned short &OUTPUT; -%typemap(argout) unsigned long &INOUT = unsigned long &OUTPUT; -%typemap(argout) unsigned long long &INOUT = unsigned long long &OUTPUT; -%typemap(argout) unsigned char &INOUT = unsigned char &OUTPUT; -%typemap(argout) char &INOUT = char &OUTPUT; -%typemap(argout) bool &INOUT = bool &OUTPUT; -%typemap(argout) float &INOUT = float &OUTPUT; -%typemap(argout) double &INOUT = double &OUTPUT; - -/* Overloading information */ - -%typemap(typecheck) double *INOUT = double; -%typemap(typecheck) bool *INOUT = bool; -%typemap(typecheck) char *INOUT = char; -%typemap(typecheck) signed char *INOUT = signed char; -%typemap(typecheck) unsigned char *INOUT = unsigned char; -%typemap(typecheck) unsigned long *INOUT = unsigned long; -%typemap(typecheck) unsigned long long *INOUT = unsigned long long; -%typemap(typecheck) unsigned short *INOUT = unsigned short; -%typemap(typecheck) unsigned int *INOUT = unsigned int; -%typemap(typecheck) long *INOUT = long; -%typemap(typecheck) long long *INOUT = long long; -%typemap(typecheck) short *INOUT = short; -%typemap(typecheck) int *INOUT = int; -%typemap(typecheck) enum SWIGTYPE *INOUT = enum SWIGTYPE; -%typemap(typecheck) float *INOUT = float; - -%typemap(typecheck) double &INOUT = double; -%typemap(typecheck) bool &INOUT = bool; -%typemap(typecheck) char &INOUT = char; -%typemap(typecheck) signed char &INOUT = signed char; -%typemap(typecheck) unsigned char &INOUT = unsigned char; -%typemap(typecheck) unsigned long &INOUT = unsigned long; -%typemap(typecheck) unsigned long long &INOUT = unsigned long long; -%typemap(typecheck) unsigned short &INOUT = unsigned short; -%typemap(typecheck) unsigned int &INOUT = unsigned int; -%typemap(typecheck) long &INOUT = long; -%typemap(typecheck) long long &INOUT = long long; -%typemap(typecheck) short &INOUT = short; -%typemap(typecheck) int &INOUT = int; -%typemap(typecheck) enum SWIGTYPE &INOUT = enum SWIGTYPE; -%typemap(typecheck) float &INOUT = float; diff --git a/Lib/clisp/clisp.swg b/Lib/clisp/clisp.swg deleted file mode 100644 index e1d330cb3..000000000 --- a/Lib/clisp/clisp.swg +++ /dev/null @@ -1,32 +0,0 @@ -/* ----------------------------------------------------------------------------- - * clisp.swg - * ----------------------------------------------------------------------------- */ - -/* Define a C preprocessor symbol that can be used in interface files - to distinguish between the SWIG language modules. */ - -#define SWIG_CLISP - -/* Typespecs for basic types. */ - -%typemap(in) void "NIL"; - -%typemap(in) char "character"; -%typemap(in) char * "ffi:c-string"; -%typemap(in) unsigned char "ffi:uchar"; -%typemap(in) signed char "ffi:char"; - -%typemap(in) short "ffi:short"; -%typemap(in) signed short "ffi:short"; -%typemap(in) unsigned short "ffi:ushort"; - -%typemap(in) int "ffi:int"; -%typemap(in) signed int "ffi:int"; -%typemap(in) unsigned int "ffi:uint"; - -%typemap(in) long "ffi:long"; -%typemap(in) signed long "ffi:long"; -%typemap(in) unsigned long "ffi:ulong"; - -%typemap(in) float "SINGLE-FLOAT"; -%typemap(in) double "DOUBLE-FLOAT"; diff --git a/Lib/cpointer.i b/Lib/cpointer.i index 881c511fc..df40c0426 100644 --- a/Lib/cpointer.i +++ b/Lib/cpointer.i @@ -5,6 +5,12 @@ * pointer objects. * ----------------------------------------------------------------------------- */ +#ifndef __cplusplus +// C uses free/calloc/malloc +%include "swigfragments.swg" +%fragment(""); +#endif + /* ----------------------------------------------------------------------------- * %pointer_class(type,name) * @@ -55,14 +61,14 @@ NAME() { return new TYPE(); } ~NAME() { - if ($self) delete $self; + delete $self; } #else NAME() { return (TYPE *) calloc(1,sizeof(TYPE)); } ~NAME() { - if ($self) free($self); + free($self); } #endif } @@ -114,7 +120,7 @@ static NAME * frompointer(TYPE *t) { %define %pointer_functions(TYPE,NAME) %{ -static TYPE *new_##NAME() { %} +static TYPE *new_##NAME(void) { %} #ifdef __cplusplus %{ return new TYPE(); %} #else @@ -134,9 +140,9 @@ static TYPE *copy_##NAME(TYPE value) { %} static void delete_##NAME(TYPE *obj) { %} #ifdef __cplusplus -%{ if (obj) delete obj; %} +%{ delete obj; %} #else -%{ if (obj) free(obj); %} +%{ free(obj); %} #endif %{} @@ -149,7 +155,7 @@ static TYPE NAME ##_value(TYPE *obj) { } %} -TYPE *new_##NAME(); +TYPE *new_##NAME(void); TYPE *copy_##NAME(TYPE value); void delete_##NAME(TYPE *obj); void NAME##_assign(TYPE *obj, TYPE value); diff --git a/Lib/csharp/csharp.swg b/Lib/csharp/csharp.swg index 832206386..0e180f576 100644 --- a/Lib/csharp/csharp.swg +++ b/Lib/csharp/csharp.swg @@ -875,6 +875,15 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { global::System.IntPtr ret = $imcall;$excode return ret; } +%typemap(csvarin, excode=SWIGEXCODE2) void *VOID_INT_PTR %{ + set { + $imcall;$excode + } %} +%typemap(csvarout, excode=SWIGEXCODE2) void *VOID_INT_PTR %{ + get { + global::System.IntPtr ret = $imcall;$excode + return ret; + } %} %typemap(csdirectorin) void *VOID_INT_PTR "$iminput" %typemap(csdirectorout) void *VOID_INT_PTR "$cscall" @@ -885,6 +894,7 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { %typemap(csinterfaces) SWIGTYPE "global::System.IDisposable" %typemap(csinterfaces) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" %typemap(csinterfaces_derived) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" +%typemap(csinterfacemodifiers) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "public interface" // csbody typemaps... these are in macros so that the visibility of the methods can be easily changed by users. diff --git a/Lib/csharp/csharphead.swg b/Lib/csharp/csharphead.swg index 7db4c0e3c..56a019bd5 100644 --- a/Lib/csharp/csharphead.swg +++ b/Lib/csharp/csharphead.swg @@ -335,5 +335,5 @@ SWIGEXPORT void SWIGSTDCALL SWIGRegisterStringCallback_$module(SWIG_CSharpString %insert(runtime) %{ /* Contract support */ -#define SWIG_contract_assert(nullreturn, expr, msg) if (!(expr)) {SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException, msg, ""); return nullreturn; } else +#define SWIG_contract_assert(nullreturn, expr, msg) do { if (!(expr)) {SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException, msg, ""); return nullreturn; } } while (0) %} diff --git a/Lib/csharp/csharpkw.swg b/Lib/csharp/csharpkw.swg index 824f61874..1904fce94 100644 --- a/Lib/csharp/csharpkw.swg +++ b/Lib/csharp/csharpkw.swg @@ -2,9 +2,9 @@ #define CSHARP_CSHARPKW_SWG_ /* Warnings for C# keywords */ -#define CSHARPKW(x) %keywordwarn("'" `x` "' is a C# keyword, renaming to '" `x` "_'",rename="%s_") `x` +#define CSHARPKW(x) %keywordwarn("'" `x` "' is a C# keyword",rename="%s_") `x` -#define CSHARPCLASSKW(x) %keywordwarn("'" `x` "' is a special method name used in the C# wrapper classes, class renamed to '" `x` "_'",%$isclass,rename="%s_") `x` +#define CSHARPCLASSKW(x) %keywordwarn("'" `x` "' is a special method name used in the C# wrapper classes",%$isclass,rename="%s_") `x` /* from diff --git a/Lib/csharp/std_auto_ptr.i b/Lib/csharp/std_auto_ptr.i index d7e5f167e..1d91c9872 100644 --- a/Lib/csharp/std_auto_ptr.i +++ b/Lib/csharp/std_auto_ptr.i @@ -1,5 +1,5 @@ /* - The typemaps here allow to handle functions returning std::auto_ptr<>, + The typemaps here allow handling functions returning std::auto_ptr<>, which is the most common use of this type. If you have functions taking it as parameter, these typemaps can't be used for them and you need to do something else (e.g. use shared_ptr<> which SWIG supports fully). diff --git a/Lib/csharp/std_string.i b/Lib/csharp/std_string.i index 5f8fa44cb..c8920c09e 100644 --- a/Lib/csharp/std_string.i +++ b/Lib/csharp/std_string.i @@ -20,7 +20,7 @@ namespace std { class string; // string -%typemap(ctype) string "char *" +%typemap(ctype) string "const char *" %typemap(imtype) string "string" %typemap(cstype) string "string" @@ -42,7 +42,7 @@ class string; } $result.assign($input); %} -%typemap(directorin) string %{ $input = SWIG_csharp_string_callback($1.c_str()); %} +%typemap(directorin) string %{ $input = $1.c_str(); %} %typemap(csin) string "$csinput" %typemap(csout, excode=SWIGEXCODE) string { @@ -57,7 +57,7 @@ class string; return $null; %} // const string & -%typemap(ctype) const string & "char *" +%typemap(ctype) const string & "const char *" %typemap(imtype) const string & "string" %typemap(cstype) const string & "string" @@ -89,7 +89,7 @@ class string; $1_str = $input; $result = &$1_str; %} -%typemap(directorin) const string & %{ $input = SWIG_csharp_string_callback($1.c_str()); %} +%typemap(directorin) const string & %{ $input = $1.c_str(); %} %typemap(csvarin, excode=SWIGEXCODE2) const string & %{ set { diff --git a/Lib/csharp/wchar.i b/Lib/csharp/wchar.i index 798194114..1ece767da 100644 --- a/Lib/csharp/wchar.i +++ b/Lib/csharp/wchar.i @@ -92,7 +92,7 @@ SWIGEXPORT void SWIGSTDCALL SWIGRegisterWStringCallback_$module(SWIG_CSharpWStri } %} %typemap(csvarout, excode=SWIGEXCODE2) wchar_t * %{ get { - string ret = $imcall;$excode + string ret = global::System.Runtime.InteropServices.Marshal.PtrToStringUni($imcall);$excode return ret; } %} diff --git a/Lib/d/cpointer.i b/Lib/d/cpointer.i index 75e610f67..da3084b7a 100644 --- a/Lib/d/cpointer.i +++ b/Lib/d/cpointer.i @@ -54,14 +54,14 @@ NAME() { return new TYPE(); } ~NAME() { - if (self) delete self; + delete self; } #else NAME() { return (TYPE *) calloc(1,sizeof(TYPE)); } ~NAME() { - if (self) free(self); + free(self); } #endif } @@ -133,9 +133,9 @@ static TYPE *copy_##NAME(TYPE value) { %} static void delete_##NAME(TYPE *self) { %} #ifdef __cplusplus -%{ if (self) delete self; %} +%{ delete self; %} #else -%{ if (self) free(self); %} +%{ free(self); %} #endif %{} diff --git a/Lib/d/dhead.swg b/Lib/d/dhead.swg index 50e9c2e87..1ef1e4164 100644 --- a/Lib/d/dhead.swg +++ b/Lib/d/dhead.swg @@ -12,7 +12,7 @@ #include /* Contract support. */ -#define SWIG_contract_assert(nullreturn, expr, msg) if (!(expr)) {SWIG_DSetPendingException(SWIG_DException, msg); return nullreturn; } else +#define SWIG_contract_assert(nullreturn, expr, msg) do { if (!(expr)) {SWIG_DSetPendingException(SWIG_DException, msg); return nullreturn; } } while (0) %} diff --git a/Lib/d/dkw.swg b/Lib/d/dkw.swg index 581093f96..2a189ed64 100644 --- a/Lib/d/dkw.swg +++ b/Lib/d/dkw.swg @@ -2,7 +2,7 @@ #define D_DKW_SWG_ /* Warnings for D keywords */ -#define DKEYWORD(x) %keywordwarn("'" `x` "' is a D keyword, renaming to '_" `x` "'",rename="_%s") `x` +#define DKEYWORD(x) %keywordwarn("'" `x` "' is a D keyword",rename="_%s") `x` // Source: http://www.digitalmars.com/d/{1.0,2.0}/lex.html and DKEYWORD(Error); diff --git a/Lib/d/doperators.swg b/Lib/d/doperators.swg index 0cb63533c..0a82a6cb4 100644 --- a/Lib/d/doperators.swg +++ b/Lib/d/doperators.swg @@ -58,7 +58,7 @@ template SwigOperatorDefinitions() { %rename(opCall) *::operator(); -// !a is not overrideable in D1. +// !a is not overridable in D1. %ignoreoperator(LNOT) operator!; // opCmp is used in D. @@ -71,7 +71,7 @@ template SwigOperatorDefinitions() { // a != b is rewritten as !a.opEquals(b) in D. %ignoreoperator(NOTEQUAL) operator!=; -// The logic operators are not overrideable in D. +// The logic operators are not overridable in D. %ignoreoperator(LAND) operator&&; %ignoreoperator(LOR) operator||; @@ -198,7 +198,7 @@ mixin template SwigOperatorDefinitions() { // a != b is rewritten as !a.opEquals(b) in D. %ignoreoperator(NOTEQUAL) operator!=; -// The logic operators are not overrideable in D. +// The logic operators are not overridable in D. %ignoreoperator(LAND) operator&&; %ignoreoperator(LOR) operator||; diff --git a/Lib/exception.i b/Lib/exception.i index ee9ce9bc6..5cdea58e8 100644 --- a/Lib/exception.i +++ b/Lib/exception.i @@ -12,10 +12,20 @@ %insert("runtime") "swigerrors.swg" -#ifdef SWIGPHP7 +#ifdef SWIGPHP %{ -#include "zend_exceptions.h" -#define SWIG_exception(code, msg) do { zend_throw_exception(NULL, (char*)msg, code); goto thrown; } while (0) +#if PHP_MAJOR_VERSION >= 8 +# define SWIG_HANDLE_VALUE_ERROR_FOR_PHP8(code) code == SWIG_ValueError ? zend_ce_value_error : +#else +# define SWIG_HANDLE_VALUE_ERROR_FOR_PHP8(code) +#endif +#define SWIG_exception(code, msg) do { zend_throw_exception( \ + code == SWIG_TypeError ? zend_ce_type_error : \ + SWIG_HANDLE_VALUE_ERROR_FOR_PHP8(code) \ + code == SWIG_DivisionByZero ? zend_ce_division_by_zero_error : \ + code == SWIG_SyntaxError ? zend_ce_parse_error : \ + code == SWIG_OverflowError ? zend_ce_arithmetic_error : \ + NULL, msg, code); SWIG_fail; } while (0) %} #endif diff --git a/Lib/go/gokw.swg b/Lib/go/gokw.swg index dd9f35aa3..354283002 100644 --- a/Lib/go/gokw.swg +++ b/Lib/go/gokw.swg @@ -1,6 +1,6 @@ /* Rename keywords. */ -#define GOKW(x) %keywordwarn("'" `x` "' is a Go keyword, renaming to 'X"`x`"'",rename="X%s") `x` +#define GOKW(x) %keywordwarn("'" `x` "' is a Go keyword",rename="X%s") `x` #define GOBN(x) %builtinwarn("'" `x` "' conflicts with a built-in name in Go") "::"`x` GOKW(break); diff --git a/Lib/go/goruntime.swg b/Lib/go/goruntime.swg index 269a4eefd..c3401b1a8 100644 --- a/Lib/go/goruntime.swg +++ b/Lib/go/goruntime.swg @@ -23,46 +23,38 @@ static void* Swig_malloc(int c) { %} -#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 #ifndef SWIGGO_GCCGO // Set the host compiler struct attribute that will be @@ -89,8 +81,6 @@ typedef struct { void* array; intgo len; intgo cap; } _goslice_; %} -#ifdef SWIGGO_CGO - %insert(cgo_comment_typedefs) %{ typedef struct { char *p; intgo n; } _gostring_; @@ -98,91 +88,7 @@ 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. */ -%insert(runtime) %{ - -#define swiggo_size_assert_eq(x, y, name) typedef char name[(x-y)*(x-y)*-2+1]; -#define swiggo_size_assert(t, n) swiggo_size_assert_eq(sizeof(t), n, swiggo_sizeof_##t##_is_not_##n) - -swiggo_size_assert(char, 1) -swiggo_size_assert(short, 2) -swiggo_size_assert(int, 4) -typedef long long swiggo_long_long; -swiggo_size_assert(swiggo_long_long, 8) -swiggo_size_assert(float, 4) -swiggo_size_assert(double, 8) - -#ifdef __cplusplus -extern "C" { -#endif -extern void crosscall2(void (*fn)(void *, int), void *, int); -extern char* _cgo_topofstack(void) __attribute__ ((weak)); -extern void _cgo_allocate(void *, int); -extern void _cgo_panic(void *, int); -#ifdef __cplusplus -} -#endif - -static char *_swig_topofstack() { - if (_cgo_topofstack) { - return _cgo_topofstack(); - } else { - return 0; - } -} - -static void _swig_gopanic(const char *p) { - struct { - const char *p; - } SWIGSTRUCTPACKED 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; - void *ret; - } SWIGSTRUCTPACKED a; - a.len = len; - crosscall2(_cgo_allocate, &a, (int) sizeof a); - return a.ret; -} - -%} - -#endif - -#if !SWIGGO_CGO - -/* Boilerplate for C code when using 6g/8g. This code is compiled - with 6c/8c. */ -%insert(gc_header) %{ -#include "runtime.h" -#include "cgocall.h" - -#pragma dataflag 16 -static void *cgocall = runtime·cgocall; -#pragma dataflag 16 -void *·_cgo_runtime_cgocall = &cgocall; - -%} - -#endif - -#else +#ifdef SWIGGO_GCCGO /* Boilerplate for C/C++ code when using gccgo. */ %insert(runtime) %{ @@ -201,115 +107,12 @@ extern void _cgo_panic(const char *); #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 - a prefix of the module name. The implementations here call the - routine in libgo. The routines to call vary depending on the gccgo - 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__) - -#if SWIG_GCC_VERSION < 40700 -#define SwigDoCgocall() -#define SwigDoCgocallDone() -#define SwigDoCgocallBack() -#define SwigDoCgocallBackDone() -#elif SWIG_GCC_VERSION == 40700 -void SwigDoCgocall(void) __asm__("libgo_syscall.syscall.Entersyscall"); -void SwigDoCgocallDone(void) __asm__("libgo_syscall.syscall.Exitsyscall"); -void SwigDoCgocallBack(void) __asm__("libgo_syscall.syscall.Exitsyscall"); -void SwigDoCgocallBackDone(void) __asm__("libgo_syscall.syscall.Entersyscall"); -#else -void SwigDoCgocall(void) __asm__("syscall.Cgocall"); -void SwigDoCgocallDone(void) __asm__("syscall.CgocallDone"); -void SwigDoCgocallBack(void) __asm__("syscall.CgocallBack"); -void SwigDoCgocallBackDone(void) __asm__("syscall.CgocallBackDone"); -#endif - -#define SWIGSTRINGIFY2(s) #s -#define SWIGSTRINGIFY(s) SWIGSTRINGIFY2(s) - -void SwigCgocall() - __asm__(SWIGSTRINGIFY(SWIGGO_PREFIX) ".SwigCgocall"); -void SwigCgocall() { - SwigDoCgocall(); -} - -void SwigCgocallDone() - __asm__(SWIGSTRINGIFY(SWIGGO_PREFIX) ".SwigCgocallDone"); -void SwigCgocallDone() { - SwigDoCgocallDone(); -} - -void SwigCgocallBack() - __asm__(SWIGSTRINGIFY(SWIGGO_PREFIX) ".SwigCgocallBack"); -void SwigCgocallBack() { - SwigDoCgocallBack(); -} - -void SwigCgocallBackDone() - __asm__(SWIGSTRINGIFY(SWIGGO_PREFIX) ".SwigCgocallBackDone"); -void SwigCgocallBackDone() { - SwigDoCgocallBackDone(); -} - -#undef SWIGSTRINGIFY -#undef SWIGSTRINGIFY2 - -#ifdef __cplusplus -} -#endif - -%} - -#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); - memcpy(ret.p, p, l); - ret.n = l; - return ret; -} - -%} - -#endif - -%insert(runtime) %{ - -#define SWIG_contract_assert(expr, msg) \ - if (!(expr)) { _swig_gopanic(msg); } else -%} - #ifndef SWIGGO_GCCGO %go_import("unsafe", _ "runtime/cgo") -#if !SWIGGO_CGO -%insert(go_header) %{ -var _cgo_runtime_cgocall func(unsafe.Pointer, uintptr) -%} -#endif - #else %go_import("syscall", "unsafe") diff --git a/Lib/go/std_array.i b/Lib/go/std_array.i new file mode 100644 index 000000000..36c790e3c --- /dev/null +++ b/Lib/go/std_array.i @@ -0,0 +1,43 @@ +/* ----------------------------------------------------------------------------- + * std_array.i + * ----------------------------------------------------------------------------- */ + +%include + +namespace std { + + template class array { + public: + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef T value_type; + typedef value_type* pointer; + typedef const value_type* const_pointer; + typedef value_type& reference; + typedef const value_type& const_reference; + + array(); + array(const array& other); + + size_type size() const; + %rename(isEmpty) empty; + bool empty() const; + void fill(const T& u); + %extend { + const_reference get(int i) throw (std::out_of_range) { + int size = int(self->size()); + if (i>=0 && isize()); + if (i>=0 && iGetMethodID(baseclass, name, desc); + } + }; + /* Java object wrapper */ JObjectWrapper swig_self_; @@ -238,6 +247,11 @@ namespace Swig { } } + jclass swig_new_global_ref(JNIEnv *jenv, const char *classname) { + jclass clz = jenv->FindClass(classname); + return clz ? (jclass)jenv->NewGlobalRef(clz) : 0; + } + public: Director(JNIEnv *jenv) : swig_jvm_((JavaVM *) NULL), swig_self_() { /* Acquire the Java VM pointer */ diff --git a/Lib/java/java.swg b/Lib/java/java.swg index e9309331a..8f95f3a3b 100644 --- a/Lib/java/java.swg +++ b/Lib/java/java.swg @@ -1196,6 +1196,7 @@ Swig::LocalRefGuard $1_refguard(jenv, $input); } %typemap(javacode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" %typemap(javaimports) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" %typemap(javainterfaces) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" +%typemap(javainterfacemodifiers) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "public interface" /* javabody typemaps */ diff --git a/Lib/java/javahead.swg b/Lib/java/javahead.swg index 2e10254f3..758a037d1 100644 --- a/Lib/java/javahead.swg +++ b/Lib/java/javahead.swg @@ -30,18 +30,6 @@ #endif %insert(runtime) %{ -/* Fix for jlong on some versions of gcc on Windows */ -#if defined(__GNUC__) && !defined(__INTEL_COMPILER) - typedef long long __int64; -#endif - -/* Fix for jlong on 64-bit x86 Solaris */ -#if defined(__x86_64) -# ifdef _LP64 -# undef _LP64 -# endif -#endif - #include #include #include @@ -99,5 +87,5 @@ static void SWIGUNUSED SWIG_JavaThrowException(JNIEnv *jenv, SWIG_JavaExceptionC %insert(runtime) %{ /* Contract support */ -#define SWIG_contract_assert(nullreturn, expr, msg) if (!(expr)) {SWIG_JavaThrowException(jenv, SWIG_JavaIllegalArgumentException, msg); return nullreturn; } else +#define SWIG_contract_assert(nullreturn, expr, msg) do { if (!(expr)) {SWIG_JavaThrowException(jenv, SWIG_JavaIllegalArgumentException, msg); return nullreturn; } } while (0) %} diff --git a/Lib/java/javakw.swg b/Lib/java/javakw.swg index 99cd54770..8a5b76eef 100644 --- a/Lib/java/javakw.swg +++ b/Lib/java/javakw.swg @@ -2,7 +2,7 @@ #define JAVA_JAVAKW_SWG_ /* Warnings for Java keywords */ -#define JAVAKW(x) %keywordwarn("'" `x` "' is a java keyword, renaming to '_"`x`"'",rename="_%s") `x` +#define JAVAKW(x) %keywordwarn("'" `x` "' is a java keyword",rename="_%s") `x` /* from diff --git a/Lib/java/std_auto_ptr.i b/Lib/java/std_auto_ptr.i index 9b3cd7315..69ac2841f 100644 --- a/Lib/java/std_auto_ptr.i +++ b/Lib/java/std_auto_ptr.i @@ -1,5 +1,5 @@ /* - The typemaps here allow to handle functions returning std::auto_ptr<>, + The typemaps here allow handling functions returning std::auto_ptr<>, which is the most common use of this type. If you have functions taking it as parameter, these typemaps can't be used for them and you need to do something else (e.g. use shared_ptr<> which SWIG supports fully). diff --git a/Lib/java/swiginterface.i b/Lib/java/swiginterface.i index 334464157..0a0f7806a 100644 --- a/Lib/java/swiginterface.i +++ b/Lib/java/swiginterface.i @@ -28,7 +28,7 @@ } %typemap(javaout) CTYPE *const& { long cPtr = $jnicall; - return (cPtr == 0) ? null : ($javainterfacename)new $javaclassname(cPtr, $owner); + return (cPtr == 0) ? null : ($*javainterfacename)new $*javaclassname(cPtr, $owner); } %typemap(javadirectorin) CTYPE "($&javainterfacename)new $&javaclassname($jniinput, true)" diff --git a/Lib/javascript/jsc/arrays_javascript.i b/Lib/javascript/jsc/arrays_javascript.i index b9199d86b..713b7ef23 100644 --- a/Lib/javascript/jsc/arrays_javascript.i +++ b/Lib/javascript/jsc/arrays_javascript.i @@ -21,34 +21,39 @@ * fs = example.FiddleSticks; * ----------------------------------------------------------------------------- */ -%fragment("SWIG_JSCGetIntProperty", "header", fragment=SWIG_AsVal_frag(int)) {} + +%fragment("SWIG_JSCGetIntProperty", "header", fragment=SWIG_AsVal_frag(int)) {} %fragment("SWIG_JSCGetNumberProperty", "header", fragment=SWIG_AsVal_frag(double)) {} +%fragment("SWIG_JSCOutInt", "header", fragment=SWIG_From_frag(int)) {} +%fragment("SWIG_JSCOutNumber", "header", fragment=SWIG_From_frag(double)) {} -%typemap(in, fragment="SWIG_JSCGetIntProperty") int[], int[ANY] - (int length = 0, JSObjectRef array, JSValueRef jsvalue, int i = 0, int res = 0, $*1_ltype temp) { +%define JAVASCRIPT_ARRAYS_IN_DECL(NAME, CTYPE, ANY, ANYLENGTH) + +%typemap(in, fragment=NAME) CTYPE[ANY] { if (JSValueIsObject(context, $input)) { + int i; // Convert into Array - array = JSValueToObject(context, $input, NULL); + JSObjectRef array = JSValueToObject(context, $input, NULL); - length = $1_dim0; + int length = ANYLENGTH; $1 = ($*1_ltype *)malloc(sizeof($*1_ltype) * length); // Get each element from array for (i = 0; i < length; i++) { - jsvalue = JSObjectGetPropertyAtIndex(context, array, i, NULL); + JSValueRef jsvalue = JSObjectGetPropertyAtIndex(context, array, i, NULL); + $*1_ltype temp; // Get primitive value from JSObject - res = SWIG_AsVal(int)(jsvalue, &temp); + int res = SWIG_AsVal(CTYPE)(jsvalue, &temp); if (!SWIG_IsOK(res)) { SWIG_exception_fail(SWIG_ERROR, "Failed to convert $input to double"); } arg$argnum[i] = temp; } - } else { @@ -56,68 +61,34 @@ } } -%typemap(freearg) int[], int[ANY] { +%typemap(freearg) CTYPE[ANY] { free($1); } -%typemap(out, fragment=SWIG_From_frag(int)) int[], int[ANY] (int length = 0, int i = 0) -{ - length = $1_dim0; +%enddef + +%define JAVASCRIPT_ARRAYS_OUT_DECL(NAME, CTYPE) + +%typemap(out, fragment=NAME) CTYPE[ANY] { + int length = $1_dim0; JSValueRef values[length]; + int i; for (i = 0; i < length; i++) { - values[i] = SWIG_From(int)($1[i]); + values[i] = SWIG_From(CTYPE)($1[i]); } $result = JSObjectMakeArray(context, length, values, NULL); } -%typemap(in, fragment="SWIG_JSCGetNumberProperty") double[], double[ANY] - (int length = 0, JSObjectRef array, JSValueRef jsvalue, int i = 0, int res = 0, $*1_ltype temp) { - if (JSValueIsObject(context, $input)) - { - // Convert into Array - array = JSValueToObject(context, $input, NULL); +%enddef - length = $1_dim0; +JAVASCRIPT_ARRAYS_IN_DECL("SWIG_JSCGetIntProperty", int, , SWIGJSC_ArrayLength(context, array)) +JAVASCRIPT_ARRAYS_IN_DECL("SWIG_JSCGetIntProperty", int, ANY, $1_dim0) +JAVASCRIPT_ARRAYS_IN_DECL("SWIG_JSCGetNumberProperty", double, , SWIGJSC_ArrayLength(context, array)) +JAVASCRIPT_ARRAYS_IN_DECL("SWIG_JSCGetNumberProperty", double, ANY, $1_dim0) - $1 = ($*1_ltype *)malloc(sizeof($*1_ltype) * length); +JAVASCRIPT_ARRAYS_OUT_DECL("SWIG_JSCOutInt", int) +JAVASCRIPT_ARRAYS_OUT_DECL("SWIG_JSCOutNumber", double) - // Get each element from array - for (i = 0; i < length; i++) - { - jsvalue = JSObjectGetPropertyAtIndex(context, array, i, NULL); - - // Get primitive value from JSObject - res = SWIG_AsVal(double)(jsvalue, &temp); - if (!SWIG_IsOK(res)) - { - SWIG_exception_fail(SWIG_ERROR, "Failed to convert $input to double"); - } - arg$argnum[i] = temp; - } - - } - else - { - SWIG_exception_fail(SWIG_ERROR, "$input is not JSObjectRef"); - } -} - -%typemap(freearg) double[], double[ANY] { - free($1); -} - -%typemap(out, fragment=SWIG_From_frag(double)) double[], double[ANY] (int length = 0, int i = 0) -{ - length = $1_dim0; - JSValueRef values[length]; - - for (i = 0; i < length; i++) - { - values[i] = SWIG_From(double)($1[i]); - } - - $result = JSObjectMakeArray(context, length, values, NULL); -} diff --git a/Lib/javascript/jsc/ccomplex.i b/Lib/javascript/jsc/ccomplex.i index 50f0f95fe..e58dbf719 100644 --- a/Lib/javascript/jsc/ccomplex.i +++ b/Lib/javascript/jsc/ccomplex.i @@ -12,15 +12,16 @@ #include %} +#define complex _Complex /* C complex constructor */ #define CCplxConst(r, i) ((r) + I*(i)) -%swig_cplxflt_convn(float complex, CCplxConst, creal, cimag); -%swig_cplxdbl_convn(double complex, CCplxConst, creal, cimag); -%swig_cplxdbl_convn(complex, CCplxConst, creal, cimag); +%swig_cplxflt_convn(float _Complex, CCplxConst, creal, cimag); +%swig_cplxdbl_convn(double _Complex, CCplxConst, creal, cimag); +%swig_cplxdbl_convn(_Complex, CCplxConst, creal, cimag); /* declaring the typemaps */ -%typemaps_primitive(SWIG_TYPECHECK_CPLXFLT, float complex); -%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, double complex); -%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, complex); +%typemaps_primitive(SWIG_TYPECHECK_CPLXFLT, float _Complex); +%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, double _Complex); +%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, _Complex); diff --git a/Lib/javascript/jsc/javascriptcomplex.swg b/Lib/javascript/jsc/javascriptcomplex.swg index 7be120b3b..dcc205dbd 100644 --- a/Lib/javascript/jsc/javascriptcomplex.swg +++ b/Lib/javascript/jsc/javascriptcomplex.swg @@ -127,7 +127,7 @@ SWIG_AsVal_dec(Type)(JSValueRef o, Type *val) float re; int res = SWIG_AddCast(SWIG_AsVal(float)(o, &re)); if (SWIG_IsOK(res)) { - if (val) *val = Constructor(re, 0.0); + if (val) *val = Constructor(re, 0.0f); return res; } } diff --git a/Lib/javascript/jsc/javascriptinit.swg b/Lib/javascript/jsc/javascriptinit.swg index a32ba336c..b0138b39a 100644 --- a/Lib/javascript/jsc/javascriptinit.swg +++ b/Lib/javascript/jsc/javascriptinit.swg @@ -1,14 +1,59 @@ %insert(init) %{ SWIGRUNTIME void -SWIG_JSC_SetModule(swig_module_info *swig_module) {} +SWIG_JSC_SetModule(JSGlobalContextRef context, swig_module_info *swig_module) { + JSObjectRef globalObject; + JSStringRef moduleName; + JSClassDefinition classDef; + JSClassRef classRef; + JSObjectRef object; + if(context == 0){ + return; + } + + globalObject = JSContextGetGlobalObject(context); + moduleName = JSStringCreateWithUTF8CString("swig_module_info_data"); + + classDef = kJSClassDefinitionEmpty; + classRef = JSClassCreate(&classDef); + + object = JSObjectMake(context, classRef, NULL); + JSObjectSetPrivate(object, (void*)swig_module); + + JSObjectSetProperty(context, globalObject, moduleName, object, kJSPropertyAttributeNone, NULL); + + JSClassRelease(classRef); + JSStringRelease(moduleName); +} SWIGRUNTIME swig_module_info * -SWIG_JSC_GetModule(void) { - return 0; +SWIG_JSC_GetModule(JSGlobalContextRef context) { + JSObjectRef globalObject; + JSStringRef moduleName; + JSValueRef value; + JSObjectRef object; + + if(context == 0){ + return 0; + } + + globalObject = JSContextGetGlobalObject(context); + moduleName = JSStringCreateWithUTF8CString("swig_module_info_data"); + + if(JSObjectHasProperty(context, globalObject, moduleName) == false) { + JSStringRelease(moduleName); + return 0; + } + + value = JSObjectGetProperty(context, globalObject, moduleName, NULL); + object = JSValueToObject(context, value, NULL); + JSStringRelease(moduleName); + + return (swig_module_info*)JSObjectGetPrivate(object); } -#define SWIG_GetModule(clientdata) SWIG_JSC_GetModule() -#define SWIG_SetModule(clientdata, pointer) SWIG_JSC_SetModule(pointer) +#define SWIG_GetModule(clientdata) SWIG_JSC_GetModule(clientdata) +#define SWIG_SetModule(clientdata, pointer) SWIG_JSC_SetModule(clientdata, pointer) +#define SWIG_INIT_CLIENT_DATA_TYPE JSGlobalContextRef %} %insert(init) "swiginit.swg" @@ -26,7 +71,7 @@ extern "C" { #endif bool SWIGJSC_INIT (JSGlobalContextRef context, JSObjectRef *exports) { - SWIG_InitializeModule(0); + SWIG_InitializeModule(context); %} /* ----------------------------------------------------------------------------- diff --git a/Lib/javascript/jsc/javascriptrun.swg b/Lib/javascript/jsc/javascriptrun.swg index 4a8fc5be5..d092ea4ab 100644 --- a/Lib/javascript/jsc/javascriptrun.swg +++ b/Lib/javascript/jsc/javascriptrun.swg @@ -117,27 +117,25 @@ SWIGRUNTIME int SWIG_JSC_ConvertInstancePtr(JSContextRef context, JSObjectRef ob SwigPrivData *cdata; cdata = (SwigPrivData *) JSObjectGetPrivate(objRef); - if(cdata == NULL) { + if (cdata == NULL) { return SWIG_ERROR; } - if(cdata->info != info) { - bool type_valid = false; - swig_cast_info *t = info->cast; - while(t != NULL) { - if(t->type == cdata->info) { - type_valid = true; - break; - } - t = t->next; - } - if(!type_valid) { - return SWIG_TypeError; + assert(ptr); + *ptr = NULL; + if (cdata->info == info) { + *ptr = cdata->swigCObject; + } else { + swig_cast_info *tc = SWIG_TypeCheckStruct(cdata->info, info); + if (tc) { + int newmemory = 0; + *ptr = SWIG_TypeCast(tc, cdata->swigCObject, &newmemory); + assert(!newmemory); /* newmemory handling not yet implemented */ + } else { + return SWIG_ERROR; } } - *ptr = cdata->swigCObject; - - if(flags & SWIG_POINTER_DISOWN) { + if (flags & SWIG_POINTER_DISOWN) { cdata->swigCMemOwn = false; } @@ -317,6 +315,30 @@ unsigned int SWIGJSC_ArrayLength(JSContextRef context, JSObjectRef arr) { } } +SWIGRUNTIME +bool SWIGJSC_ValueIsArray(JSContextRef context, JSValueRef value) { + if (JSValueIsObject(context, value)) { + static JSStringRef ArrayString = NULL; + static JSStringRef isArrayString = NULL; + JSObjectRef array = NULL; + JSObjectRef isArray = NULL; + JSValueRef retval = NULL; + + if (!ArrayString) + ArrayString = JSStringCreateWithUTF8CString("Array"); + if (!isArrayString) + isArrayString = JSStringCreateWithUTF8CString("isArray"); + + array = (JSObjectRef)JSObjectGetProperty(context, JSContextGetGlobalObject(context), ArrayString, NULL); + isArray = (JSObjectRef)JSObjectGetProperty(context, array, isArrayString, NULL); + retval = JSObjectCallAsFunction(context, isArray, NULL, 1, &value, NULL); + + if (JSValueIsBoolean(context, retval)) + return JSValueToBoolean(context, retval); + } + return false; +} + SWIGRUNTIME JSValueRef SWIGJSC_AppendOutput(JSContextRef context, JSValueRef value, JSValueRef obj) { JSObjectRef arr; @@ -324,6 +346,8 @@ JSValueRef SWIGJSC_AppendOutput(JSContextRef context, JSValueRef value, JSValueR if (JSValueIsUndefined(context, value)) { arr = JSObjectMakeArray(context, 0, 0, 0); + } else if (!SWIGJSC_ValueIsArray(context, value)) { + arr = JSObjectMakeArray(context, 1, &value, 0); } else { arr = JSValueToObject(context, value, 0); } diff --git a/Lib/javascript/jsc/javascriptruntime.swg b/Lib/javascript/jsc/javascriptruntime.swg index 8f8390890..a626390cc 100644 --- a/Lib/javascript/jsc/javascriptruntime.swg +++ b/Lib/javascript/jsc/javascriptruntime.swg @@ -11,6 +11,7 @@ #include #include #include +#include %} %insert(runtime) "swigrun.swg"; /* SWIG API */ diff --git a/Lib/javascript/jsc/typemaps.i b/Lib/javascript/jsc/typemaps.i index d3d8afb19..b5b441bc7 100644 --- a/Lib/javascript/jsc/typemaps.i +++ b/Lib/javascript/jsc/typemaps.i @@ -72,7 +72,7 @@ multiple output values, they are returned in the form of a Python tuple. For example, suppose you were trying to wrap the modf() function in the C math library which splits x into integral and fractional parts (and -returns the integer part in one of its parameters).K: +returns the integer part in one of its parameters) : double modf(double x, double *ip); diff --git a/Lib/javascript/v8/arrays_javascript.i b/Lib/javascript/v8/arrays_javascript.i index 22b50be8f..6dc7e4b9b 100644 --- a/Lib/javascript/v8/arrays_javascript.i +++ b/Lib/javascript/v8/arrays_javascript.i @@ -21,105 +21,66 @@ * fs = example.FiddleSticks; * ----------------------------------------------------------------------------- */ -%fragment("SWIG_JSCGetIntProperty", "header", fragment=SWIG_AsVal_frag(int)) {} + +%fragment("SWIG_JSCGetIntProperty", "header", fragment=SWIG_AsVal_frag(int)) {} %fragment("SWIG_JSCGetNumberProperty", "header", fragment=SWIG_AsVal_frag(double)) {} +%fragment("SWIG_JSCOutInt", "header", fragment=SWIG_From_frag(int)) {} +%fragment("SWIG_JSCOutNumber", "header", fragment=SWIG_From_frag(double)) {} -%typemap(in, fragment="SWIG_JSCGetIntProperty") int[], int[ANY] - (int length = 0, v8::Local array, v8::Local jsvalue, int i = 0, int res = 0, $*1_ltype temp) { - if ($input->IsArray()) - { +%define JAVASCRIPT_ARRAYS_IN_DECL(NAME, CTYPE, ANY, ANYLENGTH) + +%typemap(in, fragment=NAME) CTYPE[ANY] { + if ($input->IsArray()) { // Convert into Array - array = v8::Local::Cast($input); + v8::Local array = v8::Local::Cast($input); - length = $1_dim0; + int length = ANYLENGTH; - $1 = ($*1_ltype *)malloc(sizeof($*1_ltype) * length); + $1 = ($*1_ltype *)malloc(sizeof($*1_ltype) * length); // Get each element from array - for (i = 0; i < length; i++) - { - jsvalue = array->Get(i); + for (int i = 0; i < length; i++) { + v8::Local jsvalue = SWIGV8_ARRAY_GET(array, i); + $*1_ltype temp; // Get primitive value from JSObject - res = SWIG_AsVal(int)(jsvalue, &temp); - if (!SWIG_IsOK(res)) - { + int res = SWIG_AsVal(CTYPE)(jsvalue, &temp); + if (!SWIG_IsOK(res)) { SWIG_exception_fail(SWIG_ERROR, "Failed to convert $input to double"); } arg$argnum[i] = temp; } - - } - else - { - SWIG_exception_fail(SWIG_ERROR, "$input is not JSObjectRef"); + } else { + SWIG_exception_fail(SWIG_ERROR, "$input is not an array"); } } -%typemap(freearg) int[], int[ANY] { - free($1); +%typemap(freearg) CTYPE[ANY] { + free($1); } -%typemap(out, fragment=SWIG_From_frag(int)) int[], int[ANY] (int length = 0, int i = 0) -{ - length = $1_dim0; - v8::Local array = v8::Array::New(length); +%enddef - for (i = 0; i < length; i++) - { - array->Set(i, SWIG_From(int)($1[i])); +%define JAVASCRIPT_ARRAYS_OUT_DECL(NAME, CTYPE) + +%typemap(out, fragment=NAME) CTYPE[ANY] { + int length = $1_dim0; + v8::Local array = SWIGV8_ARRAY_NEW(length); + + for (int i = 0; i < length; i++) { + SWIGV8_ARRAY_SET(array, i, SWIG_From(CTYPE)($1[i])); } - $result = array; } -%typemap(in, fragment="SWIG_JSCGetNumberProperty") double[], double[ANY] - (int length = 0, v8::Local array, v8::Local jsvalue, int i = 0, int res = 0, $*1_ltype temp) { - if ($input->IsArray()) - { - // Convert into Array - array = v8::Local::Cast($input); +%enddef - length = $1_dim0; +JAVASCRIPT_ARRAYS_IN_DECL("SWIG_JSCGetIntProperty", int, , array->Length()) +JAVASCRIPT_ARRAYS_IN_DECL("SWIG_JSCGetIntProperty", int, ANY, $1_dim0) +JAVASCRIPT_ARRAYS_IN_DECL("SWIG_JSCGetNumberProperty", double, , array->Length()) +JAVASCRIPT_ARRAYS_IN_DECL("SWIG_JSCGetNumberProperty", double, ANY, $1_dim0) - $1 = ($*1_ltype *)malloc(sizeof($*1_ltype) * length); +JAVASCRIPT_ARRAYS_OUT_DECL("SWIG_JSCOutInt", int) +JAVASCRIPT_ARRAYS_OUT_DECL("SWIG_JSCOutNumber", double) - // Get each element from array - for (i = 0; i < length; i++) - { - jsvalue = array->Get(i); - - // Get primitive value from JSObject - res = SWIG_AsVal(double)(jsvalue, &temp); - if (!SWIG_IsOK(res)) - { - SWIG_exception_fail(SWIG_ERROR, "Failed to convert $input to double"); - } - arg$argnum[i] = temp; - } - - } - else - { - SWIG_exception_fail(SWIG_ERROR, "$input is not JSObjectRef"); - } -} - -%typemap(freearg) double[], double[ANY] { - free($1); -} - -%typemap(out, fragment=SWIG_From_frag(double)) double[], double[ANY] (int length = 0, int i = 0) -{ - length = $1_dim0; - v8::Local array = v8::Array::New(length); - - for (i = 0; i < length; i++) - { - array->Set(i, SWIG_From(double)($1[i])); - } - - - $result = array; -} diff --git a/Lib/javascript/v8/ccomplex.i b/Lib/javascript/v8/ccomplex.i index 8eda920bb..e58dbf719 100644 --- a/Lib/javascript/v8/ccomplex.i +++ b/Lib/javascript/v8/ccomplex.i @@ -6,21 +6,22 @@ * ----------------------------------------------------------------------------- */ -%include +%include %{ #include %} +#define complex _Complex /* C complex constructor */ #define CCplxConst(r, i) ((r) + I*(i)) -%swig_cplxflt_convn(float complex, CCplxConst, creal, cimag); -%swig_cplxdbl_convn(double complex, CCplxConst, creal, cimag); -%swig_cplxdbl_convn(complex, CCplxConst, creal, cimag); +%swig_cplxflt_convn(float _Complex, CCplxConst, creal, cimag); +%swig_cplxdbl_convn(double _Complex, CCplxConst, creal, cimag); +%swig_cplxdbl_convn(_Complex, CCplxConst, creal, cimag); /* declaring the typemaps */ -%typemaps_primitive(SWIG_TYPECHECK_CPLXFLT, float complex); -%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, double complex); -%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, complex); +%typemaps_primitive(SWIG_TYPECHECK_CPLXFLT, float _Complex); +%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, double _Complex); +%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, _Complex); diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index c4aaf3db0..dcda0ee63 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -10,9 +10,10 @@ %fragment("js_ctor", "templates") %{ static SwigV8ReturnValue $jswrapper(const SwigV8Arguments &args) { SWIGV8_HANDLESCOPE(); - - v8::Handle self = args.Holder(); + + SWIGV8_OBJECT self = args.Holder(); $jslocals + if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor $jswrapper."); if(args.Length() != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); $jscode @@ -53,7 +54,7 @@ static SwigV8ReturnValue $jswrapper(const SwigV8Arguments &args) { SWIGV8_HANDLESCOPE(); OverloadErrorHandler errorHandler; - v8::Handle self; + SWIGV8_VALUE self; // switch all cases by means of series of if-returns. $jsdispatchcases @@ -77,9 +78,10 @@ fail: %fragment("js_overloaded_ctor", "templates") %{ static SwigV8ReturnValue $jswrapper(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { SWIGV8_HANDLESCOPE(); - - v8::Handle self = args.Holder(); + + SWIGV8_OBJECT self = args.Holder(); $jslocals + if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor $jswrapper."); if(args.Length() != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); $jscode @@ -103,17 +105,10 @@ fail: %{ if(args.Length() == $jsargcount) { errorHandler.err.Clear(); -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) - self = $jswrapper(args, errorHandler); - if(errorHandler.err.IsEmpty()) { - SWIGV8_ESCAPE(self); - } -#else $jswrapper(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } -#endif } %} @@ -125,22 +120,8 @@ fail: %fragment ("js_dtor", "templates") %{ -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) -static void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) { - SWIGV8_Proxy *proxy = static_cast(parameter); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) -static void $jswrapper(v8::Isolate *isolate, v8::Persistent object, void *parameter) { - SWIGV8_Proxy *proxy = static_cast(parameter); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) -static void $jswrapper(v8::Isolate *isolate, v8::Persistent *object, SWIGV8_Proxy *proxy) { -#elif (V8_MAJOR_VERSION-0) < 5 -static void $jswrapper(const v8::WeakCallbackData &data) { - v8::Local object = data.GetValue(); +static void $jswrapper(const v8::WeakCallbackInfo &data) { SWIGV8_Proxy *proxy = data.GetParameter(); -#else - static void $jswrapper(const v8::WeakCallbackInfo &data) { - SWIGV8_Proxy *proxy = data.GetParameter(); -#endif if(proxy->swigCMemOwn && proxy->swigCObject) { #ifdef SWIGRUNTIME_DEBUG @@ -149,20 +130,6 @@ static void $jswrapper(const v8::WeakCallbackData &dat $jsfree proxy->swigCObject; } delete proxy; - -#if (V8_MAJOR_VERSION-0) < 5 - object.Clear(); -#endif - -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) - object.Dispose(); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) - object.Dispose(isolate); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) - object->Dispose(isolate); -#elif (V8_MAJOR_VERSION-0) < 5 - object->Dispose(); -#endif } %} @@ -174,40 +141,14 @@ static void $jswrapper(const v8::WeakCallbackData &dat * ----------------------------------------------------------------------------- */ %fragment ("js_dtoroverride", "templates") %{ -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) -static void $jswrapper(v8::Persistent object, void *parameter) { - SWIGV8_Proxy *proxy = static_cast(parameter); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) -static void $jswrapper(v8::Isolate *isolate, v8::Persistent object, void *parameter) { - SWIGV8_Proxy *proxy = static_cast(parameter); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) -static void $jswrapper(v8::Isolate *isolate, v8::Persistent< v8::Object> *object, SWIGV8_Proxy *proxy) { -#elif (V8_MAJOR_VERSION-0) < 5 -static void $jswrapper(const v8::WeakCallbackData &data) { - v8::Local object = data.GetValue(); - SWIGV8_Proxy *proxy = data.GetParameter(); -#else static void $jswrapper(const v8::WeakCallbackInfo &data) { SWIGV8_Proxy *proxy = data.GetParameter(); -#endif if(proxy->swigCMemOwn && proxy->swigCObject) { $jstype arg1 = ($jstype)proxy->swigCObject; ${destructor_action} } delete proxy; - -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) - object.Dispose(); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) - object.Dispose(isolate); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) - object->Dispose(isolate); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) - object->Dispose(); -#elif (V8_MAJOR_VERSION-0) < 5 - object.Clear(); -#endif } %} @@ -219,14 +160,10 @@ static void $jswrapper(const v8::WeakCallbackInfo &data) { * ----------------------------------------------------------------------------- */ %fragment("js_getter", "templates") %{ -#if (V8_MAJOR_VERSION-0) < 5 -static SwigV8ReturnValue $jswrapper(v8::Local property, const SwigV8PropertyCallbackInfo &info) { -#else static SwigV8ReturnValue $jswrapper(v8::Local property, const SwigV8PropertyCallbackInfo &info) { -#endif SWIGV8_HANDLESCOPE(); - v8::Handle jsresult; + SWIGV8_VALUE jsresult; $jslocals $jscode SWIGV8_RETURN_INFO(jsresult, info); @@ -245,11 +182,7 @@ fail: * ----------------------------------------------------------------------------- */ %fragment("js_setter", "templates") %{ -#if (V8_MAJOR_VERSION-0) < 5 -static void $jswrapper(v8::Local property, v8::Local value, const SwigV8PropertyCallbackInfoVoid &info) { -#else static void $jswrapper(v8::Local property, v8::Local value, const SwigV8PropertyCallbackInfoVoid &info) { -#endif SWIGV8_HANDLESCOPE(); $jslocals @@ -271,7 +204,7 @@ fail: static SwigV8ReturnValue $jswrapper(const SwigV8Arguments &args) { SWIGV8_HANDLESCOPE(); - v8::Handle jsresult; + SWIGV8_VALUE jsresult; $jslocals if(args.Length() != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); @@ -296,7 +229,7 @@ fail: static SwigV8ReturnValue $jswrapper(const SwigV8Arguments &args) { SWIGV8_HANDLESCOPE(); - v8::Handle jsresult; + SWIGV8_VALUE jsresult; OverloadErrorHandler errorHandler; $jscode @@ -320,7 +253,7 @@ static SwigV8ReturnValue $jswrapper(const SwigV8Arguments &args, V8ErrorHandler { SWIGV8_HANDLESCOPE(); - v8::Handle jsresult; + SWIGV8_VALUE jsresult; $jslocals $jscode SWIGV8_RETURN(jsresult); @@ -342,17 +275,10 @@ fail: if(args.Length() == $jsargcount) { errorHandler.err.Clear(); -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) - jsresult = $jswrapper(args, errorHandler); - if(errorHandler.err.IsEmpty()) { - SWIGV8_ESCAPE(jsresult); - } -#else $jswrapper(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } -#endif } %} @@ -374,7 +300,7 @@ fail: %fragment("jsv8_define_class_template", "templates") %{ /* Name: $jsmangledname, Type: $jsmangledtype, Dtor: $jsdtor */ - v8::Handle $jsmangledname_class = SWIGV8_CreateClassTemplate("$jsmangledname"); + SWIGV8_FUNCTION_TEMPLATE $jsmangledname_class = SWIGV8_CreateClassTemplate("$jsmangledname"); SWIGV8_SET_CLASS_TEMPL($jsmangledname_clientData.class_templ, $jsmangledname_class); $jsmangledname_clientData.dtor = $jsdtor; if (SWIGTYPE_$jsmangledtype->clientdata == 0) { @@ -392,15 +318,11 @@ fail: %{ if (SWIGTYPE_p$jsbaseclass->clientdata && !(static_cast(SWIGTYPE_p$jsbaseclass->clientdata)->class_templ.IsEmpty())) { -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) - $jsmangledname_class->Inherit(static_cast(SWIGTYPE_p$jsbaseclass->clientdata)->class_templ); -#else $jsmangledname_class->Inherit( v8::Local::New( v8::Isolate::GetCurrent(), static_cast(SWIGTYPE_p$jsbaseclass->clientdata)->class_templ) ); -#endif #ifdef SWIGRUNTIME_DEBUG printf("Inheritance successful $jsmangledname $jsbaseclass\n"); @@ -420,11 +342,15 @@ fail: %fragment("jsv8_create_class_instance", "templates") %{ /* Class: $jsname ($jsmangledname) */ - v8::Handle $jsmangledname_class_0 = SWIGV8_CreateClassTemplate("$jsname"); + SWIGV8_FUNCTION_TEMPLATE $jsmangledname_class_0 = SWIGV8_CreateClassTemplate("$jsname"); $jsmangledname_class_0->SetCallHandler($jsctor); $jsmangledname_class_0->Inherit($jsmangledname_class); +#if (SWIG_V8_VERSION < 0x0704) $jsmangledname_class_0->SetHiddenPrototype(true); - v8::Handle $jsmangledname_obj = $jsmangledname_class_0->GetFunction(); + v8::Local $jsmangledname_obj = $jsmangledname_class_0->GetFunction(); +#else + v8::Local $jsmangledname_obj = $jsmangledname_class_0->GetFunction(context).ToLocalChecked(); +#endif %} /* ----------------------------------------------------------------------------- @@ -435,7 +361,7 @@ fail: * ----------------------------------------------------------------------------- */ %fragment("jsv8_register_class", "templates") %{ - $jsparent_obj->Set(SWIGV8_SYMBOL_NEW("$jsname"), $jsmangledname_obj); + SWIGV8_MAYBE_CHECK($jsparent_obj->Set(context, SWIGV8_SYMBOL_NEW("$jsname"), $jsmangledname_obj)); %} /* ----------------------------------------------------------------------------- @@ -444,7 +370,7 @@ fail: * ----------------------------------------------------------------------------- */ %fragment("jsv8_create_namespace", "templates") %{ - v8::Handle $jsmangledname_obj = SWIGV8_OBJECT_NEW(); + SWIGV8_OBJECT $jsmangledname_obj = SWIGV8_OBJECT_NEW(); %} /* ----------------------------------------------------------------------------- @@ -455,7 +381,7 @@ fail: * ----------------------------------------------------------------------------- */ %fragment("jsv8_register_namespace", "templates") %{ - $jsparent_obj->Set(SWIGV8_SYMBOL_NEW("$jsname"), $jsmangledname_obj); + SWIGV8_MAYBE_CHECK($jsparent_obj->Set(context, SWIGV8_SYMBOL_NEW("$jsname"), $jsmangledname_obj)); %} /* ----------------------------------------------------------------------------- @@ -491,7 +417,7 @@ fail: * ----------------------------------------------------------------------------- */ %fragment("jsv8_register_static_function", "templates") %{ - SWIGV8_AddStaticFunction($jsparent_obj, "$jsname", $jswrapper); + SWIGV8_AddStaticFunction($jsparent_obj, "$jsname", $jswrapper, context); %} /* ----------------------------------------------------------------------------- @@ -505,5 +431,5 @@ fail: * ----------------------------------------------------------------------------- */ %fragment("jsv8_register_static_variable", "templates") %{ - SWIGV8_AddStaticVariable($jsparent_obj, "$jsname", $jsgetter, $jssetter); + SWIGV8_AddStaticVariable($jsparent_obj, "$jsname", $jsgetter, $jssetter, context); %} diff --git a/Lib/javascript/v8/javascriptcomplex.swg b/Lib/javascript/v8/javascriptcomplex.swg index d3b4aaffa..7b3c5547e 100644 --- a/Lib/javascript/v8/javascriptcomplex.swg +++ b/Lib/javascript/v8/javascriptcomplex.swg @@ -12,15 +12,15 @@ %fragment(SWIG_From_frag(Type),"header", fragment=SWIG_From_frag(double)) { -SWIGINTERNINLINE v8::Handle +SWIGINTERNINLINE SWIGV8_VALUE SWIG_From_dec(Type)(%ifcplusplus(const Type&, Type) c) { SWIGV8_HANDLESCOPE_ESC(); - v8::Local vals = SWIGV8_ARRAY_NEW(); + v8::Local vals = SWIGV8_ARRAY_NEW(0); - vals->Set(0, SWIG_From(double)(Real(c))); - vals->Set(1, SWIG_From(double)(Imag(c))); + SWIGV8_ARRAY_SET(vals, 0, SWIG_From(double)(Real(c))); + SWIGV8_ARRAY_SET(vals, 1, SWIG_From(double)(Imag(c))); SWIGV8_ESCAPE(vals); } } @@ -32,30 +32,30 @@ SWIG_From_dec(Type)(%ifcplusplus(const Type&, Type) c) fragment=SWIG_AsVal_frag(double)) { SWIGINTERN int -SWIG_AsVal_dec(Type) (v8::Handle o, Type* val) +SWIG_AsVal_dec(Type) (SWIGV8_VALUE o, Type* val) { SWIGV8_HANDLESCOPE(); if (o->IsArray()) { - v8::Handle array = v8::Handle::Cast(o); + SWIGV8_ARRAY array = SWIGV8_ARRAY::Cast(o); - if(array->Length() != 2) SWIG_Error(SWIG_TypeError, "Illegal argument for complex: must be array[2]."); + if (array->Length() != 2) SWIG_Error(SWIG_TypeError, "Illegal argument for complex: must be array[2]."); double re, im; int res; - res = SWIG_AsVal(double)(array->Get(0), &re); - if(!SWIG_IsOK(res)) { + res = SWIG_AsVal(double)(SWIGV8_ARRAY_GET(array, 0), &re); + if (!SWIG_IsOK(res)) { return SWIG_TypeError; } - res = SWIG_AsVal(double)(array->Get(1), &im); - if(!SWIG_IsOK(res)) { + res = SWIG_AsVal(double)(SWIGV8_ARRAY_GET(array, 1), &im); + if (!SWIG_IsOK(res)) { return SWIG_TypeError; } if (val) *val = Constructor(re, im); return SWIG_OK; - } else if(o->IsNumber()){ + } else if (o->IsNumber()) { double d; int res = SWIG_AddCast(SWIG_AsVal(double)(o, &d)); if (SWIG_IsOK(res)) { @@ -74,24 +74,24 @@ SWIG_AsVal_dec(Type) (v8::Handle o, Type* val) %fragment(SWIG_AsVal_frag(Type),"header", fragment=SWIG_AsVal_frag(float)) { SWIGINTERN int -SWIG_AsVal_dec(Type) (v8::Handle o, Type* val) +SWIG_AsVal_dec(Type) (SWIGV8_VALUE o, Type* val) { SWIGV8_HANDLESCOPE(); if (o->IsArray()) { - v8::Handle array = v8::Handle::Cast(o); + SWIGV8_ARRAY array = SWIGV8_ARRAY::Cast(o); - if(array->Length() != 2) SWIG_Error(SWIG_TypeError, "Illegal argument for complex: must be array[2]."); + if (array->Length() != 2) SWIG_Error(SWIG_TypeError, "Illegal argument for complex: must be array[2]."); double re, im; int res; - res = SWIG_AsVal(double)(array->Get(0), &re); - if(!SWIG_IsOK(res)) { + res = SWIG_AsVal(double)(SWIGV8_ARRAY_GET(array, 0), &re); + if (!SWIG_IsOK(res)) { return SWIG_TypeError; } - res = SWIG_AsVal(double)(array->Get(1), &im); - if(!SWIG_IsOK(res)) { + res = SWIG_AsVal(double)(SWIGV8_ARRAY_GET(array, 1), &im); + if (!SWIG_IsOK(res)) { return SWIG_TypeError; } @@ -102,7 +102,7 @@ SWIG_AsVal_dec(Type) (v8::Handle o, Type* val) } else { return SWIG_OverflowError; } - } else if(o->IsNumber()){ + } else if (o->IsNumber()) { float re; int res = SWIG_AddCast(SWIG_AsVal(float)(o, &re)); if (SWIG_IsOK(res)) { diff --git a/Lib/javascript/v8/javascripthelpers.swg b/Lib/javascript/v8/javascripthelpers.swg index 80fbd7aa1..ea303fa3d 100644 --- a/Lib/javascript/v8/javascripthelpers.swg +++ b/Lib/javascript/v8/javascripthelpers.swg @@ -1,39 +1,26 @@ %insert(runtime) %{ -// Note: since 3.19 there are new CallBack types, since 03.21.9 the old ones have been removed -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) -typedef v8::InvocationCallback SwigV8FunctionCallback; -typedef v8::AccessorGetter SwigV8AccessorGetterCallback; -typedef v8::AccessorSetter SwigV8AccessorSetterCallback; -typedef v8::AccessorInfo SwigV8PropertyCallbackInfoVoid; -#elif (V8_MAJOR_VERSION-0) < 5 -typedef v8::FunctionCallback SwigV8FunctionCallback; -typedef v8::AccessorGetterCallback SwigV8AccessorGetterCallback; -typedef v8::AccessorSetterCallback SwigV8AccessorSetterCallback; -typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfoVoid; -#else typedef v8::FunctionCallback SwigV8FunctionCallback; typedef v8::AccessorNameGetterCallback SwigV8AccessorGetterCallback; typedef v8::AccessorNameSetterCallback SwigV8AccessorSetterCallback; typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfoVoid; -#endif /** * Creates a class template for a class with specified initialization function. */ -SWIGRUNTIME v8::Handle SWIGV8_CreateClassTemplate(const char* symbol) { +SWIGRUNTIME SWIGV8_FUNCTION_TEMPLATE SWIGV8_CreateClassTemplate(const char* symbol) { SWIGV8_HANDLESCOPE_ESC(); v8::Local class_templ = SWIGV8_FUNCTEMPLATE_NEW_VOID(); class_templ->SetClassName(SWIGV8_SYMBOL_NEW(symbol)); - v8::Handle inst_templ = class_templ->InstanceTemplate(); + SWIGV8_OBJECT_TEMPLATE inst_templ = class_templ->InstanceTemplate(); inst_templ->SetInternalFieldCount(1); - v8::Handle equals_templ = class_templ->PrototypeTemplate(); + SWIGV8_OBJECT_TEMPLATE equals_templ = class_templ->PrototypeTemplate(); equals_templ->Set(SWIGV8_SYMBOL_NEW("equals"), SWIGV8_FUNCTEMPLATE_NEW(_SWIGV8_wrap_equals)); - v8::Handle cptr_templ = class_templ->PrototypeTemplate(); + SWIGV8_OBJECT_TEMPLATE cptr_templ = class_templ->PrototypeTemplate(); cptr_templ->Set(SWIGV8_SYMBOL_NEW("getCPtr"), SWIGV8_FUNCTEMPLATE_NEW(_wrap_getCPtr)); SWIGV8_ESCAPE(class_templ); @@ -42,55 +29,44 @@ SWIGRUNTIME v8::Handle SWIGV8_CreateClassTemplate(const ch /** * Registers a class method with given name for a given class template. */ -SWIGRUNTIME void SWIGV8_AddMemberFunction(v8::Handle class_templ, const char* symbol, +SWIGRUNTIME void SWIGV8_AddMemberFunction(SWIGV8_FUNCTION_TEMPLATE class_templ, const char* symbol, SwigV8FunctionCallback _func) { - v8::Handle proto_templ = class_templ->PrototypeTemplate(); + SWIGV8_OBJECT_TEMPLATE proto_templ = class_templ->PrototypeTemplate(); proto_templ->Set(SWIGV8_SYMBOL_NEW(symbol), SWIGV8_FUNCTEMPLATE_NEW(_func)); } /** * Registers a class property with given name for a given class template. */ -SWIGRUNTIME void SWIGV8_AddMemberVariable(v8::Handle class_templ, const char* symbol, +SWIGRUNTIME void SWIGV8_AddMemberVariable(SWIGV8_FUNCTION_TEMPLATE class_templ, const char* symbol, SwigV8AccessorGetterCallback getter, SwigV8AccessorSetterCallback setter) { - v8::Handle proto_templ = class_templ->InstanceTemplate(); + SWIGV8_OBJECT_TEMPLATE proto_templ = class_templ->InstanceTemplate(); proto_templ->SetAccessor(SWIGV8_SYMBOL_NEW(symbol), getter, setter); } /** * Registers a class method with given name for a given object. */ -SWIGRUNTIME void SWIGV8_AddStaticFunction(v8::Handle obj, const char* symbol, - const SwigV8FunctionCallback& _func) { - obj->Set(SWIGV8_SYMBOL_NEW(symbol), SWIGV8_FUNCTEMPLATE_NEW(_func)->GetFunction()); +SWIGRUNTIME void SWIGV8_AddStaticFunction(SWIGV8_OBJECT obj, const char* symbol, + const SwigV8FunctionCallback& _func, v8::Local context) { + SWIGV8_MAYBE_CHECK(obj->Set(context, SWIGV8_SYMBOL_NEW(symbol), SWIGV8_FUNCTEMPLATE_NEW(_func)->GetFunction(context).ToLocalChecked())); } /** * Registers a class method with given name for a given object. */ -SWIGRUNTIME void SWIGV8_AddStaticVariable(v8::Handle obj, const char* symbol, - SwigV8AccessorGetterCallback getter, SwigV8AccessorSetterCallback setter) { -#if (V8_MAJOR_VERSION-0) < 5 - obj->SetAccessor(SWIGV8_SYMBOL_NEW(symbol), getter, setter); -#else - obj->SetAccessor(SWIGV8_CURRENT_CONTEXT(), SWIGV8_SYMBOL_NEW(symbol), getter, setter); -#endif +SWIGRUNTIME void SWIGV8_AddStaticVariable(SWIGV8_OBJECT obj, const char* symbol, + SwigV8AccessorGetterCallback getter, SwigV8AccessorSetterCallback setter, + v8::Local context) { + SWIGV8_MAYBE_CHECK(obj->SetAccessor(context, SWIGV8_SYMBOL_NEW(symbol), getter, setter)); } -#if (V8_MAJOR_VERSION-0) < 5 -SWIGRUNTIME void JS_veto_set_variable(v8::Local property, v8::Local value, const SwigV8PropertyCallbackInfoVoid& info) -#else SWIGRUNTIME void JS_veto_set_variable(v8::Local property, v8::Local value, const SwigV8PropertyCallbackInfoVoid& info) -#endif { char buffer[256]; char msg[512]; int res; -#if (V8_MAJOR_VERSION-0) < 5 - property->WriteUtf8(buffer, 256); - res = sprintf(msg, "Tried to write read-only variable: %s.", buffer); -#else v8::Local sproperty; if (property->ToString(SWIGV8_CURRENT_CONTEXT()).ToLocal(&sproperty)) { SWIGV8_WRITE_UTF8(sproperty, buffer, 256); @@ -99,7 +75,6 @@ SWIGRUNTIME void JS_veto_set_variable(v8::Local property, v8::Local global_obj = SWIGV8_CURRENT_CONTEXT()->Global(); +SWIG_V8_SetModule(v8::Local context, swig_module_info *swig_module) { + v8::Local global_obj = context->Global(); v8::Local mod = SWIGV8_EXTERNAL_NEW(swig_module); assert(!mod.IsEmpty()); -#if (V8_MAJOR_VERSION-0) < 5 - global_obj->SetHiddenValue(SWIGV8_STRING_NEW("swig_module_info_data"), mod); -#else v8::Local privateKey = v8::Private::ForApi(v8::Isolate::GetCurrent(), SWIGV8_STRING_NEW("swig_module_info_data")); - global_obj->SetPrivate(SWIGV8_CURRENT_CONTEXT(), privateKey, mod); -#endif + global_obj->SetPrivate(context, privateKey, mod); } SWIGRUNTIME swig_module_info * -SWIG_V8_GetModule(void *) { - v8::Local global_obj = SWIGV8_CURRENT_CONTEXT()->Global(); -#if (V8_MAJOR_VERSION-0) < 5 - v8::Local moduleinfo = global_obj->GetHiddenValue(SWIGV8_STRING_NEW("swig_module_info_data")); -#else +SWIG_V8_GetModule(v8::Local context) { + v8::Local global_obj = context->Global(); v8::Local privateKey = v8::Private::ForApi(v8::Isolate::GetCurrent(), SWIGV8_STRING_NEW("swig_module_info_data")); v8::Local moduleinfo; - if (!global_obj->GetPrivate(SWIGV8_CURRENT_CONTEXT(), privateKey).ToLocal(&moduleinfo)) + if (!global_obj->GetPrivate(context, privateKey).ToLocal(&moduleinfo)) return 0; -#endif if (moduleinfo.IsEmpty() || moduleinfo->IsNull() || moduleinfo->IsUndefined()) { @@ -52,6 +44,7 @@ SWIG_V8_GetModule(void *) { #define SWIG_GetModule(clientdata) SWIG_V8_GetModule(clientdata) #define SWIG_SetModule(clientdata, pointer) SWIG_V8_SetModule(clientdata, pointer) +#define SWIG_INIT_CLIENT_DATA_TYPE v8::Local %} @@ -64,20 +57,20 @@ SWIG_V8_GetModule(void *) { %} %insert(init) %{ +#if !defined(NODE_MODULE_VERSION) || (NODE_MODULE_VERSION < 12) // Note: 'extern "C"'' disables name mangling which makes it easier to load the symbol manually -// TODO: is it ok to do that? -extern "C" -#if (NODE_MODULE_VERSION < 0x000C) -void SWIGV8_INIT (v8::Handle exports) +extern "C" void SWIGV8_INIT (SWIGV8_OBJECT exports_obj) +#elif (NODE_MODULE_VERSION < 64) +void SWIGV8_INIT (SWIGV8_OBJECT exports_obj, SWIGV8_VALUE /*module*/, void*) #else -void SWIGV8_INIT (v8::Handle exports, v8::Handle /*module*/) +void SWIGV8_INIT (SWIGV8_OBJECT exports_obj, SWIGV8_VALUE /*module*/, v8::Local context, void*) #endif { - SWIG_InitializeModule(static_cast(&exports)); +#if !defined(NODE_MODULE_VERSION) || NODE_MODULE_VERSION < 64 + v8::Local context = SWIGV8_CURRENT_CONTEXT(); +#endif - SWIGV8_HANDLESCOPE(); - - v8::Handle exports_obj = exports; + SWIG_InitializeModule(context); %} @@ -124,6 +117,10 @@ void SWIGV8_INIT (v8::Handle exports, v8::Handle /*modul } #if defined(BUILDING_NODE_EXTENSION) +#if (NODE_MODULE_VERSION < 64) NODE_MODULE($jsname, $jsname_initialize) +#else +NODE_MODULE_CONTEXT_AWARE($jsname, $jsname_initialize) +#endif #endif %} diff --git a/Lib/javascript/v8/javascriptprimtypes.swg b/Lib/javascript/v8/javascriptprimtypes.swg index f76be983b..0af406b90 100644 --- a/Lib/javascript/v8/javascriptprimtypes.swg +++ b/Lib/javascript/v8/javascriptprimtypes.swg @@ -6,7 +6,7 @@ %fragment(SWIG_From_frag(bool),"header") { SWIGINTERNINLINE -v8::Handle +SWIGV8_VALUE SWIG_From_dec(bool)(bool value) { return SWIGV8_BOOLEAN_NEW(value); @@ -16,7 +16,7 @@ SWIG_From_dec(bool)(bool value) %fragment(SWIG_AsVal_frag(bool),"header", fragment=SWIG_AsVal_frag(long)) { SWIGINTERN -int SWIG_AsVal_dec(bool)(v8::Handle obj, bool *val) +int SWIG_AsVal_dec(bool)(SWIGV8_VALUE obj, bool *val) { if(!obj->IsBoolean()) { return SWIG_ERROR; @@ -31,7 +31,7 @@ int SWIG_AsVal_dec(bool)(v8::Handle obj, bool *val) %fragment(SWIG_From_frag(int),"header") { SWIGINTERNINLINE -v8::Handle SWIG_From_dec(int)(int value) +SWIGV8_VALUE SWIG_From_dec(int)(int value) { return SWIGV8_INT32_NEW(value); } @@ -39,7 +39,7 @@ v8::Handle SWIG_From_dec(int)(int value) %fragment(SWIG_AsVal_frag(int),"header") { SWIGINTERN -int SWIG_AsVal_dec(int)(v8::Handle valRef, int* val) +int SWIG_AsVal_dec(int)(SWIGV8_VALUE valRef, int* val) { if (!valRef->IsNumber()) { return SWIG_TypeError; @@ -54,7 +54,7 @@ int SWIG_AsVal_dec(int)(v8::Handle valRef, int* val) %fragment(SWIG_From_frag(long),"header") { SWIGINTERNINLINE -v8::Handle SWIG_From_dec(long)(long value) +SWIGV8_VALUE SWIG_From_dec(long)(long value) { return SWIGV8_NUMBER_NEW(value); } @@ -63,7 +63,7 @@ v8::Handle SWIG_From_dec(long)(long value) %fragment(SWIG_AsVal_frag(long),"header", fragment="SWIG_CanCastAsInteger") { SWIGINTERN -int SWIG_AsVal_dec(long)(v8::Handle obj, long* val) +int SWIG_AsVal_dec(long)(SWIGV8_VALUE obj, long* val) { if (!obj->IsNumber()) { return SWIG_TypeError; @@ -79,17 +79,16 @@ int SWIG_AsVal_dec(long)(v8::Handle obj, long* val) %fragment(SWIG_From_frag(unsigned long),"header", fragment=SWIG_From_frag(long)) { SWIGINTERNINLINE -v8::Handle SWIG_From_dec(unsigned long)(unsigned long value) +SWIGV8_VALUE SWIG_From_dec(unsigned long)(unsigned long value) { - return (value > LONG_MAX) ? - SWIGV8_INTEGER_NEW_UNS(value) : SWIGV8_INTEGER_NEW(%numeric_cast(value,long)); + return SWIGV8_INTEGER_NEW_UNS(value); } } %fragment(SWIG_AsVal_frag(unsigned long),"header", fragment="SWIG_CanCastAsInteger") { SWIGINTERN -int SWIG_AsVal_dec(unsigned long)(v8::Handle obj, unsigned long *val) +int SWIG_AsVal_dec(unsigned long)(SWIGV8_VALUE obj, unsigned long *val) { if(!obj->IsNumber()) { return SWIG_TypeError; @@ -115,7 +114,7 @@ int SWIG_AsVal_dec(unsigned long)(v8::Handle obj, unsigned long *val) fragment="SWIG_LongLongAvailable") { %#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERNINLINE -v8::Handle SWIG_From_dec(long long)(long long value) +SWIGV8_VALUE SWIG_From_dec(long long)(long long value) { return SWIGV8_NUMBER_NEW(value); } @@ -128,7 +127,7 @@ v8::Handle SWIG_From_dec(long long)(long long value) fragment="SWIG_LongLongAvailable") { %#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERN -int SWIG_AsVal_dec(long long)(v8::Handle obj, long long* val) +int SWIG_AsVal_dec(long long)(SWIGV8_VALUE obj, long long* val) { if (!obj->IsNumber()) { return SWIG_TypeError; @@ -148,10 +147,9 @@ int SWIG_AsVal_dec(long long)(v8::Handle obj, long long* val) fragment="SWIG_LongLongAvailable") { %#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERNINLINE -v8::Handle SWIG_From_dec(unsigned long long)(unsigned long long value) +SWIGV8_VALUE SWIG_From_dec(unsigned long long)(unsigned long long value) { - return (value > LONG_MAX) ? - SWIGV8_INTEGER_NEW_UNS(value) : SWIGV8_INTEGER_NEW(%numeric_cast(value,long)); + return SWIGV8_INTEGER_NEW_UNS(value); } %#endif } @@ -162,7 +160,7 @@ v8::Handle SWIG_From_dec(unsigned long long)(unsigned long long value fragment="SWIG_LongLongAvailable") { %#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERN -int SWIG_AsVal_dec(unsigned long long)(v8::Handle obj, unsigned long long *val) +int SWIG_AsVal_dec(unsigned long long)(SWIGV8_VALUE obj, unsigned long long *val) { if(!obj->IsNumber()) { return SWIG_TypeError; @@ -185,7 +183,7 @@ int SWIG_AsVal_dec(unsigned long long)(v8::Handle obj, unsigned long %fragment(SWIG_From_frag(double),"header") { SWIGINTERN -v8::Handle SWIG_From_dec(double) (double val) +SWIGV8_VALUE SWIG_From_dec(double) (double val) { return SWIGV8_NUMBER_NEW(val); } @@ -193,7 +191,7 @@ v8::Handle SWIG_From_dec(double) (double val) %fragment(SWIG_AsVal_frag(double),"header") { SWIGINTERN -int SWIG_AsVal_dec(double)(v8::Handle obj, double *val) +int SWIG_AsVal_dec(double)(SWIGV8_VALUE obj, double *val) { if(!obj->IsNumber()) { return SWIG_TypeError; @@ -203,4 +201,3 @@ int SWIG_AsVal_dec(double)(v8::Handle obj, double *val) return SWIG_OK; } } - diff --git a/Lib/javascript/v8/javascriptrun.swg b/Lib/javascript/v8/javascriptrun.swg index 2452f4040..518b19a8f 100644 --- a/Lib/javascript/v8/javascriptrun.swg +++ b/Lib/javascript/v8/javascriptrun.swg @@ -1,75 +1,44 @@ /* --------------------------------------------------------------------------- * These typedefs and defines are used to deal with v8 API changes * + * Useful table of versions: https://nodejs.org/en/download/releases/ * ---------------------------------------------------------------------------*/ -// First v8 version that uses "SetWeak" and not "MakeWeak" - -#define SWIGV8_SETWEAK_VERSION 0x032224 - -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031803) -#define SWIGV8_STRING_NEW2(cstr, len) v8::String::New(cstr, len) -#else +#if (SWIG_V8_VERSION < 0x0704) #define SWIGV8_STRING_NEW2(cstr, len) v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), cstr, v8::String::kNormalString, len) +#else +#define SWIGV8_STRING_NEW2(cstr, len) (v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), cstr, v8::NewStringType::kNormal, len)).ToLocalChecked() #endif -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) -typedef v8::Handle SwigV8ReturnValue; -typedef v8::Arguments SwigV8Arguments; -typedef v8::AccessorInfo SwigV8PropertyCallbackInfo; -#define SWIGV8_RETURN(val) return scope.Close(val) -#define SWIGV8_RETURN_INFO(val, info) return scope.Close(val) -#else typedef void SwigV8ReturnValue; typedef v8::FunctionCallbackInfo SwigV8Arguments; typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfo; #define SWIGV8_RETURN(val) args.GetReturnValue().Set(val); return #define SWIGV8_RETURN_INFO(val, info) info.GetReturnValue().Set(val); return -#endif -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032117) -#define SWIGV8_HANDLESCOPE() v8::HandleScope scope -#define SWIGV8_HANDLESCOPE_ESC() v8::HandleScope scope -#define SWIGV8_ESCAPE(val) return scope.Close(val) -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032224) -#define SWIGV8_HANDLESCOPE() v8::HandleScope scope(v8::Isolate::GetCurrent()); -#define SWIGV8_HANDLESCOPE_ESC() v8::HandleScope scope(v8::Isolate::GetCurrent()); -#define SWIGV8_ESCAPE(val) return scope.Close(val) -#else #define SWIGV8_HANDLESCOPE() v8::HandleScope scope(v8::Isolate::GetCurrent()); #define SWIGV8_HANDLESCOPE_ESC() v8::EscapableHandleScope scope(v8::Isolate::GetCurrent()); #define SWIGV8_ESCAPE(val) return scope.Escape(val) -#endif -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032224) -#define SWIGV8_ADJUST_MEMORY(size) v8::V8::AdjustAmountOfExternalAllocatedMemory(size) -#define SWIGV8_CURRENT_CONTEXT() v8::Context::GetCurrent() -#define SWIGV8_THROW_EXCEPTION(err) v8::ThrowException(err) -#define SWIGV8_STRING_NEW(str) v8::String::New(str) -#define SWIGV8_SYMBOL_NEW(sym) v8::String::NewSymbol(sym) -#else #define SWIGV8_ADJUST_MEMORY(size) v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(size) #define SWIGV8_CURRENT_CONTEXT() v8::Isolate::GetCurrent()->GetCurrentContext() #define SWIGV8_THROW_EXCEPTION(err) v8::Isolate::GetCurrent()->ThrowException(err) -#define SWIGV8_STRING_NEW(str) v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), str) -#define SWIGV8_SYMBOL_NEW(sym) v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), sym) + +#if (SWIG_V8_VERSION < 0x0704) +#define SWIGV8_STRING_NEW(str) v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), str, v8::String::kNormalString) +#define SWIGV8_SYMBOL_NEW(sym) v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), sym, v8::String::kNormalString) +#else +#define SWIGV8_STRING_NEW(str) (v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), str, v8::NewStringType::kNormal)).ToLocalChecked() +#define SWIGV8_SYMBOL_NEW(sym) (v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), sym, v8::NewStringType::kNormal)).ToLocalChecked() #endif -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032318) -#define SWIGV8_ARRAY_NEW() v8::Array::New() -#define SWIGV8_BOOLEAN_NEW(bool) v8::Boolean::New(bool) -#define SWIGV8_EXTERNAL_NEW(val) v8::External::New(val) -#define SWIGV8_FUNCTEMPLATE_NEW(func) v8::FunctionTemplate::New(func) -#define SWIGV8_FUNCTEMPLATE_NEW_VOID() v8::FunctionTemplate::New() -#define SWIGV8_INT32_NEW(num) v8::Int32::New(num) -#define SWIGV8_INTEGER_NEW(num) v8::Integer::New(num) -#define SWIGV8_INTEGER_NEW_UNS(num) v8::Integer::NewFromUnsigned(num) -#define SWIGV8_NUMBER_NEW(num) v8::Number::New(num) -#define SWIGV8_OBJECT_NEW() v8::Object::New() -#define SWIGV8_UNDEFINED() v8::Undefined() -#define SWIGV8_NULL() v8::Null() +#if (SWIG_V8_VERSION < 0x0704) +#define SWIGV8_MAYBE_CHECK(maybe) maybe.FromJust() #else -#define SWIGV8_ARRAY_NEW() v8::Array::New(v8::Isolate::GetCurrent()) +#define SWIGV8_MAYBE_CHECK(maybe) maybe.Check() +#endif + +#define SWIGV8_ARRAY_NEW(size) v8::Array::New(v8::Isolate::GetCurrent(), size) #define SWIGV8_BOOLEAN_NEW(bool) v8::Boolean::New(v8::Isolate::GetCurrent(), bool) #define SWIGV8_EXTERNAL_NEW(val) v8::External::New(v8::Isolate::GetCurrent(), val) #define SWIGV8_FUNCTEMPLATE_NEW(func) v8::FunctionTemplate::New(v8::Isolate::GetCurrent(), func) @@ -80,26 +49,18 @@ typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfo; #define SWIGV8_NUMBER_NEW(num) v8::Number::New(v8::Isolate::GetCurrent(), num) #define SWIGV8_OBJECT_NEW() v8::Object::New(v8::Isolate::GetCurrent()) #define SWIGV8_UNDEFINED() v8::Undefined(v8::Isolate::GetCurrent()) +#define SWIGV8_ARRAY v8::Local +#define SWIGV8_FUNCTION_TEMPLATE v8::Local +#define SWIGV8_OBJECT v8::Local +#define SWIGV8_OBJECT_TEMPLATE v8::Local +#define SWIGV8_VALUE v8::Local #define SWIGV8_NULL() v8::Null(v8::Isolate::GetCurrent()) -#endif +#define SWIGV8_ARRAY_GET(array, index) (array)->Get(SWIGV8_CURRENT_CONTEXT(), index).ToLocalChecked() +#define SWIGV8_ARRAY_SET(array, index, value) SWIGV8_MAYBE_CHECK((array)->Set(SWIGV8_CURRENT_CONTEXT(), index, value)) -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) -#define SWIGV8_SET_CLASS_TEMPL(class_templ, class) class_templ = v8::Persistent::New(class); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) -#define SWIGV8_SET_CLASS_TEMPL(class_templ, class) class_templ = v8::Persistent::New(v8::Isolate::GetCurrent(), class); -#else #define SWIGV8_SET_CLASS_TEMPL(class_templ, class) class_templ.Reset(v8::Isolate::GetCurrent(), class); -#endif -#ifdef NODE_VERSION -#if NODE_VERSION_AT_LEAST(10, 12, 0) -#define SWIG_NODE_AT_LEAST_1012 -#endif -#endif - -//Necessary to check Node.js version because V8 API changes are backported in Node.js -#if (defined(NODE_VERSION) && !defined(SWIG_NODE_AT_LEAST_1012)) || \ - (!defined(NODE_VERSION) && (V8_MAJOR_VERSION-0) < 7) +#if SWIG_V8_VERSION < 0x0608 #define SWIGV8_TO_OBJECT(handle) (handle)->ToObject() #define SWIGV8_TO_STRING(handle) (handle)->ToString() #define SWIGV8_NUMBER_VALUE(handle) (handle)->NumberValue() @@ -112,9 +73,13 @@ typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfo; #define SWIGV8_TO_STRING(handle) (handle)->ToString(SWIGV8_CURRENT_CONTEXT()).ToLocalChecked() #define SWIGV8_NUMBER_VALUE(handle) (handle)->NumberValue(SWIGV8_CURRENT_CONTEXT()).ToChecked() #define SWIGV8_INTEGER_VALUE(handle) (handle)->IntegerValue(SWIGV8_CURRENT_CONTEXT()).ToChecked() -#define SWIGV8_BOOLEAN_VALUE(handle) (handle)->BooleanValue(SWIGV8_CURRENT_CONTEXT()).ToChecked() #define SWIGV8_WRITE_UTF8(handle, buffer, len) (handle)->WriteUtf8(v8::Isolate::GetCurrent(), buffer, len) #define SWIGV8_UTF8_LENGTH(handle) (handle)->Utf8Length(v8::Isolate::GetCurrent()) +#if (SWIG_V8_VERSION < 0x0704) +#define SWIGV8_BOOLEAN_VALUE(handle) (handle)->BooleanValue(SWIGV8_CURRENT_CONTEXT()).ToChecked() +#else +#define SWIGV8_BOOLEAN_VALUE(handle) (handle)->BooleanValue(v8::Isolate::GetCurrent()) +#endif #endif /* --------------------------------------------------------------------------- @@ -163,7 +128,7 @@ public: SWIGV8_THROW_EXCEPTION(err); } } - v8::Handle err; + SWIGV8_VALUE err; }; /* --------------------------------------------------------------------------- @@ -182,23 +147,8 @@ public: }; ~SWIGV8_Proxy() { -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) - handle.ClearWeak(); - handle.Dispose(); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) - handle.ClearWeak(v8::Isolate::GetCurrent()); - handle.Dispose(v8::Isolate::GetCurrent()); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) - handle.ClearWeak(); - handle.Dispose(); -#else handle.ClearWeak(); handle.Reset(); -#endif - -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) - handle.Clear(); -#endif SWIGV8_ADJUST_MEMORY(-SWIGV8_AVG_OBJ_SIZE); } @@ -213,32 +163,17 @@ class SWIGV8_ClientData { public: v8::Persistent class_templ; -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) - void (*dtor) (v8::Persistent< v8::Value> object, void *parameter); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) - void (*dtor) (v8::Isolate *isolate, v8::Persistent< v8::Value> object, void *parameter); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) - void (*dtor) (v8::Isolate *isolate, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy); -#elif (V8_MAJOR_VERSION-0) < 5 - void (*dtor) (const v8::WeakCallbackData &data); -#else void (*dtor) (const v8::WeakCallbackInfo &data); -#endif }; SWIGRUNTIME v8::Persistent SWIGV8_SWIGTYPE_Proxy_class_templ; -SWIGRUNTIME int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void **ptr, swig_type_info *info, int flags) { +SWIGRUNTIME int SWIG_V8_ConvertInstancePtr(SWIGV8_OBJECT objRef, void **ptr, swig_type_info *info, int flags) { SWIGV8_HANDLESCOPE(); if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031511) - v8::Handle cdataRef = objRef->GetInternalField(0); - SWIGV8_Proxy *cdata = static_cast(v8::External::Unwrap(cdataRef)); -#else SWIGV8_Proxy *cdata = static_cast(objRef->GetAlignedPointerFromInternalField(0)); -#endif if(cdata == NULL) { return SWIG_ERROR; @@ -252,8 +187,13 @@ SWIGRUNTIME int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void * if(!type_valid) { return SWIG_TypeError; } + int newmemory = 0; + *ptr = SWIG_TypeCast(tc, cdata->swigCObject, &newmemory); + assert(!newmemory); /* newmemory handling not yet implemented */ + } else { + *ptr = cdata->swigCObject; } - *ptr = cdata->swigCObject; + if(flags & SWIG_POINTER_DISOWN) { cdata->swigCMemOwn = false; } @@ -261,39 +201,20 @@ SWIGRUNTIME int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void * } -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) -SWIGRUNTIME void SWIGV8_Proxy_DefaultDtor(v8::Persistent< v8::Value > object, void *parameter) { - SWIGV8_Proxy *proxy = static_cast(parameter); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) -SWIGRUNTIME void SWIGV8_Proxy_DefaultDtor(v8::Isolate *, v8::Persistent< v8::Value > object, void *parameter) { - SWIGV8_Proxy *proxy = static_cast(parameter); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) -SWIGRUNTIME void SWIGV8_Proxy_DefaultDtor(v8::Isolate *, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy) { -#elif (V8_MAJOR_VERSION-0) < 5 -SWIGRUNTIME void SWIGV8_Proxy_DefaultDtor(const v8::WeakCallbackData &data) { - SWIGV8_Proxy *proxy = data.GetParameter(); -#else SWIGRUNTIME void SWIGV8_Proxy_DefaultDtor(const v8::WeakCallbackInfo &data) { SWIGV8_Proxy *proxy = data.GetParameter(); -#endif - delete proxy; } -SWIGRUNTIME int SWIG_V8_GetInstancePtr(v8::Handle valRef, void **ptr) { +SWIGRUNTIME int SWIG_V8_GetInstancePtr(SWIGV8_VALUE valRef, void **ptr) { if(!valRef->IsObject()) { return SWIG_TypeError; } - v8::Handle objRef = SWIGV8_TO_OBJECT(valRef); + SWIGV8_OBJECT objRef = SWIGV8_OBJECT::Cast(valRef); if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031511) - v8::Handle cdataRef = objRef->GetInternalField(0); - SWIGV8_Proxy *cdata = static_cast(v8::External::Unwrap(cdataRef)); -#else SWIGV8_Proxy *cdata = static_cast(objRef->GetAlignedPointerFromInternalField(0)); -#endif if(cdata == NULL) { return SWIG_ERROR; @@ -304,70 +225,30 @@ SWIGRUNTIME int SWIG_V8_GetInstancePtr(v8::Handle valRef, void **ptr) return SWIG_OK; } -SWIGRUNTIME void SWIGV8_SetPrivateData(v8::Handle obj, void *ptr, swig_type_info *info, int flags) { +SWIGRUNTIME void SWIGV8_SetPrivateData(SWIGV8_OBJECT 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; cdata->info = info; -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031511) - obj->SetPointerInInternalField(0, cdata); -#else obj->SetAlignedPointerInInternalField(0, cdata); -#endif -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) - cdata->handle = v8::Persistent::New(obj); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) - cdata->handle = v8::Persistent::New(v8::Isolate::GetCurrent(), obj); -#else cdata->handle.Reset(v8::Isolate::GetCurrent(), obj); -#endif -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) - // clientdata must be set for owned data as we need to register the dtor - if(cdata->swigCMemOwn && (SWIGV8_ClientData*)info->clientdata) { - cdata->handle.MakeWeak(cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); - } else { - cdata->handle.MakeWeak(cdata, SWIGV8_Proxy_DefaultDtor); - } -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031918) - if(cdata->swigCMemOwn && (SWIGV8_ClientData*)info->clientdata) { - cdata->handle.MakeWeak(v8::Isolate::GetCurrent(), cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); - } else { - cdata->handle.MakeWeak(v8::Isolate::GetCurrent(), cdata, SWIGV8_Proxy_DefaultDtor); - } -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) - if(cdata->swigCMemOwn && (SWIGV8_ClientData*)info->clientdata) { - cdata->handle.MakeWeak(cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); - } else { - cdata->handle.MakeWeak(cdata, SWIGV8_Proxy_DefaultDtor); - } -#elif (V8_MAJOR_VERSION-0) < 5 - if(cdata->swigCMemOwn && (SWIGV8_ClientData*)info->clientdata) { - cdata->handle.SetWeak(cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); - } else { - cdata->handle.SetWeak(cdata, SWIGV8_Proxy_DefaultDtor); - } -#else if(cdata->swigCMemOwn && (SWIGV8_ClientData*)info->clientdata) { cdata->handle.SetWeak(cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor, v8::WeakCallbackType::kParameter); } else { cdata->handle.SetWeak(cdata, SWIGV8_Proxy_DefaultDtor, v8::WeakCallbackType::kParameter); } -#endif -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) - cdata->handle.MarkIndependent(); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) - cdata->handle.MarkIndependent(v8::Isolate::GetCurrent()); -#else +#if (SWIG_V8_VERSION < 0x0704) cdata->handle.MarkIndependent(); +// Looks like future versions do not require that anymore: +// https://monorail-prod.appspot.com/p/chromium/issues/detail?id=923361#c11 #endif - } -SWIGRUNTIME int SWIG_V8_ConvertPtr(v8::Handle valRef, void **ptr, swig_type_info *info, int flags) { +SWIGRUNTIME int SWIG_V8_ConvertPtr(SWIGV8_VALUE valRef, void **ptr, swig_type_info *info, int flags) { SWIGV8_HANDLESCOPE(); /* special case: JavaScript null => C NULL pointer */ @@ -378,31 +259,20 @@ SWIGRUNTIME int SWIG_V8_ConvertPtr(v8::Handle valRef, void **ptr, swi if(!valRef->IsObject()) { return SWIG_TypeError; } - v8::Handle objRef = SWIGV8_TO_OBJECT(valRef); + SWIGV8_OBJECT objRef = SWIGV8_OBJECT::Cast(valRef); return SWIG_V8_ConvertInstancePtr(objRef, ptr, info, flags); } -SWIGRUNTIME v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, int flags) { +SWIGRUNTIME SWIGV8_VALUE SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, int flags) { SWIGV8_HANDLESCOPE_ESC(); - v8::Handle class_templ; + SWIGV8_FUNCTION_TEMPLATE class_templ; if (ptr == NULL) { -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) - SWIGV8_ESCAPE(SWIGV8_NULL()); -#else v8::Local result = SWIGV8_NULL(); SWIGV8_ESCAPE(result); -#endif } -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) - if(info->clientdata != 0) { - class_templ = ((SWIGV8_ClientData*) info->clientdata)->class_templ; - } else { - class_templ = SWIGV8_SWIGTYPE_Proxy_class_templ; - } -#else v8::Isolate *isolate = v8::Isolate::GetCurrent(); if(info->clientdata != 0) { @@ -410,10 +280,9 @@ SWIGRUNTIME v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_inf } else { class_templ = v8::Local::New(isolate, SWIGV8_SWIGTYPE_Proxy_class_templ); } -#endif -// v8::Handle result = class_templ->InstanceTemplate()->NewInstance(); - v8::Local result = class_templ->InstanceTemplate()->NewInstance(); + v8::Local result = class_templ->InstanceTemplate()->NewInstance(SWIGV8_CURRENT_CONTEXT()).ToLocalChecked(); + SWIGV8_SetPrivateData(result, ptr, info, flags); SWIGV8_ESCAPE(result); @@ -433,7 +302,7 @@ SWIGRUNTIME v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_inf SWIGRUNTIME SwigV8ReturnValue _SWIGV8_wrap_equals(const SwigV8Arguments &args) { SWIGV8_HANDLESCOPE(); - v8::Handle jsresult; + SWIGV8_VALUE jsresult; void *arg1 = (void *) 0 ; void *arg2 = (void *) 0 ; bool result; @@ -463,7 +332,7 @@ fail: SWIGRUNTIME SwigV8ReturnValue _wrap_getCPtr(const SwigV8Arguments &args) { SWIGV8_HANDLESCOPE(); - v8::Handle jsresult; + SWIGV8_VALUE jsresult; void *arg1 = (void *) 0 ; long result; int res1; @@ -502,37 +371,28 @@ public: }; SWIGRUNTIMEINLINE -int SwigV8Packed_Check(v8::Handle valRef) { +int SwigV8Packed_Check(SWIGV8_VALUE valRef) { SWIGV8_HANDLESCOPE(); - v8::Handle objRef = SWIGV8_TO_OBJECT(valRef); + SWIGV8_OBJECT objRef = SWIGV8_TO_OBJECT(valRef); if(objRef->InternalFieldCount() < 1) return false; -#if (V8_MAJOR_VERSION-0) < 5 - v8::Handle flag = objRef->GetHiddenValue(SWIGV8_STRING_NEW("__swig__packed_data__")); -#else v8::Local privateKey = v8::Private::ForApi(v8::Isolate::GetCurrent(), SWIGV8_STRING_NEW("__swig__packed_data__")); v8::Local flag; if (!objRef->GetPrivate(SWIGV8_CURRENT_CONTEXT(), privateKey).ToLocal(&flag)) return false; -#endif return (flag->IsBoolean() && SWIGV8_BOOLEAN_VALUE(flag)); } SWIGRUNTIME -swig_type_info *SwigV8Packed_UnpackData(v8::Handle valRef, void *ptr, size_t size) { +swig_type_info *SwigV8Packed_UnpackData(SWIGV8_VALUE valRef, void *ptr, size_t size) { if (SwigV8Packed_Check(valRef)) { SWIGV8_HANDLESCOPE(); SwigV8PackedData *sobj; - v8::Handle objRef = SWIGV8_TO_OBJECT(valRef); + SWIGV8_OBJECT objRef = SWIGV8_TO_OBJECT(valRef); -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031511) - v8::Handle cdataRef = objRef->GetInternalField(0); - sobj = static_cast(v8::External::Unwrap(cdataRef)); -#else sobj = static_cast(objRef->GetAlignedPointerFromInternalField(0)); -#endif if (sobj == NULL || sobj->size != size) return 0; memcpy(ptr, sobj->data, size); return sobj->type; @@ -542,7 +402,7 @@ swig_type_info *SwigV8Packed_UnpackData(v8::Handle valRef, void *ptr, } SWIGRUNTIME -int SWIGV8_ConvertPacked(v8::Handle valRef, void *ptr, size_t sz, swig_type_info *ty) { +int SWIGV8_ConvertPacked(SWIGV8_VALUE valRef, void *ptr, size_t sz, swig_type_info *ty) { swig_type_info *to = SwigV8Packed_UnpackData(valRef, ptr, sz); if (!to) return SWIG_ERROR; if (ty) { @@ -555,92 +415,36 @@ int SWIGV8_ConvertPacked(v8::Handle valRef, void *ptr, size_t sz, swi return SWIG_OK; } -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) -SWIGRUNTIME void _wrap_SwigV8PackedData_delete(v8::Persistent< v8::Value > object, void *parameter) { - SwigV8PackedData *cdata = static_cast(parameter); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) -SWIGRUNTIME void _wrap_SwigV8PackedData_delete(v8::Isolate *isolate, v8::Persistent object, void *parameter) { - SwigV8PackedData *cdata = static_cast(parameter); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) -SWIGRUNTIME void _wrap_SwigV8PackedData_delete(v8::Isolate *isolate, v8::Persistent *object, SwigV8PackedData *cdata) { -#elif (V8_MAJOR_VERSION-0) < 5 -SWIGRUNTIME void _wrap_SwigV8PackedData_delete(const v8::WeakCallbackData &data) { - v8::Local object = data.GetValue(); - SwigV8PackedData *cdata = data.GetParameter(); -#else SWIGRUNTIME void _wrap_SwigV8PackedData_delete(const v8::WeakCallbackInfo &data) { SwigV8PackedData *cdata = data.GetParameter(); -#endif - delete cdata; - -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) - object.Clear(); - object.Dispose(); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) - object.Clear(); - object.Dispose(isolate); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) - object->Dispose(isolate); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) - object->Dispose(); -#elif (V8_MAJOR_VERSION-0) < 5 - object.Clear(); -#endif } SWIGRUNTIME -v8::Handle SWIGV8_NewPackedObj(void *data, size_t size, swig_type_info *type) { +SWIGV8_VALUE SWIGV8_NewPackedObj(void *data, size_t size, swig_type_info *type) { SWIGV8_HANDLESCOPE_ESC(); SwigV8PackedData *cdata = new SwigV8PackedData(data, size, type); // v8::Handle obj = SWIGV8_OBJECT_NEW(); v8::Local obj = SWIGV8_OBJECT_NEW(); -#if (V8_MAJOR_VERSION-0) < 5 - obj->SetHiddenValue(SWIGV8_STRING_NEW("__swig__packed_data__"), SWIGV8_BOOLEAN_NEW(true)); -#else v8::Local privateKey = v8::Private::ForApi(v8::Isolate::GetCurrent(), SWIGV8_STRING_NEW("__swig__packed_data__")); obj->SetPrivate(SWIGV8_CURRENT_CONTEXT(), privateKey, SWIGV8_BOOLEAN_NEW(true)); -#endif -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031511) - obj->SetPointerInInternalField(0, cdata); -#else obj->SetAlignedPointerInInternalField(0, cdata); -#endif -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) - cdata->handle = v8::Persistent::New(obj); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) - cdata->handle = v8::Persistent::New(v8::Isolate::GetCurrent(), obj); -#else cdata->handle.Reset(v8::Isolate::GetCurrent(), obj); -#endif - -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) - cdata->handle.MakeWeak(cdata, _wrap_SwigV8PackedData_delete); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031918) - cdata->handle.MakeWeak(v8::Isolate::GetCurrent(), cdata, _wrap_SwigV8PackedData_delete); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) - cdata->handle.MakeWeak(cdata, _wrap_SwigV8PackedData_delete); -#elif (V8_MAJOR_VERSION-0) < 5 - cdata->handle.SetWeak(cdata, _wrap_SwigV8PackedData_delete); -// v8::V8::SetWeak(&cdata->handle, cdata, _wrap_SwigV8PackedData_delete); -#else cdata->handle.SetWeak(cdata, _wrap_SwigV8PackedData_delete, v8::WeakCallbackType::kParameter); -#endif -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) - cdata->handle.MarkIndependent(); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) - cdata->handle.MarkIndependent(v8::Isolate::GetCurrent()); -#else +#if (SWIG_V8_VERSION < 0x0704) cdata->handle.MarkIndependent(); +// Looks like future versions do not require that anymore: +// https://monorail-prod.appspot.com/p/chromium/issues/detail?id=923361#c11 #endif SWIGV8_ESCAPE(obj); + } #define SWIG_ConvertMember(obj, ptr, sz, ty) SWIGV8_ConvertPacked(obj, ptr, sz, ty) @@ -654,22 +458,18 @@ v8::Handle SWIGV8_NewPackedObj(void *data, size_t size, swig_type_inf SWIGRUNTIME -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) -v8::Handle SWIGV8_AppendOutput(v8::Handle result, v8::Handle obj) { -#else -v8::Handle SWIGV8_AppendOutput(v8::Local result, v8::Handle obj) { -#endif +SWIGV8_VALUE SWIGV8_AppendOutput(SWIGV8_VALUE result, SWIGV8_VALUE obj) { SWIGV8_HANDLESCOPE_ESC(); if (result->IsUndefined()) { - result = SWIGV8_ARRAY_NEW(); + result = SWIGV8_ARRAY_NEW(0); + } else if (!result->IsArray()) { + SWIGV8_ARRAY tmparr = SWIGV8_ARRAY_NEW(0); + SWIGV8_ARRAY_SET(tmparr, 0, result); + result = tmparr; } -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) - v8::Handle arr = v8::Handle::Cast(result); -#else - v8::Local arr = v8::Local::Cast(result); -#endif - arr->Set(arr->Length(), obj); + SWIGV8_ARRAY arr = SWIGV8_ARRAY::Cast(result); + SWIGV8_ARRAY_SET(arr, arr->Length(), obj); SWIGV8_ESCAPE(arr); } diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index c78e04efb..4e93fc4c1 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -7,36 +7,8 @@ // ---------------- // // v8 added version macros V8_MAJOR_VERSION, V8_MINOR_VERSION, V8_BUILD_NUMBER -// and V8_PATCH_LEVEL in version 4.3.0. SWIG generated code uses these if -// they are defined - to support earlier versions you can specify the V8 version -// in use via the command line when you run SWIG: -// -// swig -c++ -javascript -v8 -DV8_VERSION=0x032530 example.i -// -// Or code in the interface file using SWIG_V8_VERSION: -// -// %begin %{#define SWIG_V8_VERSION 0x031110%} -// -// This is specified as a hex constant, but the constant is read as pairs of -// decimal digits, so for V8 3.25.30 use constant 0x032530. This scheme can't -// represent components > 99, but this constant is only useful for V8 < 4.3.0, -// and no V8 versions from that era had a component > 99. - -%define %swig_v8_define_version(version) -%insert("runtime") %{ -#ifndef SWIG_V8_VERSION -#define SWIG_V8_VERSION version -#endif -%} -%enddef - -#ifdef V8_VERSION -%swig_v8_define_version(V8_VERSION) -#else -// HACK: defining a default version -%swig_v8_define_version(0x031110) -#endif - +// and V8_PATCH_LEVEL in version 4.3.0. SWIG doesn't support anything that +// old so SWIG generated code can rely on these. // Node support // ------------ @@ -56,9 +28,16 @@ %insert(runtime) %{ #include +#undef SWIG_V8_VERSION +#define SWIG_V8_VERSION ((V8_MAJOR_VERSION / 10) * 4096 + \ + (V8_MAJOR_VERSION % 10) * 256 + \ + (V8_MINOR_VERSION / 10) * 16 + \ + (V8_MINOR_VERSION % 10)) + #include #include #include +#include %} %insert(runtime) "swigrun.swg"; /* SWIG API */ diff --git a/Lib/javascript/v8/javascriptstrings.swg b/Lib/javascript/v8/javascriptstrings.swg index e767a6d66..8dc2d945e 100644 --- a/Lib/javascript/v8/javascriptstrings.swg +++ b/Lib/javascript/v8/javascriptstrings.swg @@ -4,13 +4,13 @@ * ------------------------------------------------------------ */ %fragment("SWIG_AsCharPtrAndSize", "header", fragment="SWIG_pchar_descriptor") { SWIGINTERN int -SWIG_AsCharPtrAndSize(v8::Handle valRef, char** cptr, size_t* psize, int *alloc) +SWIG_AsCharPtrAndSize(SWIGV8_VALUE valRef, char** cptr, size_t* psize, int *alloc) { if(valRef->IsString()) { - v8::Handle js_str = SWIGV8_TO_STRING(valRef); + v8::Local js_str = v8::Local::Cast(valRef); size_t len = SWIGV8_UTF8_LENGTH(js_str) + 1; - char* cstr = new char[len]; + char* cstr = (char*) %new_array(len, char); SWIGV8_WRITE_UTF8(js_str, cstr, len); if(alloc) *alloc = SWIG_NEWOBJ; @@ -20,7 +20,7 @@ SWIG_AsCharPtrAndSize(v8::Handle valRef, char** cptr, size_t* psize, return SWIG_OK; } else { if(valRef->IsObject()) { - v8::Handle obj = SWIGV8_TO_OBJECT(valRef); + SWIGV8_OBJECT obj = SWIGV8_OBJECT::Cast(valRef); // try if the object is a wrapped char[] swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); if (pchar_descriptor) { @@ -41,7 +41,7 @@ SWIG_AsCharPtrAndSize(v8::Handle valRef, char** cptr, size_t* psize, } %fragment("SWIG_FromCharPtrAndSize","header",fragment="SWIG_pchar_descriptor") { -SWIGINTERNINLINE v8::Handle +SWIGINTERNINLINE SWIGV8_VALUE SWIG_FromCharPtrAndSize(const char* carray, size_t size) { if (carray) { @@ -49,7 +49,7 @@ SWIG_FromCharPtrAndSize(const char* carray, size_t size) // TODO: handle extra long strings return SWIGV8_UNDEFINED(); } else { - v8::Handle js_str = SWIGV8_STRING_NEW2(carray, size); + v8::Local js_str = SWIGV8_STRING_NEW2(carray, size); return js_str; } } else { diff --git a/Lib/javascript/v8/javascripttypemaps.swg b/Lib/javascript/v8/javascripttypemaps.swg index 4601698e0..cb31100c5 100644 --- a/Lib/javascript/v8/javascripttypemaps.swg +++ b/Lib/javascript/v8/javascripttypemaps.swg @@ -25,7 +25,7 @@ /* Javascript types */ -#define SWIG_Object v8::Handle +#define SWIG_Object SWIGV8_VALUE #define VOID_Object SWIGV8_UNDEFINED() /* Overload of the output/constant/exception/dirout handling */ diff --git a/Lib/javascript/v8/typemaps.i b/Lib/javascript/v8/typemaps.i index d3d8afb19..e88f0019e 100644 --- a/Lib/javascript/v8/typemaps.i +++ b/Lib/javascript/v8/typemaps.i @@ -18,7 +18,7 @@ you would use a real value instead. int *INPUT short *INPUT long *INPUT - long long *INPUT + long long *INPUT unsigned int *INPUT unsigned short *INPUT unsigned long *INPUT @@ -72,7 +72,7 @@ multiple output values, they are returned in the form of a Python tuple. For example, suppose you were trying to wrap the modf() function in the C math library which splits x into integral and fractional parts (and -returns the integer part in one of its parameters).K: +returns the integer part in one of its parameters) : double modf(double x, double *ip); diff --git a/Lib/lua/lua.swg b/Lib/lua/lua.swg index 6db3add6e..5144f601d 100644 --- a/Lib/lua/lua.swg +++ b/Lib/lua/lua.swg @@ -151,7 +151,7 @@ The python/lua ones are great, but C++ ones I don't like (mainly because I cannot get the stack trace out of it) Therefore I have not bothered to try doing much in this -Therefore currently its just enough to get a few test cases running ok +Therefore currently it's just enough to get a few test cases running ok note: if you wish to throw anything related to std::exception use %include instead @@ -191,7 +191,7 @@ use %include instead Throwing object is a serious problem: Assuming some code throws a 'FooBar' There are a few options: -- return a pointer to it: but its unclear how long this will last for. +- return a pointer to it: but it's unclear how long this will last for. - return a copy of it: but not all objects are copyable (see exception_partial_info in the test suite for a case where you cannot do this) - convert to a string & throw that @@ -224,7 +224,7 @@ SWIG_fail;%} // note: no support for object pointers -// its not clear how long the pointer is valid for, therefore not supporting it +// it's not clear how long the pointer is valid for, therefore not supporting it /* ----------------------------------------------------------------------------- * extras diff --git a/Lib/lua/lua_fnptr.i b/Lib/lua/lua_fnptr.i index 481cfafa6..81fa54bd2 100644 --- a/Lib/lua/lua_fnptr.i +++ b/Lib/lua/lua_fnptr.i @@ -17,7 +17,7 @@ note: it should be passed by value, not byref or as a pointer. The SWIGLUA_FN holds a pointer to the lua_State, and the stack index where the function is held. The macro SWIGLUA_FN_GET() will put a copy of the lua function at the top of the stack. -After that its fairly simple to write the rest of the code (assuming know how to use lua), +After that it's fairly simple to write the rest of the code (assuming know how to use lua), just push the parameters, call the function and return the result. int my_func(int a, int b, SWIGLUA_FN fn) diff --git a/Lib/lua/luakw.swg b/Lib/lua/luakw.swg index fc2f92bfe..394e40053 100644 --- a/Lib/lua/luakw.swg +++ b/Lib/lua/luakw.swg @@ -2,7 +2,7 @@ Warnings for Lua keywords, built-in names and bad names. */ -#define LUAKW(x) %keywordwarn("'" `x` "' is a Lua keyword, renaming to 'c_" `x` "'", rename="c_%s") `x` +#define LUAKW(x) %keywordwarn("'" `x` "' is a Lua keyword", rename="c_%s") `x` #define LUABN(x) %namewarn(%warningmsg(SWIGWARN_PARSE_BUILTIN_NAME, "'" `x` "' conflicts with a basic function in Lua"), %$not %$ismember) `x` /* diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index b8ddf000a..572da4703 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -307,7 +307,7 @@ typedef struct { /* Contract support */ #define SWIG_contract_assert(expr, msg) \ - if (!(expr)) { SWIG_Lua_pusherrstring(L, (char *) msg); goto fail; } else + do { if (!(expr)) { SWIG_Lua_pusherrstring(L, (char *) msg); goto fail; } } while (0) /* helper #defines */ @@ -826,7 +826,7 @@ SWIGINTERN int SWIG_Lua_class_do_get_item(lua_State *L, swig_type_info *type, i /* NEW: looks for the __getitem() fn this is a user provided get fn */ SWIG_Lua_get_table(L,"__getitem"); /* find the __getitem fn */ - if (lua_iscfunction(L,-1)) /* if its there */ + if (lua_iscfunction(L,-1)) /* if it's there */ { /* found it so call the fn & return its value */ lua_pushvalue(L,substack_start+1); /* the userdata */ lua_pushvalue(L,substack_start+2); /* the parameter */ @@ -883,7 +883,7 @@ SWIGINTERN int SWIG_Lua_class_do_get(lua_State *L, swig_type_info *type, int SW lua_pushvalue(L,substack_start+2); /* key */ lua_rawget(L,-2); /* look for the fn */ lua_remove(L,-2); /* stack tidy, remove .fn table */ - if (lua_isfunction(L,-1)) /* note: if its a C function or lua function */ + if (lua_isfunction(L,-1)) /* note: if it's a C function or lua function */ { /* found it so return the fn & let lua call it */ lua_remove(L,-2); /* stack tidy, remove metatable */ if(ret) @@ -966,7 +966,7 @@ SWIGINTERN int SWIG_Lua_class_do_set(lua_State *L, swig_type_info *type, int fi /* NEW: looks for the __setitem() fn this is a user provided set fn */ SWIG_Lua_get_table(L,"__setitem"); /* find the fn */ - if (lua_iscfunction(L,-1)) /* if its there */ + if (lua_iscfunction(L,-1)) /* if it's there */ { /* found it so call the fn & return its value */ lua_pushvalue(L,substack_start+1); /* the userdata */ lua_pushvalue(L,substack_start+2); /* the parameter */ @@ -1343,15 +1343,15 @@ SWIGINTERN void SWIG_Lua_add_class_instance_details(lua_State *L, swig_lua_clas SWIGRUNTIME int SWIG_Lua_resolve_metamethod(lua_State *L); /*forward declaration*/ /* The real function that resolves a metamethod. - * Function searches given class and all it's bases(recursively) for first instance of something that is - * not equal to SWIG_Lua_resolve_metatmethod. (Almost always this 'something' is actual metamethod implementation + * Function searches given class and all its bases (recursively) for first instance of something that is + * not equal to SWIG_Lua_resolve_metamethod. (Almost always this 'something' is actual metamethod implementation * and it is a SWIG-generated C function.). It returns value on the top of the L and there is no garbage below the * answer. * Returns 1 if found, 0 otherwise. * clss is class which metatable we will search for method * metamethod_name_idx is index in L where metamethod name (as string) lies - * skip_check allows to skip searching metamethod in givel clss and immideatelly go to searching in bases. skip_check - * is not caried to subsequent recursive calls - false is always passed. It is set to true only at first call from + * skip_check allows skipping searching metamethod in the given class and immediately going to searching in bases. skip_check + * is not carried to subsequent recursive calls - false is always passed. It is set to true only at first call from * SWIG_Lua_resolve_metamethod * */ SWIGINTERN int SWIG_Lua_do_resolve_metamethod(lua_State *L, const swig_lua_class *clss, int metamethod_name_idx, @@ -1497,7 +1497,7 @@ SWIGINTERN void SWIG_Lua_add_class_user_metamethods(lua_State *L, swig_lua_class } } - lua_pop(L,1); /* remove inheritable metatmethods table */ + lua_pop(L,1); /* remove inheritable metamethods table */ /* Special handling for __tostring method */ lua_pushstring(L, "__tostring"); @@ -1796,7 +1796,7 @@ SWIGRUNTIME int SWIG_Lua_ConvertPtr(lua_State *L,int index,void **ptr,swig_type SWIGRUNTIME void* SWIG_Lua_MustGetPtr(lua_State *L,int index,swig_type_info *type,int flags, int argnum,const char *func_name){ - void *result; + void *result = 0; if (!SWIG_IsOK(SWIG_ConvertPtr(L,index,&result,type,flags))){ luaL_error (L,"Error in %s, expected a %s at argument number %d\n", func_name,(type && type->str)?type->str:"void*",argnum); diff --git a/Lib/lua/luatypemaps.swg b/Lib/lua/luatypemaps.swg index 8959f201e..f8e12846b 100644 --- a/Lib/lua/luatypemaps.swg +++ b/Lib/lua/luatypemaps.swg @@ -24,7 +24,7 @@ // additional check for unsigned numbers, to not permit negative input %typemap(in,checkfn="lua_isnumber") unsigned int, unsigned short, unsigned long, unsigned char -%{SWIG_contract_assert((lua_tonumber(L,$input)>=0),"number must not be negative") +%{SWIG_contract_assert((lua_tonumber(L,$input)>=0),"number must not be negative"); $1 = ($type)lua_tonumber(L, $input);%} %typemap(out) int,short,long, @@ -39,12 +39,12 @@ $1 = ($type)lua_tonumber(L, $input);%} // SWIG assumes that this code will need a pointer to int to be passed in // (this might be ok for objects by const ref, but not for numeric primitives) // therefore we add a set of typemaps to fix this (for both in & out) -%typemap(in,checkfn="lua_isnumber") const int&($basetype temp) -%{ temp=($basetype)lua_tonumber(L,$input); $1=&temp;%} +%typemap(in,checkfn="lua_isnumber") const int&($*1_ltype temp) +%{ temp=($*1_ltype)lua_tonumber(L,$input); $1=&temp;%} -%typemap(in,checkfn="lua_isnumber") const unsigned int&($basetype temp) -%{SWIG_contract_assert((lua_tonumber(L,$input)>=0),"number must not be negative") -temp=($basetype)lua_tonumber(L,$input); $1=&temp;%} +%typemap(in,checkfn="lua_isnumber") const unsigned int&($*1_ltype temp) +%{SWIG_contract_assert((lua_tonumber(L,$input)>=0),"number must not be negative"); +temp=($*1_ltype)lua_tonumber(L,$input); $1=&temp;%} %typemap(out) const int&, const unsigned int& %{ lua_pushnumber(L, (lua_Number) *$1); SWIG_arg++;%} @@ -237,13 +237,13 @@ $1=($1_ltype)&temp;%} // therefore a special wrapping functions SWIG_ConvertMember() & SWIG_NewMemberObj() were written %typemap(in,checkfn="lua_isuserdata") SWIGTYPE (CLASS::*) %{ - if (!SWIG_IsOK(SWIG_ConvertMember(L,$input,(void*)(&$1),sizeof($type),$descriptor))) + if (!SWIG_IsOK(SWIG_ConvertMember(L,$input,(void*)(&$1),sizeof($1),$descriptor))) SWIG_fail_ptr("$symname",$argnum,$descriptor); %} %typemap(out) SWIGTYPE (CLASS::*) -%{ - SWIG_NewMemberObj(L,(void*)(&$1),sizeof($type),$descriptor); SWIG_arg++; +%{ + SWIG_NewMemberObj(L,(void*)(&$1),sizeof($1),$descriptor); SWIG_arg++; %} @@ -252,7 +252,7 @@ $1=($1_ltype)&temp;%} /* void* is a special case A function void fn(void*) should take any kind of pointer as a parameter (just like C/C++ does) -but if its an output, then it should be wrapped like any other SWIG object (using default typemap) +but if it's an output, then it should be wrapped like any other SWIG object (using default typemap) */ %typemap(in,checkfn="SWIG_isptrtype") void* %{$1=($1_ltype)SWIG_MustGetPtr(L,$input,0,0,$argnum,"$symname");%} @@ -285,7 +285,7 @@ parameters match which function // unfortunately lua only considers one type of number // so all numbers (int,float,double) match -// you could add an advanced fn to get type & check if its integral +// you could add an advanced fn to get type & check if it's integral %typecheck(SWIG_TYPECHECK_INTEGER) int, short, long, unsigned int, unsigned short, unsigned long, @@ -396,7 +396,7 @@ parameters match which function * Specials * ----------------------------------------------------------------------------- */ // swig::LANGUAGE_OBJ was added to allow containers of native objects -// however its rather difficult to do this in lua, as you cannot hold pointers +// however it's rather difficult to do this in lua, as you cannot hold pointers // to native objects (they are held in the interpreter) // therefore for now: just ignoring this feature #ifdef __cplusplus diff --git a/Lib/lua/typemaps.i b/Lib/lua/typemaps.i index 8392e5bfa..68f6f6cca 100644 --- a/Lib/lua/typemaps.i +++ b/Lib/lua/typemaps.i @@ -28,7 +28,7 @@ The basic code looks like this: However the code below is a mixture of #defines & such, so nowhere as easy to read -To make you code work correctly its not just a matter of %including this file +To make you code work correctly it's not just a matter of %including this file You also have to give SWIG the hints on which to use where eg @@ -77,7 +77,7 @@ SWIG_NUMBER_TYPEMAP(enum SWIGTYPE); // also for long longs's SWIG_NUMBER_TYPEMAP(long long); SWIG_NUMBER_TYPEMAP(unsigned long long); SWIG_NUMBER_TYPEMAP(signed long long); -// note we dont do char, as a char* is probably a string not a ptr to a single char +// note we don't do char, as a char* is probably a string not a ptr to a single char // similar for booleans %typemap(in,checkfn="lua_isboolean") bool *INPUT(bool temp), bool &INPUT(bool temp) @@ -188,16 +188,6 @@ int SWIG_read_NAME_num_array(lua_State* L,int index,TYPE *array,int size); */ -/* Reported that you don't need to check for NULL for delete & free -There probably is some compiler that its not true for, so the code is left here just in case. -#ifdef __cplusplus -#define SWIG_ALLOC_ARRAY(TYPE,LEN) new TYPE[LEN] -#define SWIG_FREE_ARRAY(PTR) if(PTR){delete[] PTR;} -#else -#define SWIG_ALLOC_ARRAY(TYPE,LEN) (TYPE *)malloc(LEN*sizeof(TYPE)) -#define SWIG_FREE_ARRAY(PTR) if(PTR){free(PTR);} -#endif -*/ %{ #ifdef __cplusplus /* generic alloc/dealloc fns*/ #define SWIG_ALLOC_ARRAY(TYPE,LEN) new TYPE[LEN] diff --git a/Lib/math.i b/Lib/math.i index a37c92d19..ac8d9a6eb 100644 --- a/Lib/math.i +++ b/Lib/math.i @@ -9,6 +9,8 @@ #include %} +#ifndef SWIGPHP /* PHP already provides all these functions except fabs() */ + extern double cos(double x); /* Cosine of x */ @@ -54,9 +56,6 @@ extern double pow(double x, double y); extern double sqrt(double x); /* Square root. x >= 0 */ -extern double fabs(double x); -/* Absolute value of x */ - extern double ceil(double x); /* Smallest integer not less than x, as a double */ @@ -66,6 +65,13 @@ extern double floor(double x); extern double fmod(double x, double y); /* Floating-point remainder of x/y, with the same sign as x. */ +#endif + +extern double fabs(double x); +/* Absolute value of x */ + +#ifndef SWIGPHP /* PHP already provides these constants and it's an error to redefine them */ + #define M_E 2.7182818284590452354 #define M_LOG2E 1.4426950408889634074 #define M_LOG10E 0.43429448190325182765 @@ -80,3 +86,4 @@ extern double fmod(double x, double y); #define M_SQRT2 1.41421356237309504880 #define M_SQRT1_2 0.70710678118654752440 +#endif diff --git a/Lib/modula3/modula3.swg b/Lib/modula3/modula3.swg deleted file mode 100644 index 13d06e9c6..000000000 --- a/Lib/modula3/modula3.swg +++ /dev/null @@ -1,787 +0,0 @@ -/* ----------------------------------------------------------------------------- - * modula3.swg - * - * Modula3 typemaps - * ----------------------------------------------------------------------------- */ - -%include - -/* The ctype, m3rawtype and m3wraptype typemaps work together and so there should be one of each. - * The ctype typemap contains the C type used in the signature of C wrappers for C++ functions. - * The m3rawtype typemap contains the M3 type used in the raw interface. - * The m3rawintype typemap contains the M3 type used as function argument. - * The m3rawrettype typemap contains the M3 type used as return value. - * The m3wraptype typemap contains the M3 type used in the M3 type wrapper classes and module class. */ - -/* Primitive types */ -%typemap(ctype) bool, const bool & "bool" -%typemap(ctype) char, const char & "char" -%typemap(ctype) signed char, const signed char & "signed char" -%typemap(ctype) unsigned char, const unsigned char & "unsigned short" -%typemap(ctype) short, const short & "short" -%typemap(ctype) unsigned short, const unsigned short & "unsigned short" -%typemap(ctype) int, const int & "int" -%typemap(ctype) unsigned int, const unsigned int & "unsigned int" -%typemap(ctype) long, const long & "long" -%typemap(ctype) unsigned long, const unsigned long & "unsigned long" -%typemap(ctype) long long, const long long & "long long" -%typemap(ctype) unsigned long long, const unsigned long long & "unsigned long long" -%typemap(ctype) float, const float & "float" -%typemap(ctype) double, const double & "double" -%typemap(ctype) char * "char *" -%typemap(ctype) void "void" - -%typemap(m3rawtype) bool, const bool & "BOOLEAN" -%typemap(m3rawtype) char, const char & "C.char" -%typemap(m3rawtype) signed char, const signed char & "C.signed_char" -%typemap(m3rawtype) unsigned char, const unsigned char & "C.unsigned_char" -%typemap(m3rawtype) short, const short & "C.short" -%typemap(m3rawtype) unsigned short, const unsigned short & "C.unsigned_short" -%typemap(m3rawtype) int, const int & "C.int" -%typemap(m3rawtype) unsigned int, const unsigned int & "C.unsigned_int" -%typemap(m3rawtype) long, const long & "C.long" -%typemap(m3rawtype) unsigned long, const unsigned long & "C.unsigned_long" -%typemap(m3rawtype) long long, const long long & "C.long_long" -%typemap(m3rawtype) unsigned long long, const unsigned long long & "C.unsigned_long_long" -%typemap(m3rawtype) float, const float & "C.float" -%typemap(m3rawtype) double, const double & "C.double" -%typemap(m3rawtype) long double, const long double & "C.long_double" -%typemap(m3rawtype) char * "C.char_star" -%typemap(m3rawtype) void "" -%typemap(m3rawtype) FILE "Cstdio.FILE"; -%typemap(m3rawtype) FILE * "Cstdio.FILE_star"; - - -%typemap(m3rawintype) bool *, bool &, bool "BOOLEAN" -%typemap(m3rawintype) char *, char &, char "C.char" -%typemap(m3rawintype) signed char *, signed char &, signed char "C.signed_char" -%typemap(m3rawintype) unsigned char *, unsigned char &, unsigned char "C.unsigned_char" -%typemap(m3rawintype) short *, short &, short "C.short" -%typemap(m3rawintype) unsigned short *, unsigned short &, unsigned short "C.unsigned_short" -%typemap(m3rawintype) int *, int &, int "C.int" -%typemap(m3rawintype) unsigned int *, unsigned int &, unsigned int "C.unsigned_int" -%typemap(m3rawintype) long *, long &, long "C.long" -%typemap(m3rawintype) unsigned long *, unsigned long &, unsigned long "C.unsigned_long" -%typemap(m3rawintype) long long *, long long &, long long "C.long_long" -%typemap(m3rawintype) unsigned long long *, unsigned long long &, unsigned long long "C.unsigned_long_long" -%typemap(m3rawintype) float *, float &, float "C.float" -%typemap(m3rawintype) double *, double &, double "C.double" -%typemap(m3rawintype) long double *, long double &, long double "C.long_double" -%typemap(m3rawintype) char * "C.char_star" -%typemap(m3rawintype) void "" -%typemap(m3rawintype) void * "ADDRESS" -%typemap(m3rawintype) FILE "Cstdio.FILE"; -%typemap(m3rawintype) FILE * "Cstdio.FILE_star"; - -%typemap(m3rawinmode) char *, void *, FILE * "" - - -%typemap(m3rawrettype) bool, const bool & "BOOLEAN" -%typemap(m3rawrettype) char, const char & "C.char" -%typemap(m3rawrettype) signed char, const signed char & "C.signed_char" -%typemap(m3rawrettype) unsigned char, const unsigned char & "C.unsigned_char" -%typemap(m3rawrettype) short, const short & "C.short" -%typemap(m3rawrettype) unsigned short, const unsigned short & "C.unsigned_short" -%typemap(m3rawrettype) int, const int & "C.int" -%typemap(m3rawrettype) unsigned int, const unsigned int & "C.unsigned_int" -%typemap(m3rawrettype) long, const long & "C.long" -%typemap(m3rawrettype) unsigned long, const unsigned long & "C.unsigned_long" -%typemap(m3rawrettype) long long, const long long & "C.long_long" -%typemap(m3rawrettype) unsigned long long, const unsigned long long & "C.unsigned_long_long" -%typemap(m3rawrettype) float, const float & "C.float" -%typemap(m3rawrettype) double, const double & "C.double" -%typemap(m3rawrettype) long double, const long double & "C.long_double" -%typemap(m3rawrettype) char * "C.char_star" -%typemap(m3rawrettype) void "" -%typemap(m3rawrettype) void * "ADDRESS" -%typemap(m3rawrettype) FILE "Cstdio.FILE"; -%typemap(m3rawrettype) FILE * "Cstdio.FILE_star"; - - -%typemap("m3rawtype:import") - char, const char &, - signed char, const signed char &, - unsigned char, const unsigned char &, - short, const short &, - unsigned short, const unsigned short &, - int, const int &, - unsigned int, const unsigned int &, - long, const long &, - unsigned long, const unsigned long &, - long long, const long long &, - unsigned long long, const unsigned long long &, - float, const float &, - double, const double &, - long double, const long double &, - char * - "Ctypes AS C" - -%typemap("m3rawintype:import") - char, const char &, - signed char, const signed char &, - unsigned char, const unsigned char &, - short, const short &, - unsigned short, const unsigned short &, - int, const int &, - unsigned int, const unsigned int &, - long, const long &, - unsigned long, const unsigned long &, - long long, const long long &, - unsigned long long, const unsigned long long &, - float, const float &, - double, const double &, - long double, const long double &, - char * - "Ctypes AS C" - -%typemap("m3rawrettype:import") - char, const char &, - signed char, const signed char &, - unsigned char, const unsigned char &, - short, const short &, - unsigned short, const unsigned short &, - int, const int &, - unsigned int, const unsigned int &, - long, const long &, - unsigned long, const unsigned long &, - long long, const long long &, - unsigned long long, const unsigned long long &, - float, const float &, - double, const double &, - long double, const long double &, - char * - "Ctypes AS C" - -%typemap("m3rawtype:import") - FILE, FILE * - "Cstdio"; - -%typemap("m3rawintype:import") - FILE, FILE * - "Cstdio"; - -%typemap("m3rawrettype:import") - FILE, FILE * - "Cstdio"; - -%typemap(m3wraptype) bool, const bool & "BOOLEAN" -%typemap(m3wraptype) char, const char & "CHAR" -%typemap(m3wraptype) signed char, const signed char & "CHAR" -%typemap(m3wraptype) unsigned char, const unsigned char & "CHAR" -%typemap(m3wraptype) short, const short & "Integer16.T" -%typemap(m3wraptype) unsigned short, const unsigned short & "Cardinal16.T" -%typemap(m3wraptype) int, const int & "INTEGER" -%typemap(m3wraptype) unsigned int, const unsigned int & "CARDINAL" -%typemap(m3wraptype) long, const long & "Integer32.T" -%typemap(m3wraptype) unsigned long, const unsigned long & "Cardinal32.T" -%typemap(m3wraptype) long long, const long long & "Integer64.T" -%typemap(m3wraptype) unsigned long long, const unsigned long long & "Cardinal64.T" -%typemap(m3wraptype) float, const float & "REAL" -%typemap(m3wraptype) double, const double & "LONGREAL" -%typemap(m3wraptype) long double, const long double & "EXTENDED" -%typemap(m3wraptype) char * "TEXT" -%typemap(m3wraptype) void "" -%typemap(m3wraptype) FILE "Cstdio.FILE"; -%typemap(m3wraptype) FILE * "Cstdio.FILE_star"; - -%typemap(m3wrapintype) bool, const bool *, const bool & "BOOLEAN" -%typemap(m3wrapintype) char, const char *, const char & "CHAR" -%typemap(m3wrapintype) signed char, const signed char *, const signed char & "CHAR" -%typemap(m3wrapintype) unsigned char, const unsigned char *, const unsigned char & "CHAR" -%typemap(m3wrapintype) short, const short *, const short & "INTEGER" -%typemap(m3wrapintype) unsigned short, const unsigned short *, const unsigned short & "CARDINAL" -%typemap(m3wrapintype) int, const int *, const int & "INTEGER" -%typemap(m3wrapintype) unsigned int, const unsigned int *, const unsigned int & "CARDINAL" -%typemap(m3wrapintype) long, const long *, const long & "INTEGER" -%typemap(m3wrapintype) unsigned long, const unsigned long *, const unsigned long & "CARDINAL" -%typemap(m3wrapintype) long long, const long long *, const long long & "INTEGER" -%typemap(m3wrapintype) unsigned long long, const unsigned long long *, const unsigned long long & "CARDINAL" -%typemap(m3wrapintype) float, const float *, const float & "REAL" -%typemap(m3wrapintype) double, const double *, const double & "LONGREAL" -%typemap(m3wrapintype) long double, const long double *, const long double & "EXTENDED" -%typemap(m3wrapintype) const char *, const char [] "TEXT" -%typemap(m3wrapintype,numinputs=0) void "" -%typemap(m3wrapintype) FILE "Cstdio.FILE"; -%typemap(m3wrapintype) FILE * "Cstdio.FILE_star"; - - -%typemap(m3wrapouttype) bool, bool *, bool & "BOOLEAN" -%typemap(m3wrapouttype) char, char *, char & "CHAR" -%typemap(m3wrapouttype) signed char, signed char *, signed char & "CHAR" -%typemap(m3wrapouttype) unsigned char, unsigned char *, unsigned char & "CHAR" -%typemap(m3wrapouttype) short, short *, short & "INTEGER" -%typemap(m3wrapouttype) unsigned short, unsigned short *, unsigned short & "CARDINAL" -%typemap(m3wrapouttype) int, int *, int & "INTEGER" -%typemap(m3wrapouttype) unsigned int, unsigned int *, unsigned int & "CARDINAL" -%typemap(m3wrapouttype) long, long *, long & "INTEGER" -%typemap(m3wrapouttype) unsigned long, unsigned long *, unsigned long & "CARDINAL" -%typemap(m3wrapouttype) long long, long long *, long long & "INTEGER" -%typemap(m3wrapouttype) unsigned long long, unsigned long long *, unsigned long long & "CARDINAL" -%typemap(m3wrapouttype) float, float *, float & "REAL" -%typemap(m3wrapouttype) double, double *, double & "LONGREAL" -%typemap(m3wrapouttype) long double, long double *, long double & "EXTENDED" -%typemap(m3wrapouttype) char *, char [] "TEXT" -%typemap(m3wrapouttype,numinputs=0) void "" - -%typemap(m3wraprettype) bool, const bool & "BOOLEAN" -%typemap(m3wraprettype) char, const char & "CHAR" -%typemap(m3wraprettype) signed char, const signed char & "CHAR" -%typemap(m3wraprettype) unsigned char, const unsigned char & "CHAR" -%typemap(m3wraprettype) short, const short & "INTEGER" -%typemap(m3wraprettype) unsigned short, const unsigned short & "CARDINAL" -%typemap(m3wraprettype) int, const int & "INTEGER" -%typemap(m3wraprettype) unsigned int, const unsigned int & "CARDINAL" -%typemap(m3wraprettype) long, const long & "INTEGER" -%typemap(m3wraprettype) unsigned long, const unsigned long & "CARDINAL" -%typemap(m3wraprettype) long long, const long long & "INTEGER" -%typemap(m3wraprettype) unsigned long long, const unsigned long long & "CARDINAL" -%typemap(m3wraprettype) float, const float & "REAL" -%typemap(m3wraprettype) double, const double & "LONGREAL" -%typemap(m3wraprettype) long double, const long double & "EXTENDED" -%typemap(m3wraprettype) char * "TEXT" -%typemap(m3wraprettype) void "" -%typemap(m3wraprettype) FILE "Cstdio.FILE"; -%typemap(m3wraprettype) FILE * "Cstdio.FILE_star"; - - -%typemap(ctype) char[ANY] "char *" -%typemap(m3rawtype) char[ANY] "C.char_star" -%typemap(m3rawintype) char[ANY] "C.char_star" -%typemap(m3rawrettype) char[ANY] "C.char_star" -%typemap(m3wraptype) char[ANY] "TEXT" -%typemap(m3wrapintype) char[ANY] "TEXT" -%typemap(m3wrapouttype) char[ANY] "TEXT" -%typemap(m3wraprettype) char[ANY] "TEXT" - -%typemap(m3wrapinmode) const char * %{%} -%typemap(m3wrapargvar) const char * %{$1 : C.char_star;%} -%typemap(m3wrapinconv) const char * %{$1 := M3toC.SharedTtoS($1_name);%} -%typemap(m3wrapfreearg) const char * %{M3toC.FreeSharedS($1_name,$1);%} -%typemap(m3wrapargraw) const char * %{$1%} -%typemap("m3wrapargvar:import") const char * "Ctypes AS C" -%typemap("m3wrapinconv:import") const char * "M3toC" -%typemap("m3wrapfreearg:import") const char * "M3toC" - -%typemap(m3wrapretvar) char * %{result : C.char_star;%} -%typemap(m3wrapretraw) char * %{result%} -%typemap(m3wrapretconv) char * %{M3toC.CopyStoT(result)%} -%typemap("m3wrapretvar:import") char * "Ctypes AS C" -%typemap("m3wrapretconv:import") char * "M3toC" - -%typemap(m3wrapinmode) FILE * %{%} - - -%typemap("m3wraptype:import") - FILE, FILE * - "Cstdio"; - -%typemap("m3wrapintype:import") - FILE, FILE * - "Cstdio"; - -%typemap("m3wraprettype:import") - FILE, FILE * - "Cstdio"; - - -/* Composed types */ -%typemap(ctype) SWIGTYPE "$1_type" -%typemap(m3rawtype) SWIGTYPE "$1_basetype" -%typemap(m3rawrettype) SWIGTYPE "UNTRACED REF $1_basetype" -%typemap(m3wraptype) SWIGTYPE "$1_basetype" -%typemap(m3wrapintype) SWIGTYPE "$1_basetype" -%typemap(m3wrapouttype) SWIGTYPE "$1_basetype" -%typemap(m3wraprettype) SWIGTYPE "$1_basetype" - -%typemap(ctype) SWIGTYPE [] "$1_type" -%typemap(m3rawtype) const SWIGTYPE [] "UNTRACED REF ARRAY INTEGER OF $1_basetype" -%typemap(m3rawtype) SWIGTYPE [] "UNTRACED REF ARRAY INTEGER OF $1_basetype" -%typemap(m3rawintype) const SWIGTYPE [] "(*ARRAY OF*) $1_basetype" -%typemap(m3rawinmode) const SWIGTYPE [] "READONLY" -%typemap(m3rawintype) SWIGTYPE [] "(*ARRAY OF*) $1_basetype" -%typemap(m3rawinmode) SWIGTYPE [] "VAR" -%typemap(m3rawrettype) const SWIGTYPE [] "UNTRACED REF ARRAY INTEGER OF $1_basetype" -%typemap(m3rawrettype) SWIGTYPE [] "UNTRACED REF ARRAY INTEGER OF $1_basetype" -%typemap(m3wraptype) SWIGTYPE [] "$1_basetype" -%typemap(m3wrapintype) const SWIGTYPE [] "ARRAY OF $1_basetype" -%typemap(m3wrapinmode) const SWIGTYPE [] "READONLY" -%typemap(m3wrapintype) SWIGTYPE [] "ARRAY OF $1_basetype" -%typemap(m3wrapinmode) SWIGTYPE [] "VAR" -%typemap(m3wrapouttype) SWIGTYPE [] "ARRAY OF $1_basetype" -%typemap(m3wraprettype) SWIGTYPE [] "REF ARRAY OF $1_basetype" - -%typemap(ctype) SWIGTYPE * "$1_type" -%typemap(m3rawtype) const SWIGTYPE * "UNTRACED REF $1_basetype" -%typemap(m3rawtype) SWIGTYPE * "UNTRACED REF $1_basetype" -%typemap(m3rawintype) const SWIGTYPE * "$1_basetype" -%typemap(m3rawinmode) const SWIGTYPE * "READONLY" -%typemap(m3rawintype) SWIGTYPE * "$1_basetype" -%typemap(m3rawinmode) SWIGTYPE * "VAR" -%typemap(m3rawrettype) const SWIGTYPE * "UNTRACED REF $1_basetype" -%typemap(m3rawrettype) SWIGTYPE * "UNTRACED REF $1_basetype" -%typemap(m3wraptype) SWIGTYPE * "$1_basetype" -%typemap(m3wrapintype) const SWIGTYPE * "$1_basetype" -%typemap(m3wrapinmode) const SWIGTYPE * "READONLY" -%typemap(m3wrapintype) SWIGTYPE * "$1_basetype" -%typemap(m3wrapinmode) SWIGTYPE * "VAR" -%typemap(m3wrapouttype) SWIGTYPE * "$1_basetype" -%typemap(m3wraprettype) SWIGTYPE * "UNTRACED REF $1_basetype" - -%typemap(ctype) SWIGTYPE & "$1_type" -%typemap(m3rawtype) const SWIGTYPE & "UNTRACED REF $1_basetype" -%typemap(m3rawtype) SWIGTYPE & "UNTRACED REF $1_basetype" -%typemap(m3rawintype) const SWIGTYPE & "$1_basetype" -%typemap(m3rawinmode) const SWIGTYPE & "READONLY" -%typemap(m3rawintype) SWIGTYPE & "$1_basetype" -%typemap(m3rawinmode) SWIGTYPE & "VAR" -%typemap(m3rawrettype) const SWIGTYPE & "UNTRACED REF $1_basetype" -%typemap(m3rawrettype) SWIGTYPE & "UNTRACED REF $1_basetype" -%typemap(m3wraptype) SWIGTYPE & "$1_basetype" -%typemap(m3wrapintype) const SWIGTYPE & "$1_basetype" -%typemap(m3wrapinmode) const SWIGTYPE & "READONLY" -%typemap(m3wrapintype) SWIGTYPE & "$1_basetype" -%typemap(m3wrapinmode) SWIGTYPE & "VAR" -%typemap(m3wrapouttype) SWIGTYPE & "$1_basetype" -%typemap(m3wraprettype) SWIGTYPE & "UNTRACED REF $1_basetype" - -%typemap(ctype) SWIGTYPE && "$1_type" -%typemap(m3rawtype) const SWIGTYPE && "UNTRACED REF $1_basetype" -%typemap(m3rawtype) SWIGTYPE && "UNTRACED REF $1_basetype" -%typemap(m3rawintype) const SWIGTYPE && "$1_basetype" -%typemap(m3rawinmode) const SWIGTYPE && "READONLY" -%typemap(m3rawintype) SWIGTYPE && "$1_basetype" -%typemap(m3rawinmode) SWIGTYPE && "VAR" -%typemap(m3rawrettype) const SWIGTYPE && "UNTRACED REF $1_basetype" -%typemap(m3rawrettype) SWIGTYPE && "UNTRACED REF $1_basetype" -%typemap(m3wraptype) SWIGTYPE && "$1_basetype" -%typemap(m3wrapintype) const SWIGTYPE && "$1_basetype" -%typemap(m3wrapinmode) const SWIGTYPE && "READONLY" -%typemap(m3wrapintype) SWIGTYPE && "$1_basetype" -%typemap(m3wrapinmode) SWIGTYPE && "VAR" -%typemap(m3wrapouttype) SWIGTYPE && "$1_basetype" -%typemap(m3wraprettype) SWIGTYPE && "UNTRACED REF $1_basetype" - -%typemap(ctype) enum SWIGTYPE "$1_type" -%typemap(m3rawtype) enum SWIGTYPE "C.int" -%typemap(m3rawintype) enum SWIGTYPE "C.int (* $1_type *)" -%typemap(m3rawrettype) enum SWIGTYPE "C.int" -%typemap(m3wraptype) enum SWIGTYPE "$*1_type" -%typemap(m3wrapintype) enum SWIGTYPE "$1_type" -%typemap(m3wrapouttype) enum SWIGTYPE "$1_type" -%typemap(m3wraprettype) enum SWIGTYPE "$*1_type" - -/* pointer to a class member */ -%typemap(ctype) SWIGTYPE (CLASS::*) "$1_type" -%typemap(m3rawtype) SWIGTYPE (CLASS::*) "REFANY" -%typemap(m3wraptype) SWIGTYPE (CLASS::*) "$1_basetype" - -/* The following are the in, out, freearg, argout typemaps. - These are the PInvoke code generating typemaps for converting from C# to C and visa versa. */ - -/* primitive types */ -%typemap(in) bool -%{ $1 = $input ? true : false; %} - -%typemap(in) char, - signed char, - unsigned char, - short, - unsigned short, - int, - unsigned int, - long, - unsigned long, - long long, - unsigned long long, - float, - double, - enum SWIGTYPE -%{ $1 = ($1_ltype)$input; %} - -%typemap(out) bool %{ $result = $1; %} -%typemap(out) char %{ $result = $1; %} -%typemap(out) signed char %{ $result = $1; %} -%typemap(out) unsigned char %{ $result = $1; %} -%typemap(out) short %{ $result = $1; %} -%typemap(out) unsigned short %{ $result = $1; %} -%typemap(out) int %{ $result = $1; %} -%typemap(out) unsigned int %{ $result = $1; %} -%typemap(out) long %{ $result = $1; %} -%typemap(out) unsigned long %{ $result = $1; %} -%typemap(out) long long %{ $result = $1; %} -%typemap(out) unsigned long long %{ $result = $1; %} -%typemap(out) float %{ $result = $1; %} -%typemap(out) double %{ $result = $1; %} -%typemap(out) enum SWIGTYPE %{ $result = $1; %} - -/* char * - treat as String */ -%typemap(in) char * { - $1 = $input; -} -//%typemap(freearg) char * { if ($1) JCALL2(ReleaseStringUTFChars, jenv, $input, $1); } -//%typemap(out) char * { if($1) $result = JCALL1(NewStringUTF, jenv, $1); } - -%typemap(out) void "" - -/* primitive types by const reference */ -%typemap(in) const bool & (bool temp) -%{ temp = $input ? true : false; - $1 = &temp; %} - -%typemap(in) const char & (char temp), - const signed char & (signed char temp), - const unsigned char & (unsigned char temp), - const short & (short temp), - const unsigned short & (unsigned short temp), - const int & (int temp), - const unsigned int & (unsigned int temp), - const long & (long temp), - const unsigned long & (unsigned long temp), - const long long & ($*1_ltype temp), - const unsigned long long & ($*1_ltype temp), - const float & (float temp), - const double & (double temp) -%{ temp = ($*1_ltype)$input; -$1 = &temp; %} - -%typemap(out) const bool & %{ $result = *$1; %} -%typemap(out) const char & %{ $result = *$1; %} -%typemap(out) const signed char & %{ $result = *$1; %} -%typemap(out) const unsigned char & %{ $result = *$1; %} -%typemap(out) const short & %{ $result = *$1; %} -%typemap(out) const unsigned short & %{ $result = *$1; %} -%typemap(out) const int & %{ $result = *$1; %} -%typemap(out) const unsigned int & %{ $result = *$1; %} -%typemap(out) const long & %{ $result = *$1; %} -%typemap(out) const unsigned long & %{ $result = *$1; %} -%typemap(out) const long long & %{ $result = *$1; %} -%typemap(out) const unsigned long long & %{ $result = *$1; %} -%typemap(out) const float & %{ $result = *$1; %} -%typemap(out) const double & %{ $result = *$1; %} - -/* Default handling. Object passed by value. Convert to a pointer */ -%typemap(in) SWIGTYPE ($&1_type argp) -%{ argp = *($&1_ltype*)&$input; - if (!argp) { -// SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Attempt to dereference null $1_type"); - RETURN $null; - } - $1 = *argp; %} -%typemap(out) SWIGTYPE -#ifdef __cplusplus -%{*($&1_ltype*)&$result = new $1_ltype((const $1_ltype &)$1); %} -#else -{ - $&1_ltype $1ptr = ($&1_ltype) malloc(sizeof($1_ltype)); - memmove($1ptr, &$1, sizeof($1_type)); - *($&1_ltype*)&$result = $1ptr; -} -#endif - -/* Generic pointers and references */ -%typemap(in) SWIGTYPE *, SWIGTYPE (CLASS::*) %{ $1 = *($&1_ltype)&$input; %} -%typemap(in) SWIGTYPE & %{ $1 = *($&1_ltype)&$input; - if(!$1) { - //SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "$1_type reference is null"); - RETURN $null; - } %} -%typemap(in) SWIGTYPE && %{ $1 = *($&1_ltype)&$input; - if(!$1) { - //SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "$1_type reference is null"); - RETURN $null; - } %} -%typemap(out) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE (CLASS::*) %{ *($&1_ltype)&$result = $1; %} - - -/* Default array handling */ -%typemap(in) SWIGTYPE [] %{ $1 = *($&1_ltype)&$input; %} -%typemap(out) SWIGTYPE [] %{ *($&1_ltype)&$result = $1; %} - -/* char[ANY] - treat as String */ -%typemap(in) char[ANY] { - $1 = $input; -} - -%typemap(argout) char[ANY] "" -%typemap(freearg) char[ANY] ""//{ if ($1) JCALL2(ReleaseStringUTFChars, jenv, $input, $1); } -%typemap(out) char[ANY] { if($1) $result = $1; } - - -/* Typecheck typemaps - The purpose of these is merely to issue a warning for overloaded C++ functions - * that cannot be overloaded in C# as more than one C++ type maps to a single C# type */ - -%typecheck(SWIG_TYPECHECK_BOOL) /* Java boolean */ - bool, - const bool & - "" - -%typecheck(SWIG_TYPECHECK_CHAR) /* Java char */ - char, - const char & - "" - -%typecheck(SWIG_TYPECHECK_INT8) /* Java byte */ - signed char, - const signed char & - "" - -%typecheck(SWIG_TYPECHECK_INT16) /* Java short */ - unsigned char, - short, - const unsigned char &, - const short & - "" - -%typecheck(SWIG_TYPECHECK_INT32) /* Java int */ - unsigned short, - int, - long, - const unsigned short &, - const int &, - const long &, - enum SWIGTYPE - "" - -%typecheck(SWIG_TYPECHECK_INT64) /* Java long */ - unsigned int, - unsigned long, - long long, - const unsigned int &, - const unsigned long &, - const long long & - "" - -%typecheck(SWIG_TYPECHECK_INT128) /* Java BigInteger */ - unsigned long long - "" - -%typecheck(SWIG_TYPECHECK_FLOAT) /* Java float */ - float, - const float & - "" - -%typecheck(SWIG_TYPECHECK_DOUBLE) /* Java double */ - double, - const double & - "" - -%typecheck(SWIG_TYPECHECK_STRING) /* Java String */ - char *, - char[ANY] - "" - -%typecheck(SWIG_TYPECHECK_POINTER) /* Default */ - SWIGTYPE, - SWIGTYPE *, - SWIGTYPE &, - SWIGTYPE &&, - SWIGTYPE [], - SWIGTYPE (CLASS::*) - "" - -/* Exception handling */ - -%typemap(throws) int, - long, - short, - unsigned int, - unsigned long, - unsigned short { - char error_msg[256]; - sprintf(error_msg, "C++ $1_type exception thrown, value: %d", $1); - SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, error_msg); - RETURN $null; -} - -%typemap(throws) SWIGTYPE { - (void)$1; - SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, "C++ $1_type exception thrown"); - RETURN $null; -} - -%typemap(throws) char * { - SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, $1); - RETURN $null; -} - - -/* Typemaps for code generation in proxy classes and C# type wrapper classes */ - -/* The in typemap is used for converting function parameter types from the type - * used in the proxy, module or type wrapper class to the type used in the PInvoke class. */ -%typemap(m3in) bool, const bool &, - char, const char &, - signed char, const signed char &, - unsigned char, const unsigned char &, - short, const short &, - unsigned short, const unsigned short &, - int, const int &, - unsigned int, const unsigned int &, - long, const long &, - unsigned long, const unsigned long &, - long long, const long long &, - unsigned long long, const unsigned long long &, - float, const float &, - double, const double &, - char *, - char[ANY], - enum SWIGTYPE - "$input" -%typemap(m3in) SWIGTYPE "$&*1_type.getCPtr($input)" -%typemap(m3in) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "$1_basetype.getCPtr($input)" - -/* The m3out typemap is used for converting function return types from the return type - * used in the PInvoke class to the type returned by the proxy, module or type wrapper class. */ -%typemap(m3out) bool, const bool &, - char, const char &, - signed char, const signed char &, - unsigned char, const unsigned char &, - short, const short &, - unsigned short, const unsigned short &, - int, const int &, - unsigned int, const unsigned int &, - long, const long &, - unsigned long, const unsigned long &, - long long, const long long &, - unsigned long long, const unsigned long long &, - float, const float &, - double, const double &, - char *, - char[ANY], - enum SWIGTYPE -%{$imcall%} - -%typemap(m3out) void %{$imcall%} - -%typemap(m3out) SWIGTYPE %{ - RETURN NEW(REF $1_basetype, $imcall); -%} -%typemap(m3out) SWIGTYPE & %{ - RETURN NEW($1_basetype, $imcall, $owner); -%} -%typemap(m3out) SWIGTYPE && %{ - RETURN NEW($1_basetype, $imcall, $owner); -%} -%typemap(m3out) SWIGTYPE *, SWIGTYPE [], SWIGTYPE (CLASS::*) %{ - cPtr := $imcall; - RETURN (cPtr = IntPtr.Zero) ? null : NEW($1_basetype, cPtr, $owner); -%} - -/* Properties */ -%typemap(m3varin) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) %{ -PROCEDURE Set$var (value: $vartype) = - BEGIN - $imcall; - END Set$var; -%} - -%typemap(m3varout) bool, const bool &, - char, const char &, - signed char, const signed char &, - unsigned char, const unsigned char &, - short, const short &, - unsigned short, const unsigned short &, - int, const int &, - unsigned int, const unsigned int &, - long, const long &, - unsigned long, const unsigned long &, - long long, const long long &, - unsigned long long, const unsigned long long &, - float, const float &, - double, const double &, - char *, - char[ANY], - enum SWIGTYPE %{ -PROCEDURE Get$var (): $vartype = - BEGIN - RETURN $imcall; - END Get$var; -%} - -%typemap(m3varout) void %{ - get { - $imcall; - } %} -%typemap(m3varout) SWIGTYPE %{ - get { - RETURN new $&*1_mangle($imcall, true); - } %} -%typemap(m3varout) SWIGTYPE & %{ - get { - RETURN new $1_basetype($imcall, $owner); - } %} -%typemap(m3varout) SWIGTYPE && %{ - get { - RETURN new $1_basetype($imcall, $owner); - } %} -%typemap(m3varout) SWIGTYPE *, SWIGTYPE [], SWIGTYPE (CLASS::*) %{ - get { - IntPtr cPtr = $imcall; - RETURN (cPtr == IntPtr.Zero) ? null : new $1_basetype(cPtr, $owner); - } %} - -/* Typemaps used for the generation of proxy and type wrapper class code */ -%typemap(m3base) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" -%typemap(m3classmodifiers) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "public" -%typemap(m3code) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" -%typemap(m3imports) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "using System;" -%typemap(m3interfaces) SWIGTYPE "IDisposable" -%typemap(m3interfaces_derived) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" -%typemap(m3ptrconstructormodifiers) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "internal" - -%typemap(m3finalize) SWIGTYPE %{ - ~$1_basetype() { - Dispose(); - } -%} - -%typemap(m3destruct, methodname="Dispose") SWIGTYPE { - if(swigCPtr != IntPtr.Zero && swigCMemOwn) { - $imcall; - swigCMemOwn = false; - } - swigCPtr = IntPtr.Zero; - GC.SuppressFinalize(this); - } - -%typemap(m3destruct_derived, methodname="Dispose") SWIGTYPE { - if(swigCPtr != IntPtr.Zero && swigCMemOwn) { - $imcall; - swigCMemOwn = false; - } - swigCPtr = IntPtr.Zero; - GC.SuppressFinalize(this); - base.Dispose(); - } - -%typemap(m3getcptr) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) %{ - internal static IntPtr getCPtr($1_basetype obj) { - RETURN (obj == null) ? IntPtr.Zero : obj.swigCPtr; - } -%} - -/* M3 specific directives */ -#define %m3multiretval %feature("modula3:multiretval") -#define %constnumeric(num) %feature("constnumeric","num") - -%pragma(modula3) moduleimports=%{ -IMPORT BlaBla; -%} - -%pragma(modula3) imclassimports=%{ -FROM BlaBla IMPORT Bla; -%} - -/* Some ANSI C typemaps */ - -%apply unsigned long { size_t }; - -/* Array reference typemaps */ -%apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } -%apply SWIGTYPE && { SWIGTYPE ((&&)[ANY]) } - -/* const pointers */ -%apply SWIGTYPE * { SWIGTYPE *const } -%apply SWIGTYPE (CLASS::*) { SWIGTYPE (CLASS::*const) } -%apply SWIGTYPE & { SWIGTYPE (CLASS::*const&) } - diff --git a/Lib/modula3/modula3head.swg b/Lib/modula3/modula3head.swg deleted file mode 100644 index af96a78d1..000000000 --- a/Lib/modula3/modula3head.swg +++ /dev/null @@ -1,64 +0,0 @@ -/* ----------------------------------------------------------------------------- - * modula3head.swg - * - * Modula3 support code - * ----------------------------------------------------------------------------- */ - -%insert(runtime) %{ - -#include -#include -#include -%} - -#if 0 -%insert(runtime) %{ -/* Support for throwing Modula3 exceptions */ -typedef enum { - SWIG_JavaOutOfMemoryError = 1, - SWIG_JavaIOException, - SWIG_JavaRuntimeException, - SWIG_JavaIndexOutOfBoundsException, - SWIG_JavaArithmeticException, - SWIG_JavaIllegalArgumentException, - SWIG_JavaNullPointerException, - SWIG_JavaUnknownError -} SWIG_JavaExceptionCodes; - -typedef struct { - SWIG_JavaExceptionCodes code; - const char *java_exception; -} SWIG_JavaExceptions_t; - -#if defined(SWIG_NOINCLUDE) -void SWIG_JavaThrowException(JNIEnv *jenv, SWIG_JavaExceptionCodes code, const char *msg); -#else -%} -%insert(runtime) { -void SWIG_JavaThrowException(JNIEnv *jenv, SWIG_JavaExceptionCodes code, const char *msg) { - jclass excep; - static const SWIG_JavaExceptions_t java_exceptions[] = { - { SWIG_JavaOutOfMemoryError, "java/lang/OutOfMemoryError" }, - { SWIG_JavaIOException, "java/io/IOException" }, - { SWIG_JavaRuntimeException, "java/lang/RuntimeException" }, - { SWIG_JavaIndexOutOfBoundsException, "java/lang/IndexOutOfBoundsException" }, - { SWIG_JavaArithmeticException, "java/lang/ArithmeticException" }, - { SWIG_JavaIllegalArgumentException, "java/lang/IllegalArgumentException" }, - { SWIG_JavaNullPointerException, "java/lang/NullPointerException" }, - { SWIG_JavaUnknownError, "java/lang/UnknownError" }, - { (SWIG_JavaExceptionCodes)0, "java/lang/UnknownError" } }; - const SWIG_JavaExceptions_t *except_ptr = java_exceptions; - - while (except_ptr->code != code && except_ptr->code) - except_ptr++; - - JCALL0(ExceptionClear, jenv); - excep = JCALL1(FindClass, jenv, except_ptr->java_exception); - if (excep) - JCALL2(ThrowNew, jenv, excep, msg); -} -} -%insert(runtime) %{ -#endif -%} -#endif diff --git a/Lib/modula3/typemaps.i b/Lib/modula3/typemaps.i deleted file mode 100644 index 1d76ab5e0..000000000 --- a/Lib/modula3/typemaps.i +++ /dev/null @@ -1,74 +0,0 @@ -/* ----------------------------------------------------------------------------- - * typemaps.i - * - * Pointer and reference handling typemap library - * - * These mappings provide support for input/output arguments and common - * uses for C/C++ pointers and C++ references. - * ----------------------------------------------------------------------------- */ - -/* These typemaps will eventually probably maybe make their way into named typemaps - * OUTPUT * and OUTPUT & as they currently break functions that return a pointer or - * reference. */ - -%typemap(ctype) bool *, bool & "bool *" -%typemap(ctype) char & "char *" -%typemap(ctype) signed char *, signed char & "signed char *" -%typemap(ctype) unsigned char *, unsigned char & "unsigned short *" -%typemap(ctype) short *, short & "short *" -%typemap(ctype) unsigned short *, unsigned short & "unsigned short *" -%typemap(ctype) int *, int & "int *" -%typemap(ctype) unsigned int *, unsigned int & "unsigned int *" -%typemap(ctype) long *, long & "long *" -%typemap(ctype) unsigned long *, unsigned long & "unsigned long *" -%typemap(ctype) long long *, long long & "long long *" -%typemap(ctype) unsigned long long *, unsigned long long & "unsigned long long *" -%typemap(ctype) float *, float & "float *" -%typemap(ctype) double *, double & "double *" - -%typemap(imtype) bool *, bool & "ref bool" -%typemap(imtype) char & "ref char" -%typemap(imtype) signed char *, signed char & "ref sbyte" -%typemap(imtype) unsigned char *, unsigned char & "ref byte" -%typemap(imtype) short *, short & "ref short" -%typemap(imtype) unsigned short *, unsigned short & "ref ushort" -%typemap(imtype) int *, int & "ref int" -%typemap(imtype) unsigned int *, unsigned int & "ref uint" -%typemap(imtype) long *, long & "ref int" -%typemap(imtype) unsigned long *, unsigned long & "ref uint" -%typemap(imtype) long long *, long long & "ref long" -%typemap(imtype) unsigned long long *, unsigned long long & "ref ulong" -%typemap(imtype) float *, float & "ref float" -%typemap(imtype) double *, double & "ref double" - -%typemap(cstype) bool *, bool & "ref bool" -%typemap(cstype) char & "ref char" -%typemap(cstype) signed char *, signed char & "ref sbyte" -%typemap(cstype) unsigned char *, unsigned char & "ref byte" -%typemap(cstype) short *, short & "ref short" -%typemap(cstype) unsigned short *, unsigned short & "ref ushort" -%typemap(cstype) int *, int & "ref int" -%typemap(cstype) unsigned int *, unsigned int & "ref uint" -%typemap(cstype) long *, long & "ref int" -%typemap(cstype) unsigned long *, unsigned long & "ref uint" -%typemap(cstype) long long *, long long & "ref long" -%typemap(cstype) unsigned long long *, unsigned long long & "ref ulong" -%typemap(cstype) float *, float & "ref float" -%typemap(cstype) double *, double & "ref double" - -%typemap(csin) bool *, bool &, - char &, - signed char *, signed char &, - unsigned char *, unsigned char &, - short *, short &, - unsigned short *, unsigned short &, - int *, int &, - unsigned int *, unsigned int &, - long *, long &, - unsigned long *, unsigned long &, - long long *, long long &, - unsigned long long *, unsigned long long &, - float *, float &, - double *, double & - "ref $csinput" - diff --git a/Lib/mzscheme/mzrun.swg b/Lib/mzscheme/mzrun.swg index c438c9ce8..279073113 100644 --- a/Lib/mzscheme/mzrun.swg +++ b/Lib/mzscheme/mzrun.swg @@ -23,12 +23,14 @@ extern "C" { SWIG_MzScheme_MustGetPtr(s, type, argnum, flags, FUNC_NAME, argc, argv) #define SWIG_contract_assert(expr,msg) \ - if (!(expr)) { \ - char *m=(char *) scheme_malloc(strlen(msg)+1000); \ - sprintf(m,"SWIG contract, assertion failed: function=%s, message=%s", \ - (char *) FUNC_NAME,(char *) msg); \ - scheme_signal_error(m); \ - } + do { \ + if (!(expr)) { \ + char *m=(char *) scheme_malloc(strlen(msg)+1000); \ + sprintf(m,"SWIG contract, assertion failed: function=%s, message=%s", \ + (char *) FUNC_NAME,(char *) msg); \ + scheme_signal_error(m); \ + } \ + } while (0) /* Runtime API */ #define SWIG_GetModule(clientdata) SWIG_MzScheme_GetModule((Scheme_Env *)(clientdata)) diff --git a/Lib/ocaml/ocamlrun.swg b/Lib/ocaml/ocamlrun.swg index 5a923c5fe..53ad952fb 100644 --- a/Lib/ocaml/ocamlrun.swg +++ b/Lib/ocaml/ocamlrun.swg @@ -369,7 +369,7 @@ extern "C" { if( !p || len < 0 ) CAMLreturn(caml_val_ptr( (void *)p, 0 )); vv = caml_swig_alloc(1,C_string); SWIG_Store_field(vv,0,caml_alloc_string(len)); - memcpy(String_val(SWIG_Field(vv,0)),p,len); + memcpy(Bp_val(SWIG_Field(vv,0)),p,len); CAMLreturn(vv); } diff --git a/Lib/ocaml/ocamlrundec.swg b/Lib/ocaml/ocamlrundec.swg index 555f9a44f..dde0b8e5c 100644 --- a/Lib/ocaml/ocamlrundec.swg +++ b/Lib/ocaml/ocamlrundec.swg @@ -164,7 +164,7 @@ SWIGINTERN void SWIG_OCamlThrowException(SWIG_OCamlExceptionCodes code, const ch CAMLreturn0; } -#define SWIG_contract_assert(expr, msg) if(!(expr)) {SWIG_OCamlThrowException(SWIG_OCamlRuntimeException, msg);} +#define SWIG_contract_assert(expr, msg) do { if(!(expr)) {SWIG_OCamlThrowException(SWIG_OCamlRuntimeException, msg);} } while (0) SWIGINTERN int SWIG_GetPtr(void *source, void **result, swig_type_info *type, swig_type_info *result_type); diff --git a/Lib/octave/octcomplex.swg b/Lib/octave/octcomplex.swg index a3e9ebf77..553c25a3d 100644 --- a/Lib/octave/octcomplex.swg +++ b/Lib/octave/octcomplex.swg @@ -2,7 +2,7 @@ Defines the As/From conversors for double/float complex, you need to provide complex Type, the Name you want to use in the conversors, the complex Constructor method, and the Real and Imag complex - accesor methods. + accessor methods. See the std_complex.i and ccomplex.i for concrete examples. */ @@ -73,7 +73,7 @@ int res = SWIG_AddCast(SWIG_AsVal(float)(ov, &d)); if (SWIG_IsOK(res)) { if (val) - *val = Constructor(d, 0.0); + *val = Constructor(d, 0.0f); return res; } } diff --git a/Lib/octave/octcontainer.swg b/Lib/octave/octcontainer.swg index 80d593f4f..394c90bac 100644 --- a/Lib/octave/octcontainer.swg +++ b/Lib/octave/octcontainer.swg @@ -569,8 +569,17 @@ namespace swig { } else { return octseq.check() ? SWIG_OK : SWIG_ERROR; } - } catch (std::exception& e) { + } +%#if SWIG_OCTAVE_PREREQ(6,0,0) + catch (octave::execution_exception& exec) { + } +%#endif + catch (std::exception& e) { +%#if SWIG_OCTAVE_PREREQ(6,0,0) + if (seq) // Know that octave is not in an error state +%#else if (seq&&!error_state) +%#endif error("swig type error: %s",e.what()); return SWIG_ERROR; } diff --git a/Lib/octave/octrun.swg b/Lib/octave/octrun.swg index 1069e0e54..d94056c8c 100644 --- a/Lib/octave/octrun.swg +++ b/Lib/octave/octrun.swg @@ -171,7 +171,16 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); octave_function* function_value(bool = false) { return this; } +#if SWIG_OCTAVE_PREREQ(6,0,0) octave_value_list call(octave::tree_evaluator& tw, int nargout = 0, const octave_value_list& args = octave_value_list()) { + return execute(tw,nargout,args); + } +#endif +#if SWIG_OCTAVE_PREREQ(6,0,0) + octave_value_list execute(octave::tree_evaluator& tw, int nargout = 0, const octave_value_list& args = octave_value_list()) { +#else + octave_value_list call(octave::tree_evaluator& tw, int nargout = 0, const octave_value_list& args = octave_value_list()) { +#endif octave_value_list all_args; all_args.append(first_args); all_args.append(args); @@ -456,10 +465,20 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); // Fill in dim_vector for (int k=0;k a; + try { + a = out.int_vector_value(); + } + catch (octave::execution_exception& oee) { + return dim_vector(1,1); + } +#else Array a = out.int_vector_value(); if (error_state) return dim_vector(1,1); +#endif dim_vector d; d.resize(a.numel() < 2 ? 2 : a.numel()); d(0) = d(1) = 1; @@ -631,7 +660,11 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); return true; } +#if SWIG_OCTAVE_PREREQ(6,0,0) + virtual bool isstruct() const { +#else virtual bool is_map() const { +#endif return true; } @@ -779,7 +812,11 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); return as_value(); } +#if SWIG_OCTAVE_PREREQ(4,4,0) + virtual bool isobject() const { +#else virtual bool is_object() const { +#endif return true; } @@ -874,7 +911,11 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); } virtual bool load_binary (std::istream& is, bool swap, - oct_mach_info::float_format fmt) { +#if SWIG_OCTAVE_PREREQ(6,0,0) + octave::mach_info::float_format fmt) { +#else + oct_mach_info::float_format fmt) { +#endif return true; } @@ -1084,8 +1125,13 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); bool is_defined() const { return ptr->is_defined(); } +#if SWIG_OCTAVE_PREREQ(6,0,0) + virtual bool isstruct() const + { return ptr->isstruct(); } +#else virtual bool is_map() const { return ptr->is_map(); } +#endif virtual octave_value subsref(const std::string &ops, const std::list < octave_value_list > &idx) { return ptr->subsref(ops, idx); } @@ -1096,8 +1142,13 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); octave_value subsasgn(const std::string &ops, const std::list < octave_value_list > &idx, const octave_value &rhs) { return ptr->subsasgn(ops, idx, rhs); } +#if SWIG_OCTAVE_PREREQ(4,4,0) + virtual bool isobject() const + { return ptr->isobject(); } +#else virtual bool is_object() const { return ptr->is_object(); } +#endif virtual bool is_string() const { return ptr->is_string(); } @@ -1142,7 +1193,11 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); { return ptr->save_binary(os, save_as_floats); } virtual bool load_binary (std::istream& is, bool swap, - oct_mach_info::float_format fmt) +#if SWIG_OCTAVE_PREREQ(6,0,0) + octave::mach_info::float_format fmt) +#else + oct_mach_info::float_format fmt) +#endif { return ptr->load_binary(is, swap, fmt); } #if defined (HAVE_HDF5) @@ -1178,6 +1233,10 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); #endif { return ptr->print(os, pr_as_read_syntax); } +#if SWIG_OCTAVE_PREREQ(4,4,0) + static void set_type_id(int type_id) { t_id=type_id; } +#endif + virtual type_conv_info numeric_conversion_function(void) const { return octave_base_value::type_conv_info (default_numeric_conversion_function, octave_scalar::static_type_id ()); @@ -1257,7 +1316,11 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); } virtual bool load_binary (std::istream& is, bool swap, - oct_mach_info::float_format fmt) { +#if SWIG_OCTAVE_PREREQ(6,0,0) + octave::mach_info::float_format fmt) { +#else + oct_mach_info::float_format fmt) { +#endif return true; } @@ -1285,6 +1348,10 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); # endif #endif +#if SWIG_OCTAVE_PREREQ(4,4,0) + static void set_type_id(int type_id) { t_id=type_id; } +#endif + private: #if !SWIG_OCTAVE_PREREQ(4,0,0) DECLARE_OCTAVE_ALLOCATOR; @@ -1507,16 +1574,24 @@ SWIGRUNTIMEINLINE void SWIG_Octave_SetConstant(octave_swig_type *module_ns, cons } SWIGRUNTIMEINLINE octave_value SWIG_Octave_GetGlobalValue(std::string name) { +#if SWIG_OCTAVE_PREREQ(6,0,0) + octave::interpreter *interp = octave::interpreter::the_interpreter (); + return interp->global_varval(name); +#else #if SWIG_OCTAVE_PREREQ(4,4,0) octave::symbol_table& symtab = octave::interpreter::the_interpreter()->get_symbol_table(); return symtab.global_varval(name); #else return get_global_value(name, true); #endif +#endif } SWIGRUNTIME void SWIG_Octave_SetGlobalValue(std::string name, const octave_value& value) { -#if SWIG_OCTAVE_PREREQ(4,4,0) +#if SWIG_OCTAVE_PREREQ(6,0,0) + octave::interpreter *interp = octave::interpreter::the_interpreter (); + interp->global_assign(name, value); +#elif SWIG_OCTAVE_PREREQ(4,4,0) octave::symbol_table& symtab = octave::interpreter::the_interpreter()->get_symbol_table(); symtab.global_assign(name, value); #else @@ -1526,10 +1601,20 @@ SWIGRUNTIME void SWIG_Octave_SetGlobalValue(std::string name, const octave_value SWIGRUNTIME void SWIG_Octave_LinkGlobalValue(std::string name) { #if SWIG_OCTAVE_PREREQ(4,4,0) - octave::symbol_table& symtab = octave::interpreter::the_interpreter()->get_symbol_table(); octave::symbol_scope symscope = octave::interpreter::the_interpreter()->get_current_scope(); +#if SWIG_OCTAVE_PREREQ(6,0,0) + octave::interpreter *interp = octave::interpreter::the_interpreter (); + interp->assign(name, interp->global_varval(name)); + octave::tree_evaluator& tree_eval = interp->get_evaluator(); + octave::call_stack& callStack = tree_eval.get_call_stack(); + std::shared_ptr stackFrame = callStack.get_current_stack_frame(); + octave::symbol_record sym=symscope.lookup_symbol(name); + stackFrame->mark_global(sym); +#else + octave::symbol_table& symtab = octave::interpreter::the_interpreter()->get_symbol_table(); symscope.assign(name, symtab.global_varval(name)); symscope.mark_global(name); +#endif #else #if !SWIG_OCTAVE_PREREQ(3,2,0) link_to_global_variable(curr_sym_tab->lookup(name, true)); diff --git a/Lib/octave/octruntime.swg b/Lib/octave/octruntime.swg index a397fb7c1..e76151f14 100644 --- a/Lib/octave/octruntime.swg +++ b/Lib/octave/octruntime.swg @@ -19,7 +19,8 @@ static bool SWIG_init_user(octave_swig_type* module_ns); SWIGINTERN bool SWIG_Octave_LoadModule(std::string name) { bool retn = false; { -#if SWIG_OCTAVE_PREREQ(4,2,0) +#if SWIG_OCTAVE_PREREQ(6,0,0) +#elif SWIG_OCTAVE_PREREQ(4,2,0) octave::unwind_protect frame; frame.protect_var(discard_error_messages); discard_error_messages = true; frame.protect_var(discard_warning_messages); discard_warning_messages = true; @@ -62,7 +63,8 @@ SWIGINTERN bool SWIG_Octave_LoadModule(std::string name) { SWIGINTERN bool SWIG_Octave_InstallFunction(octave_function *octloadfcn, std::string name) { bool retn = false; { -#if SWIG_OCTAVE_PREREQ(4,2,0) +#if SWIG_OCTAVE_PREREQ(6,0,0) +#elif SWIG_OCTAVE_PREREQ(4,2,0) octave::unwind_protect frame; frame.protect_var(discard_error_messages); discard_error_messages = true; frame.protect_var(discard_warning_messages); discard_warning_messages = true; @@ -295,9 +297,11 @@ DEFUN_DLD( SWIG_name, args, nargout, SWIG_name_usage ) { for (int i = 0; i < types.numel(); ++i) { if (types(i) == octave_swig_ref::static_type_name()) { register_octave_swig_ref = false; + octave_swig_ref::set_type_id(i); } if (types(i) == octave_swig_packed::static_type_name()) { register_octave_swig_packed = false; + octave_swig_packed::set_type_id(i); } } if (register_octave_swig_ref) { @@ -314,7 +318,11 @@ DEFUN_DLD( SWIG_name, args, nargout, SWIG_name_usage ) { SWIG_InitializeModule(0); SWIG_PropagateClientData(); -#if SWIG_OCTAVE_PREREQ(4,4,0) +#if SWIG_OCTAVE_PREREQ(6,0,0) + octave::tree_evaluator& tree_eval = octave::interpreter::the_interpreter()->get_evaluator(); + octave::call_stack& stack = tree_eval.get_call_stack(); + octave_function *me = stack.current_function(); +#elif SWIG_OCTAVE_PREREQ(4,4,0) octave::call_stack& stack = octave::interpreter::the_interpreter()->get_call_stack(); octave_function *me = stack.current(); #else diff --git a/Lib/perl5/perlhead.swg b/Lib/perl5/perlhead.swg index 5437af5a5..bb7c1741d 100644 --- a/Lib/perl5/perlhead.swg +++ b/Lib/perl5/perlhead.swg @@ -8,22 +8,9 @@ extern "C" { #include "perl.h" #include "XSUB.h" -/* Add in functionality missing in older versions of Perl. Much of this is based on Devel-PPPort on cpan. */ - -/* Add PERL_REVISION, PERL_VERSION, PERL_SUBVERSION if missing */ -#ifndef PERL_REVISION -# if !defined(__PATCHLEVEL_H_INCLUDED__) && !(defined(PATCHLEVEL) && defined(SUBVERSION)) -# define PERL_PATCHLEVEL_H_IMPLICIT -# include -# endif -# if !(defined(PERL_VERSION) || (defined(SUBVERSION) && defined(PATCHLEVEL))) -# include -# endif -# ifndef PERL_REVISION -# define PERL_REVISION (5) -# define PERL_VERSION PATCHLEVEL -# define PERL_SUBVERSION SUBVERSION -# endif +/* PERL_REVISION was added in Perl 5.6. */ +#if !defined PERL_REVISION || (PERL_REVISION-0 == 5 && PERL_VERSION-0 < 8) +# error SWIG requires Perl >= 5.8.0 #endif #if defined(WIN32) && defined(PERL_OBJECT) && !defined(PerlIO_exportFILE) @@ -38,15 +25,6 @@ extern "C" { # define SvUOK(sv) SvIOK_UV(sv) #endif -#if ((PERL_VERSION < 4) || ((PERL_VERSION == 4) && (PERL_SUBVERSION <= 5))) -# define PL_sv_undef sv_undef -# define PL_na na -# define PL_errgv errgv -# define PL_sv_no sv_no -# define PL_sv_yes sv_yes -# define PL_markstack_ptr markstack_ptr -#endif - #ifndef IVSIZE # ifdef LONGSIZE # define IVSIZE LONGSIZE diff --git a/Lib/perl5/perlinit.swg b/Lib/perl5/perlinit.swg index b49040d26..c26b93fad 100644 --- a/Lib/perl5/perlinit.swg +++ b/Lib/perl5/perlinit.swg @@ -4,15 +4,11 @@ #ifdef __cplusplus extern "C" #endif -#ifndef PERL_OBJECT #ifndef MULTIPLICITY SWIGEXPORT void SWIG_init (CV* cv); #else SWIGEXPORT void SWIG_init (pTHXo_ CV* cv); #endif -#else -SWIGEXPORT void SWIG_init (CV *cv, CPerlObj *); -#endif %} /* Module initialization function */ diff --git a/Lib/perl5/perlrun.swg b/Lib/perl5/perlrun.swg index b04002f5d..28703d1a6 100644 --- a/Lib/perl5/perlrun.swg +++ b/Lib/perl5/perlrun.swg @@ -6,13 +6,8 @@ * type checking. * ----------------------------------------------------------------------------- */ -#ifdef PERL_OBJECT -#define SWIG_PERL_OBJECT_DECL CPerlObj *SWIGUNUSEDPARM(pPerl), -#define SWIG_PERL_OBJECT_CALL pPerl, -#else #define SWIG_PERL_OBJECT_DECL #define SWIG_PERL_OBJECT_CALL -#endif /* Common SWIG API */ @@ -88,31 +83,11 @@ extern "C" { #endif /* Macro to call an XS function */ -#ifdef PERL_OBJECT -# define SWIG_CALLXS(_name) _name(cv,pPerl) -#else -# ifndef MULTIPLICITY -# define SWIG_CALLXS(_name) _name(cv) -# else -# define SWIG_CALLXS(_name) _name(PERL_GET_THX, cv) -# endif -#endif - -#ifdef PERL_OBJECT -#define MAGIC_PPERL CPerlObj *pPerl = (CPerlObj *) this; - -#ifdef __cplusplus -extern "C" { +#ifndef MULTIPLICITY +# define SWIG_CALLXS(_name) _name(cv) +#else +# define SWIG_CALLXS(_name) _name(PERL_GET_THX, cv) #endif -typedef int (CPerlObj::*SwigMagicFunc)(SV *, MAGIC *); -#ifdef __cplusplus -} -#endif - -#define SWIG_MAGIC(a,b) (SV *a, MAGIC *b) -#define SWIGCLASS_STATIC - -#else /* PERL_OBJECT */ #define MAGIC_PPERL #define SWIGCLASS_STATIC static SWIGUNUSED @@ -141,24 +116,14 @@ typedef int (*SwigMagicFunc)(struct interpreter *, SV *, MAGIC *); #endif #endif /* MULTIPLICITY */ -#endif /* PERL_OBJECT */ -# ifdef PERL_OBJECT -# define SWIG_croak_null() SWIG_Perl_croak_null(pPerl) -static void SWIGUNUSED SWIG_Perl_croak_null(CPerlObj *pPerl) -# else static void SWIGUNUSED SWIG_croak_null() -# endif { SV *err = get_sv("@", GV_ADD); -# if (PERL_VERSION < 6) - croak("%_", err); -# else if (sv_isobject(err)) croak(0); else croak("%s", SvPV_nolen(err)); -# endif } @@ -462,20 +427,15 @@ typedef struct { } swig_variable_info; /* Magic variable code */ -#ifndef PERL_OBJECT -# ifdef __cplusplus +#ifdef __cplusplus # define swig_create_magic(s,a,b,c) _swig_create_magic(s,const_cast(a),b,c) -# else -# define swig_create_magic(s,a,b,c) _swig_create_magic(s,(char*)(a),b,c) -# endif -# ifndef MULTIPLICITY -SWIGRUNTIME void _swig_create_magic(SV *sv, char *name, int (*set)(SV *, MAGIC *), int (*get)(SV *,MAGIC *)) -# else -SWIGRUNTIME void _swig_create_magic(SV *sv, char *name, int (*set)(struct interpreter*, SV *, MAGIC *), int (*get)(struct interpreter*, SV *,MAGIC *)) -# endif #else -# define swig_create_magic(s,a,b,c) _swig_create_magic(pPerl,s,a,b,c) -SWIGRUNTIME void _swig_create_magic(CPerlObj *pPerl, SV *sv, const char *name, int (CPerlObj::*set)(SV *, MAGIC *), int (CPerlObj::*get)(SV *, MAGIC *)) +# define swig_create_magic(s,a,b,c) _swig_create_magic(s,(char*)(a),b,c) +#endif +#ifndef MULTIPLICITY +SWIGRUNTIME void _swig_create_magic(SV *sv, char *name, int (*set)(SV *, MAGIC *), int (*get)(SV *,MAGIC *)) +#else +SWIGRUNTIME void _swig_create_magic(SV *sv, char *name, int (*set)(struct interpreter*, SV *, MAGIC *), int (*get)(struct interpreter*, SV *,MAGIC *)) #endif { MAGIC *mg; diff --git a/Lib/perl5/perltypemaps.swg b/Lib/perl5/perltypemaps.swg index bf1596e9f..42f8887be 100644 --- a/Lib/perl5/perltypemaps.swg +++ b/Lib/perl5/perltypemaps.swg @@ -56,7 +56,9 @@ %define %set_output(obj) $result = obj; argvi++ %enddef /* append output */ -%define %append_output(obj) if (argvi >= items) EXTEND(sp, argvi+1); %set_output(obj) %enddef +%define %append_output(obj) +if (argvi >= items) EXTEND(sp, argvi+1); +%set_output(obj) %enddef /* variable output */ %define %set_varoutput(obj) sv_setsv($result,obj) %enddef @@ -95,7 +97,7 @@ "sv_setiv(SvRV($result), PTR2IV(&$1));"; %typemap(varout,type="$1_descriptor") SWIGTYPE (CLASS::*) { - SWIG_MakePackedObj($result, (void *) &$1, sizeof($1_type), $1_descriptor); + SWIG_MakePackedObj($result, (void *) &$1, sizeof($1), $1_descriptor); } %typemap(varout) SWIGTYPE *const = SWIGTYPE *; diff --git a/Lib/php/const.i b/Lib/php/const.i index 32b4b9b0b..6e83ffe88 100644 --- a/Lib/php/const.i +++ b/Lib/php/const.i @@ -3,6 +3,58 @@ * * Typemaps for constants * ----------------------------------------------------------------------------- */ +%typemap(classconsttab) int, + unsigned int, + short, + unsigned short, + long, + unsigned long, + unsigned char, + signed char, + enum SWIGTYPE %{ + zend_declare_class_constant_long(SWIG_Php_ce_$class, "$const_name", sizeof("$const_name") - 1, ($1_type)$value); +%} + +%typemap(classconsttab) bool %{ + zend_declare_class_constant_bool(SWIG_Php_ce_$class, "$const_name", sizeof("$const_name") - 1, ($1_type)$value); +%} + +%typemap(classconsttab) float, + double %{ + zend_declare_class_constant_double(SWIG_Php_ce_$class, "$const_name", sizeof("$const_name") - 1, $value); +%} + +%typemap(classconsttab) char %{ +{ + char swig_char = $value; + zend_declare_class_constant_stringl(SWIG_Php_ce_$class, "$const_name", sizeof("$const_name") - 1, &swig_char, 1); +} +%} + +%typemap(classconsttab) char *, + const char *, + char [], + const char [] %{ + zend_declare_class_constant_string(SWIG_Php_ce_$class, "$const_name", sizeof("$const_name") - 1, $value); +%} + +// This creates a zend_object to wrap the pointer, and we can't do that +// before the Zend runtime has been initialised so we delay it until +// RINIT. The downside is it then happens for every request. +%typemap(classconsttab,rinit=1) SWIGTYPE *, + SWIGTYPE &, + SWIGTYPE &&, + SWIGTYPE [] %{ +{ + zval z; + ZVAL_UNDEF(&z); + SWIG_SetPointerZval(&z, (void*)$value, $1_descriptor, 0); + zval_copy_ctor(&z); + zend_declare_class_constant(SWIG_Php_ce_$class, "$const_name", sizeof("$const_name") - 1, &z); +} +%} + +%typemap(classconsttab) SWIGTYPE (CLASS::*) ""; %typemap(consttab) int, unsigned int, @@ -31,11 +83,15 @@ const char [] "SWIG_STRING_CONSTANT($symname, $value);"; -%typemap(consttab) SWIGTYPE *, +// This creates a zend_object to wrap the pointer, and we can't do that +// before the Zend runtime has been initialised so we delay it until +// RINIT. The downside is it then happens for every request. +%typemap(consttab,rinit=1) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] { zend_constant c; + ZVAL_UNDEF(&c.value); SWIG_SetPointerZval(&c.value, (void*)$value, $1_descriptor, 0); zval_copy_ctor(&c.value); c.name = zend_string_init("$symname", sizeof("$symname") - 1, 0); diff --git a/Lib/php/director.swg b/Lib/php/director.swg index ea0eba8ac..55ffff516 100644 --- a/Lib/php/director.swg +++ b/Lib/php/director.swg @@ -8,6 +8,8 @@ #ifndef SWIG_DIRECTOR_PHP_HEADER_ #define SWIG_DIRECTOR_PHP_HEADER_ +#define SWIG_DIRECTOR_CAST(ARG) dynamic_cast(ARG) + #include #include #include @@ -76,31 +78,34 @@ namespace Swig { }; class Director { + private: + /* flag indicating whether the object is owned by PHP or C++ */ + mutable bool swig_disown_flag; + protected: // "mutable" so we can get a non-const pointer to it in const methods. mutable zval swig_self; typedef std::map swig_ownership_map; mutable swig_ownership_map swig_owner; + public: - Director(zval *self) { + Director(zval *self) : swig_disown_flag(false) { ZVAL_COPY_VALUE(&swig_self, self); } - static bool swig_is_overridden_method(const char *cname, const char *lc_fname) { - bool result = false; - zend_string * cname_str = zend_string_init(cname, strlen(cname), 0); - zend_class_entry *ce = zend_lookup_class(cname_str); - if (ce) { - zval * mptr = zend_hash_str_find(&ce->function_table, lc_fname, strlen(lc_fname)); - if (mptr) { - // common.scope points to zend_class_entry for the declaring class, - // and there's only one of those per class, so we can just use a - // pointer compare here. - result = Z_FUNC_P(mptr)->common.scope != ce; - } + ~Director() { + if (swig_disown_flag) { + Z_DELREF(swig_self); + } + } + + zend_object *swig_get_self() const { return Z_OBJ(swig_self); } + + void swig_disown() const { + if (!swig_disown_flag) { + swig_disown_flag = true; + Z_ADDREF(swig_self); } - zend_string_release(cname_str); - return result; } template @@ -109,6 +114,12 @@ namespace Swig { swig_owner[vptr] = new GCItem_T(vptr); } } + + void swig_acquire_ownership_obj(void *vptr, int own) const { + if (vptr && own) { + swig_owner[vptr] = new GCItem_Object(own); + } + } }; /* base class for director exceptions */ @@ -121,8 +132,8 @@ namespace Swig { swig_msg += " "; swig_msg += msg; } - SWIG_ErrorCode() = code; - SWIG_ErrorMsg() = swig_msg.c_str(); + // Don't replace an already active PHP exception. + if (!EG(exception)) zend_throw_exception(NULL, swig_msg.c_str(), code); } virtual ~DirectorException() throw() { @@ -150,8 +161,7 @@ namespace Swig { }; /* any php exception that occurs during a director method call */ - class DirectorMethodException : public DirectorException - { + class DirectorMethodException : public DirectorException { public: DirectorMethodException() : DirectorException(E_ERROR, "SWIG director method error", NULL) { diff --git a/Lib/php/factory.i b/Lib/php/factory.i index c4e082dd2..5f2b397ec 100644 --- a/Lib/php/factory.i +++ b/Lib/php/factory.i @@ -3,41 +3,41 @@ you have: ---- geometry.h -------- - struct Geometry { - enum GeomType{ - POINT, - CIRCLE - }; - - virtual ~Geometry() {} + struct Geometry { + enum GeomType{ + POINT, + CIRCLE + }; + + virtual ~Geometry() {} virtual int draw() = 0; - + // // Factory method for all the Geometry objects // - static Geometry *create(GeomType i); - }; - - struct Point : Geometry { - int draw() { return 1; } - double width() { return 1.0; } - }; - - struct Circle : Geometry { - int draw() { return 2; } - double radius() { return 1.5; } - }; - + static Geometry *create(GeomType i); + }; + + struct Point : Geometry { + int draw() { return 1; } + double width() { return 1.0; } + }; + + struct Circle : Geometry { + int draw() { return 2; } + double radius() { return 1.5; } + }; + // // Factory method for all the Geometry objects // Geometry *Geometry::create(GeomType type) { - switch (type) { - case POINT: return new Point(); - case CIRCLE: return new Circle(); - default: return 0; - } - } + switch (type) { + case POINT: return new Point(); + case CIRCLE: return new Circle(); + default: return 0; + } + } ---- geometry.h -------- @@ -57,16 +57,16 @@ NOTES: remember to fully qualify all the type names and don't use %factory inside a namespace declaration, ie, instead of - + namespace Foo { %factory(Geometry *Geometry::create, Point, Circle); } use - %factory(Foo::Geometry *Foo::Geometry::create, Foo::Point, Foo::Circle); + %factory(Foo::Geometry *Foo::Geometry::create, Foo::Point, Foo::Circle); + - */ /* for loop for macro with one argument */ @@ -90,20 +90,20 @@ /* for loop for macro with two arguments */ %define %formacro_2(macro,...)%_formacro_2(macro, __VA_ARGS__, __fordone__)%enddef -%define %_factory_dispatch(Type) +%define %_factory_dispatch(Type) if (!dcast) { Type *dobj = dynamic_cast($1); if (dobj) { dcast = 1; - SWIG_SetPointerZval(return_value, SWIG_as_voidptr(dobj),$descriptor(Type *), $owner); - } + SWIG_SetPointerZval(return_value, SWIG_as_voidptr(dobj), $descriptor(Type *), $owner); + } }%enddef %define %factory(Method,Types...) -%typemap(out) Method { +%typemap(out, phptype="?SWIGTYPE") Method { int dcast = 0; %formacro(%_factory_dispatch, Types) if (!dcast) { - SWIG_SetPointerZval(return_value, SWIG_as_voidptr($1),$descriptor, $owner); + SWIG_SetPointerZval(return_value, SWIG_as_voidptr($1), $descriptor, $owner); } }%enddef diff --git a/Lib/php/globalvar.i b/Lib/php/globalvar.i deleted file mode 100644 index 6b31207a6..000000000 --- a/Lib/php/globalvar.i +++ /dev/null @@ -1,293 +0,0 @@ -/* ----------------------------------------------------------------------------- - * globalvar.i - * - * Global variables - add the variable to PHP - * ----------------------------------------------------------------------------- */ - -%typemap(varinit) char * -{ - zval z_var; - if ($1) { - ZVAL_STRING(&z_var, $1); - } else { - ZVAL_STR(&z_var, ZSTR_EMPTY_ALLOC()); - } - zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &z_var); -} - -%typemap(varinit) char [] -{ - zval z_var; - ZVAL_STRING(&z_var, $1); - zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &z_var); -} - -%typemap(varinit) int, - unsigned int, - unsigned short, - short, - unsigned short, - long, - unsigned long, - signed char, - unsigned char, - enum SWIGTYPE -{ - zval z_var; - ZVAL_LONG(&z_var, (long)$1); - zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &z_var); -} - -%typemap(varinit) bool -{ - zval z_var; - ZVAL_BOOL(&z_var, ($1)?1:0); - zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &z_var); -} - -%typemap(varinit) float, double -{ - zval z_var; - ZVAL_DOUBLE(&z_var, (double)$1); - zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &z_var); -} - -%typemap(varinit) char -{ - zval z_var; - char c = $1; - ZVAL_STRINGL(&z_var, &c, 1); - zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &z_var); -} - -%typemap(varinit) SWIGTYPE *, SWIGTYPE [] -{ - zval z_var; - SWIG_SetPointerZval(&z_var, (void*)$1, $1_descriptor, 0); - zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &z_var); -} - -%typemap(varinit) SWIGTYPE, SWIGTYPE &, SWIGTYPE && -{ - zval z_var; - SWIG_SetPointerZval(&z_var, (void*)&$1, $&1_descriptor, 0); - zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &z_var); -} - -%typemap(varinit) char [ANY] -{ - zval z_var; - /* varinit char [ANY] */ - ZVAL_STRINGL(&z_var, $1, $1_dim0); - zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &z_var); -} - -%typemap(varinit, fragment="swig_php_init_member_ptr") SWIGTYPE (CLASS::*) -{ - zval resource; - void * p = emalloc(sizeof($1)); - memcpy(p, &$1, sizeof($1)); - ZVAL_RES(&resource, zend_register_resource(p, swig_member_ptr)); - zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &resource); -} - -%typemap(varin) int, unsigned int, short, unsigned short, long, unsigned long, signed char, unsigned char, enum SWIGTYPE -{ - zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); - $1 = zval_get_long(z_var); -} - -%typemap(varin) bool -{ - zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); - convert_to_boolean(z_var); - $1 = (Z_TYPE_P(z_var) == IS_TRUE); -} - -%typemap(varin) double,float -{ - zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); - $1 = zval_get_double(z_var); -} - -%typemap(varin) char -{ - zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); - convert_to_string(z_var); - if ($1 != Z_STRVAL_P(z_var)[0]) { - $1 = Z_STRVAL_P(z_var)[0]; - } -} - -%typemap(varin) char * -{ - zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); - char *s1; - convert_to_string(z_var); - s1 = Z_STRVAL_P(z_var); - if ((s1 == NULL) || ($1 == NULL) || strcmp(s1, $1)) { - if (s1) - $1 = estrdup(s1); - else - $1 = NULL; - } -} - - -%typemap(varin) SWIGTYPE [] -{ - if ($1) { - zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); - SWIG_SetPointerZval(z_var, (void*)$1, $1_descriptor, $owner); - } -} - -%typemap(varin) char [ANY] -{ - zval **z_var; - char *s1; - - zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1, (void**)&z_var); - s1 = Z_STRVAL_P(z_var); - if ((s1 == NULL) || ($1 == NULL) || strcmp(s1, $1)) { - if (s1) - strncpy($1, s1, $1_dim0); - } -} - -%typemap(varin) SWIGTYPE -{ - zval *z_var; - $&1_ltype _temp; - - z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); - if (SWIG_ConvertPtr(z_var, (void**)&_temp, $&1_descriptor, 0) < 0) { - SWIG_PHP_Error(E_ERROR,"Type error in value of $symname. Expected $&1_descriptor"); - } - - $1 = *($&1_ltype)_temp; -} - -%typemap(varin) SWIGTYPE *, SWIGTYPE &, SWIGTYPE && -{ - zval *z_var; - $1_ltype _temp; - - z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); - if (SWIG_ConvertPtr(z_var, (void **)&_temp, $1_descriptor, 0) < 0) { - SWIG_PHP_Error(E_ERROR,"Type error in value of $symname. Expected $&1_descriptor"); - } - - $1 = ($1_ltype)_temp; -} - -%typemap(varin, fragment="swig_php_init_member_ptr") SWIGTYPE (CLASS::*) -{ - zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); - void * p = (void*)zend_fetch_resource_ex(z_var, SWIG_MEMBER_PTR, swig_member_ptr); - memcpy(&$1, p, sizeof($1)); -} - -%typemap(varout) int, - unsigned int, - unsigned short, - short, - long, - unsigned long, - signed char, - unsigned char, - enum SWIGTYPE -{ - zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); - if ($1 != ($1_ltype)Z_LVAL_P(z_var)) { - z_var->value.lval = (long)$1; - } -} - -//SAMFIX need to cast zval->type, what if zend-hash_find fails? etc? -%typemap(varout) bool -{ - zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); - if ($1 != ($1_ltype)Z_LVAL_P(z_var)) { - z_var->value.lval = (long)$1; - } -} - -%typemap(varout) double, float -{ - zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); - if ($1 != ($1_ltype)Z_DVAL_P(z_var)) { - z_var->value.dval = (double)$1; - } -} - -%typemap(varout) char -{ - zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); - char c = $1; - if ($1 != Z_STRVAL_P(z_val)[0]) { - ZVAL_STRING(z_var, &c); - } -} - -%typemap(varout) char * -{ - zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); - const char *s1 = Z_STRVAL_P(z_var); - if ((s1 == NULL) || ($1 == NULL) || strcmp(s1, $1)) { - if (s1) - efree(s1); - if ($1) { - (z_var)->value.str.val = estrdup($1); - (z_var)->value.str.len = strlen($1) + 1; - } else { - (z_var)->value.str.val = 0; - (z_var)->value.str.len = 0; - } - } -} - -%typemap(varout) SWIGTYPE -{ - zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); - SWIG_SetPointerZval(z_var, (void*)&$1, $&1_descriptor, 0); -} - -%typemap(varout) SWIGTYPE [] -{ - if($1) { - zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); - SWIG_SetPointerZval(z_var, (void*)$1, $1_descriptor, 0); - } -} - -%typemap(varout) char [ANY] -{ - zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); - const char *s1 = Z_STRVAL_P(z_var); -deliberate error cos this code looks bogus to me - if ((s1 == NULL) || strcmp(s1, $1)) { - if ($1) { - (z_var)->value.str.val = estrdup($1); - (z_var)->value.str.len = strlen($1) + 1; - } else { - (z_var)->value.str.val = 0; - (z_var)->value.str.len = 0; - } - } -} - -%typemap(varout) SWIGTYPE *, SWIGTYPE &, SWIGTYPE && -{ - zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); - SWIG_SetPointerZval(z_var, (void*)$1, $1_descriptor, 0); -} - -%typemap(varout, fragment="swig_php_init_member_ptr") SWIGTYPE (CLASS::*) -{ - zval resource; - void * p = emalloc(sizeof($1)); - memcpy(p, &$1, sizeof($1)); - ZVAL_RES(&resource, zend_register_resource(p, swig_member_ptr)); - zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &resource); -} diff --git a/Lib/php/php.swg b/Lib/php/php.swg index 4eba6be2a..bf388a75a 100644 --- a/Lib/php/php.swg +++ b/Lib/php/php.swg @@ -4,13 +4,17 @@ * PHP configuration file * ----------------------------------------------------------------------------- */ +// Default to generating PHP type declarations (for PHP >= 8) except for +// cases which are liable to cause compatibility issues with existing +// bindings. +%feature("php:type", "compat"); + %runtime "swigrun.swg" // Common C API type-checking code %runtime "swigerrors.swg" // SWIG errors %runtime "phprun.swg" // PHP runtime functions %include // PHP initialization routine. -%include // Global variables. %include // use %init %{ "/*code goes here*/ " %} @@ -35,107 +39,125 @@ %include -%pass_by_val(bool,CONVERT_BOOL_IN); +%pass_by_val(bool, "bool", CONVERT_BOOL_IN); -%pass_by_val(size_t, CONVERT_INT_IN); +%pass_by_val(size_t, "int", CONVERT_INT_IN); -%pass_by_val(enum SWIGTYPE, CONVERT_INT_IN); +%pass_by_val(enum SWIGTYPE, "int", CONVERT_INT_IN); -%pass_by_val(signed int, CONVERT_INT_IN); -%pass_by_val(int,CONVERT_INT_IN); -%pass_by_val(unsigned int,CONVERT_INT_IN); +%pass_by_val(signed int, "int", CONVERT_INT_IN); +%pass_by_val(int,"int", CONVERT_INT_IN); +%pass_by_val(unsigned int,"int", CONVERT_INT_IN); -%pass_by_val(signed short, CONVERT_INT_IN); -%pass_by_val(short,CONVERT_INT_IN); -%pass_by_val(unsigned short, CONVERT_INT_IN); +%pass_by_val(signed short, "int", CONVERT_INT_IN); +%pass_by_val(short,"int", CONVERT_INT_IN); +%pass_by_val(unsigned short, "int", CONVERT_INT_IN); -%pass_by_val(signed long, CONVERT_INT_IN); -%pass_by_val(long, CONVERT_INT_IN); -%pass_by_val(unsigned long, CONVERT_INT_IN); +%pass_by_val(signed long, "int", CONVERT_INT_IN); +%pass_by_val(long, "int", CONVERT_INT_IN); +%pass_by_val(unsigned long, "int", CONVERT_INT_IN); -%pass_by_val(signed long long, CONVERT_LONG_LONG_IN); -%pass_by_val(long long, CONVERT_LONG_LONG_IN); -%pass_by_val(unsigned long long, CONVERT_UNSIGNED_LONG_LONG_IN); +%pass_by_val(signed long long, "int|string", CONVERT_LONG_LONG_IN); +%pass_by_val(long long, "int|string", CONVERT_LONG_LONG_IN); +%pass_by_val(unsigned long long, "int|string", CONVERT_UNSIGNED_LONG_LONG_IN); -%pass_by_val(signed char, CONVERT_INT_IN); -%pass_by_val(char, CONVERT_CHAR_IN); -%pass_by_val(unsigned char, CONVERT_INT_IN); +%pass_by_val(signed char, "int", CONVERT_INT_IN); +%pass_by_val(char, "string", CONVERT_CHAR_IN); +%pass_by_val(unsigned char, "int", CONVERT_INT_IN); -%pass_by_val(float, CONVERT_FLOAT_IN); +%pass_by_val(float, "float", CONVERT_FLOAT_IN); -%pass_by_val(double, CONVERT_FLOAT_IN); +%pass_by_val(double, "float", CONVERT_FLOAT_IN); -%pass_by_val(char *, CONVERT_STRING_IN); +%pass_by_val(char *, "string", CONVERT_STRING_IN); %typemap(in) char *& = const char *&; %typemap(directorout) char *& = const char *&; // char array can be in/out, though the passed string may not be big enough... // so we have to size it -%typemap(in) char[ANY] +%typemap(in, phptype="string") char[ANY] %{ convert_to_string(&$input); $1 = ($1_ltype) Z_STRVAL($input); %} -%typemap(in) (char *STRING, int LENGTH), (char *STRING, size_t LENGTH) %{ +%typemap(in, phptype="string") (char *STRING, int LENGTH), (char *STRING, size_t LENGTH) %{ convert_to_string(&$input); $1 = ($1_ltype) Z_STRVAL($input); $2 = ($2_ltype) Z_STRLEN($input); %} /* Object passed by value. Convert to a pointer */ -%typemap(in) SWIGTYPE ($&1_ltype tmp) +%typemap(in, phptype="SWIGTYPE") SWIGTYPE ($&1_ltype tmp) %{ - if (SWIG_ConvertPtr(&$input, (void **) &tmp, $&1_descriptor, 0) < 0 || tmp == NULL) { - SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $&1_descriptor"); - } - $1 = *tmp; + if (SWIG_ConvertPtr(&$input, (void **) &tmp, $&1_descriptor, 0) < 0 || tmp == NULL) { + zend_type_error("Expected $&1_descriptor for argument $argnum of $symname"); + return; + } + $1 = *tmp; %} %typemap(directorout) SWIGTYPE ($&1_ltype tmp) %{ - /* If exit was via exception, PHP NULL is returned so skip the conversion. */ - if (!EG(exception)) { - if (SWIG_ConvertPtr($input, (void **) &tmp, $&1_descriptor, 0) < 0 || tmp == NULL) - SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $&1_descriptor"); - $result = *tmp; - } + if (SWIG_ConvertPtr($input, (void **) &tmp, $&1_descriptor, 0) < 0 || tmp == NULL) { + zend_type_error("Expected $&1_descriptor for argument $argnum of $symname"); + SWIG_fail; + } + $result = *tmp; %} -%typemap(in) SWIGTYPE *, +%typemap(in, phptype="?SWIGTYPE") SWIGTYPE *, SWIGTYPE [] %{ - if (SWIG_ConvertPtr(&$input, (void **) &$1, $1_descriptor, 0) < 0) { - SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $1_descriptor"); - } + if (SWIG_ConvertPtr(&$input, (void **) &$1, $1_descriptor, 0) < 0) { + zend_type_error("Expected $1_descriptor for argument $argnum of $symname"); + return; + } %} -%typemap(in) SWIGTYPE & +%typemap(directorout) SWIGTYPE * (swig_owntype own), + SWIGTYPE [] (swig_owntype own) %{ - if (SWIG_ConvertPtr(&$input, (void **) &$1, $1_descriptor, 0) < 0 || $1 == NULL) { - SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $1_descriptor"); - } + if (SWIG_ConvertPtrAndOwn($input, (void **)&$result, $1_descriptor, SWIG_POINTER_DISOWN, &own) < 0) { + zend_type_error("Expected $1_descriptor for argument $argnum of $symname"); + SWIG_fail; + } + swig_acquire_ownership_obj((void*)$result, own); %} -%typemap(in) SWIGTYPE && +%typemap(in, phptype="SWIGTYPE") SWIGTYPE &, + SWIGTYPE && %{ - if (SWIG_ConvertPtr(&$input, (void **) &$1, $1_descriptor, 0) < 0 || $1 == NULL) { - SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $1_descriptor"); - } + if (SWIG_ConvertPtr(&$input, (void **) &$1, $1_descriptor, 0) < 0 || $1 == NULL) { + zend_type_error("Expected $1_descriptor for argument $argnum of $symname"); + return; + } %} -%typemap(in) SWIGTYPE *const& ($*ltype temp) +%typemap(directorout) SWIGTYPE & ($1_ltype tmp), + SWIGTYPE && ($1_ltype tmp) %{ - if (SWIG_ConvertPtr(&$input, (void **) &temp, $*1_descriptor, 0) < 0) { - SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $*1_descriptor"); - } - $1 = ($1_ltype)&temp; + if (SWIG_ConvertPtr($input, (void **) &tmp, $1_descriptor, 0) < 0 || tmp == NULL) { + zend_type_error("Expected $1_descriptor for argument $argnum of $symname"); + SWIG_fail; + } + $result = tmp; %} -%typemap(in) SWIGTYPE *DISOWN +%typemap(in, phptype="?SWIGTYPE") SWIGTYPE *const& ($*ltype temp) %{ - if (SWIG_ConvertPtr(&$input, (void **) &$1, $1_descriptor, SWIG_POINTER_DISOWN ) < 0) { - SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $1_descriptor"); + if (SWIG_ConvertPtr(&$input, (void **) &temp, $*1_descriptor, 0) < 0) { + zend_type_error("Expected $*1_descriptor for argument $argnum of $symname"); + return; + } + $1 = ($1_ltype)&temp; +%} + +%typemap(in, phptype="?SWIGTYPE") SWIGTYPE *DISOWN +%{ + if (SWIG_ConvertPtr(&$input, (void **) &$1, $1_descriptor, SWIG_POINTER_DISOWN) < 0) { + zend_type_error("Expected $1_descriptor for argument $argnum of $symname"); + return; } %} @@ -144,19 +166,22 @@ SWIGTYPE &, SWIGTYPE &&; -%typemap(in) void * +%typemap(in, phptype="?SWIGTYPE") void * %{ - if (SWIG_ConvertPtr(&$input, (void **) &$1, 0, 0) < 0) { - /* Allow NULL from php for void* */ - if (Z_ISNULL($input)) $1=0; - else - SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $1_descriptor"); - } + if (SWIG_ConvertPtr(&$input, (void **) &$1, 0, 0) < 0) { + /* Allow NULL from php for void* */ + if (Z_ISNULL($input)) { + $1=0; + } else { + zend_type_error("Expected $1_descriptor for argument $argnum of $symname"); + return; + } + } %} /* Special case when void* is passed by reference so it can be made to point to opaque api structs */ -%typemap(in) void ** ($*1_ltype ptr, int force), +%typemap(in, phptype="?SWIG\\_p_void", byref=1) void ** ($*1_ltype ptr, int force), void *& ($*1_ltype ptr, int force) { /* If they pass NULL by reference, make it into a void* @@ -165,7 +190,8 @@ /* So... we didn't get a ref or ptr, but we'll accept NULL by reference */ if (!(Z_ISREF($input) && Z_ISNULL_P(Z_REFVAL($input)))) { /* wasn't a pre/ref/thing, OR anything like an int thing */ - SWIG_PHP_Error(E_ERROR, "Type error in argument $arg of $symname."); + zend_throw_exception(zend_ce_type_error, "Type error in argument $arg of $symname", 0); + goto fail; } } force=0; @@ -183,14 +209,15 @@ %typemap(argout) void **, void *& %{ - if (force$argnum) { - SWIG_SetPointerZval(&$input, (void*) ptr$argnum, $*1_descriptor, 1); + if (force$argnum && Z_ISREF($input)) { + SWIG_SetPointerZval(Z_REFVAL($input), (void*) ptr$argnum, $*1_descriptor, 1); } %} /* Typemap for output values */ -%typemap(out) int, +%typemap(out, phptype="int") + int, unsigned int, short, unsigned short, @@ -198,18 +225,17 @@ unsigned long, signed char, unsigned char, - bool, size_t %{ RETVAL_LONG($1); %} -%typemap(out) enum SWIGTYPE +%typemap(out, phptype="int") enum SWIGTYPE %{ RETVAL_LONG((long)$1); %} -%typemap(out) long long +%typemap(out, phptype="int|string") long long %{ if ((long long)LONG_MIN <= $1 && $1 <= (long long)LONG_MAX) { RETVAL_LONG((long)($1)); @@ -219,7 +245,7 @@ RETVAL_STRING(temp); } %} -%typemap(out) unsigned long long +%typemap(out, phptype="int|string") unsigned long long %{ if ($1 <= (unsigned long long)LONG_MAX) { RETVAL_LONG((long)($1)); @@ -230,7 +256,8 @@ } %} -%typemap(out) const int &, +%typemap(out, phptype="int") + const int &, const unsigned int &, const short &, const unsigned short &, @@ -244,17 +271,17 @@ RETVAL_LONG(*$1); %} -%typemap(out) const enum SWIGTYPE & +%typemap(out, phptype="int") const enum SWIGTYPE & %{ RETVAL_LONG((long)*$1); %} -%typemap(out) const enum SWIGTYPE && +%typemap(out, phptype="int") const enum SWIGTYPE && %{ RETVAL_LONG((long)*$1); %} -%typemap(out) const long long & +%typemap(out, phptype="int|string") const long long & %{ if ((long long)LONG_MIN <= *$1 && *$1 <= (long long)LONG_MAX) { RETVAL_LONG((long)(*$1)); @@ -264,7 +291,7 @@ RETVAL_STRING(temp); } %} -%typemap(out) const unsigned long long & +%typemap(out, phptype="int|string") const unsigned long long & %{ if (*$1 <= (unsigned long long)LONG_MAX) { RETVAL_LONG((long)(*$1)); @@ -303,12 +330,12 @@ } %} -%typemap(out) bool +%typemap(out, phptype="bool") bool %{ RETVAL_BOOL(($1) ? 1 : 0); %} -%typemap(out) const bool & +%typemap(out, phptype="bool") const bool & %{ RETVAL_BOOL((*$1) ? 1 : 0); %} @@ -318,13 +345,13 @@ ZVAL_BOOL($input, ($1) ? 1 : 0); %} -%typemap(out) float, +%typemap(out, phptype="float") float, double %{ RETVAL_DOUBLE($1); %} -%typemap(out) const float &, +%typemap(out, phptype="float") const float &, const double & %{ RETVAL_DOUBLE(*$1); @@ -336,18 +363,22 @@ ZVAL_DOUBLE($input, $1); %} -%typemap(out) char +%typemap(out, phptype="string") char %{ RETVAL_STRINGL(&$1, 1); %} -%typemap(out) const char & +%typemap(out, phptype="string") const char & %{ RETVAL_STRINGL(&*$1, 1); %} -%typemap(out) char *, - char [] +%typemap(out, phptype="string") char [] +%{ + RETVAL_STRING((const char *)$1); +%} + +%typemap(out, phptype="?string") char * %{ if (!$1) { RETVAL_NULL(); @@ -356,7 +387,7 @@ } %} -%typemap(out) char *& +%typemap(out, phptype="?string") char *& %{ if (!*$1) { RETVAL_NULL(); @@ -365,17 +396,22 @@ } %} -%typemap(out) SWIGTYPE *, +%typemap(out, phptype="?SWIGTYPE") SWIGTYPE * +%{ + SWIG_SetPointerZval($result, (void *)$1, $1_descriptor, $owner); +%} + +%typemap(out, phptype="SWIGTYPE") SWIGTYPE [], SWIGTYPE &, SWIGTYPE && %{ - SWIG_SetPointerZval(return_value, (void *)$1, $1_descriptor, $owner); + SWIG_SetPointerZval($result, (void *)$1, $1_descriptor, $owner); %} -%typemap(out) SWIGTYPE *const& +%typemap(out, phptype="?SWIGTYPE") SWIGTYPE *const& %{ - SWIG_SetPointerZval(return_value, (void *)*$1, $*1_descriptor, $owner); + SWIG_SetPointerZval($result, (void *)*$1, $*1_descriptor, $owner); %} %typemap(directorin) SWIGTYPE *, @@ -383,53 +419,57 @@ SWIGTYPE &, SWIGTYPE && %{ - SWIG_SetPointerZval($input, (void *)&$1, $1_descriptor, ($owner)|2); + ZVAL_UNDEF($input); + SWIG_SetPointerZval($input, (void *)&$1, $1_descriptor, $owner); %} -%typemap(out, fragment="swig_php_init_member_ptr") SWIGTYPE (CLASS::*) +%typemap(out, phptype="SWIGTYPE") SWIGTYPE (CLASS::*) { void * p = emalloc(sizeof($1)); memcpy(p, &$1, sizeof($1)); - RETVAL_RES(zend_register_resource(p, swig_member_ptr)); + SWIG_SetPointerZval($result, (void *)p, $&1_descriptor, 1); } -%typemap(in, fragment="swig_php_init_member_ptr") SWIGTYPE (CLASS::*) +%typemap(in, phptype="SWIGTYPE") SWIGTYPE (CLASS::*) { - void * p = (void*)zend_fetch_resource_ex(&$input, SWIG_MEMBER_PTR, swig_member_ptr); + void * p = SWIG_Z_FETCH_OBJ_P(&$input)->ptr; memcpy(&$1, p, sizeof($1)); } -%typemap(out) SWIGTYPE *DYNAMIC, - SWIGTYPE &DYNAMIC +%typemap(out, phptype="?SWIGTYPE") SWIGTYPE *DYNAMIC { swig_type_info *ty = SWIG_TypeDynamicCast($1_descriptor, (void **) &$1); - SWIG_SetPointerZval(return_value, (void *)$1, ty, $owner); + SWIG_SetPointerZval($result, (void *)$1, ty, $owner); } -%typemap(out) SWIGTYPE +%typemap(out, phptype="SWIGTYPE") SWIGTYPE &DYNAMIC +{ + swig_type_info *ty = SWIG_TypeDynamicCast($1_descriptor, (void **) &$1); + SWIG_SetPointerZval($result, (void *)$1, ty, $owner); +} + +%typemap(out, phptype="SWIGTYPE") SWIGTYPE +{ #ifdef __cplusplus -{ $&1_ltype resultobj = new $1_ltype((const $1_ltype &) $1); - SWIG_SetPointerZval(return_value, (void *)resultobj, $&1_descriptor, 1); -} #else -{ - $&1_ltype resultobj = ($&1_ltype) emalloc(sizeof($1_type)); + $&1_ltype resultobj = ($&1_ltype) malloc(sizeof($1_type)); memcpy(resultobj, &$1, sizeof($1_type)); - SWIG_SetPointerZval(return_value, (void *)resultobj, $&1_descriptor, 1); -} #endif + SWIG_SetPointerZval($result, (void *)resultobj, $&1_descriptor, 1); +} %typemap(directorin) SWIGTYPE %{ - SWIG_SetPointerZval($input, SWIG_as_voidptr(new $1_ltype((const $1_ltype &)$1)), $&1_descriptor, 1|2); + ZVAL_UNDEF($input); + SWIG_SetPointerZval($input, SWIG_as_voidptr(new $1_ltype((const $1_ltype &)$1)), $&1_descriptor, 1); %} -%typemap(out) void ""; +%typemap(out, phptype="void") void ""; -%typemap(out) char [ANY] +%typemap(out, phptype="string") char [ANY] { - int len = 0; + size_t len = 0; while (len < $1_dim0 && $1[len]) ++len; RETVAL_STRINGL($1, len); } @@ -465,7 +505,10 @@ %php_typecheck(double,SWIG_TYPECHECK_DOUBLE,IS_DOUBLE) %php_typecheck(char,SWIG_TYPECHECK_CHAR,IS_STRING) -%typemap(typecheck,precedence=SWIG_TYPECHECK_STRING) char *, char *&, char [] +%typemap(typecheck,precedence=SWIG_TYPECHECK_STRING) char *, char *& + " $1 = (Z_TYPE($input) == IS_STRING || Z_TYPE($input) == IS_NULL); " + +%typemap(typecheck,precedence=SWIG_TYPECHECK_STRING) char [] " $1 = (Z_TYPE($input) == IS_STRING); " %typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE @@ -512,18 +555,18 @@ unsigned long, unsigned short %{ zend_throw_exception(NULL, "C++ $1_type exception thrown", $1); - return; + goto fail; %} %typemap(throws) SWIGTYPE, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE *, SWIGTYPE [], SWIGTYPE [ANY] %{ (void)$1; zend_throw_exception(NULL, "C++ $1_type exception thrown", 0); - return; + goto fail; %} %typemap(throws) char * %{ zend_throw_exception(NULL, $1, 0); - return; + goto fail; %} /* Array reference typemaps */ @@ -537,3 +580,6 @@ /* php keywords */ %include + +/* PHP known interfaces */ +%include diff --git a/Lib/php/phpinit.swg b/Lib/php/phpinit.swg index 1665f5dc4..40f7b0766 100644 --- a/Lib/php/phpinit.swg +++ b/Lib/php/phpinit.swg @@ -7,19 +7,6 @@ %init %{ SWIG_php_minit { + zend_class_entry SWIGUNUSED internal_ce; SWIG_InitializeModule((void*)&module_number); %} - -%fragment("swig_php_init_member_ptr2", "header") %{ -#define SWIG_MEMBER_PTR "CLASS::*" - -static void swig_member_ptr_dtor(zend_resource *res) { - efree(res->ptr); -} - -static int swig_member_ptr = 0; -%} - -%fragment("swig_php_init_member_ptr", "init", fragment="swig_php_init_member_ptr2") %{ - swig_member_ptr = zend_register_list_destructors_ex(swig_member_ptr_dtor, NULL, SWIG_MEMBER_PTR, module_number); -%} diff --git a/Lib/php/phpinterfaces.i b/Lib/php/phpinterfaces.i new file mode 100644 index 000000000..5b1da8b79 --- /dev/null +++ b/Lib/php/phpinterfaces.i @@ -0,0 +1,62 @@ +/* ----------------------------------------------------------------------------- + * phpinterfaces.i + * + * Define "known" PHP interfaces. + * + * These can be added at MINIT time (which is when PHP loads the extension + * module). + * + * Any interface can be added via phpinterfaces, but looking up the + * zend_class_entry by name has to wait until RINIT time, which means it + * happens for every request. + * ----------------------------------------------------------------------------- */ + +// Note: Abstract interfaces such as "Traversable" can't be used in +// "implements" so are not relevant here. + +%insert(header) %{ + +#define SWIG_PHP_INTERFACE_Iterator_CE zend_ce_iterator +#define SWIG_PHP_INTERFACE_Iterator_HEADER "zend_interfaces.h" + +#define SWIG_PHP_INTERFACE_IteratorAggregate_CE zend_ce_aggregate +#define SWIG_PHP_INTERFACE_IteratorAggregate_HEADER "zend_interfaces.h" + +#define SWIG_PHP_INTERFACE_ArrayAccess_CE zend_ce_arrayaccess +#define SWIG_PHP_INTERFACE_ArrayAccess_HEADER "zend_interfaces.h" + +#define SWIG_PHP_INTERFACE_Serializable_CE zend_ce_serializable +#define SWIG_PHP_INTERFACE_Serializable_HEADER "zend_interfaces.h" + +#define SWIG_PHP_INTERFACE_Countable_CE zend_ce_countable +#define SWIG_PHP_INTERFACE_Countable_HEADER "zend_interfaces.h" + +#define SWIG_PHP_INTERFACE_OuterIterator_CE spl_ce_OuterIterator +#define SWIG_PHP_INTERFACE_OuterIterator_HEADER "ext/spl/spl_iterators.h" + +#define SWIG_PHP_INTERFACE_RecursiveIterator_CE spl_ce_RecursiveIterator +#define SWIG_PHP_INTERFACE_RecursiveIterator_HEADER "ext/spl/spl_iterators.h" + +#define SWIG_PHP_INTERFACE_SeekableIterator_CE spl_ce_SeekableIterator +#define SWIG_PHP_INTERFACE_SeekableIterator_HEADER "ext/spl/spl_iterators.h" + +#define SWIG_PHP_INTERFACE_SplObserver_CE spl_ce_SplObserver +#define SWIG_PHP_INTERFACE_SplObserver_HEADER "ext/spl/spl_observer.h" + +#define SWIG_PHP_INTERFACE_SplSubject_CE spl_ce_SplSubject +#define SWIG_PHP_INTERFACE_SplSubject_HEADER "ext/spl/spl_observer.h" + +#define SWIG_PHP_INTERFACE_DateTimeInterface_CE php_date_get_interface_ce() +#define SWIG_PHP_INTERFACE_DateTimeInterface_HEADER "ext/date/php_date.h" + +// The "json" extension needs to be loaded earlier that us for this to work. +#define SWIG_PHP_INTERFACE_JsonSerializable_CE php_json_serializable_ce +#define SWIG_PHP_INTERFACE_JsonSerializable_HEADER "ext/json/php_json.h" + +// New in PHP 8.0. +#if PHP_MAJOR_VERSION >= 8 +# define SWIG_PHP_INTERFACE_Stringable_CE zend_ce_stringable +# define SWIG_PHP_INTERFACE_Stringable_HEADER "zend_interfaces.h" +#endif + +%} diff --git a/Lib/php/phpkw.swg b/Lib/php/phpkw.swg index 5c5296a1f..443ac8bf8 100644 --- a/Lib/php/phpkw.swg +++ b/Lib/php/phpkw.swg @@ -3,10 +3,13 @@ * ----------------------------------------------------------------------------- */ /* Keyword (case insensitive) */ -#define PHPKW(x) %keywordwarn("'" `x` "' is a PHP keyword, renaming to 'c_" `x` "'",sourcefmt="%(lower)s",rename="c_%s") `x` +#define PHPKW(x) %keywordwarn("'" `x` "' is a PHP keyword",sourcefmt="%(lower)s",rename="c_%s") `x` + +/* Keyword, except ok as a function */ +#define PHPKW_ok_as_function(x) %keywordwarn("'" `x` "' is a PHP keyword, renaming to 'c_" `x` "'",%$not %$isfunction,sourcefmt="%(lower)s",rename="c_%s") `x` /* Class (case insensitive) */ -#define PHPCN(x) %keywordwarn("'" `x` "' is a PHP reserved class name, renaming to 'c_" `x` "'",%$isclass,sourcefmt="%(lower)s",rename="c_%s") `x` +#define PHPCN(x) %keywordwarn("'" `x` "' is a PHP reserved class name",%$isclass,sourcefmt="%(lower)s",rename="c_%s") `x` /* Constant (case insensitive) */ #define PHPBN1a(x) %namewarn(%warningmsg(SWIGWARN_PARSE_BUILTIN_NAME, "enum conflicts with a built-in constant '"`x`"' in PHP"),%$isenumitem,sourcefmt="%(lower)s") `x` @@ -22,7 +25,7 @@ PHPBN2a(X); PHPBN2b(X) %enddef -#define PHPFN(x) %keywordwarn("'" `x` "' is a PHP built-in function, renaming to 'c_" `x` "'",sourcefmt="%(lower)s",%$isfunction,%$not %$ismember,rename="c_%s") `x` +#define PHPFN(x) %keywordwarn("'" `x` "' is a PHP built-in function",sourcefmt="%(lower)s",%$isfunction,%$not %$ismember,rename="c_%s") `x` /* From: http://php.net/manual/en/reserved.keywords.php * "You cannot use any of the following words as constants, class names, @@ -55,6 +58,7 @@ PHPKW(endwhile); PHPKW(extends); PHPKW(final); PHPKW(finally); +PHPKW(fn); // as of PHP 7.4 PHPKW(for); PHPKW(foreach); PHPKW(function); @@ -65,6 +69,7 @@ PHPKW(implements); PHPKW(instanceof); PHPKW(insteadof); PHPKW(interface); +PHPKW(match); // as of PHP 8.0 PHPKW(namespace); PHPKW(new); PHPKW(or); @@ -82,6 +87,11 @@ PHPKW(while); PHPKW(xor); PHPKW(yield); +/* PHP 8.1 made `readonly` a keyword, but (unlike any other keyword it seems) + * it may still be used as a function name. + */ +PHPKW_ok_as_function(readonly); + // Compile-time "magic" constants // From: http://php.net/manual/en/reserved.keywords.php // also at: http://php.net/manual/en/language.constants.predefined.php @@ -119,6 +129,10 @@ PHPBN2(PHP_SAPI); PHPBN2(PHP_EOL); PHPBN2(PHP_INT_MAX); PHPBN2(PHP_INT_SIZE); +PHPBN2(PHP_FLOAT_DIG); // Since 7.2.0 +PHPBN2(PHP_FLOAT_EPSILON); // Since 7.2.0 +PHPBN2(PHP_FLOAT_MIN); // Since 7.2.0 +PHPBN2(PHP_FLOAT_MAX); // Since 7.2.0 PHPBN2(DEFAULT_INCLUDE_PATH); PHPBN2(PEAR_INSTALL_DIR); PHPBN2(PEAR_EXTENSION_DIR); @@ -134,6 +148,7 @@ PHPBN2(PHP_LOCALSTATEDIR); PHPBN2(PHP_CONFIG_FILE_PATH); PHPBN2(PHP_CONFIG_FILE_SCAN_DIR); PHPBN2(PHP_SHLIB_SUFFIX); +PHPBN2(PHP_FD_SETSIZE); // Since 7.1.0 PHPBN2(E_ERROR); PHPBN2(E_WARNING); PHPBN2(E_PARSE); @@ -145,6 +160,7 @@ PHPBN2(E_COMPILE_WARNING); PHPBN2(E_USER_ERROR); PHPBN2(E_USER_WARNING); PHPBN2(E_USER_NOTICE); +PHPBN2(E_RECOVERABLE_ERROR); PHPBN2(E_DEPRECATED); PHPBN2(E_USER_DEPRECATED); PHPBN2(E_ALL); @@ -156,6 +172,9 @@ PHPBN2(__COMPILER_HALT_OFFSET__); PHPBN2(PHP_OUTPUT_HANDLER_START); PHPBN2(PHP_OUTPUT_HANDLER_CONT); PHPBN2(PHP_OUTPUT_HANDLER_END); +/* Since 7.4.0 (Microsoft Windows only) */ +PHPBN2(PHP_WINDOWS_EVENT_CTRL_C); +PHPBN2(PHP_WINDOWS_EVENT_CTRL_BREAK); /* These don't actually seem to be set (tested on Linux, I guess they're * Windows only?) */ PHPBN2(PHP_WINDOWS_NT_DOMAIN_CONTROLLER); @@ -402,21 +421,6 @@ PHPBN2(CURLOPT_TCP_NODELAY); PHPBN2(CURLOPT_TIMEOUT_MS); PHPBN2(CURLOPT_CONNECTTIMEOUT_MS); PHPBN2(GMP_VERSION); -PHPBN2(SWFTEXTFIELD_USEFONT); -PHPBN2(SWFTEXTFIELD_AUTOSIZE); -PHPBN2(SWF_SOUND_NOT_COMPRESSED); -PHPBN2(SWF_SOUND_ADPCM_COMPRESSED); -PHPBN2(SWF_SOUND_MP3_COMPRESSED); -PHPBN2(SWF_SOUND_NOT_COMPRESSED_LE); -PHPBN2(SWF_SOUND_NELLY_COMPRESSED); -PHPBN2(SWF_SOUND_5KHZ); -PHPBN2(SWF_SOUND_11KHZ); -PHPBN2(SWF_SOUND_22KHZ); -PHPBN2(SWF_SOUND_44KHZ); -PHPBN2(SWF_SOUND_8BITS); -PHPBN2(SWF_SOUND_16BITS); -PHPBN2(SWF_SOUND_MONO); -PHPBN2(SWF_SOUND_STEREO); PHPBN2(OPENSSL_VERSION_NUMBER); PHPBN2(SNMP_OID_OUTPUT_FULL); PHPBN2(SNMP_OID_OUTPUT_NUMERIC); @@ -627,27 +631,26 @@ PHPBN2(PGSQL_POLLING_OK); PHPBN2(PGSQL_POLLING_READING); PHPBN2(PGSQL_POLLING_WRITING); -/* Class names reserved by PHP (case insensitive) */ +/* Class names reserved by PHP. */ +/* Check is case insensitive - these *MUST* be listed in lower case here. */ PHPCN(directory); PHPCN(stdclass); PHPCN(__php_incomplete_class); -/* Added in PHP5. */ PHPCN(exception); PHPCN(errorexception); PHPCN(php_user_filter); PHPCN(closure); PHPCN(generator); PHPCN(self); -PHPCN(static); PHPCN(parent); /* http://php.net/manual/en/migration70.incompatible.php#migration70.incompatible.other.classes */ PHPCN(bool); // As of PHP 7.0 PHPCN(int); // As of PHP 7.0 PHPCN(float); // As of PHP 7.0 PHPCN(string); // As of PHP 7.0 -PHPCN(NULL); // As of PHP 7.0 -PHPCN(TRUE); // As of PHP 7.0 -PHPCN(FALSE); // As of PHP 7.0 +PHPCN(null); // As of PHP 7.0 +PHPCN(true); // As of PHP 7.0 +PHPCN(false); // As of PHP 7.0 PHPCN(resource); // As of PHP 7.0 (currently works but reserved) PHPCN(object); // As of PHP 7.0 (currently works but reserved) PHPCN(mixed); // As of PHP 7.0 (currently works but reserved) @@ -655,6 +658,14 @@ PHPCN(numeric); // As of PHP 7.0 (currently works but reserved) /* http://php.net/manual/en/migration71.incompatible.php#migration71.incompatible.invalid-class-names */ PHPCN(iterable); // As of PHP 7.1 PHPCN(void); // As of PHP 7.1 +/* Predefined interfaces and classes, introduced in PHP 7.0.0 */ +PHPCN(arithmeticerror); +PHPCN(assertionerror); +PHPCN(divisionbyzeroerror); +PHPCN(error); +PHPCN(throwable); +PHPCN(parseerror); +PHPCN(typeerror); /* From extensions (which of these are actually predefined depends which * extensions are loaded by default). */ PHPCN(xmlwriter); @@ -866,6 +877,7 @@ PHPFN(unset); // "Language construct" PHPFN(usort); #undef PHPKW +#undef PHPKW_ok_as_function #undef PHPBN1a #undef PHPBN1b #undef PHPBN1 diff --git a/Lib/php/phppointers.i b/Lib/php/phppointers.i index d79697b5e..a4ff3c0bd 100644 --- a/Lib/php/phppointers.i +++ b/Lib/php/phppointers.i @@ -1,16 +1,12 @@ -%define %pass_by_ref( TYPE, CONVERT_IN, CONVERT_OUT ) -%typemap(in, byref=1) TYPE *REF ($*1_ltype tmp), +%define %pass_by_ref( TYPE, PHP_TYPE, CONVERT_IN, CONVERT_OUT ) +%typemap(in,byref=1,phptype=PHP_TYPE) TYPE *REF ($*1_ltype tmp), TYPE &REF ($*1_ltype tmp) %{ - /* First Check for SWIG wrapped type */ - if (Z_ISNULL($input)) { - $1 = 0; - } else if (Z_ISREF($input)) { - /* Not swig wrapped type, so we check if it's a PHP reference type */ - CONVERT_IN(tmp, $*1_ltype, $input); - $1 = &tmp; + if (Z_ISREF($input)) { + CONVERT_IN(tmp, $*1_ltype, $input); + $1 = &tmp; } else { - SWIG_PHP_Error(E_ERROR, SWIG_PHP_Arg_Error_Msg($argnum, Expected a reference)); + zend_type_error(SWIG_PHP_Arg_Error_Msg($argnum, Expected a reference)); } %} %typemap(argout) TYPE *REF, @@ -22,25 +18,25 @@ %} %enddef -%pass_by_ref( size_t, CONVERT_INT_IN, ZVAL_LONG ); +%pass_by_ref( size_t, "int", CONVERT_INT_IN, ZVAL_LONG ); -%pass_by_ref( signed int, CONVERT_INT_IN, ZVAL_LONG ); -%pass_by_ref( int, CONVERT_INT_IN, ZVAL_LONG ); -%pass_by_ref( unsigned int, CONVERT_INT_IN, ZVAL_LONG ); +%pass_by_ref( signed int, "int", CONVERT_INT_IN, ZVAL_LONG ); +%pass_by_ref( int, "int", CONVERT_INT_IN, ZVAL_LONG ); +%pass_by_ref( unsigned int, "int", CONVERT_INT_IN, ZVAL_LONG ); -%pass_by_ref( signed short, CONVERT_INT_IN, ZVAL_LONG ); -%pass_by_ref( short, CONVERT_INT_IN, ZVAL_LONG ); -%pass_by_ref( unsigned short, CONVERT_INT_IN, ZVAL_LONG ); +%pass_by_ref( signed short, "int", CONVERT_INT_IN, ZVAL_LONG ); +%pass_by_ref( short, "int", CONVERT_INT_IN, ZVAL_LONG ); +%pass_by_ref( unsigned short, "int", CONVERT_INT_IN, ZVAL_LONG ); -%pass_by_ref( signed long, CONVERT_INT_IN, ZVAL_LONG ); -%pass_by_ref( long, CONVERT_INT_IN, ZVAL_LONG ); -%pass_by_ref( unsigned long, CONVERT_INT_IN, ZVAL_LONG ); +%pass_by_ref( signed long, "int", CONVERT_INT_IN, ZVAL_LONG ); +%pass_by_ref( long, "int", CONVERT_INT_IN, ZVAL_LONG ); +%pass_by_ref( unsigned long, "int", CONVERT_INT_IN, ZVAL_LONG ); -%pass_by_ref( signed char, CONVERT_INT_IN, ZVAL_LONG ); -%pass_by_ref( char, CONVERT_CHAR_IN, ZVAL_STRING ); -%pass_by_ref( unsigned char, CONVERT_INT_IN, ZVAL_LONG ); +%pass_by_ref( signed char, "int", CONVERT_INT_IN, ZVAL_LONG ); +%pass_by_ref( char, "string", CONVERT_CHAR_IN, ZVAL_STRING ); +%pass_by_ref( unsigned char, "int", CONVERT_INT_IN, ZVAL_LONG ); -%pass_by_ref( float, CONVERT_FLOAT_IN, ZVAL_DOUBLE ); -%pass_by_ref( double, CONVERT_FLOAT_IN, ZVAL_DOUBLE ); +%pass_by_ref( float, "float", CONVERT_FLOAT_IN, ZVAL_DOUBLE ); +%pass_by_ref( double, "float", CONVERT_FLOAT_IN, ZVAL_DOUBLE ); -%pass_by_ref( char *, CONVERT_CHAR_IN, ZVAL_STRING ); +%pass_by_ref( char *, "string", CONVERT_CHAR_IN, ZVAL_STRING ); diff --git a/Lib/php/phprun.swg b/Lib/php/phprun.swg index a07a1b9f8..a49683197 100644 --- a/Lib/php/phprun.swg +++ b/Lib/php/phprun.swg @@ -4,24 +4,44 @@ * PHP runtime library * ----------------------------------------------------------------------------- */ +#define swig_owntype int + #ifdef __cplusplus extern "C" { #endif -#include "zend.h" -#include "zend_API.h" -#include "zend_exceptions.h" + #include "php.h" -#if PHP_MAJOR_VERSION != 7 -# error These bindings need PHP7 - to generate PHP5 bindings use: SWIG < 4.0.0 and swig -php5 +#if PHP_MAJOR_VERSION < 7 +# error These bindings need PHP 7 or later - to generate PHP5 bindings use: SWIG < 4.0.0 and swig -php5 #endif -#include "ext/standard/php_string.h" -#include /* for abort(), used in generated code. */ +#include "zend_inheritance.h" +#include "zend_exceptions.h" +#include "zend_inheritance.h" -/* This indirection is to work around const correctness issues in older PHP. - * FIXME: Remove for PHP7? Or might user code be using it? */ -#define SWIG_ZEND_NAMED_FE(ZN, N, A) ZEND_NAMED_FE(ZN, N, A) +#if PHP_MAJOR_VERSION == 7 +/* These macros were new in PHP 8.0. For PHP 7.x we define them to give the + * same result except without any type declarations. PHP 7.x supports type + * declarations, but not for the return type, and alternate types aren't + * supported, so we don't try to support these. + */ +# define ZEND_BEGIN_ARG_WITH_RETURN_OBJ_TYPE_MASK_EX(name, byref, num_req, classes, types) \ + ZEND_BEGIN_ARG_INFO_EX(name, 0, byref, num_req) +# define ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(name, byref, num_req, types) \ + ZEND_BEGIN_ARG_INFO_EX(name, 0, byref, num_req) + +/* NB We can just ignore `default` here we currently always pass NULL for it + * (this mechanism for specifying default parameter values was new in PHP 8.0 + * so it's not useful while we still want to support PHP7 too). + */ +# define ZEND_ARG_OBJ_TYPE_MASK(byref, name, classes, types, default) \ + ZEND_ARG_INFO(byref, name) +# define ZEND_ARG_TYPE_MASK(byref, name, types, default) \ + ZEND_ARG_INFO(byref, name) +#endif + +#include /* for abort(), used in generated code. */ #define SWIG_BOOL_CONSTANT(N, V) REGISTER_BOOL_CONSTANT(#N, V, CONST_CS | CONST_PERSISTENT) #define SWIG_LONG_CONSTANT(N, V) REGISTER_LONG_CONSTANT(#N, V, CONST_CS | CONST_PERSISTENT) @@ -32,13 +52,27 @@ extern "C" { REGISTER_STRINGL_CONSTANT(#N, &swig_char, 1, CONST_CS | CONST_PERSISTENT);\ } while (0) -/* ZEND_CONSTANT_SET_FLAGS is new in PHP 7.3. */ +/* ZEND_CONSTANT_SET_FLAGS was new in PHP 7.3. */ #ifdef ZEND_CONSTANT_SET_FLAGS # define SWIG_ZEND_CONSTANT_SET_FLAGS ZEND_CONSTANT_SET_FLAGS #else # define SWIG_ZEND_CONSTANT_SET_FLAGS(C, F, N) do { (C)->flags = (F); (C)->module_number = (N); } while (0) #endif +/* zend_object_alloc was new in PHP 7.3. */ +#if PHP_MAJOR_VERSION == 7 && PHP_MINOR_VERSION < 3 +static zend_always_inline void *zend_object_alloc(size_t obj_size, zend_class_entry *ce) { + void *obj = emalloc(obj_size + zend_object_properties_size(ce)); + memset(obj, 0, obj_size - sizeof(zval)); + return obj; +} +#endif + +/* ZEND_THIS was new in PHP 7.4. */ +#ifndef ZEND_THIS +# define ZEND_THIS &EX(This) +#endif + #ifdef __cplusplus } #endif @@ -50,178 +84,136 @@ static int default_error_code = E_ERROR; #define SWIG_PHP_Arg_Error_Msg(argnum,extramsg) "Error in argument " #argnum " "#extramsg -#define SWIG_PHP_Error(code,msg) do { SWIG_ErrorCode() = code; SWIG_ErrorMsg() = msg; SWIG_fail; } while (0) +#define SWIG_PHP_Error(code,msg) do { zend_throw_exception(NULL, msg, code); SWIG_fail; } while (0) #define SWIG_contract_assert(expr,msg) \ - if (!(expr) ) { zend_printf("Contract Assert Failed %s\n",msg ); } else + do { if (!(expr)) zend_printf("Contract Assert Failed %s\n", msg); } while (0) /* Standard SWIG API */ #define SWIG_GetModule(clientdata) SWIG_Php_GetModule() #define SWIG_SetModule(clientdata, pointer) SWIG_Php_SetModule(pointer, *(int*)clientdata) +static zend_class_entry SWIG_Php_swig_wrapped_interface_ce; + +#if PHP_MAJOR_VERSION == 7 +/* zend_class_implements_interface() was new in PHP 8.0. + * + * We could use instanceof_function_ex(C, I, 1) here for 7.4, but for 7.3 + * and earlier that doesn't work, so instead we just provide a compatibility + * implementation which does what zend_class_implements_interface() does in 8.x + * and use that for all 7.x so there are fewer variants to worry about testing. + */ +static int zend_class_implements_interface(const zend_class_entry *class_ce, const zend_class_entry *interface_ce) { + uint32_t i; + if (class_ce->num_interfaces) { + for (i = 0; i < class_ce->num_interfaces; i++) { + if (class_ce->interfaces[i] == interface_ce) { + return 1; + } + } + } + return 0; +} +#endif + /* used to wrap returned objects in so we know whether they are newobject and need freeing, or not */ typedef struct { void * ptr; int newobject; + const swig_type_info * type; + zend_object std; } swig_object_wrapper; +#define SWIG_Z_FETCH_OBJ_P(zv) swig_php_fetch_object(Z_OBJ_P(zv)) + +static inline +swig_object_wrapper * swig_php_fetch_object(zend_object *obj) { + return (swig_object_wrapper *)((char *)obj - XtOffsetOf(swig_object_wrapper, std)); +} + #define SWIG_as_voidptr(a) const_cast< void * >(static_cast< const void * >(a)) static void SWIG_SetPointerZval(zval *z, void *ptr, swig_type_info *type, int newobject) { - /* - * First test for Null pointers. Return those as PHP native NULL - */ - if (!ptr ) { + // Return PHP NULL for a C/C++ NULL pointer. + if (!ptr) { ZVAL_NULL(z); return; } - if (type->clientdata) { - swig_object_wrapper *value; - if (! (*(int *)(type->clientdata))) - zend_error(E_ERROR, "Type: %s failed to register with zend",type->name); - value=(swig_object_wrapper *)emalloc(sizeof(swig_object_wrapper)); - value->ptr=ptr; - value->newobject=(newobject & 1); - if ((newobject & 2) == 0) { - /* Just register the pointer as a resource. */ - ZVAL_RES(z, zend_register_resource(value, *(int *)(type->clientdata))); - } else { - /* - * Wrap the resource in an object, the resource will be accessible - * via the "_cPtr" member. This is currently only used by - * directorin typemaps. - */ - zval resource; - zend_class_entry *ce = NULL; - const char *type_name = type->name+3; /* +3 so: _p_Foo -> Foo */ - size_t type_name_len; - const char * p; - HashTable * ht; - /* Namespace__Foo -> Foo */ - /* FIXME: ugly and goes wrong for classes with __ in their names. */ - while ((p = strstr(type_name, "__")) != NULL) { - type_name = p + 2; - } - type_name_len = strlen(type_name); - - ZVAL_RES(&resource, zend_register_resource(value, *(int *)(type->clientdata))); - if (SWIG_PREFIX_LEN > 0) { - zend_string * classname = zend_string_alloc(SWIG_PREFIX_LEN + type_name_len, 0); - memcpy(classname->val, SWIG_PREFIX, SWIG_PREFIX_LEN); - memcpy(classname->val + SWIG_PREFIX_LEN, type_name, type_name_len); - ce = zend_lookup_class(classname); - zend_string_release(classname); - } else { - zend_string * classname = zend_string_init(type_name, type_name_len, 0); - ce = zend_lookup_class(classname); - zend_string_release(classname); - } - if (ce == NULL) { - /* class does not exist */ - ce = zend_standard_class_def; - } - - ALLOC_HASHTABLE(ht); - zend_hash_init(ht, 1, NULL, NULL, 0); - zend_hash_str_update(ht, "_cPtr", sizeof("_cPtr") - 1, &resource); - object_and_properties_init(z, ce, ht); - } + if (!type->clientdata) { + zend_type_error("Type: %s not registered with zend", type->name); return; } - zend_error(E_ERROR, "Type: %s not registered with zend",type->name); + + { + zend_object *obj; + swig_object_wrapper *value; + if (Z_TYPE_P(z) == IS_OBJECT) { + /* The PHP object is already initialised - this is the case when wrapping + * the return value from a PHP constructor. */ + obj = Z_OBJ_P(z); + } else { + zend_class_entry *ce = (zend_class_entry*)(type->clientdata); + obj = ce->create_object(ce); + ZVAL_OBJ(z, obj); + } + value = swig_php_fetch_object(obj); + value->ptr = ptr; + value->newobject = (newobject & 1); + value->type = type; + } } -/* This pointer conversion routine takes the native pointer p (along with - its type name) and converts it by calling appropriate casting functions - according to ty. The resultant pointer is returned, or NULL is returned - if the pointer can't be cast. - - Sadly PHP has no API to find a type name from a type id, only from an - instance of a resource of the type id, so we have to pass type_name as well. - - The two functions which might call this are: - SWIG_ConvertResourcePtr which gets the type name from the resource - and the registered zend destructors for which we have one per type each - with the type name hard wired in. */ -static void * -SWIG_ConvertResourceData(void * p, const char *type_name, swig_type_info *ty) { - swig_cast_info *tc; - void *result = 0; - - if (!ty) { - /* They don't care about the target type, so just pass on the pointer! */ - return p; - } - - if (! type_name) { - /* can't convert p to ptr type ty if we don't know what type p is */ - return NULL; - } - - /* convert and cast p from type_name to ptr as ty. */ - tc = SWIG_TypeCheck(type_name, ty); - if (tc) { - int newmemory = 0; - result = SWIG_TypeCast(tc, p, &newmemory); - assert(!newmemory); /* newmemory handling not yet implemented */ - } - return result; -} - -/* This function returns a pointer of type ty by extracting the pointer - and type info from the resource in z. z must be a resource. - If it fails, NULL is returned. - It uses SWIG_ConvertResourceData to do the real work. */ -static void * -SWIG_ConvertResourcePtr(zval *z, swig_type_info *ty, int flags) { - swig_object_wrapper *value; - void *p; - const char *type_name; - - if (Z_RES_TYPE_P(z) == -1) return NULL; - value = (swig_object_wrapper *) Z_RES_VAL_P(z); - if (flags & SWIG_POINTER_DISOWN) { - value->newobject = 0; - } - p = value->ptr; - - type_name=zend_rsrc_list_get_rsrc_type(Z_RES_P(z)); - - return SWIG_ConvertResourceData(p, type_name, ty); -} - -/* We allow passing of a RESOURCE pointing to the object or an OBJECT whose - _cPtr is a resource pointing to the object */ +/* We wrap C/C++ pointers as PHP objects. */ static int -SWIG_ConvertPtr(zval *z, void **ptr, swig_type_info *ty, int flags) { +SWIG_ConvertPtrAndOwn(zval *z, void **ptr, swig_type_info *ty, int flags, swig_owntype *own) { + if (own) + *own = 0; + if (z == NULL) { *ptr = 0; - return 0; + return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; } switch (Z_TYPE_P(z)) { case IS_OBJECT: { - HashTable * ht = Z_OBJ_HT_P(z)->get_properties(z); - if (ht) { - zval * _cPtr = zend_hash_str_find(ht, "_cPtr", sizeof("_cPtr") - 1); - if (_cPtr) { - if (Z_TYPE_P(_cPtr) == IS_INDIRECT) { - _cPtr = Z_INDIRECT_P(_cPtr); - } - if (Z_TYPE_P(_cPtr) == IS_RESOURCE) { - *ptr = SWIG_ConvertResourcePtr(_cPtr, ty, flags); - return (*ptr == NULL ? -1 : 0); - } - } + zend_object *obj = Z_OBJ_P(z); + swig_object_wrapper *value; + if (ty && ty->clientdata == (void*)obj->ce) { + // Object is exactly the class asked for - this handles common cases cheaply, + // and in particular the PHP classes we use to wrap a pointer to a non-class. + } else if (!zend_class_implements_interface(obj->ce, &SWIG_Php_swig_wrapped_interface_ce)) { + // Not an object we've wrapped. + return -1; } - break; + + /* convert and cast value->ptr from value->type to ptr as ty. */ + value = swig_php_fetch_object(obj); + if (!ty) { + /* They don't care about the target type, so just pass on the pointer! */ + *ptr = value->ptr; + } else { + swig_cast_info *tc = SWIG_TypeCheckStruct(value->type, ty); + if (tc) { + int newmemory = 0; + *ptr = SWIG_TypeCast(tc, value->ptr, &newmemory); + if (newmemory == SWIG_CAST_NEW_MEMORY) { + assert(own); /* badly formed typemap which will lead to a memory leak - it must set and use own to delete *ptr */ + if (own) + *own |= SWIG_CAST_NEW_MEMORY; + } + } else { + *ptr = NULL; + } + } + if (*ptr == NULL) return SWIG_ERROR; + if (flags & SWIG_POINTER_DISOWN) { + value->newobject = 0; + } + return SWIG_OK; } - case IS_RESOURCE: - *ptr = SWIG_ConvertResourcePtr(z, ty, flags); - return (*ptr == NULL ? -1 : 0); case IS_NULL: *ptr = 0; return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; @@ -230,17 +222,43 @@ SWIG_ConvertPtr(zval *z, void **ptr, swig_type_info *ty, int flags) { return -1; } +static int +SWIG_ConvertPtr(zval *z, void **ptr, swig_type_info *ty, int flags) { + return SWIG_ConvertPtrAndOwn(z, ptr, ty, flags, 0); +} + static const char const_name[] = "swig_runtime_data_type_pointer"; -static swig_module_info *SWIG_Php_GetModule() { +static swig_module_info *SWIG_Php_GetModule(void) { zval *pointer = zend_get_constant_str(const_name, sizeof(const_name) - 1); if (pointer) { if (Z_TYPE_P(pointer) == IS_LONG) { return (swig_module_info *) pointer->value.lval; } - } + } return NULL; } static void SWIG_Php_SetModule(swig_module_info *pointer, int module_number) { REGISTER_LONG_CONSTANT(const_name, (long) pointer, CONST_CS | CONST_PERSISTENT); } + +/* Common parts of the "create_object" object handler. */ +static zend_object *SWIG_Php_do_create_object(zend_class_entry *ce, zend_object_handlers *handlers) { + swig_object_wrapper *obj = (swig_object_wrapper*)zend_object_alloc(sizeof(swig_object_wrapper), ce); + zend_object_std_init(&obj->std, ce); + object_properties_init(&obj->std, ce); + obj->std.handlers = handlers; + obj->newobject = 1; + return &obj->std; +} + +/* Common parts of the "free_obj" object handler. + Returns void* pointer if the C/C++ object should be destroyed. */ +static void* SWIG_Php_free_obj(zend_object *object) { + if (object) { + swig_object_wrapper *obj = swig_php_fetch_object(object); + zend_object_std_dtor(&obj->std); + if (obj->newobject) return obj->ptr; + } + return NULL; +} diff --git a/Lib/php/std_common.i b/Lib/php/std_common.i index 092bf012b..1b69fc779 100644 --- a/Lib/php/std_common.i +++ b/Lib/php/std_common.i @@ -7,4 +7,3 @@ %include %apply size_t { std::size_t }; - diff --git a/Lib/php/std_map.i b/Lib/php/std_map.i index 7c0157353..fed3cf0b3 100644 --- a/Lib/php/std_map.i +++ b/Lib/php/std_map.i @@ -35,7 +35,7 @@ namespace std { map(); map(const map& other); - + unsigned int size() const; void clear(); %extend { diff --git a/Lib/php/std_string.i b/Lib/php/std_string.i index b55751f07..8882c0abe 100644 --- a/Lib/php/std_string.i +++ b/Lib/php/std_string.i @@ -27,19 +27,17 @@ namespace std { $1 = (Z_TYPE($input) == IS_STRING) ? 1 : 0; %} - %typemap(in) string %{ + %typemap(in, phptype="string") string %{ convert_to_string(&$input); $1.assign(Z_STRVAL($input), Z_STRLEN($input)); %} %typemap(directorout) string %{ - if (!EG(exception)) { convert_to_string($input); $result.assign(Z_STRVAL_P($input), Z_STRLEN_P($input)); - } %} - %typemap(out) string %{ + %typemap(out, phptype="string") string %{ ZVAL_STRINGL($result, $1.data(), $1.size()); %} @@ -47,16 +45,16 @@ namespace std { ZVAL_STRINGL($input, $1.data(), $1.size()); %} - %typemap(out) const string & %{ + %typemap(out, phptype="string") const string & %{ ZVAL_STRINGL($result, $1->data(), $1->size()); %} %typemap(throws) string, const string& %{ zend_throw_exception(NULL, $1.c_str(), 0); - return; + goto fail; %} - %typemap(in) const string & ($*1_ltype temp) %{ + %typemap(in, phptype="string") const string & ($*1_ltype temp) %{ convert_to_string(&$input); temp.assign(Z_STRVAL($input), Z_STRLEN($input)); $1 = &temp; @@ -64,7 +62,7 @@ namespace std { /* These next two handle a function which takes a non-const reference to * a std::string and modifies the string. */ - %typemap(in,byref=1) string & ($*1_ltype temp) %{ + %typemap(in,byref=1, phptype="string") string & ($*1_ltype temp) %{ { zval * p = Z_ISREF($input) ? Z_REFVAL($input) : &$input; convert_to_string(p); @@ -74,12 +72,10 @@ namespace std { %} %typemap(directorout) string & ($*1_ltype *temp) %{ - if (!EG(exception)) { convert_to_string($input); temp = new $*1_ltype(Z_STRVAL_P($input), Z_STRLEN_P($input)); swig_acquire_ownership(temp); $result = temp; - } %} %typemap(argout) string & %{ diff --git a/Lib/php/std_vector.i b/Lib/php/std_vector.i index e633bc3ad..382b37ca0 100644 --- a/Lib/php/std_vector.i +++ b/Lib/php/std_vector.i @@ -112,5 +112,3 @@ namespace std { %define specialize_std_vector(T) #warning "specialize_std_vector - specialization for type T no longer needed" %enddef - - diff --git a/Lib/php/stl.i b/Lib/php/stl.i index 04f86014f..38aba67b8 100644 --- a/Lib/php/stl.i +++ b/Lib/php/stl.i @@ -7,4 +7,3 @@ %include %include %include - diff --git a/Lib/php/typemaps.i b/Lib/php/typemaps.i index c248a588e..321b1202c 100644 --- a/Lib/php/typemaps.i +++ b/Lib/php/typemaps.i @@ -25,7 +25,7 @@ * ----------------------------------------------------------------------------- */ %define BOOL_TYPEMAP(TYPE) -%typemap(in) TYPE *INPUT(TYPE temp), TYPE &INPUT(TYPE temp) +%typemap(in, phptype="bool") TYPE *INPUT(TYPE temp), TYPE &INPUT(TYPE temp) %{ convert_to_boolean(&$input); temp = (Z_TYPE($input) == IS_TRUE); @@ -39,7 +39,7 @@ ZVAL_BOOL(&o, temp$argnum); t_output_helper($result, &o); } -%typemap(in) TYPE *REFERENCE (TYPE lvalue), TYPE &REFERENCE (TYPE lvalue) +%typemap(in, phptype="float") TYPE *REFERENCE (TYPE lvalue), TYPE &REFERENCE (TYPE lvalue) %{ convert_to_boolean($input); lvalue = (Z_TYPE_P($input) == IS_TRUE); @@ -52,7 +52,7 @@ %enddef %define DOUBLE_TYPEMAP(TYPE) -%typemap(in) TYPE *INPUT(TYPE temp), TYPE &INPUT(TYPE temp) +%typemap(in, phptype="float") TYPE *INPUT(TYPE temp), TYPE &INPUT(TYPE temp) %{ temp = (TYPE) zval_get_double(&$input); $1 = &temp; @@ -65,7 +65,7 @@ ZVAL_DOUBLE(&o, temp$argnum); t_output_helper($result, &o); } -%typemap(in) TYPE *REFERENCE (TYPE dvalue), TYPE &REFERENCE (TYPE dvalue) +%typemap(in, phptype="float") TYPE *REFERENCE (TYPE dvalue), TYPE &REFERENCE (TYPE dvalue) %{ dvalue = (TYPE) zval_get_double(&$input); $1 = &dvalue; @@ -77,7 +77,7 @@ %enddef %define INT_TYPEMAP(TYPE) -%typemap(in) TYPE *INPUT(TYPE temp), TYPE &INPUT(TYPE temp) +%typemap(in, phptype="int") TYPE *INPUT(TYPE temp), TYPE &INPUT(TYPE temp) %{ temp = (TYPE) zval_get_long(&$input); $1 = &temp; @@ -90,7 +90,7 @@ ZVAL_LONG(&o, temp$argnum); t_output_helper($result, &o); } -%typemap(in) TYPE *REFERENCE (TYPE lvalue), TYPE &REFERENCE (TYPE lvalue) +%typemap(in, phptype="int") TYPE *REFERENCE (TYPE lvalue), TYPE &REFERENCE (TYPE lvalue) %{ lvalue = (TYPE) zval_get_long(&$input); $1 = &lvalue; @@ -128,7 +128,7 @@ INT_TYPEMAP(long long); } t_output_helper($result, &o); } -%typemap(in) TYPE *REFERENCE (long long lvalue) +%typemap(in, phptype="int|string") TYPE *REFERENCE (long long lvalue) %{ CONVERT_LONG_LONG_IN(lvalue, long long, $input) $1 = &lvalue; @@ -153,6 +153,7 @@ INT_TYPEMAP(long long); ZVAL_STRING($result, temp); } %} + INT_TYPEMAP(unsigned long long); %typemap(argout,fragment="t_output_helper") unsigned long long *OUTPUT { @@ -166,7 +167,7 @@ INT_TYPEMAP(unsigned long long); } t_output_helper($result, &o); } -%typemap(in) TYPE *REFERENCE (unsigned long long lvalue) +%typemap(in, phptype="int|string") TYPE *REFERENCE (unsigned long long lvalue) %{ CONVERT_UNSIGNED_LONG_LONG_IN(lvalue, unsigned long long, $input) $1 = &lvalue; @@ -252,7 +253,7 @@ INT_TYPEMAP(unsigned long long); %typemap(argout) unsigned long long &INOUT = unsigned long long *OUTPUT; %typemap(argout) signed char &INOUT = signed char *OUTPUT; -%typemap(in) char INPUT[ANY] ( char temp[$1_dim0] ) +%typemap(in, phptype="string") char INPUT[ANY] ( char temp[$1_dim0] ) %{ convert_to_string(&$input); strncpy(temp, Z_STRVAL($input), $1_dim0); @@ -267,7 +268,7 @@ INT_TYPEMAP(unsigned long long); t_output_helper($result, &o); } -%typemap(in,numinputs=0) void **OUTPUT (int force), +%typemap(in,numinputs=0,phptype="?SWIGTYPE") void **OUTPUT (int force), void *&OUTPUT (int force) %{ /* If they pass NULL by reference, make it into a void* @@ -276,7 +277,8 @@ INT_TYPEMAP(unsigned long long); /* So... we didn't get a ref or ptr, but we'll accept NULL by reference */ if (!(Z_ISREF($input) && Z_ISNULL_P(Z_REFVAL($input)))) { /* wasn't a pre/ref/thing, OR anything like an int thing */ - SWIG_PHP_Error(E_ERROR, "Type error in argument $arg of $symname."); + zend_type_error("Expected reference or NULL for argument $arg of $symname"); + return; } } force=0; diff --git a/Lib/php/utils.i b/Lib/php/utils.i index ed6e08ff4..1343495e0 100644 --- a/Lib/php/utils.i +++ b/Lib/php/utils.i @@ -16,9 +16,9 @@ char * endptr; errno = 0; lvar = (t) strtoll(Z_STRVAL(invar), &endptr, 10); - if (*endptr && !errno) break; - /* FALL THRU */ + if (*endptr == '\0' && !errno) break; } + /* FALL THRU */ default: lvar = (t) zval_get_long(&invar); } @@ -33,9 +33,9 @@ char * endptr; errno = 0; lvar = (t) strtoull(Z_STRVAL(invar), &endptr, 10); - if (*endptr && !errno) break; - /* FALL THRU */ + if (*endptr == '\0' && !errno) break; } + /* FALL THRU */ default: lvar = (t) zval_get_long(&invar); } @@ -63,28 +63,33 @@ } %enddef -%define %pass_by_val( TYPE, CONVERT_IN ) -%typemap(in) TYPE +%define %pass_by_val( TYPE, PHP_TYPE, CONVERT_IN ) +%typemap(in, phptype=PHP_TYPE) TYPE %{ CONVERT_IN($1,$1_ltype,$input); %} -%typemap(in) const TYPE & ($*1_ltype temp) +%typemap(in, phptype=PHP_TYPE) const TYPE & ($*1_ltype temp) %{ CONVERT_IN(temp,$*1_ltype,$input); $1 = &temp; %} %typemap(directorout) TYPE %{ - if (!EG(exception)) { - CONVERT_IN($result, $1_ltype, *$input); - } + CONVERT_IN($result, $1_ltype, *$input); %} -%typemap(directorout) const TYPE & ($*1_ltype temp) +%typemap(directorout) const TYPE & %{ - if (!EG(exception)) { - CONVERT_IN(temp, $*1_ltype, *$input); + $*1_ltype swig_val; + CONVERT_IN(swig_val, $*1_ltype, *$input); + $1_ltype temp = new $*1_ltype(($*1_ltype)swig_val); + swig_acquire_ownership(temp); + $result = temp; +%} +%typemap(directorfree) const TYPE & +%{ + if (director) { + director->swig_release_ownership(%as_voidptr($input)); } - $result = &temp; %} %enddef diff --git a/Lib/pike/pike.swg b/Lib/pike/pike.swg deleted file mode 100644 index a36bf3ad2..000000000 --- a/Lib/pike/pike.swg +++ /dev/null @@ -1,326 +0,0 @@ -/* ----------------------------------------------------------------------------- - * pike.swg - * - * Pike configuration module. - * ----------------------------------------------------------------------------- */ - -%insert(runtime) "swigrun.swg"; // Common C API type-checking code -%insert(runtime) "pikerun.swg"; // Pike run-time code - -%insert(runtime) %{ -#ifdef __cplusplus -extern "C" { -#endif -#include -#include -#include -#ifdef __cplusplus -} -#endif -%} - -/* ----------------------------------------------------------------------------- - * standard typemaps - * ----------------------------------------------------------------------------- */ - -/* --- Input arguments --- */ - -/* Primitive datatypes. */ - -%typemap(in, pikedesc="tInt") - int, unsigned int, short, unsigned short, - long, unsigned long, char, signed char, unsigned char, - bool, enum SWIGTYPE, long long, unsigned long long -{ - if ($input.type != T_INT) - Pike_error("Bad argument: Expected an integer.\n"); - $1 = ($1_ltype) $input.u.integer; -} - -%typemap(in, pikedesc="tFloat") float, double { - if ($input.type != T_FLOAT) - Pike_error("Bad argument: Expected a float.\n"); - $1 = ($1_ltype) $input.u.float_number; -} - -%typemap(in, pikedesc="tStr") char *, char [ANY] { - if ($input.type != T_STRING) - Pike_error("Bad argument: Expected a string.\n"); - $1 = ($1_ltype) STR0($input.u.string); -} - -/* Pointers, references and arrays */ - -%typemap(in) SWIGTYPE *, - SWIGTYPE &, - SWIGTYPE &&, - SWIGTYPE [] - "SWIG_ConvertPtr($input.u.object, (void **) &$1, $1_descriptor, 1);" - -/* Void pointer. Accepts any kind of pointer */ -%typemap(in) void * "/* FIXME */"; - -/* Object passed by value. Convert to a pointer */ -%typemap(in) SWIGTYPE ($&1_ltype argp) "/* FIXME */"; - -/* Pointer to a class member */ -%typemap(in) SWIGTYPE (CLASS::*) "/* FIXME */"; - -/* Const primitive references. Passed by value */ - -%typemap(in, pikedesc="tInt") const int & (int temp), - const short & (short temp), - const long & (long temp), - const unsigned int & (unsigned int temp), - const unsigned short & (unsigned short temp), - const unsigned long & (unsigned long temp), - const char & (char temp), - const signed char & (signed char temp), - const unsigned char & (unsigned char temp), - const bool & (bool temp), - const long long & ($*1_ltype temp), - const unsigned long long & ($*1_ltype temp), - const enum SWIGTYPE & ($*1_ltype temp), - const enum SWIGTYPE && ($*1_ltype temp) -{ - if ($input.type != T_INT) - Pike_error("Bad argument: Expected an integer.\n"); - temp = ($*1_ltype) $input.u.integer; - $1 = &temp; -} - -%typemap(in, pikedesc="tFloat") const float & (float temp), - const double & (double temp) -{ - if ($input.type != T_FLOAT) - Pike_error("Bad argument: Expected a float.\n"); - temp = ($*1_ltype) $input.u.float_number; - $1 = &temp; -} - -/* ----------------------------------------------------------------------------- - * Output Typemaps - * ----------------------------------------------------------------------------- */ -%typemap(out, pikedesc="tInt") - int, unsigned int, - short, unsigned short, - long, unsigned long, - char, signed char, unsigned char, - bool, enum SWIGTYPE - "push_int($1);"; - -%typemap(out, pikedesc="tInt") long long "push_int64($1);"; -%typemap(out, pikedesc="tInt") unsigned long long "push_int64($1);"; -%typemap(out, pikedesc="tFloat") float, double "push_float($1);"; -%typemap(out, pikedesc="tStr") char * "push_text($1);"; - -/* Pointers, references, and arrays */ -%typemap(out, pikedesc="tObj") SWIGTYPE*, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] "push_object(SWIG_NewPointerObj((void *) $1, $1_descriptor, $owner));"; - -/* Void return value; don't push anything */ -%typemap(out, pikedesc="tVoid") void ""; - -/* Dynamic casts */ - -%typemap(out) SWIGTYPE *DYNAMIC, SWIGTYPE &DYNAMIC "/* FIXME */"; - -/* Member pointer */ -%typemap(out) SWIGTYPE (CLASS::*) "/* FIXME */"; - -/* Special typemap for character array return values */ -%typemap(out, pikedesc="tStr") char [ANY], const char [ANY] "push_text($1);"; - -/* Primitive types--return by value */ -%typemap(out, pikedesc="tObj") SWIGTYPE -#ifdef __cplusplus -{ - $&1_ltype resultptr; - resultptr = new $1_ltype((const $1_ltype &) $1); - push_object(SWIG_NewPointerObj((void *) resultptr, $&1_descriptor, 1)); -} -#else -{ - $&1_ltype resultptr; - resultptr = ($&1_ltype) malloc(sizeof($1_type)); - memmove(resultptr, &$1, sizeof($1_type)); - push_object(SWIG_NewPointerObj((void *) resultptr, $&1_descriptor, 1)); -} -#endif - -/* References to primitive types. Return by value */ - -%typemap(out, pikedesc="tInt") const int &, const unsigned int &, - const short &, const unsigned short &, - const long &, const unsigned long &, - const char &, const signed char &, const unsigned char &, - const bool &, - const long long &, const unsigned long long &, - const enum SWIGTYPE & ($*1_ltype temp), - const enum SWIGTYPE && ($*1_ltype temp) - "push_int(*($1));"; - -%typemap(out, pikedesc="tFloat") const float &, const double & "push_float(*($1));"; - -/************************ Constant Typemaps *****************************/ - -%typemap(constant) - int, unsigned int, - short, unsigned short, - long, unsigned long, - signed char, unsigned char, - bool, enum SWIGTYPE, - long long, unsigned long long - "add_integer_constant(\"$symname\", $1, 0);"; - -%typemap(constant) char - "add_integer_constant(\"$symname\", '$1', 0);"; - -%typemap(constant) long long, unsigned long long - "add_integer_constant(\"$symname\", $1, 0);"; - -%typemap(constant) float, double - "add_float_constant(\"$symname\", $1, 0);"; - -%typemap(constant) char * - "add_string_constant(\"$symname\", \"$1\", 0);"; - -/* ------------------------------------------------------------ - * String & length - * ------------------------------------------------------------ */ - -%typemap(in) (char *STRING, int LENGTH), (char *STRING, size_t LENGTH) { - if ($input.type != T_STRING) - Pike_error("Bad argument: Expected a string.\n"); - $1 = ($1_ltype) STR0($input.u.string); - $2 = ($2_ltype) $input.u.string->length; -} - -/* ------------------------------------------------------------ - * ANSI C typemaps - * ------------------------------------------------------------ */ - -%typemap(in, pikedesc="tInt") size_t { - if ($input.type != T_INT) - Pike_error("Bad argument: Expected an integer.\n"); - $1 = ($1_ltype) $input.u.integer; -} - -%typemap(out) size_t = long; - -/* ------------------------------------------------------------ - * Typechecking rules - * ------------------------------------------------------------ */ - -%typecheck(SWIG_TYPECHECK_INTEGER) - int, short, long, - unsigned int, unsigned short, unsigned long, - signed char, unsigned char, - long long, unsigned long long, - const int &, const short &, const long &, - const unsigned int &, const unsigned short &, const unsigned long &, - const long long &, const unsigned long long &, - enum SWIGTYPE, enum SWIGTYPE &, SWIGTYPE &&, - bool, const bool & -{ - $1 = ($input.type == T_INT) ? 1 : 0; -} - -%typecheck(SWIG_TYPECHECK_DOUBLE) - float, double, - const float &, const double & -{ - $1 = (($input.type == T_FLOAT) || ($input.type == T_INT)) ? 1 : 0; -} - -%typecheck(SWIG_TYPECHECK_CHAR) char { - $1 = ($input.type == T_INT) ? 1 : 0; -} - -%typecheck(SWIG_TYPECHECK_STRING) char * { - $1 = ($input.type == T_STRING) ? 1 : 0; -} - -%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] { - void *ptr; - if (SWIG_ConvertPtr($input.u.object, (void **) &ptr, $1_descriptor, 0) == -1) { - $1 = 0; - } else { - $1 = 1; - } -} - -%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE { - void *ptr; - if (SWIG_ConvertPtr($input.u.object, (void **) &ptr, $&1_descriptor, 0) == -1) { - $1 = 0; - } else { - $1 = 1; - } -} - -%typecheck(SWIG_TYPECHECK_VOIDPTR) void * { - void *ptr; - if (SWIG_ConvertPtr($input.u.object, (void **) &ptr, 0, 0) == -1) { - $1 = 0; - } else { - $1 = 1; - } -} - -/* Array reference typemaps */ -%apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } -%apply SWIGTYPE && { SWIGTYPE ((&&)[ANY]) } - -/* const pointers */ -%apply SWIGTYPE * { SWIGTYPE *const } -%apply SWIGTYPE (CLASS::*) { SWIGTYPE (CLASS::*const) } -%apply SWIGTYPE & { SWIGTYPE (CLASS::*const&) } - -/* ------------------------------------------------------------ - * Overloaded operator support - * ------------------------------------------------------------ */ - -#ifdef __cplusplus -%rename("`+") *::operator+; -%rename("`-") *::operator-; -%rename("`*") *::operator*; -%rename("`/") *::operator/; -%rename("`%") *::operator%; -%rename("`<<") *::operator<<; -%rename("`>>") *::operator>>; -%rename("`&") *::operator&; -%rename("`|") *::operator|; -%rename("`^") *::operator^; -%rename("`~") *::operator~; -%rename("`<") *::operator<; -%rename("`>") *::operator>; -%rename("`==") *::operator==; - -/* Special cases */ -%rename("`()") *::operator(); - -#endif - -/* ------------------------------------------------------------ - * The start of the Pike initialization function - * ------------------------------------------------------------ */ - -%init "swiginit.swg" - -%init %{ -#ifdef __cplusplus -extern "C" -#endif -PIKE_MODULE_EXIT {} - -#ifdef __cplusplus -extern "C" -#endif -PIKE_MODULE_INIT -{ - struct program *pr; - SWIG_InitializeModule(0); -%} - -/* pike keywords */ -%include diff --git a/Lib/pike/pikekw.swg b/Lib/pike/pikekw.swg deleted file mode 100644 index 844b1f189..000000000 --- a/Lib/pike/pikekw.swg +++ /dev/null @@ -1,55 +0,0 @@ -#ifndef PIKE_PIKEKW_SWG_ -#define PIKE_PIKEKW_SWG_ - -/* Warnings for Pike keywords */ -#define PIKEKW(x) %namewarn("314: '" #x "' is a pike keyword") #x - -/* - from - http://www.http://docs.linux.cz/pike/tutorial_C.html - -*/ - - -PIKEKW(array); -PIKEKW(break); -PIKEKW(case); -PIKEKW(catch); -PIKEKW(continue); -PIKEKW(default); -PIKEKW(do); -PIKEKW(else); -PIKEKW(float); -PIKEKW(for); -PIKEKW(foreach); -PIKEKW(function); -PIKEKW(gauge); -PIKEKW(if); -PIKEKW(inherit); -PIKEKW(inline); -PIKEKW(int); -PIKEKW(lambda); -PIKEKW(mapping); -PIKEKW(mixed); -PIKEKW(multiset); -PIKEKW(nomask); -PIKEKW(object); -PIKEKW(predef); -PIKEKW(private); -PIKEKW(program); -PIKEKW(protected); -PIKEKW(public); -PIKEKW(return); -PIKEKW(sscanf); -PIKEKW(static); -PIKEKW(string); -PIKEKW(switch); -PIKEKW(typeof); -PIKEKW(varargs); -PIKEKW(void); -PIKEKW(while); - - -#undef PIKEKW - -#endif //PIKE_PIKEKW_SWG_ diff --git a/Lib/pike/pikerun.swg b/Lib/pike/pikerun.swg deleted file mode 100644 index 6ec1143cf..000000000 --- a/Lib/pike/pikerun.swg +++ /dev/null @@ -1,71 +0,0 @@ -/* ----------------------------------------------------------------------------- - * pikerun.swg - * - * This file contains the runtime support for Pike modules - * and includes code for managing global variables and pointer - * type checking. - * ----------------------------------------------------------------------------- */ - -#ifdef __cplusplus -extern "C" { -#endif -#include "pike/object.h" -#include "pike/program.h" -#ifdef __cplusplus -} -#endif -#include - -/* Stores information about a wrapped object */ -typedef struct swig_object_wrapper { - void *self; - swig_type_info *type; -} swig_object_wrapper; - -#ifdef THIS -#undef THIS -#endif -#define THIS (((swig_object_wrapper *) Pike_fp->current_storage)->self) - -#define SWIG_ConvertPtr SWIG_Pike_ConvertPtr -#define SWIG_NewPointerObj SWIG_Pike_NewPointerObj -#define SWIG_GetModule(clientdata) SWIG_Pike_GetModule(clientdata) -#define SWIG_SetModule(clientdata, pointer) SWIG_Pike_SetModule(pointer) - -/* These need to be filled in before type sharing between modules will work */ -static swig_module_info *SWIG_Pike_GetModule(void *SWIGUNUSEDPARM(clientdata)) { - return 0; -} - -static void SWIG_Pike_SetModule(swig_module_info *pointer) { - -} - -/* Convert a pointer value */ -static int -SWIG_Pike_ConvertPtr(struct object *obj, void **ptr, swig_type_info *ty, int flags) { - struct program *pr; - swig_cast_info *tc; - swig_object_wrapper *obj_wrapper; - - if (ty) { - pr = (struct program *) ty->clientdata; - obj_wrapper = (swig_object_wrapper *) get_storage(obj, pr); - if (obj_wrapper && obj_wrapper->type) { - tc = SWIG_TypeCheckStruct(obj_wrapper->type, ty); - if (tc) { - int newmemory = 0; - *ptr = SWIG_TypeCast(tc, obj_wrapper->self, &newmemory); - assert(!newmemory); /* newmemory handling not yet implemented */ - return 0; - } - } - } - return -1; -} - -/* Create a new pointer object */ -static struct object * -SWIG_Pike_NewPointerObj(void *ptr, swig_type_info *type, int own) { - return 0; -} diff --git a/Lib/pike/std_string.i b/Lib/pike/std_string.i deleted file mode 100644 index b32b3c112..000000000 --- a/Lib/pike/std_string.i +++ /dev/null @@ -1,60 +0,0 @@ -/* ----------------------------------------------------------------------------- - * std_string.i - * - * SWIG typemaps for std::string - * ----------------------------------------------------------------------------- */ - -%{ -#include -%} - -namespace std { - - %naturalvar string; - - class string; - - /* Overloading check */ - - %typemap(typecheck) string = char *; - %typemap(typecheck) const string & = char *; - - %typemap(in, pikedesc="tStr") string { - if ($input.type != T_STRING) - Pike_error("Bad argument: Expected a string.\n"); - $1.assign(STR0($input.u.string)); - } - - %typemap(in, pikedesc="tStr") const string & ($*1_ltype temp) { - if ($input.type != T_STRING) - Pike_error("Bad argument: Expected a string.\n"); - temp.assign(STR0($input.u.string)); - $1 = &temp; - } - - %typemap(out, pikedesc="tStr") string "push_text($1.c_str());"; - - %typemap(out, pikedesc="tStr") const string & "push_text($1->c_str());"; - - %typemap(directorin) string, const string &, string & "$1.c_str()"; - - %typemap(directorin) string *, const string * "$1->c_str()"; - - %typemap(directorout) string { - if ($input.type == T_STRING) - $result.assign(STR0($input.u.string)); - else - throw Swig::DirectorTypeMismatchException("string expected"); - } - - %typemap(directorout) const string & ($*1_ltype temp) { - if ($input.type == T_STRING) { - temp.assign(STR0($input.u.string)); - $result = &temp; - } else { - throw Swig::DirectorTypeMismatchException("string expected"); - } - } - -} - diff --git a/Lib/python/builtin.swg b/Lib/python/builtin.swg index 5308748b7..ec092233d 100644 --- a/Lib/python/builtin.swg +++ b/Lib/python/builtin.swg @@ -414,10 +414,10 @@ SwigPyBuiltin_ThisClosure (PyObject *self, void *SWIGUNUSEDPARM(closure)) { SWIGINTERN void SwigPyBuiltin_SetMetaType (PyTypeObject *type, PyTypeObject *metatype) { -#if PY_VERSION_HEX >= 0x03000000 - type->ob_base.ob_base.ob_type = metatype; +#if PY_VERSION_HEX >= 0x030900A4 + Py_SET_TYPE(type, metatype); #else - type->ob_type = metatype; + Py_TYPE(type) = metatype; #endif } diff --git a/Lib/python/ccomplex.i b/Lib/python/ccomplex.i index 28872b985..b99f96a48 100644 --- a/Lib/python/ccomplex.i +++ b/Lib/python/ccomplex.i @@ -12,15 +12,16 @@ #include %} +#define complex _Complex /* C complex constructor */ #define CCplxConst(r, i) ((r) + I*(i)) -%swig_cplxflt_convn(float complex, CCplxConst, creal, cimag); -%swig_cplxdbl_convn(double complex, CCplxConst, creal, cimag); -%swig_cplxdbl_convn(complex, CCplxConst, creal, cimag); +%swig_cplxflt_convn(float _Complex, CCplxConst, creal, cimag); +%swig_cplxdbl_convn(double _Complex, CCplxConst, creal, cimag); +%swig_cplxdbl_convn(_Complex, CCplxConst, creal, cimag); /* declaring the typemaps */ -%typemaps_primitive(SWIG_TYPECHECK_CPLXFLT, float complex); -%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, double complex); -%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, complex); +%typemaps_primitive(SWIG_TYPECHECK_CPLXFLT, float _Complex); +%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, double _Complex); +%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, _Complex); diff --git a/Lib/python/defarg.swg b/Lib/python/defarg.swg index 59450bd82..ba5ff43d4 100644 --- a/Lib/python/defarg.swg +++ b/Lib/python/defarg.swg @@ -33,5 +33,5 @@ SWIGINTERN PyObject *swig_call_defargs(PyObject *self, PyObject *args) { SWIG_PYTHON_THREAD_END_BLOCK; return NULL; } - return PyEval_CallObject(func,parms); + return PyObject_Call(func, parms, NULL); } diff --git a/Lib/python/pybuffer.i b/Lib/python/pybuffer.i index 577eb69c8..2fdaa6d6e 100644 --- a/Lib/python/pybuffer.i +++ b/Lib/python/pybuffer.i @@ -17,13 +17,13 @@ int res; Py_ssize_t size = 0; void *buf = 0; Py_buffer view; res = PyObject_GetBuffer($input, &view, PyBUF_WRITABLE); - size = view.len; - buf = view.buf; - PyBuffer_Release(&view); if (res < 0) { PyErr_Clear(); %argument_fail(res, "(TYPEMAP, SIZE)", $symname, $argnum); } + size = view.len; + buf = view.buf; + PyBuffer_Release(&view); $1 = ($1_ltype) buf; $2 = ($2_ltype) (size/sizeof($*1_type)); } @@ -47,12 +47,12 @@ int res; void *buf = 0; Py_buffer view; res = PyObject_GetBuffer($input, &view, PyBUF_WRITABLE); - buf = view.buf; - PyBuffer_Release(&view); if (res < 0) { PyErr_Clear(); %argument_fail(res, "(TYPEMAP)", $symname, $argnum); } + buf = view.buf; + PyBuffer_Release(&view); $1 = ($1_ltype) buf; } %enddef @@ -76,13 +76,13 @@ int res; Py_ssize_t size = 0; const void *buf = 0; Py_buffer view; res = PyObject_GetBuffer($input, &view, PyBUF_CONTIG_RO); - size = view.len; - buf = view.buf; - PyBuffer_Release(&view); if (res < 0) { PyErr_Clear(); %argument_fail(res, "(TYPEMAP, SIZE)", $symname, $argnum); } + size = view.len; + buf = view.buf; + PyBuffer_Release(&view); $1 = ($1_ltype) buf; $2 = ($2_ltype) (size / sizeof($*1_type)); } @@ -108,14 +108,12 @@ int res; const void *buf = 0; Py_buffer view; res = PyObject_GetBuffer($input, &view, PyBUF_CONTIG_RO); - buf = view.buf; - PyBuffer_Release(&view); if (res < 0) { + PyErr_Clear(); %argument_fail(res, "(TYPEMAP)", $symname, $argnum); } + buf = view.buf; + PyBuffer_Release(&view); $1 = ($1_ltype) buf; } %enddef - - - diff --git a/Lib/python/pycomplex.swg b/Lib/python/pycomplex.swg index 087c50f90..28c963617 100644 --- a/Lib/python/pycomplex.swg +++ b/Lib/python/pycomplex.swg @@ -65,7 +65,7 @@ SWIG_AsVal(Type)(PyObject *o, Type *val) float re; int res = SWIG_AddCast(SWIG_AsVal(float)(o, &re)); if (SWIG_IsOK(res)) { - if (val) *val = Constructor(re, 0.0); + if (val) *val = Constructor(re, 0.0f); return res; } } diff --git a/Lib/python/pyerrors.swg b/Lib/python/pyerrors.swg index dcd99c939..2628de8e6 100644 --- a/Lib/python/pyerrors.swg +++ b/Lib/python/pyerrors.swg @@ -95,8 +95,12 @@ SWIG_Python_RaiseOrModifyTypeError(const char *message) #else newvalue = PyString_FromFormat("%s\nAdditional information:\n%s", PyString_AsString(value), message); #endif - Py_XDECREF(value); - PyErr_Restore(type, newvalue, traceback); + if (newvalue) { + Py_XDECREF(value); + PyErr_Restore(type, newvalue, traceback); + } else { + PyErr_Restore(type, value, traceback); + } } else { /* Raise TypeError using given message */ PyErr_SetString(PyExc_TypeError, message); diff --git a/Lib/python/pyhead.swg b/Lib/python/pyhead.swg index b3bd39dfc..669990719 100644 --- a/Lib/python/pyhead.swg +++ b/Lib/python/pyhead.swg @@ -13,7 +13,6 @@ #define PyString_Size(str) PyBytes_Size(str) #define PyString_InternFromString(key) PyUnicode_InternFromString(key) #define Py_TPFLAGS_HAVE_CLASS Py_TPFLAGS_BASETYPE -#define PyString_AS_STRING(x) PyUnicode_AS_STRING(x) #define _PyLong_FromSsize_t(x) PyLong_FromSsize_t(x) #endif @@ -79,8 +78,7 @@ SWIG_Python_str_FromChar(const char *c) # define PyObject_DEL PyObject_Del #endif -// SWIGPY_USE_CAPSULE is no longer used within SWIG itself, but some user -// interface files check for it. +/* SWIGPY_USE_CAPSULE is no longer used within SWIG itself, but some user interface files check for it. */ # define SWIGPY_USE_CAPSULE # define SWIGPY_CAPSULE_NAME ("swig_runtime_data" SWIG_RUNTIME_VERSION ".type_pointer_capsule" SWIG_TYPE_TABLE_NAME) diff --git a/Lib/python/pyinit.swg b/Lib/python/pyinit.swg index a6d609d56..53ee5a318 100644 --- a/Lib/python/pyinit.swg +++ b/Lib/python/pyinit.swg @@ -8,6 +8,8 @@ %fragment(""); // For offsetof #endif +#if defined SWIGPYTHON_FASTPROXY && !defined SWIGPYTHON_BUILTIN + %insert(runtime) %{ #ifdef __cplusplus extern "C" { @@ -24,226 +26,14 @@ SWIGINTERN PyObject *SWIG_PyStaticMethod_New(PyObject *SWIGUNUSEDPARM(self), PyO #endif %} +#endif + %init %{ #ifdef __cplusplus extern "C" { #endif -/* Python-specific SWIG API */ -#define SWIG_newvarlink() SWIG_Python_newvarlink() -#define SWIG_addvarlink(p, name, get_attr, set_attr) SWIG_Python_addvarlink(p, name, get_attr, set_attr) -#define SWIG_InstallConstants(d, constants) SWIG_Python_InstallConstants(d, constants) - -/* ----------------------------------------------------------------------------- - * global variable support code. - * ----------------------------------------------------------------------------- */ - -typedef struct swig_globalvar { - char *name; /* Name of global variable */ - PyObject *(*get_attr)(void); /* Return the current value */ - int (*set_attr)(PyObject *); /* Set the value */ - struct swig_globalvar *next; -} swig_globalvar; - -typedef struct swig_varlinkobject { - PyObject_HEAD - swig_globalvar *vars; -} swig_varlinkobject; - -SWIGINTERN PyObject * -swig_varlink_repr(swig_varlinkobject *SWIGUNUSEDPARM(v)) { -#if PY_VERSION_HEX >= 0x03000000 - return PyUnicode_InternFromString(""); -#else - return PyString_FromString(""); -#endif -} - -SWIGINTERN PyObject * -swig_varlink_str(swig_varlinkobject *v) { -#if PY_VERSION_HEX >= 0x03000000 - PyObject *str = PyUnicode_InternFromString("("); - PyObject *tail; - PyObject *joined; - swig_globalvar *var; - for (var = v->vars; var; var=var->next) { - tail = PyUnicode_FromString(var->name); - joined = PyUnicode_Concat(str, tail); - Py_DecRef(str); - Py_DecRef(tail); - str = joined; - if (var->next) { - tail = PyUnicode_InternFromString(", "); - joined = PyUnicode_Concat(str, tail); - Py_DecRef(str); - Py_DecRef(tail); - str = joined; - } - } - tail = PyUnicode_InternFromString(")"); - joined = PyUnicode_Concat(str, tail); - Py_DecRef(str); - Py_DecRef(tail); - str = joined; -#else - PyObject *str = PyString_FromString("("); - swig_globalvar *var; - for (var = v->vars; var; var=var->next) { - PyString_ConcatAndDel(&str,PyString_FromString(var->name)); - if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(", ")); - } - PyString_ConcatAndDel(&str,PyString_FromString(")")); -#endif - return str; -} - -SWIGINTERN void -swig_varlink_dealloc(swig_varlinkobject *v) { - swig_globalvar *var = v->vars; - while (var) { - swig_globalvar *n = var->next; - free(var->name); - free(var); - var = n; - } -} - -SWIGINTERN PyObject * -swig_varlink_getattr(swig_varlinkobject *v, char *n) { - PyObject *res = NULL; - swig_globalvar *var = v->vars; - while (var) { - if (strcmp(var->name,n) == 0) { - res = (*var->get_attr)(); - break; - } - var = var->next; - } - if (res == NULL && !PyErr_Occurred()) { - PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); - } - return res; -} - -SWIGINTERN int -swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) { - int res = 1; - swig_globalvar *var = v->vars; - while (var) { - if (strcmp(var->name,n) == 0) { - res = (*var->set_attr)(p); - break; - } - var = var->next; - } - if (res == 1 && !PyErr_Occurred()) { - PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); - } - return res; -} - -SWIGINTERN PyTypeObject* -swig_varlink_type(void) { - static char varlink__doc__[] = "Swig var link object"; - static PyTypeObject varlink_type; - static int type_init = 0; - if (!type_init) { - const PyTypeObject tmp = { -#if PY_VERSION_HEX >= 0x03000000 - PyVarObject_HEAD_INIT(NULL, 0) -#else - PyObject_HEAD_INIT(NULL) - 0, /* ob_size */ -#endif - "swigvarlink", /* tp_name */ - sizeof(swig_varlinkobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor) swig_varlink_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - (getattrfunc) swig_varlink_getattr, /* tp_getattr */ - (setattrfunc) swig_varlink_setattr, /* tp_setattr */ - 0, /* tp_compare */ - (reprfunc) swig_varlink_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - (reprfunc) swig_varlink_str, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - 0, /* tp_flags */ - varlink__doc__, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */ - 0, /* tp_del */ - 0, /* tp_version_tag */ -#if PY_VERSION_HEX >= 0x03040000 - 0, /* tp_finalize */ -#endif -#if PY_VERSION_HEX >= 0x03080000 - 0, /* tp_vectorcall */ -#endif -#if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000) - 0, /* tp_print */ -#endif -#ifdef COUNT_ALLOCS - 0, /* tp_allocs */ - 0, /* tp_frees */ - 0, /* tp_maxalloc */ - 0, /* tp_prev */ - 0 /* tp_next */ -#endif - }; - varlink_type = tmp; - type_init = 1; - if (PyType_Ready(&varlink_type) < 0) - return NULL; - } - return &varlink_type; -} - -/* Create a variable linking object for use later */ -SWIGINTERN PyObject * -SWIG_Python_newvarlink(void) { - swig_varlinkobject *result = PyObject_NEW(swig_varlinkobject, swig_varlink_type()); - if (result) { - result->vars = 0; - } - return ((PyObject*) result); -} - -SWIGINTERN void -SWIG_Python_addvarlink(PyObject *p, const char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) { - swig_varlinkobject *v = (swig_varlinkobject *) p; - swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar)); - if (gv) { - size_t size = strlen(name)+1; - gv->name = (char *)malloc(size); - if (gv->name) { - memcpy(gv->name, name, size); - gv->get_attr = get_attr; - gv->set_attr = set_attr; - gv->next = v->vars; - } - } - v->vars = gv; -} - -SWIGINTERN PyObject * -SWIG_globals(void) { - static PyObject *globals = 0; - if (!globals) { - globals = SWIG_newvarlink(); - } - return globals; -} - /* ----------------------------------------------------------------------------- * constants/methods manipulation * ----------------------------------------------------------------------------- */ @@ -272,15 +62,12 @@ SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) { } } -/* -----------------------------------------------------------------------------*/ -/* Fix SwigMethods to carry the callback ptrs when needed */ -/* -----------------------------------------------------------------------------*/ +/* ----------------------------------------------------------------------------- + * Patch %callback methods' docstrings to hold the callback ptrs + * -----------------------------------------------------------------------------*/ SWIGINTERN void -SWIG_Python_FixMethods(PyMethodDef *methods, - swig_const_info *const_table, - swig_type_info **types, - swig_type_info **types_initial) { +SWIG_Python_FixMethods(PyMethodDef *methods, const swig_const_info *const_table, swig_type_info **types, swig_type_info **types_initial) { size_t i; for (i = 0; methods[i].ml_name; ++i) { const char *c = methods[i].ml_doc; @@ -288,7 +75,7 @@ SWIG_Python_FixMethods(PyMethodDef *methods, c = strstr(c, "swig_ptr: "); if (c) { int j; - swig_const_info *ci = 0; + const swig_const_info *ci = 0; const char *name = c + 10; for (j = 0; const_table[j].type; ++j) { if (strncmp(const_table[j].name, name, @@ -320,6 +107,8 @@ SWIG_Python_FixMethods(PyMethodDef *methods, } } +#if defined SWIGPYTHON_FASTPROXY && !defined SWIGPYTHON_BUILTIN + /* ----------------------------------------------------------------------------- * Method creation and docstring support functions * ----------------------------------------------------------------------------- */ @@ -378,6 +167,8 @@ SWIGINTERN PyObject *SWIG_PyStaticMethod_New(PyObject *SWIGUNUSEDPARM(self), PyO return PyStaticMethod_New(func); } +#endif + #ifdef __cplusplus } #endif diff --git a/Lib/python/pyrun.swg b/Lib/python/pyrun.swg index 63ff82ff8..a49cbb5b3 100644 --- a/Lib/python/pyrun.swg +++ b/Lib/python/pyrun.swg @@ -127,7 +127,12 @@ SWIG_Python_AppendOutput(PyObject* result, PyObject* obj) { if (!PyList_Check(result)) { PyObject *o2 = result; result = PyList_New(1); - PyList_SetItem(result, 0, o2); + if (result) { + PyList_SET_ITEM(result, 0, o2); + } else { + Py_DECREF(obj); + return o2; + } } PyList_Append(result,obj); Py_DECREF(obj); @@ -209,6 +214,230 @@ SWIG_Python_CheckNoKeywords(PyObject *kwargs, const char *name) { #define SWIG_STATIC_POINTER(var) var = 0; if (!var) var #endif +#ifdef __cplusplus +extern "C" { +#endif + +/* Python-specific SWIG API */ +#define SWIG_newvarlink() SWIG_Python_newvarlink() +#define SWIG_addvarlink(p, name, get_attr, set_attr) SWIG_Python_addvarlink(p, name, get_attr, set_attr) +#define SWIG_InstallConstants(d, constants) SWIG_Python_InstallConstants(d, constants) + +/* ----------------------------------------------------------------------------- + * global variable support code. + * ----------------------------------------------------------------------------- */ + +typedef struct swig_globalvar { + char *name; /* Name of global variable */ + PyObject *(*get_attr)(void); /* Return the current value */ + int (*set_attr)(PyObject *); /* Set the value */ + struct swig_globalvar *next; +} swig_globalvar; + +typedef struct swig_varlinkobject { + PyObject_HEAD + swig_globalvar *vars; +} swig_varlinkobject; + +SWIGINTERN PyObject * +swig_varlink_repr(swig_varlinkobject *SWIGUNUSEDPARM(v)) { +#if PY_VERSION_HEX >= 0x03000000 + return PyUnicode_InternFromString(""); +#else + return PyString_FromString(""); +#endif +} + +SWIGINTERN PyObject * +swig_varlink_str(swig_varlinkobject *v) { +#if PY_VERSION_HEX >= 0x03000000 + PyObject *str = PyUnicode_InternFromString("("); + PyObject *tail; + PyObject *joined; + swig_globalvar *var; + for (var = v->vars; var; var=var->next) { + tail = PyUnicode_FromString(var->name); + joined = PyUnicode_Concat(str, tail); + Py_DecRef(str); + Py_DecRef(tail); + str = joined; + if (var->next) { + tail = PyUnicode_InternFromString(", "); + joined = PyUnicode_Concat(str, tail); + Py_DecRef(str); + Py_DecRef(tail); + str = joined; + } + } + tail = PyUnicode_InternFromString(")"); + joined = PyUnicode_Concat(str, tail); + Py_DecRef(str); + Py_DecRef(tail); + str = joined; +#else + PyObject *str = PyString_FromString("("); + swig_globalvar *var; + for (var = v->vars; var; var=var->next) { + PyString_ConcatAndDel(&str,PyString_FromString(var->name)); + if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(", ")); + } + PyString_ConcatAndDel(&str,PyString_FromString(")")); +#endif + return str; +} + +SWIGINTERN void +swig_varlink_dealloc(swig_varlinkobject *v) { + swig_globalvar *var = v->vars; + while (var) { + swig_globalvar *n = var->next; + free(var->name); + free(var); + var = n; + } +} + +SWIGINTERN PyObject * +swig_varlink_getattr(swig_varlinkobject *v, char *n) { + PyObject *res = NULL; + swig_globalvar *var = v->vars; + while (var) { + if (strcmp(var->name,n) == 0) { + res = (*var->get_attr)(); + break; + } + var = var->next; + } + if (res == NULL && !PyErr_Occurred()) { + PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); + } + return res; +} + +SWIGINTERN int +swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) { + int res = 1; + swig_globalvar *var = v->vars; + while (var) { + if (strcmp(var->name,n) == 0) { + res = (*var->set_attr)(p); + break; + } + var = var->next; + } + if (res == 1 && !PyErr_Occurred()) { + PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); + } + return res; +} + +SWIGINTERN PyTypeObject* +swig_varlink_type(void) { + static char varlink__doc__[] = "Swig var link object"; + static PyTypeObject varlink_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp = { +#if PY_VERSION_HEX >= 0x03000000 + PyVarObject_HEAD_INIT(NULL, 0) +#else + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ +#endif + "swigvarlink", /* tp_name */ + sizeof(swig_varlinkobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor) swig_varlink_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + (getattrfunc) swig_varlink_getattr, /* tp_getattr */ + (setattrfunc) swig_varlink_setattr, /* tp_setattr */ + 0, /* tp_compare */ + (reprfunc) swig_varlink_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + (reprfunc) swig_varlink_str, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + 0, /* tp_flags */ + varlink__doc__, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */ + 0, /* tp_del */ + 0, /* tp_version_tag */ +#if PY_VERSION_HEX >= 0x03040000 + 0, /* tp_finalize */ +#endif +#if PY_VERSION_HEX >= 0x03080000 + 0, /* tp_vectorcall */ +#endif +#if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000) + 0, /* tp_print */ +#endif +#ifdef COUNT_ALLOCS + 0, /* tp_allocs */ + 0, /* tp_frees */ + 0, /* tp_maxalloc */ + 0, /* tp_prev */ + 0 /* tp_next */ +#endif + }; + varlink_type = tmp; + type_init = 1; + if (PyType_Ready(&varlink_type) < 0) + return NULL; + } + return &varlink_type; +} + +/* Create a variable linking object for use later */ +SWIGINTERN PyObject * +SWIG_Python_newvarlink(void) { + swig_varlinkobject *result = PyObject_NEW(swig_varlinkobject, swig_varlink_type()); + if (result) { + result->vars = 0; + } + return ((PyObject*) result); +} + +SWIGINTERN void +SWIG_Python_addvarlink(PyObject *p, const char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) { + swig_varlinkobject *v = (swig_varlinkobject *) p; + swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar)); + if (gv) { + size_t size = strlen(name)+1; + gv->name = (char *)malloc(size); + if (gv->name) { + memcpy(gv->name, name, size); + gv->get_attr = get_attr; + gv->set_attr = set_attr; + gv->next = v->vars; + } + } + v->vars = gv; +} + + +static PyObject *Swig_Globals_global = NULL; + +SWIGINTERN PyObject * +SWIG_globals(void) { + if (Swig_Globals_global == NULL) { + Swig_Globals_global = SWIG_newvarlink(); + } + return Swig_Globals_global; +} + +#ifdef __cplusplus +} +#endif + /* ----------------------------------------------------------------------------- * Pointer declarations * ----------------------------------------------------------------------------- */ @@ -279,18 +508,25 @@ SwigPyClientData_New(PyObject* obj) /* the newraw method and newargs arguments used to create a new raw instance */ if (PyClass_Check(obj)) { data->newraw = 0; - data->newargs = obj; Py_INCREF(obj); + data->newargs = obj; } else { data->newraw = PyObject_GetAttrString(data->klass, "__new__"); if (data->newraw) { - Py_INCREF(data->newraw); - data->newargs = PyTuple_New(1); - PyTuple_SetItem(data->newargs, 0, obj); + data->newargs = PyTuple_New(1); + if (data->newargs) { + Py_INCREF(obj); + PyTuple_SET_ITEM(data->newargs, 0, obj); + } else { + Py_DECREF(data->newraw); + Py_DECREF(data->klass); + free(data); + return 0; + } } else { - data->newargs = obj; + Py_INCREF(obj); + data->newargs = obj; } - Py_INCREF(data->newargs); } /* the destroy method, aka as the C++ delete method */ data->destroy = PyObject_GetAttrString(data->klass, "__swig_destroy__"); @@ -299,10 +535,7 @@ SwigPyClientData_New(PyObject* obj) data->destroy = 0; } if (data->destroy) { - int flags; - Py_INCREF(data->destroy); - flags = PyCFunction_GET_FLAGS(data->destroy); - data->delargs = !(flags & (METH_O)); + data->delargs = !(PyCFunction_GET_FLAGS(data->destroy) & METH_O); } else { data->delargs = 0; } @@ -313,10 +546,13 @@ SwigPyClientData_New(PyObject* obj) } SWIGRUNTIME void -SwigPyClientData_Del(SwigPyClientData *data) { +SwigPyClientData_Del(SwigPyClientData *data) +{ + Py_XDECREF(data->klass); Py_XDECREF(data->newraw); Py_XDECREF(data->newargs); Py_XDECREF(data->destroy); + free(data); } /* =============== SwigPyObject =====================*/ @@ -343,7 +579,7 @@ SwigPyObject_get___dict__(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) if (!sobj->dict) sobj->dict = PyDict_New(); - Py_INCREF(sobj->dict); + Py_XINCREF(sobj->dict); return sobj->dict; } @@ -361,18 +597,21 @@ SwigPyObject_format(const char* fmt, SwigPyObject *v) PyObject *res = NULL; PyObject *args = PyTuple_New(1); if (args) { - if (PyTuple_SetItem(args, 0, SwigPyObject_long(v)) == 0) { - PyObject *ofmt = SWIG_Python_str_FromChar(fmt); + PyObject *val = SwigPyObject_long(v); + if (val) { + PyObject *ofmt; + PyTuple_SET_ITEM(args, 0, val); + ofmt = SWIG_Python_str_FromChar(fmt); if (ofmt) { #if PY_VERSION_HEX >= 0x03000000 - res = PyUnicode_Format(ofmt,args); + res = PyUnicode_Format(ofmt,args); #else - res = PyString_Format(ofmt,args); + res = PyString_Format(ofmt,args); #endif - Py_DECREF(ofmt); + Py_DECREF(ofmt); } - Py_DECREF(args); } + Py_DECREF(args); } return res; } @@ -394,18 +633,23 @@ SwigPyObject_repr(SwigPyObject *v) { const char *name = SWIG_TypePrettyName(v->ty); PyObject *repr = SWIG_Python_str_FromFormat("", (name ? name : "unknown"), (void *)v); - if (v->next) { + if (repr && v->next) { PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next); + if (nrep) { # if PY_VERSION_HEX >= 0x03000000 - PyObject *joined = PyUnicode_Concat(repr, nrep); - Py_DecRef(repr); - Py_DecRef(nrep); - repr = joined; + PyObject *joined = PyUnicode_Concat(repr, nrep); + Py_DecRef(repr); + Py_DecRef(nrep); + repr = joined; # else - PyString_ConcatAndDel(&repr,nrep); + PyString_ConcatAndDel(&repr,nrep); # endif + } else { + Py_DecRef(repr); + repr = NULL; + } } - return repr; + return repr; } /* We need a version taking two PyObject* parameters so it's a valid @@ -501,8 +745,12 @@ SwigPyObject_dealloc(PyObject *v) if (data->delargs) { /* we need to create a temporary object to carry the destroy operation */ PyObject *tmp = SwigPyObject_New(sobj->ptr, ty, 0); - res = SWIG_Python_CallFunctor(destroy, tmp); - Py_DECREF(tmp); + if (tmp) { + res = SWIG_Python_CallFunctor(destroy, tmp); + } else { + res = 0; + } + Py_XDECREF(tmp); } else { PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); PyObject *mself = PyCFunction_GET_SELF(destroy); @@ -523,6 +771,9 @@ SwigPyObject_dealloc(PyObject *v) #endif } Py_XDECREF(next); +#ifdef SWIGPYTHON_BUILTIN + Py_XDECREF(sobj->dict); +#endif PyObject_DEL(v); } @@ -578,9 +829,9 @@ SwigPyObject_own(PyObject *v, PyObject *args) PyObject *obj = PyBool_FromLong(sobj->own); if (val) { if (PyObject_IsTrue(val)) { - SwigPyObject_acquire(v,args); + Py_DECREF(SwigPyObject_acquire(v,args)); } else { - SwigPyObject_disown(v,args); + Py_DECREF(SwigPyObject_disown(v,args)); } } return obj; @@ -725,7 +976,7 @@ SwigPyObject_TypeOnce(void) { }; swigpyobject_type = tmp; type_init = 1; - if (PyType_Ready(&swigpyobject_type) < 0) + if (PyType_Ready(&swigpyobject_type) != 0) return NULL; } return &swigpyobject_type; @@ -740,6 +991,9 @@ SwigPyObject_New(void *ptr, swig_type_info *ty, int own) sobj->ty = ty; sobj->own = own; sobj->next = 0; +#ifdef SWIGPYTHON_BUILTIN + sobj->dict = 0; +#endif } return (PyObject *)sobj; } @@ -892,7 +1146,7 @@ SwigPyPacked_TypeOnce(void) { }; swigpypacked_type = tmp; type_init = 1; - if (PyType_Ready(&swigpypacked_type) < 0) + if (PyType_Ready(&swigpypacked_type) != 0) return NULL; } return &swigpypacked_type; @@ -1200,12 +1454,17 @@ SWIG_Python_NewShadowInstance(SwigPyClientData *data, PyObject *swig_this) #if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) PyObject **dictptr = _PyObject_GetDictPtr(inst); if (dictptr != NULL) { - PyObject *dict = *dictptr; - if (dict == NULL) { - dict = PyDict_New(); - *dictptr = dict; - PyDict_SetItem(dict, SWIG_This(), swig_this); - } + PyObject *dict = *dictptr; + if (dict == NULL) { + dict = PyDict_New(); + *dictptr = dict; + } + if (dict) { + PyDict_SetItem(dict, SWIG_This(), swig_this); + } else{ + Py_DECREF(inst); + inst = 0; + } } #else if (PyObject_SetAttr(inst, SWIG_This(), swig_this) == -1) { @@ -1256,7 +1515,11 @@ SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this) dict = PyDict_New(); *dictptr = dict; } - return PyDict_SetItem(dict, SWIG_This(), swig_this); + if (dict) { + return PyDict_SetItem(dict, SWIG_This(), swig_this); + } else{ + return -1; + } } #endif return PyObject_SetAttr(inst, SWIG_This(), swig_this); @@ -1271,7 +1534,7 @@ SWIG_Python_InitShadowInstance(PyObject *args) { } else { SwigPyObject *sthis = SWIG_Python_GetSwigThis(obj[0]); if (sthis) { - SwigPyObject_append((PyObject*) sthis, obj[1]); + Py_DECREF(SwigPyObject_append((PyObject*) sthis, obj[1])); } else { if (SWIG_Python_SetSwigThis(obj[0], obj[1]) != 0) return NULL; @@ -1310,7 +1573,9 @@ SWIG_Python_NewPointerObj(PyObject *self, void *ptr, swig_type_info *type, int f } else { newobj = PyObject_New(SwigPyObject, clientdata->pytype); #ifdef SWIGPYTHON_BUILTIN - newobj->dict = 0; + if (newobj) { + newobj->dict = 0; + } #endif } if (newobj) { @@ -1349,6 +1614,17 @@ SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) { void *SWIG_ReturnGlobalTypeList(void *); #endif +static PyObject *Swig_TypeCache_global = NULL; + +/* The python cached type query */ +SWIGRUNTIME PyObject * +SWIG_Python_TypeCache(void) { + if (Swig_TypeCache_global == NULL) { + Swig_TypeCache_global = PyDict_New(); + } + return Swig_TypeCache_global; +} + SWIGRUNTIME swig_module_info * SWIG_Python_GetModule(void *SWIGUNUSEDPARM(clientdata)) { static void *type_pointer = (void *)0; @@ -1377,11 +1653,16 @@ SWIG_Python_DestroyModule(PyObject *obj) swig_type_info *ty = types[i]; if (ty->owndata) { SwigPyClientData *data = (SwigPyClientData *) ty->clientdata; + ty->clientdata = 0; if (data) SwigPyClientData_Del(data); } } Py_DECREF(SWIG_This()); Swig_This_global = NULL; + Py_DECREF(SWIG_globals()); + Swig_Globals_global = NULL; + Py_DECREF(SWIG_Python_TypeCache()); + Swig_TypeCache_global = NULL; } SWIGRUNTIME void @@ -1395,19 +1676,14 @@ SWIG_Python_SetModule(swig_module_info *swig_module) { #endif PyObject *pointer = PyCapsule_New((void *) swig_module, SWIGPY_CAPSULE_NAME, SWIG_Python_DestroyModule); if (pointer && module) { - PyModule_AddObject(module, "type_pointer_capsule" SWIG_TYPE_TABLE_NAME, pointer); + if (PyModule_AddObject(module, "type_pointer_capsule" SWIG_TYPE_TABLE_NAME, pointer) != 0) { + Py_DECREF(pointer); + } } else { Py_XDECREF(pointer); } } -/* The python cached type query */ -SWIGRUNTIME PyObject * -SWIG_Python_TypeCache(void) { - static PyObject *SWIG_STATIC_POINTER(cache) = PyDict_New(); - return cache; -} - SWIGRUNTIME swig_type_info * SWIG_Python_TypeQuery(const char *type) { @@ -1422,8 +1698,10 @@ SWIG_Python_TypeQuery(const char *type) descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type); if (descriptor) { obj = PyCapsule_New((void*) descriptor, NULL, NULL); - PyDict_SetItem(cache, key, obj); - Py_DECREF(obj); + if (obj) { + PyDict_SetItem(cache, key, obj); + Py_DECREF(obj); + } } } Py_DECREF(key); @@ -1566,7 +1844,7 @@ SWIG_Python_NonDynamicSetAttr(PyObject *obj, PyObject *name, PyObject *value) { } if (!tp->tp_dict) { - if (PyType_Ready(tp) < 0) + if (PyType_Ready(tp) != 0) goto done; } @@ -1581,7 +1859,7 @@ SWIG_Python_NonDynamicSetAttr(PyObject *obj, PyObject *name, PyObject *value) { } else { encoded_name = PyUnicode_AsUTF8String(name); if (!encoded_name) - return -1; + goto done; } PyErr_Format(PyExc_AttributeError, "'%.100s' object has no attribute '%.200s'", tp->tp_name, PyString_AsString(encoded_name)); Py_DECREF(encoded_name); diff --git a/Lib/python/pyruntime.swg b/Lib/python/pyruntime.swg index 751bc8d5f..843fa6ce1 100644 --- a/Lib/python/pyruntime.swg +++ b/Lib/python/pyruntime.swg @@ -4,6 +4,13 @@ # include #endif +#if defined(_MSC_VER) && _MSC_VER >= 1930 +/* Workaround what seems to be a bug in the Python headers with MSVC 2022. + * https://github.com/swig/swig/issues/2090 + */ +# include +#endif + #if defined(_DEBUG) && defined(SWIG_PYTHON_INTERPRETER_NO_DEBUG) /* Use debug wrappers with the Python release dll */ # undef _DEBUG diff --git a/Lib/python/pythonkw.swg b/Lib/python/pythonkw.swg index 0138e40e4..a21034524 100644 --- a/Lib/python/pythonkw.swg +++ b/Lib/python/pythonkw.swg @@ -2,7 +2,7 @@ Warnings for Python keywords, built-in names and bad names. */ -#define PYTHONKW(x) %keywordwarn("'" `x` "' is a python keyword, renaming to '_" `x` "'", rename="_%s") `x` +#define PYTHONKW(x) %keywordwarn("'" `x` "' is a python keyword", rename="_%s") `x` #define PYTHONBN(x) %builtinwarn("'" `x` "' conflicts with a built-in name in python") `x` diff --git a/Lib/python/pythreads.swg b/Lib/python/pythreads.swg index d8797e659..8d6c5ab49 100644 --- a/Lib/python/pythreads.swg +++ b/Lib/python/pythreads.swg @@ -8,8 +8,12 @@ # define SWIG_PYTHON_USE_GIL # endif # if defined(SWIG_PYTHON_USE_GIL) /* Use PyGILState threads calls */ -# ifndef SWIG_PYTHON_INITIALIZE_THREADS -# define SWIG_PYTHON_INITIALIZE_THREADS PyEval_InitThreads() +# if !defined(SWIG_PYTHON_INITIALIZE_THREADS) +# if PY_VERSION_HEX < 0x03070000 +# define SWIG_PYTHON_INITIALIZE_THREADS PyEval_InitThreads() +# else +# define SWIG_PYTHON_INITIALIZE_THREADS +# endif # endif # ifdef __cplusplus /* C++ code */ class SWIG_Python_Thread_Block { diff --git a/Lib/python/std_auto_ptr.i b/Lib/python/std_auto_ptr.i index e310e00c8..c94006a68 100644 --- a/Lib/python/std_auto_ptr.i +++ b/Lib/python/std_auto_ptr.i @@ -1,5 +1,5 @@ /* - The typemaps here allow to handle functions returning std::auto_ptr<>, + The typemaps here allow handling functions returning std::auto_ptr<>, which is the most common use of this type. If you have functions taking it as parameter, these typemaps can't be used for them and you need to do something else (e.g. use shared_ptr<> which SWIG supports fully). diff --git a/Lib/python/typemaps.i b/Lib/python/typemaps.i index 5d438ecab..dba63dd59 100644 --- a/Lib/python/typemaps.i +++ b/Lib/python/typemaps.i @@ -72,7 +72,7 @@ multiple output values, they are returned in the form of a Python tuple. For example, suppose you were trying to wrap the modf() function in the C math library which splits x into integral and fractional parts (and -returns the integer part in one of its parameters).K: +returns the integer part in one of its parameters) : double modf(double x, double *ip); diff --git a/Lib/r/rkw.swg b/Lib/r/rkw.swg index 074d7dfd9..c4af7084f 100644 --- a/Lib/r/rkw.swg +++ b/Lib/r/rkw.swg @@ -2,8 +2,8 @@ Warnings for R keywords, built-in names and bad names. */ -#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` +#define RKW(x) %keywordwarn("'" `x` "' is a R keyword", rename="_%s") `x` +#define RSWIGKW(x) %keywordwarn("'" `x` "' is a SWIG R reserved parameter name", rename="_%s") `x` /* Warnings for R reserved words taken from diff --git a/Lib/ruby/rubyautodoc.swg b/Lib/ruby/rubyautodoc.swg index 1e6b0d9dc..6b0472ce8 100644 --- a/Lib/ruby/rubyautodoc.swg +++ b/Lib/ruby/rubyautodoc.swg @@ -77,7 +77,7 @@ AUTODOC(operator>, "Higher than comparison operator"); AUTODOC(operator<<, "Left shifting or appending operator"); AUTODOC(operator>>, "Right shifting operator or extracting operator"); AUTODOC(operator+, "Add operator"); -AUTODOC(operator-, "Substraction operator"); +AUTODOC(operator-, "Subtraction operator"); AUTODOC(operator+(), "Positive operator"); AUTODOC(operator-(), "Negation operator"); AUTODOC(operator&, "AND operator"); @@ -93,7 +93,7 @@ AUTODOC(__gt__, "Higher than comparison operator"); AUTODOC(__lshift__, "Left shifting or appending operator"); AUTODOC(__rshift__, "Right shifting operator or extracting operator"); AUTODOC(__add___, "Add operator"); -AUTODOC(__sub__, "Substraction operator"); +AUTODOC(__sub__, "Subtraction operator"); AUTODOC(__pos__, "Positive operator"); AUTODOC(__neg__, "Negation operator"); AUTODOC(__and__, "AND operator"); diff --git a/Lib/ruby/rubyclasses.swg b/Lib/ruby/rubyclasses.swg index b345fcebe..c43f38fc5 100644 --- a/Lib/ruby/rubyclasses.swg +++ b/Lib/ruby/rubyclasses.swg @@ -207,8 +207,8 @@ namespace swig { (VALUEFUNC(swig_rescue_swallow)), Qnil); } if (ret == Qnil) { - VALUE a = rb_funcall( _obj, hash_id, 0 ); - VALUE b = rb_funcall( VALUE(other), hash_id, 0 ); + VALUE a = rb_funcall2( _obj, hash_id, 0, 0 ); + VALUE b = rb_funcall2( VALUE(other), hash_id, 0, 0 ); res = op_func(a, b); } else { res = RTEST(ret); diff --git a/Lib/ruby/rubycomplex.swg b/Lib/ruby/rubycomplex.swg index 4e249c71f..d2aaf6cb1 100644 --- a/Lib/ruby/rubycomplex.swg +++ b/Lib/ruby/rubycomplex.swg @@ -36,12 +36,12 @@ SWIGINTERN int SWIG_Is_Complex( VALUE obj ) { SWIGINTERN VALUE SWIG_Complex_Real(VALUE obj) { static ID real_id = rb_intern("real"); - return rb_funcall(obj, real_id, 0); + return rb_funcall2(obj, real_id, 0, 0); } SWIGINTERN VALUE SWIG_Complex_Imaginary(VALUE obj) { static ID imag_id = rb_intern("imag"); - return rb_funcall(obj, imag_id, 0); + return rb_funcall2(obj, imag_id, 0, 0); } } @@ -127,7 +127,7 @@ SWIG_AsVal(Type)(VALUE o, Type *val) float re; int res = SWIG_AddCast(SWIG_AsVal(float)(o, &re)); if (SWIG_IsOK(res)) { - if (val) *val = Constructor(re, 0.0); + if (val) *val = Constructor(re, 0.0f); return res; } } diff --git a/Lib/ruby/rubycontainer.swg b/Lib/ruby/rubycontainer.swg index e72330853..597ae83d2 100644 --- a/Lib/ruby/rubycontainer.swg +++ b/Lib/ruby/rubycontainer.swg @@ -803,9 +803,9 @@ namespace swig static ID id_start = rb_intern("begin"); static ID id_noend = rb_intern("exclude_end?"); - VALUE start = rb_funcall( i, id_start, 0 ); - VALUE end = rb_funcall( i, id_end, 0 ); - bool noend = ( rb_funcall( i, id_noend, 0 ) == Qtrue ); + VALUE start = rb_funcall2( i, id_start, 0, 0 ); + VALUE end = rb_funcall2( i, id_end, 0, 0 ); + bool noend = ( rb_funcall2( i, id_noend, 0, 0 ) == Qtrue ); int len = $self->size(); diff --git a/Lib/ruby/rubykw.swg b/Lib/ruby/rubykw.swg index 194687b95..6b4685eb8 100644 --- a/Lib/ruby/rubykw.swg +++ b/Lib/ruby/rubykw.swg @@ -2,7 +2,7 @@ #define RUBY_RUBYKW_SWG_ /* Warnings for Ruby keywords */ -#define RUBYKW(x) %keywordwarn("'" `x` "' is a ruby keyword, renaming to 'C_" `x` "'",rename="C_%s",fullname=1) `x` +#define RUBYKW(x) %keywordwarn("'" `x` "' is a ruby keyword",rename="C_%s",fullname=1) `x` /* diff --git a/Lib/ruby/rubyrun.swg b/Lib/ruby/rubyrun.swg index 3b6fd32b0..7c94c4e12 100644 --- a/Lib/ruby/rubyrun.swg +++ b/Lib/ruby/rubyrun.swg @@ -443,7 +443,7 @@ int SWIG_Ruby_arity( VALUE proc, int minimal ) { if ( rb_respond_to( proc, swig_arity_id ) ) { - VALUE num = rb_funcall( proc, swig_arity_id, 0 ); + VALUE num = rb_funcall2( proc, swig_arity_id, 0, 0 ); int arity = NUM2INT(num); if ( arity < 0 && (arity+1) < -minimal ) return 1; if ( arity == minimal ) return 1; diff --git a/Lib/ruby/std_auto_ptr.i b/Lib/ruby/std_auto_ptr.i index 3a415b942..eab8ec53d 100644 --- a/Lib/ruby/std_auto_ptr.i +++ b/Lib/ruby/std_auto_ptr.i @@ -1,5 +1,5 @@ /* - The typemaps here allow to handle functions returning std::auto_ptr<>, + The typemaps here allow handling functions returning std::auto_ptr<>, which is the most common use of this type. If you have functions taking it as parameter, these typemaps can't be used for them and you need to do something else (e.g. use shared_ptr<> which SWIG supports fully). diff --git a/Lib/ruby/std_map.i b/Lib/ruby/std_map.i index 7077fa104..6dd2ffa72 100644 --- a/Lib/ruby/std_map.i +++ b/Lib/ruby/std_map.i @@ -96,7 +96,7 @@ int res = SWIG_ERROR; if ( TYPE(obj) == T_HASH ) { static ID id_to_a = rb_intern("to_a"); - VALUE items = rb_funcall(obj, id_to_a, 0); + VALUE items = rb_funcall2(obj, id_to_a, 0, 0); res = traits_asptr_stdseq, std::pair >::asptr(items, val); } else { map_type *p; diff --git a/Lib/ruby/std_multimap.i b/Lib/ruby/std_multimap.i index 762a87653..5d8e33e97 100644 --- a/Lib/ruby/std_multimap.i +++ b/Lib/ruby/std_multimap.i @@ -23,7 +23,7 @@ int res = SWIG_ERROR; if ( TYPE(obj) == T_HASH ) { static ID id_to_a = rb_intern("to_a"); - VALUE items = rb_funcall(obj, id_to_a, 0); + VALUE items = rb_funcall2(obj, id_to_a, 0, 0); return traits_asptr_stdseq, std::pair >::asptr(items, val); } else { multimap_type *p; diff --git a/Lib/ruby/std_unordered_map.i b/Lib/ruby/std_unordered_map.i index 48c875214..3c6b65027 100644 --- a/Lib/ruby/std_unordered_map.i +++ b/Lib/ruby/std_unordered_map.i @@ -23,7 +23,7 @@ int res = SWIG_ERROR; if (TYPE(obj) == T_HASH) { static ID id_to_a = rb_intern("to_a"); - VALUE items = rb_funcall(obj, id_to_a, 0); + VALUE items = rb_funcall2(obj, id_to_a, 0, 0); res = traits_asptr_stdseq, std::pair >::asptr(items, val); } else { map_type *p; diff --git a/Lib/ruby/std_unordered_multimap.i b/Lib/ruby/std_unordered_multimap.i index ebc53b597..c3261f9e6 100644 --- a/Lib/ruby/std_unordered_multimap.i +++ b/Lib/ruby/std_unordered_multimap.i @@ -23,7 +23,7 @@ int res = SWIG_ERROR; if ( TYPE(obj) == T_HASH ) { static ID id_to_a = rb_intern("to_a"); - VALUE items = rb_funcall(obj, id_to_a, 0); + VALUE items = rb_funcall2(obj, id_to_a, 0, 0); return traits_asptr_stdseq, std::pair >::asptr(items, val); } else { multimap_type *p; diff --git a/Lib/ruby/timeval.i b/Lib/ruby/timeval.i index e7bc2d322..94a75c802 100644 --- a/Lib/ruby/timeval.i +++ b/Lib/ruby/timeval.i @@ -55,7 +55,7 @@ struct timeval rb_time_timeval(VALUE); if (NIL_P($input)) $1 = (time_t)-1; else - $1 = NUM2LONG(rb_funcall($input, rb_intern("tv_sec"), 0)); + $1 = NUM2LONG(rb_funcall2($input, rb_intern("tv_sec"), 0, 0)); } %typemap(typecheck) time_t diff --git a/Lib/ruby/typemaps.i b/Lib/ruby/typemaps.i index c4db82161..1d28b1318 100644 --- a/Lib/ruby/typemaps.i +++ b/Lib/ruby/typemaps.i @@ -119,7 +119,7 @@ multiple output values, they are returned in the form of a Ruby Array. For example, suppose you were trying to wrap the modf() function in the C math library which splits x into integral and fractional parts (and -returns the integer part in one of its parameters).K: +returns the integer part in one of its parameters) : double modf(double x, double *ip); diff --git a/Lib/scilab/scienum.swg b/Lib/scilab/scienum.swg index 54ec1f85c..cc1f7c977 100644 --- a/Lib/scilab/scienum.swg +++ b/Lib/scilab/scienum.swg @@ -18,7 +18,7 @@ SWIG_Int_AsEnum(void *pvApiCtx, int iVar, int *enumValue, char *fname) { } %fragment(SWIG_From_frag(Enum), "header", fragment="SWIG_Int_FromEnum") { -%#define SWIG_From_Enum(scilabValue) SWIG_Int_FromEnum(pvApiCtx, SWIG_Scilab_GetOutputPosition(), scilabValue, SWIG_Scilab_GetFuncName()) +%#define SWIG_From_Enum(scilabValue) SWIG_Int_FromEnum(pvApiCtx, SWIG_Scilab_GetOutputPosition(), (int)scilabValue, SWIG_Scilab_GetFuncName()) } %fragment("SWIG_Int_FromEnum", "header", fragment="SWIG_SciDouble_FromInt") { SWIGINTERN int diff --git a/Lib/scilab/scirun.swg b/Lib/scilab/scirun.swg index 51df9a59e..2e4084c15 100644 --- a/Lib/scilab/scirun.swg +++ b/Lib/scilab/scirun.swg @@ -47,10 +47,8 @@ static char *SWIG_Scilab_GetFuncName(void) { return SwigFuncName; } static void SWIG_Scilab_SetFuncName(char *funcName) { - if (SwigFuncName != NULL) { - free(SwigFuncName); - SwigFuncName = NULL; - } + free(SwigFuncName); + SwigFuncName = NULL; if (funcName) { SwigFuncName = (char *)malloc(strlen(funcName) + 1); if (SwigFuncName) diff --git a/Lib/scilab/sciruntime.swg b/Lib/scilab/sciruntime.swg index 3de138e11..a2c11d708 100644 --- a/Lib/scilab/sciruntime.swg +++ b/Lib/scilab/sciruntime.swg @@ -40,7 +40,7 @@ SWIG_Scilab_TypeQuery(const char *name) { #ifdef __cplusplus extern "C" #endif -int _Init(SWIG_GatewayParameters) { +int SWIG__Init(SWIG_GatewayParameters) { SWIG_InitializeModule(NULL); SWIG_CreateScilabVariables(pvApiCtx); swig_module_initialized = 1; diff --git a/Lib/swig.swg b/Lib/swig.swg index 6dc215dcf..223d46482 100644 --- a/Lib/swig.swg +++ b/Lib/swig.swg @@ -172,7 +172,7 @@ #define %novaluewrapper %feature("novaluewrapper") #define %clearnovaluewrapper %feature("novaluewrapper","") -/* Contract support - Experimental and undocumented */ +/* Contract support - Experimental */ #define %contract %feature("contract") #define %nocontract %feature("contract","0") #define %clearcontract %feature("contract","") @@ -268,7 +268,9 @@ static int NAME(TYPE x) { */ -%define %$not "not" %enddef +/* Note that when %$not is used with another macro, say %enum as follows: %$not %$enum, the result is "notmatch=enum" */ +%define %$not "not" %enddef + %define %$isenum "match"="enum" %enddef %define %$isenumitem "match"="enumitem" %enddef %define %$isaccess "match"="access" %enddef @@ -279,6 +281,7 @@ static int NAME(TYPE x) { %define %$isnamespace "match"="namespace" %enddef %define %$istemplate "match"="template" %enddef %define %$isconstant "match"="constant" %enddef /* %constant definition */ +%define %$isusing "match"="using" %enddef %define %$isunion "match$kind"="union" %enddef %define %$isfunction "match$kind"="function" %enddef @@ -453,7 +456,7 @@ namespace std { /* Default typemap for handling char * members */ #ifdef __cplusplus -%typemap(memberin) char * { +%typemap(memberin,fragment="") char * { delete [] $1; if ($input) { $1 = ($1_type) (new char[strlen((const char *)$input)+1]); @@ -462,7 +465,7 @@ namespace std { $1 = 0; } } -%typemap(memberin,warning=SWIGWARN_TYPEMAP_CHARLEAK_MSG) const char * { +%typemap(memberin,warning=SWIGWARN_TYPEMAP_CHARLEAK_MSG,fragment="") const char * { if ($input) { $1 = ($1_type) (new char[strlen((const char *)$input)+1]); strcpy((char *)$1, (const char *)$input); @@ -470,7 +473,7 @@ namespace std { $1 = 0; } } -%typemap(globalin) char * { +%typemap(globalin,fragment="") char * { delete [] $1; if ($input) { $1 = ($1_type) (new char[strlen((const char *)$input)+1]); @@ -479,7 +482,7 @@ namespace std { $1 = 0; } } -%typemap(globalin,warning=SWIGWARN_TYPEMAP_CHARLEAK_MSG) const char * { +%typemap(globalin,warning=SWIGWARN_TYPEMAP_CHARLEAK_MSG,fragment="") const char * { if ($input) { $1 = ($1_type) (new char[strlen((const char *)$input)+1]); strcpy((char *)$1, (const char *)$input); @@ -488,7 +491,7 @@ namespace std { } } #else -%typemap(memberin) char * { +%typemap(memberin,fragment="") char * { free($1); if ($input) { $1 = ($1_type) malloc(strlen((const char *)$input)+1); @@ -497,7 +500,7 @@ namespace std { $1 = 0; } } -%typemap(memberin,warning=SWIGWARN_TYPEMAP_CHARLEAK_MSG) const char * { +%typemap(memberin,warning=SWIGWARN_TYPEMAP_CHARLEAK_MSG,fragment="") const char * { if ($input) { $1 = ($1_type) malloc(strlen((const char *)$input)+1); strcpy((char *)$1, (const char *)$input); @@ -505,7 +508,7 @@ namespace std { $1 = 0; } } -%typemap(globalin) char * { +%typemap(globalin,fragment="") char * { free($1); if ($input) { $1 = ($1_type) malloc(strlen((const char *)$input)+1); @@ -514,7 +517,7 @@ namespace std { $1 = 0; } } -%typemap(globalin,warning=SWIGWARN_TYPEMAP_CHARLEAK_MSG) const char * { +%typemap(globalin,warning=SWIGWARN_TYPEMAP_CHARLEAK_MSG,fragment="") const char * { if ($input) { $1 = ($1_type) malloc(strlen((const char *)$input)+1); strcpy((char *)$1, (const char *)$input); @@ -527,7 +530,7 @@ namespace std { /* Character array handling */ -%typemap(memberin) char [ANY] { +%typemap(memberin,fragment="") char [ANY] { if($input) { strncpy((char*)$1, (const char *)$input, $1_dim0-1); $1[$1_dim0-1] = 0; @@ -536,7 +539,7 @@ namespace std { } } -%typemap(globalin) char [ANY] { +%typemap(globalin,fragment="") char [ANY] { if($input) { strncpy((char*)$1, (const char *)$input, $1_dim0-1); $1[$1_dim0-1] = 0; @@ -545,25 +548,25 @@ namespace std { } } -%typemap(memberin) char [] { +%typemap(memberin,fragment="") char [] { if ($input) strcpy((char *)$1, (const char *)$input); else $1[0] = 0; } -%typemap(globalin) char [] { +%typemap(globalin,fragment="") char [] { if ($input) strcpy((char *)$1, (const char *)$input); else $1[0] = 0; } /* memberin/globalin typemap for arrays. */ -%typemap(memberin) SWIGTYPE [ANY] { +%typemap(memberin,fragment="") SWIGTYPE [ANY] { size_t ii; $1_basetype *b = ($1_basetype *) $1; for (ii = 0; ii < (size_t)$1_size; ii++) b[ii] = *(($1_basetype *) $input + ii); } -%typemap(globalin) SWIGTYPE [ANY] { +%typemap(globalin,fragment="") SWIGTYPE [ANY] { size_t ii; $1_basetype *b = ($1_basetype *) $1; for (ii = 0; ii < (size_t)$1_size; ii++) b[ii] = *(($1_basetype *) $input + ii); @@ -571,7 +574,7 @@ namespace std { /* memberin/globalin typemap for double arrays. */ -%typemap(memberin) SWIGTYPE [ANY][ANY] { +%typemap(memberin,fragment="") SWIGTYPE [ANY][ANY] { $basetype (*inp)[$1_dim1] = ($basetype (*)[$1_dim1])($input); $basetype (*dest)[$1_dim1] = ($basetype (*)[$1_dim1])($1); size_t ii = 0; @@ -583,7 +586,7 @@ namespace std { } } -%typemap(globalin) SWIGTYPE [ANY][ANY] { +%typemap(globalin,fragment="") SWIGTYPE [ANY][ANY] { $basetype (*inp)[$1_dim1] = ($basetype (*)[$1_dim1])($input); $basetype (*dest)[$1_dim1] = ($basetype (*)[$1_dim1])($1); size_t ii = 0; diff --git a/Lib/swigfragments.swg b/Lib/swigfragments.swg index 2cbef7cce..28aa1180f 100644 --- a/Lib/swigfragments.swg +++ b/Lib/swigfragments.swg @@ -29,6 +29,10 @@ #include %} +%fragment("", "header") %{ +#include +%} + %fragment("", "header") %{ #include %} diff --git a/Lib/swiginit.swg b/Lib/swiginit.swg index 33926b10f..e50b1b46d 100644 --- a/Lib/swiginit.swg +++ b/Lib/swiginit.swg @@ -50,9 +50,12 @@ extern "C" { #define SWIGRUNTIME_DEBUG #endif +#ifndef SWIG_INIT_CLIENT_DATA_TYPE +#define SWIG_INIT_CLIENT_DATA_TYPE void * +#endif SWIGRUNTIME void -SWIG_InitializeModule(void *clientdata) { +SWIG_InitializeModule(SWIG_INIT_CLIENT_DATA_TYPE clientdata) { size_t i; swig_module_info *module_head, *iter; int init; diff --git a/Lib/swigrun.swg b/Lib/swigrun.swg index 59118ecad..de0db2dc3 100644 --- a/Lib/swigrun.swg +++ b/Lib/swigrun.swg @@ -115,7 +115,7 @@ SWIG errors code. Finally, if the SWIG_CASTRANK_MODE is enabled, the result code - allows to return the 'cast rank', for example, if you have this + allows returning the 'cast rank', for example, if you have this int food(double) int fooi(int); @@ -290,7 +290,7 @@ SWIG_TypeCheck(const char *c, swig_type_info *ty) { Identical to SWIG_TypeCheck, except strcmp is replaced with a pointer comparison */ SWIGRUNTIME swig_cast_info * -SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *ty) { +SWIG_TypeCheckStruct(const swig_type_info *from, swig_type_info *ty) { if (ty) { swig_cast_info *iter = ty->cast; while (iter) { diff --git a/Lib/tcl/mactkinit.c b/Lib/tcl/mactkinit.c index 8d1420088..18f1f0203 100644 --- a/Lib/tcl/mactkinit.c +++ b/Lib/tcl/mactkinit.c @@ -126,7 +126,7 @@ MacintoshInit() * * This procedure calls initialization routines require a Tcl * interp as an argument. This call effectively makes the passed - * iterpreter the "main" interpreter for the application. + * interpreter the "main" interpreter for the application. * * Results: * Returns TCL_OK if everything went fine. If it didn't the diff --git a/Lib/tcl/std_vector.i b/Lib/tcl/std_vector.i index 5fba5379f..e35588788 100644 --- a/Lib/tcl/std_vector.i +++ b/Lib/tcl/std_vector.i @@ -88,12 +88,12 @@ namespace std { int i; T* temp; - if (SWIG_ConvertPtr($input, (void **) &v, \ + if (SWIG_ConvertPtr($input, (void **) &v, $&1_descriptor, 0) == 0){ $1 = *v; } else { // It isn't a vector< T > so it should be a list of T's - if(Tcl_ListObjGetElements(interp, $input, \ + if(Tcl_ListObjGetElements(interp, $input, &nitems, &listobjv) == TCL_ERROR) return TCL_ERROR; $1 = std::vector< T >(); @@ -117,8 +117,8 @@ namespace std { int i; T* temp; - if(SWIG_ConvertPtr($input, (void **) &v, \ - $&1_descriptor, 0) == 0) { + if(SWIG_ConvertPtr($input, (void **) &v, + $1_descriptor, 0) == 0) { $1 = v; } else { // It isn't a vector< T > so it should be a list of T's @@ -143,7 +143,7 @@ namespace std { %typemap(out) vector< T > { for (unsigned int i=0; i<$1.size(); i++) { T* ptr = new T((($1_type &)$1)[i]); - Tcl_ListObjAppendElement(interp, $result, \ + Tcl_ListObjAppendElement(interp, $result, SWIG_NewInstanceObj(ptr, $descriptor(T *), 0)); @@ -156,7 +156,7 @@ namespace std { T* temp; std::vector< T > *v; - if(SWIG_ConvertPtr($input, (void **) &v, \ + if(SWIG_ConvertPtr($input, (void **) &v, $&1_descriptor, 0) == 0) { /* wrapped vector */ $1 = 1; @@ -168,7 +168,7 @@ namespace std { else if (nitems == 0) $1 = 1; - //check the first value to see if it is of correct type + //check the first value to see if it is of correct type else if ((SWIG_ConvertPtr(listobjv[0], (void **) &temp, $descriptor(T *),0)) != 0) @@ -185,7 +185,7 @@ namespace std { T* temp; std::vector< T > *v; - if(SWIG_ConvertPtr($input, (void **) &v, \ + if(SWIG_ConvertPtr($input, (void **) &v, $1_descriptor, 0) == 0){ /* wrapped vector */ $1 = 1; @@ -197,7 +197,7 @@ namespace std { else if (nitems == 0) $1 = 1; - //check the first value to see if it is of correct type + //check the first value to see if it is of correct type else if ((SWIG_ConvertPtr(listobjv[0], (void **) &temp, $descriptor(T *),0)) != 0) @@ -264,7 +264,7 @@ namespace std { int i; T temp; - if(SWIG_ConvertPtr($input, (void **) &v, \ + if(SWIG_ConvertPtr($input, (void **) &v, $&1_descriptor, 0) == 0) { $1 = *v; } else { @@ -288,7 +288,7 @@ namespace std { int i; T temp; - if(SWIG_ConvertPtr($input, (void **) &v, \ + if(SWIG_ConvertPtr($input, (void **) &v, $1_descriptor, 0) == 0) { $1 = v; } else { @@ -308,7 +308,7 @@ namespace std { %typemap(out) vector< T > { for (unsigned int i=0; i<$1.size(); i++) { - Tcl_ListObjAppendElement(interp, $result, \ + Tcl_ListObjAppendElement(interp, $result, CONVERT_TO((($1_type &)$1)[i])); } } @@ -319,7 +319,7 @@ namespace std { T temp; std::vector< T > *v; - if(SWIG_ConvertPtr($input, (void **) &v, \ + if(SWIG_ConvertPtr($input, (void **) &v, $&1_descriptor, 0) == 0){ /* wrapped vector */ $1 = 1; @@ -331,11 +331,11 @@ namespace std { else if (nitems == 0) $1 = 1; - //check the first value to see if it is of correct type - if (CONVERT_FROM(interp, listobjv[0], &temp) == TCL_ERROR) - $1 = 0; - else - $1 = 1; + //check the first value to see if it is of correct type + else if (CONVERT_FROM(interp, listobjv[0], &temp) == TCL_ERROR) + $1 = 0; + else + $1 = 1; } } @@ -346,7 +346,7 @@ namespace std { T temp; std::vector< T > *v; - if(SWIG_ConvertPtr($input, (void **) &v, \ + if(SWIG_ConvertPtr($input, (void **) &v, $1_descriptor, 0) == 0){ /* wrapped vector */ $1 = 1; @@ -358,11 +358,11 @@ namespace std { else if (nitems == 0) $1 = 1; - //check the first value to see if it is of correct type - if (CONVERT_FROM(interp, listobjv[0], &temp) == TCL_ERROR) - $1 = 0; - else - $1 = 1; + //check the first value to see if it is of correct type + else if (CONVERT_FROM(interp, listobjv[0], &temp) == TCL_ERROR) + $1 = 0; + else + $1 = 1; } } diff --git a/Lib/tcl/tclrun.swg b/Lib/tcl/tclrun.swg index 9010b9c87..938ec9854 100644 --- a/Lib/tcl/tclrun.swg +++ b/Lib/tcl/tclrun.swg @@ -67,7 +67,7 @@ #define SWIG_GetConstant SWIG_GetConstantObj #define SWIG_Tcl_GetConstant SWIG_Tcl_GetConstantObj -#if TCL_MAJOR_VERSION >= 8 && TCL_MINOR_VERSION >= 5 +#if TCL_MAJOR_VERSION > 8 || (TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION >= 5) #define SWIG_TCL_HASHTABLE_INIT {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} #else #define SWIG_TCL_HASHTABLE_INIT {0} diff --git a/Lib/tcl/tclsh.i b/Lib/tcl/tclsh.i index 160ba8d8f..a119b93ac 100644 --- a/Lib/tcl/tclsh.i +++ b/Lib/tcl/tclsh.i @@ -46,11 +46,7 @@ int Tcl_AppInit(Tcl_Interp *interp){ if (SWIG_init(interp) == TCL_ERROR) return TCL_ERROR; -#if TCL_MAJOR_VERSION > 7 || TCL_MAJOR_VERSION == 7 && TCL_MINOR_VERSION >= 5 - Tcl_SetVar(interp, (char *) "tcl_rcFileName",SWIG_RcFileName,TCL_GLOBAL_ONLY); -#else - tcl_RcFileName = SWIG_RcFileName; -#endif + Tcl_SetVar(interp, (char *) "tcl_rcFileName",SWIG_RcFileName,TCL_GLOBAL_ONLY); #ifdef SWIG_RcRsrcName Tcl_SetVar(interp, (char *) "tcl_rcRsrcName",SWIG_RcRsrcName,TCL_GLOBAL); #endif @@ -58,7 +54,6 @@ int Tcl_AppInit(Tcl_Interp *interp){ return TCL_OK; } -#if TCL_MAJOR_VERSION > 7 || TCL_MAJOR_VERSION == 7 && TCL_MINOR_VERSION >= 4 int main(int argc, char **argv) { #ifdef MAC_TCL char *newArgv[2]; @@ -77,9 +72,6 @@ int main(int argc, char **argv) { return(0); } -#else -extern int main(); -#endif %} diff --git a/Lib/tcl/wish.i b/Lib/tcl/wish.i index 260032a81..bfd2c5fa9 100644 --- a/Lib/tcl/wish.i +++ b/Lib/tcl/wish.i @@ -104,11 +104,7 @@ int Tcl_AppInit(Tcl_Interp *interp) * then no user-specific startup file will be run under any conditions. */ -#if TCL_MAJOR_VERSION >= 8 || TCL_MAJOR_VERSION == 7 && TCL_MINOR_VERSION >= 5 Tcl_SetVar(interp, (char *) "tcl_rcFileName",SWIG_RcFileName,TCL_GLOBAL_ONLY); -#else - tcl_RcFileName = SWIG_RcFileName; -#endif /* For Macintosh might also want this */ diff --git a/Lib/typemaps/attribute.swg b/Lib/typemaps/attribute.swg index 988113991..7d4767f52 100644 --- a/Lib/typemaps/attribute.swg +++ b/Lib/typemaps/attribute.swg @@ -7,132 +7,6 @@ /* The following macros convert a pair of set/get methods into a "native" attribute. - - Use %attribute when you have a pair of get/set methods to a primitive type - like in: - - %attribute(A, int, a, get_a, set_a); - - struct A - { - int get_a() const; - void set_a(int aa); - }; - - If you don't provide a 'set' method, a 'read-only' attribute - is generated, ie, like in: - - %attribute(A, int, c, get_c); - - Use %attributeref when you have const/non-const reference access methods - for primitive types or class/structs, like in: - - %attributeref(A, int, b); - - struct A - { - const int& b() const; - int& b(); - }; - - %attributeref(B, int, c); - - struct B - { - int& c(); - }; - - You can also use - - %attributeref(Class, AttributeType, AttributeName, AccessorMethod) - - if the internal C++ reference methods have a different name from the - attribute you want, so - - %attributeref(B, int, d, c); - - is the same as the last example, but instead of the attribute 'c' being - called 'c', it is called 'd'. - - Now you can use the attributes like so: - - x = A() - x.a = 3 # calls A::set_a - print x.a # calls A::get_a - - x.b = 3 # calls A::b() - print x.b # calls A::b() const - - Use %attribute2 instead of %attribute to indicate that reference-pointer - translation is required. You use %attribute2 instead of %attribute in - cases like this: - - %attribute2(MyClass, MyFoo, Foo, GetFoo, SetFoo); - %inline %{ - struct MyFoo { - int x; - }; - class MyClass { - MyFoo foo; - public: - MyFoo& GetFoo() { return foo; } - void SetFoo(const MyFoo& other) { foo = other; } - }; - %} - - Here, the data type of the property is a wrapped type (MyFoo) and on the - C++ side it is passed by reference. The problem is that the SWIG wrapper will - pass around a pointer (MyFoo *) which is not compatible with the reference - type of the accessors (MyFoo &). Therefore, if you use %attribute, you'll get - an error from your C/C++ compiler. %attribute2 translates between a pointer - and a reference to eliminate the error. In case you're confused, let's make it - simple: just use %attribute at first, but if the C/C++ compiler gives an error - while compiling the wrapper, try %attribute2 instead. - - NOTE: remember that if the type contains commas, such as 'std::pair', - you need to use the macro like: - - %attributeref(A, %arg(std::pair), pval); - - where %arg() 'normalizes' the type to be understood as a single - argument, otherwise the macro will get confused by the comma. - - The %attributeval is the same as %attribute, but should be used when the type - is a class/struct (ie a non-primitive type) and when the get and set methods - return/pass by value. The following is very similar to the above example, but - note that the access is by value rather than reference. - - %attributeval(MyClassVal, MyFoo, ReadWriteFoo, GetFoo, SetFoo); - %attributeval(MyClassVal, MyFoo, ReadOnlyFoo, GetFoo); - %inline %{ - class MyClassVal { - MyFoo foo; - public: - MyFoo GetFoo() { return foo; } - void SetFoo(MyFoo other) { foo = other; } - }; - %} - - The %attributestring is the same as %attributeval, but should be used for string - class types, which are unusual as they are a class on the C++ side, but normally an - immutable/primitive type in the target language. Example usage for std::string: - - %include - %attributestring(MyStringyClass, std::string, ReadWriteString, GetString, SetString); - %attributestring(MyStringyClass, std::string, ReadOnlyString, GetString); - %inline %{ - class MyStringyClass { - std::string str; - public: - MyStringyClass(const std::string &val) : str(val) {} - std::string GetString() { return str; } - void SetString(std::string other) { str = other; } - }; - %} - - The %attributestring also works for class types that have %naturalvar turned - on and so is also useful for shared_ptr which has %naturalvar turned on in %shared_ptr. - */ // @@ -224,7 +98,7 @@ #if #AccessorMethod != "" %attribute_custom(%arg(Class), %arg(AttributeType), AttributeName, AccessorMethod, AccessorMethod, &self_->AccessorMethod(), self_->AccessorMethod() = *val_) #else - %attribute_custom(%arg(Class), %arg(AttributeType), AccessorName, AccessorName, AccessorName, &self_->AccessorName(), self_->AccessorName() = *val_) + %attribute_custom(%arg(Class), %arg(AttributeType), AttributeName, AttributeName, AttributeName, &self_->AttributeName(), self_->AttributeName() = *val_) #endif %enddef diff --git a/Lib/typemaps/cpointer.swg b/Lib/typemaps/cpointer.swg index 94bbbd6bc..a5ac07d85 100644 --- a/Lib/typemaps/cpointer.swg +++ b/Lib/typemaps/cpointer.swg @@ -55,7 +55,7 @@ typedef struct { return %new_instance(TYPE); } ~NAME() { - if ($self) %delete($self); + %delete($self); } } @@ -105,7 +105,7 @@ typedef struct { %define %pointer_functions(TYPE,NAME) %{ - static TYPE *new_##NAME() { + static TYPE *new_##NAME(void) { return %new_instance(TYPE); } @@ -114,7 +114,7 @@ typedef struct { } static void delete_##NAME(TYPE *obj) { - if (obj) %delete(obj); + %delete(obj); } static void NAME ##_assign(TYPE *obj, TYPE value) { @@ -126,7 +126,7 @@ typedef struct { } %} -TYPE *new_##NAME(); +TYPE *new_##NAME(void); TYPE *copy_##NAME(TYPE value); void delete_##NAME(TYPE *obj); void NAME##_assign(TYPE *obj, TYPE value); diff --git a/Lib/typemaps/exception.swg b/Lib/typemaps/exception.swg index b60a32996..e48294c3f 100644 --- a/Lib/typemaps/exception.swg +++ b/Lib/typemaps/exception.swg @@ -30,7 +30,7 @@ %define_as(SWIG_exception_fail(code, msg), %block(%error(code, msg); SWIG_fail)) -%define_as(SWIG_contract_assert(expr, msg), if (!(expr)) { %error(SWIG_RuntimeError, msg); SWIG_fail; } else) +%define_as(SWIG_contract_assert(expr, msg), do { if (!(expr)) { %error(SWIG_RuntimeError, msg); SWIG_fail; } } while (0)) } diff --git a/Lib/typemaps/swigtype.swg b/Lib/typemaps/swigtype.swg index 581de1a90..402313ebf 100644 --- a/Lib/typemaps/swigtype.swg +++ b/Lib/typemaps/swigtype.swg @@ -562,29 +562,29 @@ * ------------------------------------------------------------ */ %typemap(in) SWIGTYPE (CLASS::*) { - int res = SWIG_ConvertMember($input, %as_voidptr(&$1), sizeof($type),$descriptor); + int res = SWIG_ConvertMember($input, %as_voidptr(&$1), sizeof($1),$descriptor); if (!SWIG_IsOK(res)) { %argument_fail(res,"$type",$symname, $argnum); } } %typemap(out,noblock=1) SWIGTYPE (CLASS::*) { - %set_output(SWIG_NewMemberObj(%as_voidptr(&$1), sizeof($type), $descriptor)); + %set_output(SWIG_NewMemberObj(%as_voidptr(&$1), sizeof($1), $descriptor)); } %typemap(varin) SWIGTYPE (CLASS::*) { - int res = SWIG_ConvertMember($input,%as_voidptr(&$1), sizeof($type), $descriptor); + int res = SWIG_ConvertMember($input,%as_voidptr(&$1), sizeof($1), $descriptor); if (!SWIG_IsOK(res)) { %variable_fail(res, "$type", "$name"); } } %typemap(varout,noblock=1) SWIGTYPE (CLASS::*) { - %set_varoutput(SWIG_NewMemberObj(%as_voidptr(&$1), sizeof($type), $descriptor)); + %set_varoutput(SWIG_NewMemberObj(%as_voidptr(&$1), sizeof($1), $descriptor)); } %typemap(constcode,noblock=1) SWIGTYPE (CLASS::*) { - %set_constant("$symname", SWIG_NewMemberObj(%as_voidptr(&$value), sizeof($type), $descriptor)); + %set_constant("$symname", SWIG_NewMemberObj(%as_voidptr(&$value), sizeof($value), $descriptor)); } #if defined(SWIG_DIRECTOR_TYPEMAPS) @@ -592,13 +592,13 @@ /* directorin */ %typemap(directorin,noblock=1) SWIGTYPE (CLASS::*) { - $input = SWIG_NewMemberObj(%as_voidptr(&$1), sizeof($type), $descriptor); + $input = SWIG_NewMemberObj(%as_voidptr(&$1), sizeof($1), $descriptor); } /* directorout */ %typemap(directorout) SWIGTYPE (CLASS::*) { - int swig_res = SWIG_ConvertMember($input,%as_voidptr(&$result), sizeof($type), $descriptor); + int swig_res = SWIG_ConvertMember($input,%as_voidptr(&$result), sizeof($result), $descriptor); if (!SWIG_IsOK(swig_res)) { %dirout_fail(swig_res,"$type"); } diff --git a/Lib/uffi/uffi.swg b/Lib/uffi/uffi.swg deleted file mode 100644 index 41b085998..000000000 --- a/Lib/uffi/uffi.swg +++ /dev/null @@ -1,101 +0,0 @@ -/* Define a C preprocessor symbol that can be used in interface files - to distinguish between the SWIG language modules. */ - -#define SWIG_UFFI - -/* Typespecs for basic types. */ - -%typemap(ffitype) char ":char"; -%typemap(ffitype) unsigned char ":unsigned-char"; -%typemap(ffitype) signed char ":char"; -%typemap(ffitype) short ":short"; -%typemap(ffitype) signed short ":short"; -%typemap(ffitype) unsigned short ":unsigned-short"; -%typemap(ffitype) int ":int"; -%typemap(ffitype) signed int ":int"; -%typemap(ffitype) unsigned int ":unsigned-int"; -%typemap(ffitype) long ":long"; -%typemap(ffitype) signed long ":long"; -%typemap(ffitype) unsigned long ":unsigned-long"; -%typemap(ffitype) float ":float"; -%typemap(ffitype) double ":double"; -%typemap(ffitype) char * ":cstring"; -%typemap(ffitype) void * ":pointer-void"; -%typemap(ffitype) void ":void"; - -// FIXME: This is guesswork -typedef long size_t; - -%wrapper %{ -(eval-when (compile eval) - -;;; You can define your own identifier converter if you want. -;;; Use the -identifier-converter command line argument to -;;; specify its name. - -(defun identifier-convert-null (id &key type) - (declare (ignore type)) - (read-from-string id)) - -(defun identifier-convert-lispify (cname &key type) - (assert (stringp cname)) - (if (eq type :constant) - (setf cname (format nil "*~A*" cname))) - (setf cname (replace-regexp cname "_" "-")) - (let ((lastcase :other) - newcase char res) - (dotimes (n (length cname)) - (setf char (schar cname n)) - (if* (alpha-char-p char) - then - (setf newcase (if (upper-case-p char) :upper :lower)) - - (when (or (and (eq lastcase :upper) (eq newcase :lower)) - (and (eq lastcase :lower) (eq newcase :upper))) - ;; case change... add a dash - (push #\- res) - (setf newcase :other)) - - (push (char-downcase char) res) - - (setf lastcase newcase) - - else - (push char res) - (setf lastcase :other))) - (read-from-string (coerce (nreverse res) 'string)))) - -(defun identifier-convert-low-level (cname &key type) - (assert (stringp cname)) - (if (eq type :constant) - (setf cname (format nil "+~A+" cname))) - (setf cname (substitute #\- #\_ cname)) - (if (eq type :operator) - (setf cname (format nil "%~A" cname))) - (if (eq type :constant-function) - nil) - (read-from-string cname)) - - - -(defmacro swig-defconstant (string value &key (export T)) - (let ((symbol (funcall *swig-identifier-converter* string :type :constant))) - `(eval-when (compile load eval) - (uffi:def-constant ,symbol ,value ,export)))) - -(defmacro swig-defun (name &rest rest) - (let ((symbol (funcall *swig-identifier-converter* name :type :operator))) - `(eval-when (compile load eval) - (uffi:def-function (,name ,symbol) ,@rest) - (export (quote ,symbol))))) - -(defmacro swig-def-struct (name &rest fields) - "Declare a struct object" - (let ((symbol (funcall *swig-identifier-converter* name :type :type))) - `(eval-when (compile load eval) - (uffi:def-struct ,symbol ,@fields) - (export (quote ,symbol))))) - - -) ;; eval-when -%} diff --git a/Makefile.in b/Makefile.in index 39816bed5..6edfc240a 100644 --- a/Makefile.in +++ b/Makefile.in @@ -29,7 +29,7 @@ TARGET = $(TARGET_NOEXE)@EXEEXT@ SOURCE = Source CCACHE = CCache DOCS = Doc/Manual -HAVE_CXX11_COMPILER = @HAVE_CXX11_COMPILER@ +HAVE_CXX11 = @HAVE_CXX11@ swig: libfiles source ccache @@ -249,7 +249,7 @@ check-%-test-suite: echo warning: cannot $(ACTION) $* test-suite "(no dir $$dir)";\ else \ echo $(ACTION)ing $* test-suite; \ - (cd $$dir && $(MAKE) $(FLAGS) $(ACTION) HAVE_CXX11_COMPILER=$(HAVE_CXX11_COMPILER)) \ + (cd $$dir && $(MAKE) $(FLAGS) $(ACTION) HAVE_CXX11=$(HAVE_CXX11)) \ || passed=false; \ fi; \ test $$passed = true diff --git a/RELEASENOTES b/RELEASENOTES index cc3ba0712..1fedffc8a 100644 --- a/RELEASENOTES +++ b/RELEASENOTES @@ -7,6 +7,14 @@ Release Notes Detailed release notes are available with the release and are also published on the SWIG web site at http://swig.org/release.html. +SWIG-4.1.0 summary: +- Add PHP 8 support. +- PHP wrapping is now done entirely via PHP's C API - no more .php wrapper. +- Perl 5.8.0 is now the oldest version SWIG supports. +- Common cases of `<` and `>` comparisons in constant expressions are now + supported. +- GitHub Actions is now used instead of Travis CI for continuous integration. + SWIG-4.0.2 summary: - A few fixes around doxygen comment handling. - Ruby 2.7 support added. diff --git a/Source/CParse/cscanner.c b/Source/CParse/cscanner.c index 19a013803..44ac39bd3 100644 --- a/Source/CParse/cscanner.c +++ b/Source/CParse/cscanner.c @@ -93,7 +93,7 @@ int isStructuralDoxygen(String *s) { const size_t len = strlen(structuralTags[n]); if (strncmp(slashPointer, structuralTags[n], len) == 0) { /* Take care to avoid false positives with prefixes of other tags. */ - if (slashPointer[len] == '\0' || isspace(slashPointer[len])) + if (slashPointer[len] == '\0' || isspace((int)slashPointer[len])) return 1; } } @@ -214,13 +214,13 @@ void skip_decl(void) { tok = Scanner_token(scan); if (tok == 0) { if (!Swig_error_count()) { - Swig_error(cparse_file, start_line, "Missing semicolon. Reached end of input.\n"); + Swig_error(cparse_file, start_line, "Missing semicolon (';'). Reached end of input.\n"); } return; } if (tok == SWIG_TOKEN_LBRACE) { if (Scanner_skip_balanced(scan,'{','}') < 0) { - Swig_error(cparse_file, start_line, "Missing '}'. Reached end of input.\n"); + Swig_error(cparse_file, start_line, "Missing closing brace ('}'). Reached end of input.\n"); } break; } @@ -267,7 +267,7 @@ static int yylook(void) { case SWIG_TOKEN_RBRACE: num_brace--; if (num_brace < 0) { - Swig_error(cparse_file, cparse_line, "Syntax error. Extraneous '}'\n"); + Swig_error(cparse_file, cparse_line, "Syntax error. Extraneous closing brace ('}')\n"); num_brace = 0; } else { return RBRACE; @@ -351,6 +351,9 @@ static int yylook(void) { } break; + case SWIG_TOKEN_ELLIPSIS: + return ELLIPSIS; + /* Look for multi-character sequences */ case SWIG_TOKEN_RSTRING: @@ -908,7 +911,7 @@ int yylex(void) { if (strcmp(yytext, "class") == 0) { Swig_warning(WARN_PARSE_CLASS_KEYWORD, cparse_file, cparse_line, "class keyword used, but not in C++ mode.\n"); } - if (strcmp(yytext, "complex") == 0) { + if (strcmp(yytext, "_Complex") == 0) { yylval.type = NewSwigType(T_COMPLEX); return (TYPE_COMPLEX); } @@ -1028,8 +1031,23 @@ int yylex(void) { if (strcmp(yytext, "%warn") == 0) return (WARN); - /* Note down the apparently unknown directive for error reporting. */ + /* Note down the apparently unknown directive for error reporting - if + * we end up reporting a generic syntax error we'll instead report an + * error for his as an unknown directive. Then we treat it as MODULO + * (`%`) followed by an identifier and if that parses OK then + * `cparse_unknown_directive` doesn't get used. + * + * This allows `a%b` to be handled in expressions without a space after + * the operator. + */ cparse_unknown_directive = NewString(yytext); + String *stext = NewString(yytext + 1); + Seek(stext,0,SEEK_SET); + Setfile(stext,cparse_file); + Setline(stext,cparse_line); + Scanner_push(scan,stext); + Delete(stext); + return (MODULO); } /* 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 8029dee3d..8f5428915 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1587,6 +1587,9 @@ static String *add_qualifier_to_declarator(SwigType *type, SwigType *qualifier) Node *node; }; +// Define special token END for end of input. +%token END 0 + %token ID %token HBLOCK %token POUND @@ -1596,7 +1599,7 @@ static String *add_qualifier_to_declarator(SwigType *type, SwigType *qualifier) %token NUM_INT NUM_FLOAT NUM_UNSIGNED NUM_LONG NUM_ULONG NUM_LONGLONG NUM_ULONGLONG NUM_BOOL %token TYPEDEF %token TYPE_INT TYPE_UNSIGNED TYPE_SHORT TYPE_LONG TYPE_FLOAT TYPE_DOUBLE TYPE_CHAR TYPE_WCHAR TYPE_VOID TYPE_SIGNED TYPE_BOOL TYPE_COMPLEX TYPE_TYPEDEF TYPE_RAW TYPE_NON_ISO_INT8 TYPE_NON_ISO_INT16 TYPE_NON_ISO_INT32 TYPE_NON_ISO_INT64 -%token LPAREN RPAREN COMMA SEMI EXTERN INIT LBRACE RBRACE PERIOD +%token LPAREN RPAREN COMMA SEMI EXTERN INIT LBRACE RBRACE PERIOD ELLIPSIS %token CONST_QUAL VOLATILE REGISTER STRUCT UNION EQUAL SIZEOF MODULE LBRACKET RBRACKET %token BEGINFILE ENDOFFILE %token ILLEGAL CONSTANT @@ -1671,11 +1674,11 @@ static String *add_qualifier_to_declarator(SwigType *type, SwigType *qualifier) %type

    templateparameter ; %type templcpptype cpptype classkey classkeyopt access_specifier; %type base_specifier; -%type ellipsis variadic; +%type variadic; %type type rawtype type_right anon_bitfield_type decltype ; %type base_list inherit raw_inherit; %type definetype def_args etype default_delete deleted_definition explicit_default; -%type expr exprnum exprcompound valexpr exprmem; +%type expr exprnum exprsimple exprcompound valexpr exprmem callparms callptail; %type ename ; %type less_valparms_greater; %type type_qualifier; @@ -1860,7 +1863,7 @@ extend_directive : EXTEND options classkeyopt idcolon LBRACE { } else { /* Previous typedef class definition. Use its symbol table. Deprecated, just the real name should be used. - Note that %extend before the class typedef never worked, only %extend after the class typdef. */ + Note that %extend before the class typedef never worked, only %extend after the class typedef. */ prev_symtab = Swig_symbol_setscope(Getattr(cls, "symtab")); current_class = cls; SWIG_WARN_NODE_BEGIN(cls); @@ -2010,6 +2013,10 @@ constant_directive : CONSTANT identifier EQUAL definetype SEMI { Swig_warning(WARN_PARSE_BAD_VALUE,cparse_file,cparse_line,"Bad constant value (ignored).\n"); $$ = 0; } + | CONSTANT error END { + Swig_error(cparse_file,cparse_line,"Missing semicolon (';') after %%constant.\n"); + SWIG_exit(EXIT_FAILURE); + } ; /* ------------------------------------------------------------ @@ -2963,6 +2970,7 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va String *nname = NewStringf("__dummy_%d__", cnt++); Swig_cparse_template_expand(templnode,nname,temparms,tscope); Setattr(templnode,"sym:name",nname); + SetFlag(templnode,"hidden"); Delete(nname); Setattr(templnode,"feature:onlychildren", "typemap,typemapitem,typemapcopy,typedef,types,fragment,apply"); if ($3) { @@ -3126,14 +3134,22 @@ c_declaration : c_decl { Setattr($$,"name",$2); appendChild($$,n); while (n) { - SwigType *decl = Getattr(n,"decl"); - if (SwigType_isfunction(decl) && !Equal(Getattr(n, "storage"), "typedef")) { + String *s = Getattr(n, "storage"); + if (s) { + if (Strstr(s, "thread_local")) { + Insert(s,0,"externc "); + } else if (!Equal(s, "typedef")) { + Setattr(n,"storage","externc"); + } + } else { Setattr(n,"storage","externc"); } n = nextSibling(n); } } else { - Swig_warning(WARN_PARSE_UNDEFINED_EXTERN,cparse_file, cparse_line,"Unrecognized extern type \"%s\".\n", $2); + if (!Equal($2,"C++")) { + Swig_warning(WARN_PARSE_UNDEFINED_EXTERN,cparse_file, cparse_line,"Unrecognized extern type \"%s\".\n", $2); + } $$ = new_node("extern"); Setattr($$,"name",$2); appendChild($$,firstChild($5)); @@ -3355,9 +3371,9 @@ c_decl_tail : SEMI { | error { $$ = 0; if (yychar == RPAREN) { - Swig_error(cparse_file, cparse_line, "Unexpected ')'.\n"); + Swig_error(cparse_file, cparse_line, "Unexpected closing parenthesis (')').\n"); } else { - Swig_error(cparse_file, cparse_line, "Syntax error - possibly a missing semicolon.\n"); + Swig_error(cparse_file, cparse_line, "Syntax error - possibly a missing semicolon (';').\n"); } SWIG_exit(EXIT_FAILURE); } @@ -3376,6 +3392,10 @@ cpp_alternate_rettype : primitive_type { $$ = $1; } */ | TYPE_RAW { $$ = $1; } | idcolon { $$ = $1; } + | idcolon AND { + $$ = $1; + SwigType_add_reference($$); + } | decltype { $$ = $1; } ; @@ -4355,18 +4375,30 @@ cpp_template_decl : TEMPLATE LESSTHAN template_parms GREATERTHAN { parsing_template_declaration = 0; } - /* Explicit template instantiation */ + /* Class template explicit instantiation definition */ | TEMPLATE cpptype idcolon { Swig_warning(WARN_PARSE_EXPLICIT_TEMPLATE, cparse_file, cparse_line, "Explicit template instantiation ignored.\n"); $$ = 0; } - /* Explicit template instantiation without the translation unit */ + /* Function template explicit instantiation definition */ + | TEMPLATE cpp_alternate_rettype idcolon LPAREN parms RPAREN { + Swig_warning(WARN_PARSE_EXPLICIT_TEMPLATE, cparse_file, cparse_line, "Explicit template instantiation ignored.\n"); + $$ = 0; + } + + /* Class template explicit instantiation declaration (extern template) */ | EXTERN TEMPLATE cpptype idcolon { - Swig_warning(WARN_PARSE_EXPLICIT_TEMPLATE, cparse_file, cparse_line, "Explicit template instantiation ignored.\n"); + Swig_warning(WARN_PARSE_EXTERN_TEMPLATE, cparse_file, cparse_line, "Extern template ignored.\n"); $$ = 0; } - ; + + /* Function template explicit instantiation declaration (extern template) */ + | EXTERN TEMPLATE cpp_alternate_rettype idcolon LPAREN parms RPAREN { + Swig_warning(WARN_PARSE_EXTERN_TEMPLATE, cparse_file, cparse_line, "Extern template ignored.\n"); + $$ = 0; + } + ; cpp_template_possible: c_decl { $$ = $1; @@ -5062,7 +5094,13 @@ extern_string : EXTERN string { storage_class : EXTERN { $$ = "extern"; } | extern_string { $$ = $1; } - | extern_string THREAD_LOCAL { $$ = "thread_local"; } + | extern_string THREAD_LOCAL { + if (Equal($1, "extern")) { + $$ = "extern thread_local"; + } else { + $$ = "externc thread_local"; + } + } | extern_string TYPEDEF { $$ = "typedef"; } | STATIC { $$ = "static"; } | TYPEDEF { $$ = "typedef"; } @@ -5143,7 +5181,7 @@ parm_no_dox : rawtype parameter_declarator { Setattr($$,"value",$7.val); } } - | PERIOD PERIOD PERIOD { + | ELLIPSIS { SwigType *t = NewString("v(...)"); $$ = NewParmWithoutFileLineInfo(t, 0); previousNode = currentNode; @@ -5230,6 +5268,20 @@ valparm : parm { } ; +callparms : valexpr callptail { + $$ = $1; + Printf($$.val, "%s", $2); + } + | empty { $$.val = NewStringEmpty(); } + ; + +callptail : COMMA valexpr callptail { + $$.val = NewStringf(",%s%s", $2, $3); + $$.type = 0; + } + | empty { $$.val = NewStringEmpty(); } + ; + def_args : EQUAL definetype { $$ = $2; if ($2.type == T_ERROR) { @@ -5488,16 +5540,16 @@ declarator : pointer notso_direct_declarator { /* Variadic versions eg. MyClasses&... myIds */ - | pointer PERIOD PERIOD PERIOD notso_direct_declarator { - $$ = $5; + | pointer ELLIPSIS notso_direct_declarator { + $$ = $3; if ($$.type) { SwigType_push($1,$$.type); Delete($$.type); } $$.type = $1; } - | pointer AND PERIOD PERIOD PERIOD notso_direct_declarator { - $$ = $6; + | pointer AND ELLIPSIS notso_direct_declarator { + $$ = $4; SwigType_add_reference($1); if ($$.type) { SwigType_push($1,$$.type); @@ -5505,8 +5557,8 @@ declarator : pointer notso_direct_declarator { } $$.type = $1; } - | pointer LAND PERIOD PERIOD PERIOD notso_direct_declarator { - $$ = $6; + | pointer LAND ELLIPSIS notso_direct_declarator { + $$ = $4; SwigType_add_rvalue_reference($1); if ($$.type) { SwigType_push($1,$$.type); @@ -5514,34 +5566,34 @@ declarator : pointer notso_direct_declarator { } $$.type = $1; } - | PERIOD PERIOD PERIOD direct_declarator { - $$ = $4; + | ELLIPSIS direct_declarator { + $$ = $2; if (!$$.type) $$.type = NewStringEmpty(); } - | AND PERIOD PERIOD PERIOD notso_direct_declarator { - $$ = $5; + | AND ELLIPSIS notso_direct_declarator { + $$ = $3; $$.type = NewStringEmpty(); SwigType_add_reference($$.type); - if ($5.type) { - SwigType_push($$.type,$5.type); - Delete($5.type); + if ($3.type) { + SwigType_push($$.type,$3.type); + Delete($3.type); } } - | LAND PERIOD PERIOD PERIOD notso_direct_declarator { + | LAND ELLIPSIS notso_direct_declarator { /* Introduced in C++11, move operator && */ /* Adds one S/R conflict */ - $$ = $5; + $$ = $3; $$.type = NewStringEmpty(); SwigType_add_rvalue_reference($$.type); - if ($5.type) { - SwigType_push($$.type,$5.type); - Delete($5.type); + if ($3.type) { + SwigType_push($$.type,$3.type); + Delete($3.type); } } - | idcolon DSTAR PERIOD PERIOD PERIOD notso_direct_declarator { + | idcolon DSTAR ELLIPSIS notso_direct_declarator { SwigType *t = NewStringEmpty(); - $$ = $6; + $$ = $4; SwigType_add_memberpointer(t,$1); if ($$.type) { SwigType_push(t,$$.type); @@ -5549,9 +5601,9 @@ declarator : pointer notso_direct_declarator { } $$.type = t; } - | pointer idcolon DSTAR PERIOD PERIOD PERIOD notso_direct_declarator { + | pointer idcolon DSTAR ELLIPSIS notso_direct_declarator { SwigType *t = NewStringEmpty(); - $$ = $7; + $$ = $5; SwigType_add_memberpointer(t,$2); SwigType_push($1,t); if ($$.type) { @@ -5561,8 +5613,8 @@ declarator : pointer notso_direct_declarator { $$.type = $1; Delete(t); } - | pointer idcolon DSTAR AND PERIOD PERIOD PERIOD notso_direct_declarator { - $$ = $8; + | pointer idcolon DSTAR AND ELLIPSIS notso_direct_declarator { + $$ = $6; SwigType_add_memberpointer($1,$2); SwigType_add_reference($1); if ($$.type) { @@ -5571,8 +5623,8 @@ declarator : pointer notso_direct_declarator { } $$.type = $1; } - | pointer idcolon DSTAR LAND PERIOD PERIOD PERIOD notso_direct_declarator { - $$ = $8; + | pointer idcolon DSTAR LAND ELLIPSIS notso_direct_declarator { + $$ = $6; SwigType_add_memberpointer($1,$2); SwigType_add_rvalue_reference($1); if ($$.type) { @@ -5581,9 +5633,9 @@ declarator : pointer notso_direct_declarator { } $$.type = $1; } - | idcolon DSTAR AND PERIOD PERIOD PERIOD notso_direct_declarator { + | idcolon DSTAR AND ELLIPSIS notso_direct_declarator { SwigType *t = NewStringEmpty(); - $$ = $7; + $$ = $5; SwigType_add_memberpointer(t,$1); SwigType_add_reference(t); if ($$.type) { @@ -5592,9 +5644,9 @@ declarator : pointer notso_direct_declarator { } $$.type = t; } - | idcolon DSTAR LAND PERIOD PERIOD PERIOD notso_direct_declarator { + | idcolon DSTAR LAND ELLIPSIS notso_direct_declarator { SwigType *t = NewStringEmpty(); - $$ = $7; + $$ = $5; SwigType_add_memberpointer(t,$1); SwigType_add_rvalue_reference(t); if ($$.type) { @@ -6232,19 +6284,19 @@ primitive_type_list : type_specifier { } else if (Cmp($1.type,"double") == 0) { if (Cmp($2.type,"long") == 0) { $$.type = NewString("long double"); - } else if (Cmp($2.type,"complex") == 0) { - $$.type = NewString("double complex"); + } else if (Cmp($2.type,"_Complex") == 0) { + $$.type = NewString("double _Complex"); } else { err = 1; } } else if (Cmp($1.type,"float") == 0) { - if (Cmp($2.type,"complex") == 0) { - $$.type = NewString("float complex"); + if (Cmp($2.type,"_Complex") == 0) { + $$.type = NewString("float _Complex"); } else { err = 1; } - } else if (Cmp($1.type,"complex") == 0) { - $$.type = NewStringf("%s complex", $2.type); + } else if (Cmp($1.type,"_Complex") == 0) { + $$.type = NewStringf("%s _Complex", $2.type); } else { err = 1; } @@ -6294,7 +6346,7 @@ type_specifier : TYPE_INT { $$.type = 0; } | TYPE_COMPLEX { - $$.type = NewString("complex"); + $$.type = NewString("_Complex"); $$.us = 0; } | TYPE_NON_ISO_INT8 { @@ -6505,23 +6557,38 @@ exprmem : ID ARROW ID { $$.val = NewStringf("%s->%s", $1, $3); $$.type = 0; } + | ID ARROW ID LPAREN callparms RPAREN { + $$.val = NewStringf("%s->%s(%s)", $1, $3, $5); + $$.type = 0; + } | exprmem ARROW ID { $$ = $1; Printf($$.val, "->%s", $3); } -/* This generates a shift-reduce + | exprmem ARROW ID LPAREN callparms RPAREN { + $$ = $1; + Printf($$.val, "->%s(%s)", $3, $5); + } | ID PERIOD ID { $$.val = NewStringf("%s.%s", $1, $3); $$.type = 0; } -*/ + | ID PERIOD ID LPAREN callparms RPAREN { + $$.val = NewStringf("%s.%s(%s)", $1, $3, $5); + $$.type = 0; + } | exprmem PERIOD ID { $$ = $1; Printf($$.val, ".%s", $3); } + | exprmem PERIOD ID LPAREN callparms RPAREN { + $$ = $1; + Printf($$.val, ".%s(%s)", $3, $5); + } ; -valexpr : exprnum { +/* Non-compound expression */ +exprsimple : exprnum { $$ = $1; } | exprmem { @@ -6536,12 +6603,30 @@ valexpr : exprnum { $$.val = NewStringf("sizeof(%s)",SwigType_str($3,0)); $$.type = T_ULONG; } - | SIZEOF PERIOD PERIOD PERIOD LPAREN type parameter_declarator RPAREN { - SwigType_push($6,$7.type); - $$.val = NewStringf("sizeof...(%s)",SwigType_str($6,0)); + | SIZEOF ELLIPSIS LPAREN type parameter_declarator RPAREN { + SwigType_push($4,$5.type); + $$.val = NewStringf("sizeof...(%s)",SwigType_str($4,0)); $$.type = T_ULONG; } - | exprcompound { $$ = $1; } + /* We don't support all valid expressions here currently - e.g. + * sizeof( x) doesn't work - but those are unlikely to + * be seen in real code. + * + * Note: sizeof(x) is not handled here, but instead by the rule + * for sizeof() because it matches that syntactically. + */ + | SIZEOF LPAREN exprsimple RPAREN { + $$.val = NewStringf("sizeof(%s)", $3.val); + $$.type = T_ULONG; + } + /* `sizeof expr` without parentheses is valid for an expression, + * but not for a type. This doesn't support `sizeof x` in + * addition to the case not supported above. + */ + | SIZEOF exprsimple { + $$.val = NewStringf("sizeof(%s)", $2.val); + $$.type = T_ULONG; + } | wstring { $$.val = $1; $$.rawval = NewStringf("L\"%s\"", $$.val); @@ -6576,6 +6661,11 @@ valexpr : exprnum { $$.final = 0; } + ; + +valexpr : exprsimple { $$ = $1; } + | exprcompound { $$ = $1; } + /* grouping */ | LPAREN expr RPAREN %prec CAST { $$.val = NewStringf("(%s)",$2.val); @@ -6654,7 +6744,7 @@ valexpr : exprnum { $$ = $2; $$.val = NewStringf("*%s",$2.val); } - ; + ; exprnum : NUM_INT { $$ = $1; } | NUM_FLOAT { $$ = $1; } @@ -6722,16 +6812,24 @@ exprcompound : expr PLUS expr { $$.val = NewStringf("%s!=%s",COMPOUND_EXPR_VAL($1),COMPOUND_EXPR_VAL($3)); $$.type = cparse_cplusplus ? T_BOOL : T_INT; } -/* Sadly this causes 2 reduce-reduce conflicts with templates. FIXME resolve these. - | expr GREATERTHAN expr { - $$.val = NewStringf("%s > %s", COMPOUND_EXPR_VAL($1), COMPOUND_EXPR_VAL($3)); + /* Trying to parse `>` in the general case results in conflicts + * in the parser, but all user-reported cases are actually inside + * parentheses and we can handle that case. + */ + | LPAREN expr GREATERTHAN expr RPAREN { + $$.val = NewStringf("%s > %s", COMPOUND_EXPR_VAL($2), COMPOUND_EXPR_VAL($4)); $$.type = cparse_cplusplus ? T_BOOL : T_INT; } - | expr LESSTHAN expr { - $$.val = NewStringf("%s < %s", COMPOUND_EXPR_VAL($1), COMPOUND_EXPR_VAL($3)); + + /* Similarly for `<` except trying to handle exprcompound on the + * left side gives a shift/reduce conflict, so also restrict + * handling to non-compound subexpressions there. Again this + * covers all user-reported cases. + */ + | LPAREN exprsimple LESSTHAN expr RPAREN { + $$.val = NewStringf("%s < %s", COMPOUND_EXPR_VAL($2), COMPOUND_EXPR_VAL($4)); $$.type = cparse_cplusplus ? T_BOOL : T_INT; } -*/ | expr GREATERTHANOREQUALTO expr { $$.val = NewStringf("%s >= %s", COMPOUND_EXPR_VAL($1), COMPOUND_EXPR_VAL($3)); $$.type = cparse_cplusplus ? T_BOOL : T_INT; @@ -6778,14 +6876,9 @@ exprcompound : expr PLUS expr { } ; -ellipsis : PERIOD PERIOD PERIOD { +variadic : ELLIPSIS { $$ = NewString("..."); } - ; - -variadic : ellipsis { - $$ = $1; - } | empty { $$ = 0; } @@ -6875,11 +6968,11 @@ templcpptype : CLASS { $$ = (char *)"typename"; if (!inherit_list) last_cpptype = $$; } - | CLASS PERIOD PERIOD PERIOD { + | CLASS ELLIPSIS { $$ = (char *)"class..."; if (!inherit_list) last_cpptype = $$; } - | TYPENAME PERIOD PERIOD PERIOD { + | TYPENAME ELLIPSIS { $$ = (char *)"typename..."; if (!inherit_list) last_cpptype = $$; } @@ -7085,8 +7178,8 @@ ctor_initializer : COLON mem_initializer_list mem_initializer_list : mem_initializer | mem_initializer_list COMMA mem_initializer - | mem_initializer PERIOD PERIOD PERIOD - | mem_initializer_list COMMA mem_initializer PERIOD PERIOD PERIOD + | mem_initializer ELLIPSIS + | mem_initializer_list COMMA mem_initializer ELLIPSIS ; mem_initializer : idcolon LPAREN { diff --git a/Source/CParse/templ.c b/Source/CParse/templ.c index 5f43bad82..3a9cfc72e 100644 --- a/Source/CParse/templ.c +++ b/Source/CParse/templ.c @@ -338,7 +338,7 @@ String *partial_arg(String *s, String *p) { } prefix = NewStringWithSize(cp, (int)(c - cp)); newarg = Copy(s); - Replace(newarg, prefix, "", DOH_REPLACE_ANY | DOH_REPLACE_FIRST); + Replace(newarg, prefix, "", DOH_REPLACE_FIRST); Delete(prefix); return newarg; } @@ -930,6 +930,7 @@ Node *Swig_cparse_template_locate(String *name, Parm *tparms, Symtab *tscope) { String *nodeType = nodeType(n); int isclass = 0; assert(Equal(nodeType, "template")); + (void)nodeType; isclass = (Equal(Getattr(n, "templatetype"), "class")); if (!isclass) { /* If not a templated class we must have a templated function. diff --git a/Source/DOH/doh.h b/Source/DOH/doh.h index fd0530e9c..a948bc849 100644 --- a/Source/DOH/doh.h +++ b/Source/DOH/doh.h @@ -364,7 +364,7 @@ extern void DohMemoryDebug(void); #define Push(s,x) DohInsertitem(s,DOH_BEGIN,x) #define Len DohLen #define Data DohData -#define Char (char *) Data +#define Char(X) ((char *) Data(X)) #define Cmp DohCmp #define Equal DohEqual #define Setline DohSetline diff --git a/Source/DOH/file.c b/Source/DOH/file.c index 570f84ed5..96f700223 100644 --- a/Source/DOH/file.c +++ b/Source/DOH/file.c @@ -64,6 +64,7 @@ static void open_files_list_remove(DohFile *f) { } Delete(sf); assert(removed); + (void)removed; } /* ----------------------------------------------------------------------------- @@ -80,6 +81,7 @@ void DohCloseAllOpenFiles() { DOHString *sf = Getitem(all_open_files, i); int check = sscanf(Char(sf), "%p", (void **)&f); assert(check == 1); + (void)check; if (f->closeondel) { if (f->filep) { check = fclose(f->filep); diff --git a/Source/DOH/string.c b/Source/DOH/string.c index 3689f4ffe..093330b89 100644 --- a/Source/DOH/string.c +++ b/Source/DOH/string.c @@ -836,7 +836,9 @@ static int replace_simple(String *str, char *token, char *rep, int flags, int co memmove(t, s, (str->str + str->len) - s + 1); } } else { - t += (c - s); + if (c) { + t += (c - s); + } } s = c; ic--; diff --git a/Source/Doxygen/doxyparser.cxx b/Source/Doxygen/doxyparser.cxx index 35d18363f..db0fca9f5 100644 --- a/Source/Doxygen/doxyparser.cxx +++ b/Source/Doxygen/doxyparser.cxx @@ -1081,6 +1081,13 @@ bool DoxygenParser::addDoxyCommand(DoxygenParser::TokenList &tokList, const std: tokList.push_back(Token(COMMAND, cmd)); return true; } else { + if (cmd.empty()) { + // This actually indicates a bug in the code in this file, as this + // function shouldn't be called at all in this case. + printListError(WARN_DOXYGEN_UNKNOWN_COMMAND, "Unexpected empty Doxygen command."); + return false; + } + // This function is called for the special Doxygen commands, but also for // HTML commands (or anything that looks like them, actually) and entities. // We don't recognize all of those, so just ignore them and pass them @@ -1181,6 +1188,11 @@ void DoxygenParser::processWordCommands(size_t &pos, const std::string &line) { size_t endOfWordPos = getEndOfWordCommand(line, pos); string cmd = line.substr(pos, endOfWordPos - pos); + if (cmd.empty()) { + // This was a bare backslash, just ignore it. + return; + } + addDoxyCommand(m_tokenList, cmd); // A flag for whether we want to skip leading spaces after the command @@ -1229,18 +1241,21 @@ void DoxygenParser::processHtmlTags(size_t &pos, const std::string &line) { // prepend '<' to distinguish HTML tags from doxygen commands if (!cmd.empty() && addDoxyCommand(m_tokenList, '<' + cmd)) { // it is a valid HTML command + if (pos == string::npos) { + pos = line.size(); + } if (line[pos] != '>') { // it should be HTML tag with args, // for example , , ... if (isEndHtmlTag) { m_tokenListIt = m_tokenList.end(); - printListError(WARN_DOXYGEN_HTML_ERROR, "Doxygen HTML error for tag " + cmd + ": Illegal end HTML tag without '>' found."); + printListError(WARN_DOXYGEN_HTML_ERROR, "Doxygen HTML error for tag " + cmd + ": Illegal end HTML tag without greater-than ('>') found."); } endHtmlPos = line.find(">", pos); if (endHtmlPos == string::npos) { m_tokenListIt = m_tokenList.end(); - printListError(WARN_DOXYGEN_HTML_ERROR, "Doxygen HTML error for tag " + cmd + ": HTML tag without '>' found."); + printListError(WARN_DOXYGEN_HTML_ERROR, "Doxygen HTML error for tag " + cmd + ": HTML tag without greater-than ('>') found."); } // add args of HTML command, like link URL, image URL, ... m_tokenList.push_back(Token(PLAINSTRING, line.substr(pos, endHtmlPos - pos))); @@ -1254,7 +1269,7 @@ void DoxygenParser::processHtmlTags(size_t &pos, const std::string &line) { } } - if (pos != string::npos) { + if (pos < line.size()) { pos++; // skip '>' } } else { diff --git a/Source/Doxygen/doxytranslator.h b/Source/Doxygen/doxytranslator.h index f07b632a2..a72a31df6 100644 --- a/Source/Doxygen/doxytranslator.h +++ b/Source/Doxygen/doxytranslator.h @@ -53,13 +53,13 @@ public: virtual ~DoxygenTranslator(); /* - * Return the documentation for a given node formated for the correct + * Return the documentation for a given node formatted for the correct * documentation system. */ String *getDocumentation(Node *node, const_String_or_char_ptr indentationString); /* - * Returns truem is the specified node has comment attached. + * Returns true if the specified node has comment attached. */ bool hasDocumentation(Node *node); diff --git a/Source/Doxygen/javadoc.cxx b/Source/Doxygen/javadoc.cxx index d9313f981..eafa57317 100644 --- a/Source/Doxygen/javadoc.cxx +++ b/Source/Doxygen/javadoc.cxx @@ -152,7 +152,7 @@ void JavaDocConverter::fillStaticTables() { tagHandlers["f{"] = make_pair(&JavaDocConverter::handleTagVerbatim, ""); tagHandlers["warning"] = make_pair(&JavaDocConverter::handleTagMessage, "Warning: "); - // this command just prints it's contents + // this command just prints its contents // (it is internal command of swig's parser, contains plain text) tagHandlers["plainstd::string"] = make_pair(&JavaDocConverter::handlePlainString, ""); tagHandlers["plainstd::endl"] = make_pair(&JavaDocConverter::handleNewLine, ""); diff --git a/Source/Doxygen/pydoc.cxx b/Source/Doxygen/pydoc.cxx index c84095b8f..7b47a814c 100644 --- a/Source/Doxygen/pydoc.cxx +++ b/Source/Doxygen/pydoc.cxx @@ -302,7 +302,7 @@ void PyDocConverter::fillStaticTables() { tagHandlers["ref"] = make_handler(&PyDocConverter::handleTagRef); tagHandlers["result"] = tagHandlers["return"] = tagHandlers["returns"] = make_handler(&PyDocConverter::handleTagReturn); - // this command just prints it's contents + // this command just prints its contents // (it is internal command of swig's parser, contains plain text) tagHandlers["plainstd::string"] = make_handler(&PyDocConverter::handlePlainString); tagHandlers["plainstd::endl"] = make_handler(&PyDocConverter::handleNewLine); diff --git a/Source/Doxygen/pydoc.h b/Source/Doxygen/pydoc.h index 07c5ce51e..19885276f 100644 --- a/Source/Doxygen/pydoc.h +++ b/Source/Doxygen/pydoc.h @@ -195,7 +195,7 @@ private: typedef std::map >TagHandlersMap; static TagHandlersMap tagHandlers; - // this contains the sections tittles, like 'Arguments:' or 'Notes:', that are printed only once + // this contains the sections titles, like 'Arguments:' or 'Notes:', that are printed only once static std::map sectionTitles; // Helper functions for fillStaticTables(): make a new tag handler object. diff --git a/Source/Include/swigwarn.h b/Source/Include/swigwarn.h index a08693ac8..e33ca467e 100644 --- a/Source/Include/swigwarn.h +++ b/Source/Include/swigwarn.h @@ -93,6 +93,7 @@ #define WARN_PARSE_NESTED_TEMPLATE 324 #define WARN_PARSE_NAMED_NESTED_CLASS 325 #define WARN_PARSE_EXTEND_NAME 326 +#define WARN_PARSE_EXTERN_TEMPLATE 327 #define WARN_CPP11_LAMBDA 340 #define WARN_CPP11_ALIAS_DECLARATION 341 /* redundant now */ @@ -147,7 +148,7 @@ #define WARN_IGNORE_OPERATOR_DELARR 395 /* delete [] */ #define WARN_IGNORE_OPERATOR_REF 396 /* operator *() */ -/* 394-399 are reserved */ +/* please leave 350-399 free for WARN_IGNORE_OPERATOR_* */ /* -- Type system and typemaps -- */ @@ -157,9 +158,9 @@ #define WARN_TYPE_REDEFINED 404 #define WARN_TYPE_RVALUE_REF_QUALIFIER_IGNORED 405 -#define WARN_TYPEMAP_SOURCETARGET 450 +#define WARN_TYPEMAP_SOURCETARGET 450 /* No longer issued */ #define WARN_TYPEMAP_CHARLEAK 451 -#define WARN_TYPEMAP_SWIGTYPE 452 +#define WARN_TYPEMAP_SWIGTYPE 452 /* No longer issued */ #define WARN_TYPEMAP_APPLY_UNDEF 453 #define WARN_TYPEMAP_SWIGTYPELEAK 454 @@ -212,6 +213,7 @@ #define WARN_LANG_EXTEND_DESTRUCTOR 523 #define WARN_LANG_EXPERIMENTAL 524 #define WARN_LANG_DIRECTOR_FINAL 525 +#define WARN_LANG_USING_NAME_DIFFERENT 526 /* -- Doxygen comments -- */ @@ -223,7 +225,7 @@ #define WARN_DOXYGEN_UNKNOWN_CHARACTER 565 #define WARN_DOXYGEN_UNEXPECTED_ITERATOR_VALUE 566 -/* -- Reserved (600-799) -- */ +/* -- Reserved (600-699) -- */ /* -- Language module specific warnings (700 - 899) -- */ @@ -277,6 +279,7 @@ #define WARN_JAVA_TYPEMAP_DIRECTORIN_NODESC 824 #define WARN_JAVA_NO_DIRECTORCONNECT_ATTR 825 #define WARN_JAVA_NSPACE_WITHOUT_PACKAGE 826 +#define WARN_JAVA_TYPEMAP_INTERFACEMODIFIERS_UNDEF 847 /* please leave 810-829 free for Java */ @@ -297,22 +300,11 @@ #define WARN_CSHARP_EXCODE 844 #define WARN_CSHARP_CANTHROW 845 #define WARN_CSHARP_NO_DIRECTORCONNECT_ATTR 846 +#define WARN_CSHARP_TYPEMAP_INTERFACEMODIFIERS_UNDEF 847 /* please leave 830-849 free for C# */ -#define WARN_MODULA3_TYPEMAP_TYPE_UNDEF 850 -#define WARN_MODULA3_TYPEMAP_GETCPTR_UNDEF 851 -#define WARN_MODULA3_TYPEMAP_CLASSMOD_UNDEF 852 -#define WARN_MODULA3_TYPEMAP_PTRCONSTMOD_UNDEF 853 -#define WARN_MODULA3_TYPEMAP_MULTIPLE_RETURN 854 -#define WARN_MODULA3_MULTIPLE_INHERITANCE 855 -#define WARN_MODULA3_TYPECONSTRUCTOR_UNKNOWN 856 -#define WARN_MODULA3_UNKNOWN_PRAGMA 857 -#define WARN_MODULA3_BAD_ENUMERATION 858 -#define WARN_MODULA3_DOUBLE_ID 859 -#define WARN_MODULA3_BAD_IMPORT 860 - -/* please leave 850-869 free for Modula 3 */ +/* 850-860 were used by Modula 3 (removed in SWIG 4.1.0) - avoid reusing for now */ #define WARN_PHP_MULTIPLE_INHERITANCE 870 #define WARN_PHP_UNKNOWN_PRAGMA 871 diff --git a/Source/Modules/allegrocl.cxx b/Source/Modules/allegrocl.cxx deleted file mode 100644 index 97af186fe..000000000 --- a/Source/Modules/allegrocl.cxx +++ /dev/null @@ -1,2963 +0,0 @@ -/* ----------------------------------------------------------------------------- - * This file is part of SWIG, which is licensed as a whole under version 3 - * (or any later version) of the GNU General Public License. Some additional - * terms also apply to certain portions of SWIG. The full details of the SWIG - * license and copyrights can be found in the LICENSE and COPYRIGHT files - * included with the SWIG source code as distributed by the SWIG developers - * and at http://www.swig.org/legal.html. - * - * allegrocl.cxx - * - * ALLEGROCL language module for SWIG. - * ----------------------------------------------------------------------------- */ - -#include "swigmod.h" -#include "cparse.h" -#include - -// #define ALLEGROCL_DEBUG -// #define ALLEGROCL_WRAP_DEBUG -// #define ALLEGROCL_TYPE_DEBUG -// #define ALLEGROCL_CLASS_DEBUG - -static const char *usage = "\ -Allegro CL Options (available with -allegrocl)\n\ - -identifier-converter - \n\ - Specifies the type of conversion to do on C identifiers to convert\n\ - them to symbols. There are two built-in converters: 'null' and\n\ - 'lispify'. The default is 'null'. If you supply a name other\n\ - than one of the built-ins, then a function by that name will be\n\ - called to convert identifiers to symbols.\n\ - -[no]cwrap - Turn on or turn off generation of an intermediate C file when\n\ - creating a C interface. By default this is only done for C++ code.\n\ - -isolate - Define all SWIG helper functions in a package unique to this\n\ - module. Avoids redefinition warnings when loading multiple\n\ - SWIGged modules into the same running Allegro CL image.\n\ -"; - -static File *f_cl = 0; -String *f_clhead = NewString(""); -String *f_clwrap = NewString("(swig-in-package ())\n\n"); -static File *f_begin; -static File *f_runtime; -static File *f_cxx_header = 0; -static File *f_cxx_wrapper = 0; - -static String *module_name = 0; -static String *swig_package = 0; - -static String *identifier_converter = NewString("identifier-convert-null"); - -static bool CWrap = true; // generate wrapper file for C code by default. most correct. -static bool Generate_Wrapper = false; -static bool unique_swig_package = false; - -static SwigType *fwdref_ffi_type = NewString("__SWIGACL_FwdReference"); - -static String *current_namespace = NewString(""); -static String *current_package = NewString(""); -static Hash *defined_namespace_packages = NewHash(); -static Node *in_class = 0; - -static Node *first_linked_type = 0; -static Hash *defined_foreign_types = NewHash(); -static Hash *defined_foreign_ltypes = NewHash(); - -static String *anon_type_name = NewString("anontype"); -static int anon_type_count = 0; - -// stub -String *convert_literal(String *num_param, String *type, bool try_to_split = true); - -class ALLEGROCL:public Language { -public: - virtual void main(int argc, char *argv[]); - virtual int top(Node *n); - virtual int functionWrapper(Node *n); - virtual int namespaceDeclaration(Node *n); - virtual int constructorHandler(Node *n); - virtual int destructorHandler(Node *n); - virtual int globalvariableHandler(Node *n); - virtual int variableWrapper(Node *n); - virtual int constantWrapper(Node *n); - virtual int memberfunctionHandler(Node *n); - virtual int membervariableHandler(Node *n); - virtual int classHandler(Node *n); - virtual int emit_one(Node *n); - virtual int enumDeclaration(Node *n); - virtual int enumvalueDeclaration(Node *n); - virtual int typedefHandler(Node *n); - virtual int classforwardDeclaration(Node *n); - virtual int templateDeclaration(Node *n); - virtual int validIdentifier(String *s); -private: - int emit_defun(Node *n, File *f_cl); - int emit_dispatch_defun(Node *n); - int emit_buffered_defuns(Node *n); - int cClassHandler(Node *n); - int cppClassHandler(Node *n); -}; -static ALLEGROCL *allegrocl = 0; - -static String *trim(String *str) { - char *c = Char(str); - while (*c != '\0' && isspace((int) *c)) - ++c; - String *result = NewString(c); - Chop(result); - return result; -} - -int is_integer(String *s) { - char *c = Char(s); - if (c[0] == '#' && (c[1] == 'x' || c[1] == 'o')) - c += 2; - - while (*c) { - if (!isdigit(*c)) - return 0; - c++; - } - return 1; -} - -String *class_from_class_or_class_ref(String *type) { - SwigType *stripped = SwigType_strip_qualifiers(type); - if (SwigType_isclass(stripped)) - return stripped; - - if (SwigType_ispointer(stripped) || SwigType_isreference(stripped)) { - // Printf(stderr,"It is a pointer/reference. Is it a class?\n"); - SwigType_pop(stripped); - if (SwigType_isclass(stripped)) { - return stripped; - } - } - return 0; -} - -String *lookup_defined_foreign_type(String *k) { - -#ifdef ALLEGROCL_TYPE_DEBUG - Printf(stderr, "Looking up defined type '%s'.\n Found: '%s'\n", k, Getattr(defined_foreign_types, k)); -#endif - - return Getattr(defined_foreign_types, k); -} - -String *listify_namespace(String *namespaze) { - if (Len(namespaze) == 0) - return NewString("()"); - String *result = NewStringf("(\"%s\")", namespaze); - Replaceall(result, "::", "\" \""); - return result; -} - -String *namespaced_name(Node *n, String *ns = current_namespace) { - - return NewStringf("%s%s%s", ns, (Len(ns) != 0) ? "::" : "", Getattr(n, "sym:name")); -} - -// "Namespace::Nested::Class2::Baz" -> "Baz" -static String *strip_namespaces(String *str) { - return Swig_scopename_last(str); -} - -void add_linked_type(Node *n) { -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, "Adding linked node of type: %s(%s) %s(%p)\n\n", nodeType(n), Getattr(n, "storage"), Getattr(n, "name"), n); - // Swig_print_node(n); -#endif - if (!first_linked_type) { - first_linked_type = n; - Setattr(n, "allegrocl:last_linked_type", n); - } else { - Node *t = Getattr(first_linked_type, "allegrocl:last_linked_type"); - Setattr(t, "allegrocl:next_linked_type", n); - Setattr(first_linked_type, "allegrocl:last_linked_type", n); - } -} - -void replace_linked_type(Node *old, Node *new_node) { - Node *prev = Getattr(old, "allegrocl:prev_linked_type"); - - Setattr(new_node, "allegrocl:next_linked_type", Getattr(old, "allegrocl:next_linked_type")); - if (prev) - Setattr(prev, "allegrocl:next_linked_type", new_node); - Delattr(old, "allegrocl:next_linked_type"); - Delattr(old, "allegrocl:prev_linked_type"); - - // check if we're replacing the first link. - if (first_linked_type == old) { - first_linked_type = new_node; - Setattr(first_linked_type, "allegrocl:last_linked_type", Getattr(old, "allegrocl:last_linked_type")); - } - // check if we're replacing the last link. - if (Getattr(first_linked_type, "allegrocl:last_linked_type") == old) - Setattr(first_linked_type, "allegrocl:last_linked_type", new_node); -} - -void insert_linked_type_at(Node *old, Node *new_node, int before = 1) { - Node *p = 0; - - if (!first_linked_type) { - add_linked_type(new_node); - return; - } - - if (!before) { - Setattr(new_node, "allegrocl:next_linked_type", Getattr(old, "allegrocl:next_linked_type")); - Setattr(old, "allegrocl:next_linked_type", new_node); - if (Getattr(first_linked_type, "allegrocl:last_linked_type") == old) - Setattr(first_linked_type, "allegrocl:last_linked_type", new_node); - } else { - Node *c = first_linked_type; - while (c) { - if (c == old) { - break; - } else { - p = c; - c = Getattr(c, "allegrocl:next_linked_type"); - } - } - if (c == old) { - Setattr(new_node, "allegrocl:next_linked_type", c); - if (first_linked_type == c) { - first_linked_type = new_node; - Setattr(first_linked_type, "allegrocl:last_linked_type", Getattr(c, "allegrocl:last_linked_type")); - Delattr(c, "allegrocl:last_linked_type"); - } - if (p) - Setattr(p, "allegrocl:next_linked_type", new_node); - } - } -} - -Node *find_linked_type_by_name(String *name) { - Node *p = 0; - Node *c = first_linked_type; - - // Printf(stderr,"in find_linked_type_by_name '%s'...", name); - while (c) { - String *key = Getattr(c, "name"); - if (!Strcmp(key, name)) { - break; - } else { - p = c; - c = Getattr(c, "allegrocl:next_linked_type"); - } - } - // Printf(stderr,"exit find_linked_type_by_name.\n"); - - if (p && c) - Setattr(c, "allegrocl:prev_linked_type", p); - // Printf(stderr,"find_linked_type_by_name: DONE\n"); - return c; -} - -Node *get_primary_synonym_of(Node *n) { - Node *p = Getattr(n, "allegrocl:synonym-of"); - Node *prim = n; - - // Printf(stderr, "getting primary synonym of %p\n", n); - while (p) { - // Printf(stderr, " found one! %p\n", p); - prim = p; - p = Getattr(p, "allegrocl:synonym-of"); - } - // Printf(stderr,"get_primary_syn: DONE. returning %s(%p)\n", Getattr(prim,"name"),prim); - return prim; -} - -void add_forward_referenced_type(Node *n, int overwrite = 0) { - String *k = Getattr(n, "name"); - String *name = Getattr(n, "sym:name"); - String *ns = listify_namespace(current_namespace); - - String *val = Getattr(defined_foreign_types, k); - - if (!val || overwrite) { -#ifdef ALLEGROCL_TYPE_DEBUG - Printf(stderr, "Adding forward reference for %s (overwrite=%d)\n", k, overwrite); -#endif - Setattr(defined_foreign_types, Copy(k), NewString("forward-reference")); - - String *mangled_lname_gen = NewStringf("#.(swig-insert-id \"%s\" %s :type :class)", name, ns); - - Setattr(defined_foreign_ltypes, Copy(k), mangled_lname_gen); - // Printf(f_cl, ";; forward reference stub\n" - // "(swig-def-foreign-class \"%s\" (ff:foreign-pointer) (:class ))\n\n" - // , name); - -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, "Linking forward reference type = %s(%p)\n", k, n); -#endif - add_linked_type(n); - } -} - -void add_defined_foreign_type(Node *n, int overwrite = 0, String *k = 0, - String *name = 0, String *ns = current_namespace) { - - String *val; - String *ns_list = listify_namespace(ns); - String *templated = n ? Getattr(n, "template") : 0; - String *cDeclName = n ? Getattr(n, "name") : 0; - -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, "IN A-D-F-T. (n=%p, ow=%d, k=%s, name=%s, ns=%s\n", n, overwrite, k, name, ns); - Printf(stderr, " templated = '%p', classDecl = '%p'\n", templated, cDeclName); -#endif - if (n) { - if (!name) - name = Getattr(n, "sym:name"); - if (!name) - name = strip_namespaces(Getattr(n, "name")); - if (templated) { - k = namespaced_name(n); - } else { - String *kind_of_type = Getattr(n, "kind"); - - /* - For typedefs of the form: - - typedef struct __xxx { ... } xxx; - - behavior differs between C mode and C++ mode. - - C Mode: - add_defined_foreign_type will be called once via classHandler - to define the type for 'struct __xxx' and add the mapping from - 'struct __xxx' -> 'xxx' - - It will also be called once via typedefHandler to add the - mapping 'xxx' -> 'xxx' - - C++ Mode: - add_defined_foreign_type will be called once via classHandler - to define the type for 'xxx'. it also adds the mapping from - 'xxx' -> 'xxx' and also for 'struct xxx' -> 'xxx' - - In typedefHandler, we again try to add the mapping from - 'xxx' -> 'xxx', which already exists. This second mapping - is ignored. - - Both modes: - - All references to this typedef'd struct will appear in - generated lisp code as an objectd of type 'xxx'. For - non-typedef'd structs, the classHand mapping will be - - struct __xxx -> (swig-insert-id "__xxx") - */ - // Swig_print_node(n); - String *unnamed = Getattr(n, "unnamed"); - if (kind_of_type && (!Strcmp(kind_of_type, "struct") - || !Strcmp(kind_of_type, "union")) && cDeclName && !unnamed) { - k = NewStringf("%s %s", kind_of_type, cDeclName); - } else { - if (!Strcmp(nodeType(n), "enum") && unnamed) { - name = NewStringf("%s%d", anon_type_name, anon_type_count++); - k = NewStringf("enum %s", name); - Setattr(n, "allegrocl:name", name); - - } else { - k = k ? k : Getattr(n, "name"); - } - } - } - // Swig_print_node(n); - } - - String *tname = SwigType_istemplate_templateprefix(name); - if (tname) { - String *temp = strip_namespaces(tname); - name = NewStringf("%s%s%s", temp, SwigType_templateargs(name), SwigType_templatesuffix(name)); - Delete(temp); - Delete(tname); - } - - val = lookup_defined_foreign_type(k); - - int is_fwd_ref = 0; - if (val) - is_fwd_ref = !Strcmp(val, "forward-reference"); - - if (!val || overwrite || is_fwd_ref) { -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, "Adding defined type '%s' = '%s' '%s' (overwrite=%d, in-class=%d)\n", k, ns, name, overwrite, in_class); -#endif - String *mangled_name_gen = NewStringf("#.(swig-insert-id \"%s\" %s :type :type)", name, ns_list); - String *mangled_lname_gen = NewStringf("#.(swig-insert-id \"%s\" %s :type :class)", name, ns_list); - - Setattr(defined_foreign_types, Copy(k), Copy(mangled_name_gen)); - Setattr(defined_foreign_ltypes, Copy(k), Copy(mangled_lname_gen)); - - if (CPlusPlus) { - bool cpp_struct = Strstr(k, "struct ") ? true : false; - bool cpp_union = Strstr(k, "union ") ? true : false; - - String *cpp_type = 0; - if (cpp_struct) { - cpp_type = Copy(k); - Replaceall(cpp_type, "struct ", ""); - } else if (cpp_union) { - cpp_type = Copy(k); - Replaceall(cpp_type, "union ", ""); - } - - if (cpp_struct || cpp_union) { -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, " Also adding defined type '%s' = '%s' '%s' (overwrite=%d)\n", cpp_type, ns, name, overwrite); -#endif - Setattr(defined_foreign_types, Copy(cpp_type), Copy(mangled_name_gen)); - Setattr(defined_foreign_ltypes, Copy(cpp_type), Copy(mangled_lname_gen)); - } - } -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, "looking to add %s/%s(%p) to linked_type_list...\n", k, name, n); -#endif - if (is_fwd_ref) { - // Printf(stderr,"*** 1\n"); - if (n) - add_linked_type(n); - } else { - // Printf(stderr,"*** 1-a\n"); - if (SwigType_istemplate(k)) { - SwigType *resolved = SwigType_typedef_resolve_all(k); - // Printf(stderr,"*** 1-b\n"); - Node *match = find_linked_type_by_name(resolved); - Node *new_node = 0; - // Printf(stderr, "*** temp-1\n"); - if (n) { - new_node = n; - } else { -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, "Creating a new templateInst:\n"); - Printf(stderr, " name = %s\n", resolved); - Printf(stderr, " sym:name = %s\n", name); - Printf(stderr, " real-name = %s\n", k); - Printf(stderr, " type = %s\n", resolved); - Printf(stderr, " ns = %s\n\n", ns); -#endif - new_node = NewHash(); - Setattr(new_node, "nodeType", "templateInst"); - Setattr(new_node, "name", Copy(resolved)); - Setattr(new_node, "sym:name", Copy(name)); - Setattr(new_node, "real-name", Copy(k)); - Setattr(new_node, "type", Copy(resolved)); - Setattr(new_node, "allegrocl:namespace", ns); - Setattr(new_node, "allegrocl:package", ns); - } - - if (!match) { - if (!Strcmp(nodeType(new_node), "templateInst") && in_class) { - /* this is an implicit template instantiation found while - walking a class. need to insert this into the - linked_type list before the current class definition */ -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, "trying to insert a templateInst before a class\n"); -#endif - insert_linked_type_at(in_class, new_node); -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, "DID IT!\n"); -#endif - } else { - // Printf(stderr,"*** 3\n"); - add_linked_type(new_node); - } - Setattr(new_node, "allegrocl:synonym:is-primary", "1"); - } else { - // a synonym type was found (held in variable 'match') - // Printf(stderr, "setting primary synonym of %p to %p\n", new_node, match); - if (new_node == match) - Printf(stderr, "Hey-4 * - '%s' is a synonym of itself!\n", Getattr(new_node, "name")); - Setattr(new_node, "allegrocl:synonym-of", match); - // Printf(stderr,"*** 4\n"); - add_linked_type(new_node); - } - } else { - Node *match; - - if (!Strcmp(nodeType(n), "cdecl") && !Strcmp(Getattr(n, "storage"), "typedef")) { - SwigType *type = SwigType_strip_qualifiers(Getattr(n, "type")); -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, "Examining typedef '%s' for class references. (%d)\n", type, SwigType_isclass(type)); -#endif - if (SwigType_isclass(type)) { -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, "Found typedef of a class '%s'\n", type); -#endif - /* - For the following parsed expression: - - typedef struct __xxx { ... } xxx; - - if n is of kind "class" (defining the class 'struct __xxx' - then we add n to the linked type list. - - if n is "cdecl" node of storage "typedef" (to note - that xxx is equivalent to 'struct __xxx' then we don't - want to add this node to the linked type list. - */ - String *defined_type = lookup_defined_foreign_type(type); - String *defined_key_type = lookup_defined_foreign_type(k); - - if ((Strstr(type, "struct ") || Strstr(type, "union ")) - && defined_type && !Strcmp(defined_type, defined_key_type)) { - // mark as a synonym but don't add to linked_type list - // Printf(stderr,"*** 4.8\n"); - Setattr(n, "allegrocl:synonym", "1"); - } else { - SwigType *lookup_type = SwigType_istemplate(type) ? SwigType_typedef_resolve_all(type) : Copy(type); - match = find_linked_type_by_name(lookup_type); - if (match) { - Setattr(n, "allegrocl:synonym", "1"); - Setattr(n, "allegrocl:synonym-of", match); - Setattr(n, "real-name", Copy(lookup_type)); - - // Printf(stderr, "*** pre-5: found match of '%s'(%p)\n", Getattr(match,"name"),match); - // if(n == match) Printf(stderr, "Hey-5 *** setting synonym of %p to %p\n", n, match); - // Printf(stderr,"*** 5\n"); - add_linked_type(n); - } else { -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, "Creating classfoward node for struct stub in typedef.\n"); -#endif - Node *new_node = NewHash(); - String *symname = Copy(type); - Replaceall(symname, "struct ", ""); - Setattr(new_node, "nodeType", "classforward"); - Setattr(new_node, "name", Copy(type)); - Setattr(new_node, "sym:name", symname); - Setattr(new_node, "allegrocl:namespace", ns); - Setattr(new_node, "allegrocl:package", ns); - - String *mangled_new_name = NewStringf("#.(swig-insert-id \"%s\" %s)", symname, ns_list); - String *mangled_new_lname = NewStringf("#.(swig-insert-id \"%s\" %s :type :class)", symname, ns_list); - Setattr(defined_foreign_types, Copy(symname), Copy(mangled_new_name)); - Setattr(defined_foreign_ltypes, Copy(symname), Copy(mangled_new_lname)); - - // Printf(stderr,"Weird! Can't find the type!\n"); - add_forward_referenced_type(new_node); - add_linked_type(new_node); - - Setattr(n, "allegrocl:synonym", "1"); - Setattr(n, "allegrocl:synonym-of", new_node); - - add_linked_type(n); - } - Delete(lookup_type); - } - } else { - // check if it's a pointer or reference to a class. - // Printf(stderr,"Checking if '%s' is a p. or r. to a class\n", type); - String *class_ref = class_from_class_or_class_ref(type); - if (class_ref) { - match = find_linked_type_by_name(class_ref); - Setattr(n, "allegrocl:synonym", "1"); - Setattr(n, "allegrocl:synonym-of", match); - add_linked_type(n); - } - } - Delete(type); - // synonym types have already been added. - // Printf(stderr,"*** 10\n"); - if (!Getattr(n, "allegrocl:synonym")) - add_linked_type(n); - } else if (Getattr(n, "template")) { - // Printf(stderr, "this is a class template node(%s)\n", nodeType(n)); - String *resolved = SwigType_typedef_resolve_all(Getattr(n, "name")); - -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, " looking up %s for linked type match with %s...\n", Getattr(n, "sym:name"), resolved); -#endif - match = find_linked_type_by_name(resolved); - if (!match) { -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, "found no implicit instantiation of %%template node %s(%p)\n", Getattr(n, "name"), n); -#endif - add_linked_type(n); - } else { - Node *primary = get_primary_synonym_of(match); - - Setattr(n, "allegrocl:synonym:is-primary", "1"); - Delattr(primary, "allegrocl:synonym:is-primary"); - if (n == match) - Printf(stderr, "Hey-7 * setting synonym of %p to %p\n (match = %p)", primary, n, match); - Setattr(primary, "allegrocl:synonym-of", n); - // Printf(stderr,"*** 7\n"); - add_linked_type(n); - } - } else { -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, "linking type '%s'(%p)\n", k, n); -#endif - // Printf(stderr,"*** 8\n"); - add_linked_type(n); - } - } - } - Delete(mangled_name_gen); - Delete(mangled_lname_gen); - } else { - if (!CPlusPlus || Strcmp(Getattr(n,"kind"),"typedef")) { - Swig_warning(WARN_TYPE_REDEFINED, Getfile(n), Getline(n), - "Attempting to store a foreign type that exists: %s (%s)\n", - k, val); - } - } - - Delete(ns_list); - -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, "OUT A-D-F-T\n"); -#endif -} - -void note_implicit_template_instantiation(SwigType *t) { - // the namespace of the implicit instantiation is not necessarily - // current_namespace. Attempt to cull this from the type. -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, "culling namespace of '%s' from '%s'\n", t, SwigType_templateprefix(t)); -#endif - SwigType *type = Copy(t); - SwigType *tok = SwigType_pop(type); - String *implicit_ns = SwigType_istemplate(tok) ? Swig_scopename_prefix(SwigType_templateprefix(tok)) : 0; - add_defined_foreign_type(0, 0, t, t, implicit_ns ? implicit_ns : current_namespace); - - Delete(type); -} - -String *get_ffi_type(Node *n, SwigType *ty, const_String_or_char_ptr name) { - /* lookup defined foreign type. - if it exists, it will return a form suitable for placing - into lisp code to generate the def-foreign-type name */ - -#ifdef ALLEGROCL_TYPE_DEBUG - Printf(stderr, "inside g_f_t: looking up '%s' '%s'\n", ty, name); -#endif - - String *found_type = lookup_defined_foreign_type(ty); - - if (found_type) { -#ifdef ALLEGROCL_TYPE_DEBUG - Printf(stderr, "found_type '%s'\n", found_type); -#endif - return (Strcmp(found_type, "forward-reference") ? Copy(found_type) : get_ffi_type(n, fwdref_ffi_type, "")); - } else { - Node *node = NewHash(); - Setattr(node, "type", ty); - Setfile(node, Getfile(n)); - Setline(node, Getline(n)); - const String *tm = Swig_typemap_lookup("ffitype", node, name, 0); - Delete(node); - - if (tm) { -#ifdef ALLEGROCL_TYPE_DEBUG - Printf(stderr, "g-f-t: found ffitype typemap '%s'\n", tm); -#endif - return NewString(tm); - } - - if (SwigType_istemplate(ty)) { - note_implicit_template_instantiation(ty); - return Copy(lookup_defined_foreign_type(ty)); - } - } - return 0; -} - -String *lookup_defined_foreign_ltype(String *l) { - -#ifdef ALLEGROCL_TYPE_DEBUG - Printf(stderr, "Looking up defined ltype '%s'.\n Found: '%s'\n", l, Getattr(defined_foreign_ltypes, l)); -#endif - return Getattr(defined_foreign_ltypes, l); -} - -/* walk type and return string containing lisp version. - recursive. */ -String *internal_compose_foreign_type(Node *n, SwigType *ty) { - - SwigType *tok; - String *ffiType = NewString(""); - - // for a function type, need to walk the parm list. - while (Len(ty) != 0) { - tok = SwigType_pop(ty); - - if (SwigType_isfunction(tok)) { - // Generate Function wrapper - Printf(ffiType, "(:function "); - // walk parm list - List *pl = SwigType_parmlist(tok); - - Printf(ffiType, "("); // start parm list - for (Iterator i = First(pl); i.item; i = Next(i)) { - SwigType *f_arg = SwigType_strip_qualifiers(i.item); - Printf(ffiType, "%s ", internal_compose_foreign_type(n, f_arg)); - Delete(f_arg); - } - Printf(ffiType, ")"); // end parm list. - - // do function return type. - Printf(ffiType, " %s)", internal_compose_foreign_type(n, ty)); - break; - } else if (SwigType_ispointer(tok) || SwigType_isreference(tok)) { - Printf(ffiType, "(* %s)", internal_compose_foreign_type(n, ty)); - } else if (SwigType_isarray(tok)) { - Printf(ffiType, "(:array %s", internal_compose_foreign_type(n, ty)); - String *atype = NewString("int"); - String *dim = convert_literal(SwigType_array_getdim(tok, 0), atype); - Delete(atype); - if (is_integer(dim)) { - Printf(ffiType, " %s)", dim); - } else { - Printf(ffiType, " #| %s |#)", SwigType_array_getdim(tok, 0)); - } - } else if (SwigType_ismemberpointer(tok)) { - // temp - Printf(ffiType, "(* %s)", internal_compose_foreign_type(n, ty)); - } else { - String *res = get_ffi_type(n, tok, ""); - if (res) { - Printf(ffiType, "%s", res); - } else { - SwigType *resolved_type = SwigType_typedef_resolve_all(tok); - if (Cmp(resolved_type, tok) != 0) { - res = get_ffi_type(n, resolved_type, ""); - if (res) { - } else { - res = internal_compose_foreign_type(n, resolved_type); - } - if (res) - Printf(ffiType, "%s", res); - } - - if (!res) { - String *is_struct = 0; - String *tok_remove_text = 0; - String *tok_name = Copy(tok); - String *tok_key = SwigType_str(tok,0); - if ((is_struct = Strstr(tok_key, "struct ")) || Strstr(tok_key, "union ")) { - tok_remove_text = NewString(is_struct ? "struct " : "union "); - } - - /* be more permissive of opaque types. This is the swig way. - compiles will notice if these types are ultimately not - present. */ - - if(tok_remove_text) { - Replaceall(tok_name,tok_remove_text,""); - } - tok_name = strip_namespaces(tok_name); - Delete(tok_remove_text); - // Swig_warning(WARN_TYPE_UNDEFINED_CLASS, Getfile(tok), Getline(tok), "Unable to find definition of '%s', assuming forward reference.\n", tok); - -#ifdef ALLEGROCL_TYPE_DEBUG - Printf(stderr, "i-c-f-t: adding forward reference for unknown type '%s'. mapping: %s -> %s\n", tok, tok_key, tok_name); -#endif - Node *nn = NewHash(); - Setattr(nn,"nodeType","classforward"); - Setattr(nn,"kind","class"); - Setattr(nn,"sym:name",tok_name); - Setattr(nn,"name",tok_key); - Setattr(nn,"allegrocl:package",current_namespace); - - add_forward_referenced_type(nn, 0); - // tok_name is dangling here, unused. ouch. why? - Printf(ffiType, "%s", get_ffi_type(n, tok, ""), tok_name); - } - } - } - } - return ffiType; -} - -String *compose_foreign_type(Node *n, SwigType *ty, String * /*id*/ = 0) { - -#ifdef ALLEGROCL_TYPE_DEBUG - Printf(stderr, "compose_foreign_type: ENTER (%s)...\n ", ty); - // Printf(stderr, "compose_foreign_type: ENTER (%s)(%s)...\n ", ty, (id ? id : 0)); - /* String *id_ref = SwigType_str(ty, id); - Printf(stderr, "looking up typemap for %s, found '%s'(%p)\n", - id_ref, lookup_res ? Getattr(lookup_res, "code") : 0, lookup_res); - if (lookup_res) Swig_print_node(lookup_res); - */ -#endif - - /* should we allow named lookups in the typemap here? YES! */ - /* unnamed lookups should be found in get_ffi_type, called - by internal_compose_foreign_type(), below. */ - - /* I'm reverting to 'no' for the question above. I can no longer - remember why I needed it. If a user needed it, I'll find out - as soon as they upgrade. Sigh. -mutandiz 9/16/2008. */ - -/* - if(id && lookup_res) { -#ifdef ALLEGROCL_TYPE_DEBUG - Printf(stderr, "compose_foreign_type: EXIT-1 (%s)\n ", Getattr(lookup_res, "code")); -#endif - return NewString(Getattr(lookup_res, "code")); - } -*/ - - SwigType *temp = SwigType_strip_qualifiers(ty); - String *res = internal_compose_foreign_type(n, temp); - Delete(temp); - -#ifdef ALLEGROCL_TYPE_DEBUG - Printf(stderr, "compose_foreign_type: EXIT (%s)\n ", res); -#endif - - return res; -} - -void update_package_if_needed(Node *n, File *f = f_clwrap) { -#ifdef ALLEGROCL_DEBUG - Printf(stderr, "update_package: ENTER... \n"); - Printf(stderr, " current_package = '%s'\n", current_package); - Printf(stderr, " node_package = '%s'\n", Getattr(n, "allegrocl:package")); - Printf(stderr, " node(%p) = '%s'\n", n, Getattr(n, "name")); -#endif - String *node_package = Getattr(n, "allegrocl:package"); - if (Strcmp(current_package, node_package)) { - String *lispy_package = listify_namespace(node_package); - - Delete(current_package); - current_package = Copy(node_package); - Printf(f, "\n(swig-in-package %s)\n", lispy_package); - Delete(lispy_package); - } -#ifdef ALLEGROCL_DEBUG - Printf(stderr, "update_package: EXIT.\n"); -#endif -} - -static String *mangle_name(Node *n, char const *prefix = "ACL", String *ns = current_namespace) { - String *suffix = Getattr(n, "sym:overname"); - String *pre_mangled_name = NewStringf("%s_%s__%s%s", prefix, ns, Getattr(n, "sym:name"), suffix); - String *mangled_name = Swig_name_mangle(pre_mangled_name); - Delete(pre_mangled_name); - return mangled_name; -} - -/* utilities */ - -/* remove a pointer from ffitype. non-destructive. - (* :char) ==> :char - (* (:array :int 30)) ==> (:array :int 30) */ -String *dereference_ffitype(String *ffitype) { - char *start; - char *temp = Char(ffitype); - String *reduced_type = 0; - - if(temp && temp[0] == '(' && temp[1] == '*') { - temp += 2; - - // walk past start of pointer references - while(*temp == ' ') temp++; - start = temp; - // temp = Char(reduced_type); - reduced_type = NewString(start); - temp = Char(reduced_type); - // walk to end of string. remove closing paren - while(*temp != '\0') temp++; - *(--temp) = '\0'; - } - - return reduced_type ? reduced_type : Copy(ffitype); -} - -/* returns new string w/ parens stripped */ -String *strip_parens(String *string) { - string = Copy(string); - Replaceall(string, "(", ""); - Replaceall(string, ")", ""); - return string; -} - -int ALLEGROCL::validIdentifier(String *s) { -#ifdef ALLEGROCL_DEBUG - Printf(stderr, "validIdentifier %s\n", s); -#endif - - char *c = Char(s); - - bool got_dot = false; - bool only_dots = true; - - /* Check that s is a valid common lisp symbol. There's a lot of leeway here. - A common lisp symbol is essentially any token that's not a number and - does not consist of only dots. - - We are expressly not allowing spaces in identifiers here, but spaces - could be added via the identifier converter. */ - while (*c) { - if (*c == '.') { - got_dot = true; - } else { - only_dots = false; - } - if (!isgraph(*c)) - return 0; - c++; - } - - return (got_dot && only_dots) ? 0 : 1; -} - -String *infix_to_prefix(String *val, char split_op, const String *op, String *type) { - List *ored = Split(val, split_op, -1); - - // some float hackery - if (((split_op == '+') || (split_op == '-')) && Len(ored) == 2 && - (SwigType_type(type) == T_FLOAT || SwigType_type(type) == T_DOUBLE || SwigType_type(type) == T_LONGDOUBLE)) { - // check that we're not splitting a float - String *possible_result = convert_literal(val, type, false); - if (possible_result) - return possible_result; - - } - // try parsing the split results. if any part fails, kick out. - bool part_failed = false; - if (Len(ored) > 1) { - String *result = NewStringf("(%s", op); - for (Iterator i = First(ored); i.item; i = Next(i)) { - String *converted = convert_literal(i.item, type); - if (converted) { - Printf(result, " %s", converted); - Delete(converted); - } else { - part_failed = true; - break; - } - } - Printf(result, ")"); - Delete(ored); - return part_failed ? 0 : result; - } - Delete(ored); - return 0; -} - -/* To be called by code generating the lisp interface - Will return a containing the literal based on type. - Will return null if there are problems. - - try_to_split defaults to true (see stub above). - */ -String *convert_literal(String *literal, String *type, bool try_to_split) { - String *num_param = Copy(literal); - String *trimmed = trim(num_param); - String *num = strip_parens(trimmed), *res = 0; - char *s = Char(num); - - String *ns = listify_namespace(current_namespace); - - // very basic parsing of infix expressions. - if (try_to_split && SwigType_type(type) != T_STRING) { - if ((res = infix_to_prefix(num, '|', "logior", type))) - return res; - if ((res = infix_to_prefix(num, '&', "logand", type))) - return res; - if ((res = infix_to_prefix(num, '^', "logxor", type))) - return res; - if ((res = infix_to_prefix(num, '*', "*", type))) - return res; - if ((res = infix_to_prefix(num, '/', "/", type))) - return res; - if ((res = infix_to_prefix(num, '+', "+", type))) - return res; - if ((res = infix_to_prefix(num, '-', "-", type))) - return res; - // if ((res = infix_to_prefix(num, '~', "lognot", type))) return res; - // if( (res = infix_to_prefix(num, '<<', "ash", type)) ) return res; - } - - // unary complement... - if (s[0] == '~' && Len(num) >= 2) { - String *id = NewString(++s); - String *id_conv = convert_literal(id, type, false); - Delete(id); - if (id_conv) - return NewStringf("(lognot %s)", id_conv); - s--; - } - - if (SwigType_type(type) == T_FLOAT || SwigType_type(type) == T_DOUBLE || SwigType_type(type) == T_LONGDOUBLE) { - // Use CL syntax for float literals - String *oldnum = Copy(num); - - // careful. may be a float identifier or float constant. - char *num_start = Char(num); - char *num_end = num_start + strlen(num_start) - 1; - - bool is_literal = isdigit(*num_start) || (*num_start == '.'); - - String *lisp_exp = 0; - if (is_literal) { - if (*num_end == 'f' || *num_end == 'F') { - lisp_exp = NewString("f"); - } else { - lisp_exp = NewString("d"); - } - - if (*num_end == 'l' || *num_end == 'L' || *num_end == 'f' || *num_end == 'F') { - *num_end = '\0'; - num_end--; - } - - int exponents = Replaceall(num, "e", lisp_exp) + Replaceall(num, "E", lisp_exp); - - if (!exponents) - Printf(num, "%s0", lisp_exp); - - if (exponents > 1 || (exponents + Replaceall(num, ".", ".") == 0)) { - // Printf(stderr, "Can't parse '%s' as type '%s'.\n", oldnum, type); - Delete(num); - num = 0; - } - Delete(lisp_exp); - } else { - String *id = NewStringf("#.(swig-insert-id \"%s\" %s :type :constant)", - num, ns); - Delete(num); - num = id; - } - - Delete(oldnum); - Delete(trimmed); - Delete(ns); - return num; - } else if (SwigType_type(type) == T_CHAR) { - /* Use CL syntax for character literals */ - Delete(num); - Delete(trimmed); - return NewStringf("#\\%s", num_param); - } else if (SwigType_type(type) == T_STRING) { - /* Use CL syntax for string literals */ - Delete(num); - Delete(trimmed); - return NewStringf("\"%s\"", num_param); - } else if (Len(num) >= 1 && (isdigit(s[0]) || s[0] == '+' || s[0] == '-')) { - /* use CL syntax for numbers */ - String *oldnum = Copy(num); - int usuffixes = Replaceall(num, "u", "") + Replaceall(num, "U", ""); - int lsuffixes = Replaceall(num, "l", "") + Replaceall(num, "L", ""); - if (usuffixes > 1 || lsuffixes > 1) { - Printf(stderr, "Weird!! number %s looks invalid.\n", oldnum); - SWIG_exit(EXIT_FAILURE); - } - s = Char(num); - if (s[0] == '0' && Len(num) >= 2) { - /*octal or hex */ - res = NewStringf("#%c%s", tolower(s[1]) == 'x' ? 'x' : 'o', s + 2); - Delete(num); - } else { - res = num; - } - Delete(oldnum); - Delete(trimmed); - return res; - } else if (allegrocl->validIdentifier(num)) { - /* convert C/C++ identifiers to CL symbols */ - res = NewStringf("#.(swig-insert-id \"%s\" %s :type :constant)", num, ns); - Delete(num); - Delete(trimmed); - Delete(ns); - return res; - } else { - Delete(trimmed); - return num; - } -} - - -void emit_stub_class(Node *n) { - -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_stub_class: ENTER... '%s'(%p)\n", Getattr(n, "sym:name"), n); - Swig_print_node(n); -#endif - - - String *name = Getattr(n, "sym:name"); - - if (Getattr(n, "allegrocl:synonym:already-been-stubbed")) - return; - - String *tname = SwigType_istemplate_templateprefix(name); - if (tname) { - String *temp = strip_namespaces(tname); - name = NewStringf("%s%s%s", temp, SwigType_templateargs(name), SwigType_templatesuffix(name)); - Delete(temp); - Delete(tname); - } else { - name = strip_namespaces(name); - } - - // Printf(f_clhead, ";; from emit-stub-class\n"); - update_package_if_needed(n, f_clhead); - Printf(f_clhead, ";; class template stub.\n"); - Printf(f_clhead, "(swig-def-foreign-stub \"%s\")\n", name); - - Setattr(n, "allegrocl:synonym:already-been-stubbed", "1"); - -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_stub_class: EXIT\n"); -#endif -} - -void emit_synonym(Node *synonym) { - -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_synonym: ENTER... \n"); -#endif - - // Printf(stderr,"in emit_synonym for %s(%p)\n", Getattr(synonym,"name"),synonym); - int is_tempInst = !Strcmp(nodeType(synonym), "templateInst"); - String *synonym_type; - - Node *of = get_primary_synonym_of(synonym); - - if (is_tempInst) { - // Printf(stderr, "*** using real-name '%s'\n", Getattr(synonym,"real-name")); - synonym_type = Getattr(synonym, "real-name"); - } else { - // Printf(stderr, "*** using name '%s'\n", Getattr(synonym,"name")); - synonym_type = Getattr(synonym, "name"); - } - - String *synonym_ns = listify_namespace(Getattr(synonym, "allegrocl:namespace")); - String *syn_ltype, *syn_type, *of_ltype; - // String *of_cdeclname = Getattr(of,"allegrocl:classDeclarationName"); - String *of_ns = Getattr(of, "allegrocl:namespace"); - String *of_ns_list = listify_namespace(of_ns); - // String *of_name = of_cdeclname ? NewStringf("struct %s", Getattr(of,"name")) : NewStringf("%s::%s", of_ns, Getattr(of,"sym:name")); - // String *of_name = NewStringf("%s::%s", of_ns, Getattr(of,"sym:name")); - String *of_name = namespaced_name(of, of_ns); - - if (CPlusPlus && !Strcmp(nodeType(synonym), "cdecl")) { - String *real_name = Getattr(synonym, "real-name"); - if (!real_name) - real_name = NewString("Unknown"); // TODO: fix - syn_ltype = NewStringf("#.(swig-insert-id \"%s\" %s :type :class)", strip_namespaces(real_name), synonym_ns); - syn_type = NewStringf("#.(swig-insert-id \"%s\" %s :type :type)", strip_namespaces(real_name), synonym_ns); - } else { - syn_ltype = lookup_defined_foreign_ltype(synonym_type); - syn_type = lookup_defined_foreign_type(synonym_type); - } - - of_ltype = lookup_defined_foreign_ltype(of_name); - - // Printf(stderr,";; from emit-synonym syn='%s' of_ltype='%s'\n", syn_ltype, of_ltype); - if( of_ltype ) - Printf(f_clhead, "(swig-def-synonym-type %s\n %s\n %s)\n", syn_ltype, of_ltype, syn_type); - - Delete(synonym_ns); - Delete(of_ns_list); - Delete(of_name); - -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_synonym: EXIT\n"); -#endif -} - -void emit_full_class(Node *n) { - -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_full_class: ENTER... \n"); -#endif - - String *name = Getattr(n, "sym:name"); - String *kind = Getattr(n, "kind"); - - // Printf(stderr,"in emit_full_class: '%s'(%p).", Getattr(n,"name"),n); - if (Getattr(n, "allegrocl:synonym-of")) { - // Printf(stderr,"but it's a synonym of something.\n"); - update_package_if_needed(n, f_clhead); - emit_synonym(n); - return; - } - // collect superclasses - String *bases = Getattr(n, "bases"); - String *supers = NewString("("); - if (bases) { - int first = 1; - for (Iterator i = First(bases); i.item; i = Next(i)) { - if (!first) - Printf(supers, " "); - String *s = lookup_defined_foreign_ltype(Getattr(i.item, "name")); - // String *name = Getattr(i.item,"name"); - if (s) { - Printf(supers, "%s", s); - } else { -#ifdef ALLEGROCL_TYPE_DEBUG - Printf(stderr, "emit_templ_inst: did not find ltype for base class %s (%s)", Getattr(i.item, "name"), Getattr(n, "allegrocl:namespace")); -#endif - } - } - } else { - Printf(supers, "ff:foreign-pointer"); - } - - // check for "feature:aclmixins" and add those as well. - Printf(supers, " %s)", Getattr(n,"feature:aclmixins")); - - // Walk children to generate type definition. - String *slotdefs = NewString(" "); - -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, " walking children...\n"); -#endif - - Node *c; - for (c = firstChild(n); c; c = nextSibling(c)) { - String *storage_type = Getattr(c, "storage"); - if ((!Strcmp(nodeType(c), "cdecl") && (!storage_type || Strcmp(storage_type, "typedef")))) { - String *access = Getattr(c, "access"); - - // hack. why would decl have a value of "variableHandler" and now "0"? - String *childDecl = Getattr(c, "decl"); - // Printf(stderr,"childDecl = '%s' (%s)\n", childDecl, Getattr(c,"view")); - if (!childDecl || !Strcmp(childDecl, "0")) - childDecl = NewString(""); - - SwigType *childType; - String *cname; - - // don't include types for private slots (yet). spr33959. - if(access && Strcmp(access,"public")) { - childType = NewStringf("int"); - cname = NewString("nil"); - } else { - childType = NewStringf("%s%s", childDecl, Getattr(c, "type")); - cname = Copy(Getattr(c, "name")); - } - - if (!SwigType_isfunction(childType)) { - // Printf(slotdefs, ";;; member functions don't appear as slots.\n "); - // Printf(slotdefs, ";; "); - String *ns = listify_namespace(Getattr(n, "allegrocl:package")); - -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "slot name = '%s' ns = '%s' class-of '%s' and type = '%s'\n", cname, ns, name, childType); -#endif - Printf(slotdefs, "(#.(swig-insert-id \"%s\" %s :type :slot :class \"%s\") %s)", cname, ns, name, compose_foreign_type(n, childType)); - Delete(ns); - if (access && Strcmp(access, "public")) - Printf(slotdefs, " ;; %s member", access); - - Printf(slotdefs, "\n "); - } - Delete(childType); - Delete(cname); - } - } - - String *ns_list = listify_namespace(Getattr(n, "allegrocl:namespace")); - update_package_if_needed(n, f_clhead); - Printf(f_clhead, "(swig-def-foreign-class \"%s\"\n %s\n (:%s\n%s))\n\n", name, supers, kind, slotdefs); - - Delete(supers); - Delete(ns_list); - - Setattr(n, "allegrocl:synonym:already-been-stubbed", "1"); -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_full_class: EXIT\n"); -#endif - -} - -void emit_class(Node *n) { - -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_class: ENTER... '%s'(%p)\n", Getattr(n, "sym:name"), n); -#endif - - int is_tempInst = !Strcmp(nodeType(n), "templateInst"); - - String *ns_list = listify_namespace(Getattr(n, "allegrocl:namespace")); - String *name = Getattr(n, is_tempInst ? "real-name" : "name"); - - String *tname = SwigType_istemplate_templateprefix(name); - if (tname) { - String *temp = strip_namespaces(tname); - name = NewStringf("%s%s%s", temp, SwigType_templateargs(name), SwigType_templatesuffix(name)); - Delete(temp); - Delete(tname); - } else { - name = strip_namespaces(name); - } - - if (Getattr(n, "allegrocl:synonym:is-primary")) { - // Printf(stderr," is primary... "); - if (is_tempInst) { - emit_stub_class(n); - } else { - emit_full_class(n); - } - } else { - // Node *primary = Getattr(n,"allegrocl:synonym-of"); - Node *primary = get_primary_synonym_of(n); - if (primary && (primary != n)) { - // Printf(stderr," emitting synonym... "); - emit_stub_class(primary); - update_package_if_needed(n, f_clhead); - emit_synonym(n); - } else { - emit_full_class(n); - } - } - // Printf(stderr,"DONE\n"); - Delete(name); - Delete(ns_list); - -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_class: EXIT\n"); -#endif -} - -void emit_typedef(Node *n) { - -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_typedef: ENTER... \n"); -#endif - - String *name; - String *sym_name = Getattr(n, "sym:name"); - String *type = NewStringf("%s%s", Getattr(n, "decl"), Getattr(n, "type")); - String *lisp_type = compose_foreign_type(n, type); - Delete(type); - Node *in_class = Getattr(n, "allegrocl:typedef:in-class"); - - // Printf(stderr,"in emit_typedef: '%s'(%p).",Getattr(n,"name"),n); - if (Getattr(n, "allegrocl:synonym-of")) { - // Printf(stderr," but it's a synonym of something.\n"); - emit_synonym(n); - return; - } - - if (in_class) { - String *class_name = Getattr(in_class, "name"); - String *tname = SwigType_istemplate_templateprefix(class_name); - if (tname) { - String *temp = strip_namespaces(tname); - class_name = NewStringf("%s%s%s", temp, SwigType_templateargs(class_name), SwigType_templatesuffix(class_name)); - Delete(temp); - Delete(tname); - } - - name = NewStringf("%s__%s", class_name, sym_name); - Setattr(n, "allegrocl:in-class", in_class); - } else { - name = sym_name ? Copy(sym_name) : Copy(Getattr(n, "name")); - } - - // leave these in for now. might want to change these to def-foreign-class at some point. -// Printf(f_clhead, ";; %s\n", SwigType_typedef_resolve_all(lisp_type)); - Printf(f_clhead, "(swig-def-foreign-type \"%s\"\n %s)\n", name, lisp_type); - - Delete(name); - -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_typedef: EXIT\n"); -#endif -} - -void emit_enum_type_no_wrap(Node *n) { - -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_enum_type_no_wrap: ENTER... \n"); -#endif - - String *unnamed = Getattr(n, "unnamed"); - String *name; - // SwigType *enumtype; - - name = unnamed ? Getattr(n, "allegrocl:name") : Getattr(n, "sym:name"); - SwigType *tmp = NewStringf("enum %s", unnamed ? unnamed : name); - - Node *node = NewHash(); - Setattr(node, "type", tmp); - Setfile(node, Getfile(n)); - Setline(node, Getline(n)); - const String *enumtype = Swig_typemap_lookup("ffitype", node, "", 0); - Delete(node); - - Delete(tmp); - - if (name) { - String *ns = listify_namespace(current_namespace); - - Printf(f_clhead, "(swig-def-foreign-type \"%s\" %s)\n", name, enumtype); - Delete(ns); - - // walk children. - Node *c; - for (c = firstChild(n); c; c = nextSibling(c)) { - if (!Getattr(c, "error")) { - String *val = Getattr(c, "enumvalue"); - if (!val) - val = Getattr(c, "enumvalueex"); - String *converted_val = convert_literal(val, Getattr(c, "type")); - String *valname = Getattr(c, "sym:name"); - - if (converted_val) { - Printf(f_clhead, "(swig-defconstant \"%s\" %s)\n", valname, converted_val); - Delete(converted_val); - } else { - Swig_warning(WARN_LANG_DISCARD_CONST, Getfile(n), Getline(n), "Unable to parse enum value '%s'. Setting to NIL\n", val); - Printf(f_clhead, "(swig-defconstant \"%s\" nil #| %s |#)\n", valname, val); - } - } - } - } - Printf(f_clhead, "\n"); - -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_enum_type_no_wrap: EXIT\n"); -#endif - -} - -void emit_enum_type(Node *n) { - -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_enum_type: ENTER... \n"); -#endif - - if (!Generate_Wrapper) { - emit_enum_type_no_wrap(n); - return; - } - - String *unnamed = Getattr(n, "unnamed"); - String *name; - // SwigType *enumtype; - - name = unnamed ? Getattr(n, "allegrocl:name") : Getattr(n, "sym:name"); - SwigType *tmp = NewStringf("enum %s", unnamed ? unnamed : name); - - Node *node = NewHash(); - Setattr(node, "type", tmp); - Setfile(node, Getfile(n)); - Setline(node, Getline(n)); - const String *enumtype = Swig_typemap_lookup("ffitype", node, "", 0); - Delete(node); - - Delete(tmp); - - if (name) { - String *ns = listify_namespace(current_namespace); - - Printf(f_clhead, "(swig-def-foreign-type \"%s\" %s)\n", name, enumtype); - Delete(ns); - - // walk children. - Node *c; - for(c = firstChild(n); c; c=nextSibling(c)) { - String *mangled_name = mangle_name(c, "ACL_ENUM", Getattr(c,"allegrocl:package")); - Printf(f_clhead, "(swig-defvar \"%s\" \"%s\" :type :constant :ftype :signed-long)\n", Getattr(c, "sym:name"), mangled_name); - Delete(mangled_name); - } - } -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_enum_type: EXIT\n"); -#endif - -} - -void emit_default_linked_type(Node *n) { - -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_default_linked_type: ENTER... \n"); -#endif - - // catchall for non class types. - if (!Strcmp(nodeType(n), "classforward")) { - Printf(f_clhead, ";; forward referenced stub.\n"); - Printf(f_clhead, "(swig-def-foreign-class \"%s\" (ff:foreign-pointer) (:class ))\n\n", Getattr(n, "sym:name")); - } else if (!Strcmp(nodeType(n), "enum")) { - emit_enum_type(n); - } else { - Printf(stderr, "Don't know how to emit node type '%s' named '%s'\n", nodeType(n), Getattr(n, "name")); - } - -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_default_linked_type: EXIT\n"); -#endif - -} - -void dump_linked_types(File *f) { - Node *n = first_linked_type; - int i = 0; - while (n) { - Printf(f, "%d: (%p) node '%s' name '%s'\n", i++, n, nodeType(n), Getattr(n, "sym:name")); - - Node *t = Getattr(n, "allegrocl:synonym-of"); - if (t) - Printf(f, " synonym-of %s(%p)\n", Getattr(t, "name"), t); - n = Getattr(n, "allegrocl:next_linked_type"); - } -} - -void emit_linked_types() { - -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_linked_types: ENTER... "); -#endif - - Node *n = first_linked_type; - - while (n) { - String *node_type = nodeType(n); - - // Printf(stderr,"emitting node %s(%p) of type %s.", Getattr(n,"name"),n, nodeType(n)); - if (!Strcmp(node_type, "class") || !Strcmp(node_type, "templateInst")) { - // may need to emit a stub, so it will update the package itself. - // Printf(stderr," Passing to emit_class."); - emit_class(n); - } else if (!Strcmp(nodeType(n), "cdecl")) { - // Printf(stderr," Passing to emit_typedef."); - update_package_if_needed(n, f_clhead); - emit_typedef(n); - } else { - // Printf(stderr," Passing to default_emitter."); - update_package_if_needed(n, f_clhead); - emit_default_linked_type(n); - } - - n = Getattr(n, "allegrocl:next_linked_type"); - // Printf(stderr,"returned.\n"); - } - -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_linked_types: EXIT\n"); -#endif -} - -extern "C" Language *swig_allegrocl(void) { - return (allegrocl = new ALLEGROCL()); -} - -void ALLEGROCL::main(int argc, char *argv[]) { - int i; - - Preprocessor_define("SWIGALLEGROCL 1", 0); - SWIG_library_directory("allegrocl"); - SWIG_config_file("allegrocl.swg"); - - for (i = 1; i < argc; i++) { - if (!strcmp(argv[i], "-identifier-converter")) { - char *conv = argv[i + 1]; - - if (!conv) - Swig_arg_error(); - - Swig_mark_arg(i); - Swig_mark_arg(i + 1); - i++; - - /* check for built-ins */ - if (!strcmp(conv, "lispify")) { - Delete(identifier_converter); - identifier_converter = NewString("identifier-convert-lispify"); - } else if (!strcmp(conv, "null")) { - Delete(identifier_converter); - identifier_converter = NewString("identifier-convert-null"); - } else { - /* Must be user defined */ - Delete(identifier_converter); - identifier_converter = NewString(conv); - } - } else if (!strcmp(argv[i], "-cwrap")) { - CWrap = true; - Swig_mark_arg(i); - } else if (!strcmp(argv[i], "-nocwrap")) { - CWrap = false; - Swig_mark_arg(i); - } else if (!strcmp(argv[i], "-isolate")) { - unique_swig_package = true; - Swig_mark_arg(i); - } - - if (!strcmp(argv[i], "-help")) { - Printf(stdout, "%s\n", usage); - } - - } - - allow_overloading(); -} - -int ALLEGROCL::top(Node *n) { - module_name = Getattr(n, "name"); - String *cxx_filename = Getattr(n, "outfile"); - String *cl_filename = NewString(""); - - swig_package = unique_swig_package ? NewStringf("swig.%s", module_name) : NewString("swig"); - - Printf(cl_filename, "%s%s.cl", SWIG_output_directory(), module_name); - - f_cl = NewFile(cl_filename, "w", SWIG_output_files()); - if (!f_cl) { - Printf(stderr, "Unable to open %s for writing\n", cl_filename); - SWIG_exit(EXIT_FAILURE); - } - - Generate_Wrapper = CPlusPlus || CWrap; - - if (Generate_Wrapper) { - f_begin = NewFile(cxx_filename, "w", SWIG_output_files()); - if (!f_begin) { - Delete(f_cl); - Printf(stderr, "Unable to open %s for writing\n", cxx_filename); - SWIG_exit(EXIT_FAILURE); - } - } else - f_begin = NewString(""); - - f_runtime = NewString(""); - f_cxx_header = f_runtime; - f_cxx_wrapper = NewString(""); - - Swig_register_filebyname("header", f_cxx_header); - Swig_register_filebyname("wrapper", f_cxx_wrapper); - Swig_register_filebyname("begin", f_begin); - Swig_register_filebyname("runtime", f_runtime); - Swig_register_filebyname("lisp", f_clwrap); - Swig_register_filebyname("lisphead", f_cl); - - Swig_banner(f_begin); - - Printf(f_runtime, "\n\n#ifndef SWIGALLEGROCL\n#define SWIGALLEGROCL\n#endif\n\n"); - - Swig_banner_target_lang(f_cl, ";;"); - - Printf(f_cl, "\n" - "(defpackage :%s\n" - " (:use :common-lisp :ff :excl)\n" - " (:export #:*swig-identifier-converter* #:*swig-module-name*\n" - " #:*void* #:*swig-export-list*))\n" - "(in-package :%s)\n\n" - "(eval-when (:compile-toplevel :load-toplevel :execute)\n" - " (defparameter *swig-identifier-converter* '%s)\n" - " (defparameter *swig-module-name* :%s))\n\n", swig_package, swig_package, identifier_converter, module_name); - Printf(f_cl, "(defpackage :%s\n" " (:use :common-lisp :%s :ff :excl))\n\n", module_name, swig_package); - - Printf(f_clhead, "(in-package :%s)\n", module_name); - - Language::top(n); - -#ifdef ALLEGROCL_TYPE_DEBUG - dump_linked_types(stderr); -#endif - emit_linked_types(); - - Printf(f_clwrap, "\n(cl::in-package :%s)\n", swig_package); - Printf(f_clwrap, "\n(macrolet ((swig-do-export ()\n"); - Printf(f_clwrap, " `(dolist (s ',*swig-export-list*)\n"); - Printf(f_clwrap, " (apply #'export s))))\n"); - Printf(f_clwrap, " (swig-do-export))\n"); - Printf(f_clwrap, "\n(setq *swig-export-list* nil)\n"); - - Printf(f_cl, "%s\n", f_clhead); - Printf(f_cl, "%s\n", f_clwrap); - - Delete(f_cl); - Delete(f_clhead); - Delete(f_clwrap); - - Dump(f_runtime, f_begin); - Printf(f_begin, "%s\n", f_cxx_wrapper); - - Delete(f_runtime); - Delete(f_begin); - Delete(f_cxx_wrapper); - - // Swig_print_tree(n); - - return SWIG_OK; -} - -int any_varargs(ParmList *pl) { - Parm *p; - - for (p = pl; p; p = nextSibling(p)) { - if (SwigType_isvarargs(Getattr(p, "type"))) - return 1; - } - - return 0; -} - -String *get_lisp_type(Node *n, SwigType *ty, const_String_or_char_ptr name) { - Node *node = NewHash(); - Setattr(node, "type", ty); - Setattr(node, "name", name); - Setfile(node, Getfile(n)); - Setline(node, Getline(n)); - const String *tm = Swig_typemap_lookup("lisptype", node, "", 0); - Delete(node); - - return tm ? NewString(tm) : NewString(""); -} - -Node *parent_node_skipping_extends(Node *n) { - Node *result = n; - do { - result = parentNode(result); - } - while (Cmp("extend", nodeType(result)) == 0); - return result; -} - -/* ----------------------------------------------------------------------------- - * emit_num_lin_arguments() - * - * Calculate the total number of arguments. This function is safe for use - * with multi-argument typemaps which may change the number of arguments in - * strange ways. - * ----------------------------------------------------------------------------- */ - -int emit_num_lin_arguments(ParmList *parms) { - Parm *p = parms; - int nargs = 0; - - while (p) { - // Printf(stderr,"enla: '%s' lin='%p' numinputs='%s'\n", Getattr(p,"name"), Getattr(p,"tmap:lin"), Getattr(p,"tmap:lin:numinputs")); - if (Getattr(p, "tmap:lin")) { - nargs += GetInt(p, "tmap:lin:numinputs"); - p = Getattr(p, "tmap:lin:next"); - } else { - p = nextSibling(p); - } - } - - /* DB 04/02/2003: Not sure this is necessary with tmap:in:numinputs */ - /* - if (parms && (p = Getattr(parms,"emit:varargs"))) { - if (!nextSibling(p)) { - nargs--; - } - } - */ - return nargs; -} - -String *id_converter_type(SwigType const *type) { - SwigType *t = Copy(type); - String *result = 0; - - if (SwigType_ispointer(t)) { - SwigType_pop(t); - String *pointee = id_converter_type(t); - result = NewStringf("(:* %s)", pointee); - Delete(pointee); - } else if (SwigType_ismemberpointer(t)) { - String *klass = SwigType_parm(t); - SwigType_pop(t); - String *member = id_converter_type(t); - result = NewStringf("(:member \"%s\" %s)", klass, member); - Delete(klass); - Delete(member); - } else if (SwigType_isreference(t)) { - SwigType_pop(t); - String *referencee = id_converter_type(t); - result = NewStringf("(:& %s)", referencee); - Delete(referencee); - } else if (SwigType_isarray(t)) { - String *size = SwigType_parm(t); - SwigType_pop(t); - String *element_type = id_converter_type(t); - result = NewStringf("(:array %s \"%s\")", element_type, size); - Delete(size); - Delete(element_type); - } else if (SwigType_isfunction(t)) { - result = NewString("(:function ("); - String *parmlist_str = SwigType_parm(t); - List *parms = SwigType_parmlist(parmlist_str); - - for (Iterator i = First(parms); i.item;) { - String *parm = id_converter_type((SwigType *) i.item); - Printf(result, "%s", parm); - i = Next(i); - if (i.item) - Printf(result, " "); - Delete(parm); - } - SwigType_pop(t); - String *ret = id_converter_type(t); - Printf(result, ") %s)", ret); - - Delete(parmlist_str); - Delete(parms); - Delete(ret); - } else if (SwigType_isqualifier(t)) { - result = NewString("(:qualified ("); - String *qualifiers_str = Copy(SwigType_parm(t)); // ?! - // Replaceall below SEGVs if we don't put the Copy here... - SwigType_pop(t); - String *qualifiee = id_converter_type(t); - - Replaceall(qualifiers_str, " ", " :"); - if (Len(qualifiers_str) > 0) - Printf(result, ":"); - Printf(result, "%s) %s)", qualifiers_str, qualifiee); - - Delete(qualifiers_str); - Delete(qualifiee); - } else if (SwigType_istemplate(t)) { - result = NewStringf("(:template \"%s\")", t); - } else { /* if (SwigType_issimple(t)) */ - - if (Strstr(Char(t), "::")) { - result = listify_namespace(t); - } else { - result = NewStringf("\"%s\"", t); - } - } - - Delete(t); - return result; -} - -static ParmList *parmlist_with_names(ParmList *pl) { - ParmList *pl2 = CopyParmList(pl); - for (Parm *p = pl, *p2 = pl2; p2; p = nextSibling(p), p2 = nextSibling(p2)) { - if (!Getattr(p2, "name")) - Setattr(p2, "name", Getattr(p2, "lname")); - Setattr(p2, "name", strip_namespaces(Getattr(p2, "name"))); - Setattr(p2, "tmap:ctype", Getattr(p, "tmap:ctype")); - - String *temp = Getattr(p, "tmap:lin"); - if (temp) { - Setattr(p2, "tmap:lin", temp); - Setattr(p2, "tmap:lin:next", Getattr(p, "tmap:lin:next")); - } - } - return pl2; -} - -static String *parmlist_str_id_converter(ParmList *pl) { - String *result = NewString(""); - for (Parm *p = pl; p;) { - String *lispy_type = id_converter_type(Getattr(p, "type")); - Printf(result, "(\"%s\" %s)", Getattr(p, "name"), lispy_type); - Delete(lispy_type); - if ((p = nextSibling(p))) - Printf(result, " "); - } - return result; -} - -String *collect_others_args(Node *overload) { - String *overloaded_from = Getattr(overload, "sym:overloaded"); - String *others_args = NewString(""); - int first_overload = 1; - - for (Node *overload2 = overloaded_from; overload2; overload2 = Getattr(overload2, "sym:nextSibling")) { - if (overload2 == overload || GetInt(overload2, "overload:ignore")) - continue; - - ParmList *opl = parmlist_with_names(Getattr(overload2, "wrap:parms")); - String *args = parmlist_str_id_converter(opl); - if (!first_overload) - Printf(others_args, "\n "); - Printf(others_args, "(%s)", args); - Delete(args); - Delete(opl); - first_overload = 0; - } - return others_args; -} - -struct IDargs { - String *name; - String *type; - String *klass; - String *arity; - - IDargs():name(0), type(0), klass(0), arity(0) { - } - - String *full_quoted_str() { - String *result = no_others_quoted_str(); - if (arity) - Printf(result, " :arity %s", arity); - return result; - } - - String *no_others_quoted_str() { - String *result = NewString(""); - Printf(result, "\"%s\" :type :%s", name, type); - if (klass) - Printf(result, " :class \"%s\"", klass); - return result; - } - - String *noname_str(bool include_class = true) { - String *result = NewString(""); - Printf(result, " :type :%s", type); - if (klass && include_class) - Printf(result, " :class \"%s\"", klass); - if (arity) - Printf(result, " :arity %s", arity); - return result; - } - - String *noname_no_others_str(bool include_class = true) { - String *result = NewString(""); - Printf(result, " :type :%s", type); - if (klass && include_class) - Printf(result, " :class \"%s\"", klass); - return result; - } -}; -IDargs *id_converter_arguments(Node *n) { - IDargs *result = (IDargs *) GetVoid(n, "allegrocl:id-converter-args"); - if (!result) - result = new IDargs; - - // Base name - if (!result->name) { - result->name = Getattr(n, "allegrocl:old-sym:name"); - if (!result->name) - result->name = Getattr(n, "sym:name"); - result->name = Copy(result->name); - } - // :type - if (result->type) - Delete(result->type); - if (!Getattr(n, "allegrocl:kind")) - Setattr(n, "allegrocl:kind", "function"); - if (Strstr(Getattr(n, "name"), "operator ")) - Replaceall(Getattr(n, "allegrocl:kind"), "function", "operator"); - if (Strstr(Getattr(n, "allegrocl:kind"), "variable")) { - int name_end = Len(Getattr(n, "sym:name")) - 4; - char *str = Char(Getattr(n, "sym:name")); - String *get_set = NewString(str + name_end + 1); - result->type = Copy(Getattr(n, "allegrocl:kind")); - Replaceall(result->type, "variable", ""); - Printf(result->type, "%ster", get_set); - Delete(get_set); - } else { - result->type = Copy(Getattr(n, "allegrocl:kind")); - } - - // :class - if (Strstr(result->type, "member ")) { - Replaceall(result->type, "member ", ""); - if (!result->klass) { - result->klass = Copy(Getattr(parent_node_skipping_extends(n), "sym:name")); - } - } - // :arity - if (Getattr(n, "sym:overloaded")) { - if (result->arity) - Delete(result->arity); - result->arity = NewStringf("%d", - // emit_num_arguments(Getattr(n, "wrap:parms"))); - emit_num_lin_arguments(Getattr(n, "wrap:parms"))); - // Printf(stderr, "got arity of '%s' node '%s' '%p'\n", result->arity, Getattr(n,"name"), Getattr(n,"wrap:parms")); - } - - SetVoid(n, "allegrocl:id-converter-args", result); - return result; -} - -int ALLEGROCL::emit_buffered_defuns(Node *n) { - - Node *overloaded_from = Getattr(n, "sym:overloaded"); - - String *wrap; - - if (!overloaded_from) { - wrap = Getattr(n, "allegrocl:lisp-wrap"); - - Printf(f_clwrap, "%s\n", wrap); - Delattr(n, "allegrocl:lisp-wrap"); - Delete(wrap); - } else { - for (Node *overload = overloaded_from; overload; overload = Getattr(overload, "sym:nextSibling")) { - String *others_args = collect_others_args(overload); - wrap = Getattr(overload, "allegrocl:lisp-wrap"); - - Replaceall(wrap, "@@OTHERS-ARGS-GO-HERE@@", others_args); -// IDargs* id_args = id_converter_arguments(overload); -// Replaceall(id_args->others_args, "@@OTHERS-ARGS-GO-HERE@@", others_args); - - if (!GetInt(overload, "overload:ignore")) - Printf(f_clwrap, "%s", wrap); - - Delattr(overload, "allegrocl:lisp-wrap"); - Delete(wrap); - } - } - return SWIG_OK; -} - -String *dispatching_type(Node *n, Parm *p) { - String *result = 0; - - String *parsed = Getattr(p, "type"); //Swig_cparse_type(Getattr(p,"tmap:ctype")); - String *cl_t = SwigType_typedef_resolve_all(parsed); - - Node *node = NewHash(); - Setattr(node, "type", parsed); - Setfile(node, Getfile(n)); - Setline(node, Getline(n)); - const String *tm = Swig_typemap_lookup("lispclass", node, Getattr(p, "name"), 0); - Delete(node); - - if (tm) { - result = Copy(tm); - } else { - String *lookup_type = class_from_class_or_class_ref(parsed); - if (lookup_type) - result = lookup_defined_foreign_ltype(lookup_type); - } - - // if (!result && SwigType_ispointer(cl_t)) { - // SwigType_pop(cl_t); - // result = lookup_defined_foreign_ltype(cl_t); - // } - - if (!result) - result = NewStringf("ff:foreign-pointer"); - - // Delete(parsed); - Delete(cl_t); - return result; -} - -int ALLEGROCL::emit_dispatch_defun(Node *n) { -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_dispatch_defun: ENTER... "); -#endif - List *overloads = Swig_overload_rank(n, true); - - // Printf(stderr,"\ndispatch node=%p\n\n", n); - // Swig_print_node(n); - - Node *overloaded_from = Getattr(n,"sym:overloaded"); - bool include_class = Getattr(overloaded_from, "allegrocl:dispatcher:include-class") ? true : false; - String *id_args = id_converter_arguments(n)->noname_no_others_str(include_class); - Printf(f_clwrap, "(swig-dispatcher (\"%s\" %s :arities (", Getattr(overloaded_from, "allegrocl:dispatcher:name"), id_args); - - Delattr(overloaded_from, "allegrocl:dispatcher:include-class"); - Delattr(overloaded_from, "allegrocl:dispatcher:name"); - - int last_arity = -1; - for (Iterator i = First(overloads); i.item; i = Next(i)) { - int arity = emit_num_lin_arguments(Getattr(i.item, "wrap:parms")); - if (arity == last_arity) - continue; - - Printf(f_clwrap, "%s%d", last_arity == -1 ? "" : " ", arity); - - last_arity = arity; - } - Printf(f_clwrap, ")))\n"); - - Delete(id_args); - Delete(overloads); - -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_dispatch_defun: EXIT\n"); -#endif - - return SWIG_OK; -} - -int ALLEGROCL::emit_defun(Node *n, File *fcl) { -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_defun: ENTER... "); -#endif - - // avoid name conflicts between smart pointer wrappers and the wrappers for the - // actual class. - bool smartmemberwrapper = (!Cmp(Getattr(n, "view"), "memberfunctionHandler") && - Getattr(n,"allocate:smartpointeraccess")); - -#ifdef ALLEGROCL_DEBUG - int auto_generated = Cmp(Getattr(n, "view"), "globalfunctionHandler"); - Printf(stderr, "%s%sfunction %s%s%s\n", auto_generated ? "> " : "", Getattr(n, "sym:overloaded") - ? "overloaded " : "", current_namespace, (current_namespace) > 0 ? "::" : "", Getattr(n, "sym:name")); - Printf(stderr, " (view: %s)\n", Getattr(n, "view")); - Swig_print_node(n); -#endif - - - String *funcname = Getattr(n, "allegrocl:old-sym:name"); - if (smartmemberwrapper || !funcname) - funcname = Getattr(n, "sym:name"); - - String *mangled_name = Getattr(n, "wrap:name"); - ParmList *pl = parmlist_with_names(Getattr(n, "wrap:parms")); - - // attach typemap info. - Wrapper *wrap = NewWrapper(); - Swig_typemap_attach_parms("lin", pl, wrap); - // Swig_typemap_attach_parms("ffitype", pl, wrap); - Swig_typemap_lookup("lout", n, Swig_cresult_name(), 0); - - SwigType *result_type = Swig_cparse_type(Getattr(n, "tmap:ctype")); - // prime the pump, with support for OUTPUT, INOUT typemaps. - Printf(wrap->code, - "(cl::let ((ACL_ffresult %s:*void*)\n ACL_result)\n $body\n (cl::if (cl::eq ACL_ffresult %s:*void*)\n (cl::values-list ACL_result)\n (cl::values-list (cl::cons ACL_ffresult ACL_result))))", - swig_package, swig_package); - - Parm *p; - int largnum = 0, argnum = 0, first = 1; - // int varargs=0; - if (Generate_Wrapper) { - String *extra_parms = id_converter_arguments(n)->noname_str(smartmemberwrapper ? false : true); - Node *overloaded_from = Getattr(n,"sym:overloaded"); - if (overloaded_from) { - if(!GetFlag(overloaded_from,"allegrocl:dispatcher:name")) { - Setattr(overloaded_from,"allegrocl:dispatcher:name",funcname); - Setattr(overloaded_from,"allegrocl:dispatcher:include-class", smartmemberwrapper ? 0 : "1"); - // Printf(stderr, " set a:d:name='%s', a:d:i-c='%s'\n", Getattr(n,"allegrocl:dispatcher:name"), Getattr(n,"allegrocl:dispatcher:include-class")); - } - Printf(fcl, "(swig-defmethod (\"%s\" \"%s\"%s)\n", funcname, mangled_name, extra_parms); - } else - Printf(fcl, "(swig-defun (\"%s\" \"%s\"%s)\n", funcname, mangled_name, extra_parms); - Delete(extra_parms); - } - // Just C - else { - Printf(fcl, "(swig-defun (\"%s\" \"%s\")\n", funcname, Generate_Wrapper ? mangled_name : funcname); - } - - ////////////////////////////////////// - // Lisp foreign call parameter list // - ////////////////////////////////////// - Printf(fcl, " ("); - - /* Special cases */ - - if (ParmList_len(pl) == 0) { - Printf(fcl, ":void"); -/* } else if (any_varargs(pl)) { - Printf(fcl, "#| varargs |#"); - varargs=1; */ - } else { - String *largs = NewString(""); - - for (p = pl; p; p = nextSibling(p), argnum++, largnum++) { - // SwigType *argtype=Getattr(p, "type"); - SwigType *argtype = Swig_cparse_type(Getattr(p, "tmap:ctype")); - SwigType *parmtype = Getattr(p,"type"); - - if (!first) { - Printf(fcl, "\n "); - } - - /* by default, skip varargs */ - if (!SwigType_isvarargs(parmtype)) { - String *argname = NewStringf("PARM%d_%s", largnum, Getattr(p, "name")); - - // Printf(stderr,"%s\n", Getattr(p,"tmap:lin")); - String *ffitype = compose_foreign_type(n, argtype, Getattr(p,"name")); - String *deref_ffitype = dereference_ffitype(ffitype); - String *lisptype = get_lisp_type(n, parmtype, Getattr(p, "name")); - -#ifdef ALLEGROCL_DEBUG - Printf(stderr, "lisptype of '%s' '%s' = '%s'\n", parmtype, - Getattr(p, "name"), lisptype); -#endif - - // while we're walking the parameters, generating LIN - // wrapper code... - Setattr(p, "lname", NewStringf("SWIG_arg%d", largnum)); - - String *parm_code = Getattr(p, "tmap:lin"); - if (parm_code) { - String *lname = Getattr(p, "lname"); - - Printf(largs, " %s", lname); - Replaceall(parm_code, "$in_fftype", ffitype); // must come before $in - Replaceall(parm_code, "$in", argname); - Replaceall(parm_code, "$out", lname); - Replaceall(parm_code, "$*in_fftype", deref_ffitype); - Replaceall(wrap->code, "$body", parm_code); - } - - String *dispatchtype = Getattr(n, "sym:overloaded") ? dispatching_type(n, p) : NewString(""); - - // if this parameter has been removed from the C/++ wrapper - // it shouldn't be in the lisp wrapper either. - if (!checkAttribute(p, "tmap:in:numinputs", "0")) { - Printf(fcl, "(%s %s %s %s %s)", - // parms in the ff wrapper, but not in the lisp wrapper. - (checkAttribute(p, "tmap:lin:numinputs", "0") ? ":p-" : ":p+"), argname, dispatchtype, ffitype, lisptype); - - first = 0; - } - - Delete(argname); - Delete(ffitype); - Delete(deref_ffitype); - Delete(lisptype); - } - } - - Printf(wrap->locals, "%s", largs); - } - - String *lout = Getattr(n, "tmap:lout"); - Replaceall(lout, "$owner", GetFlag(n, "feature:new") ? "t" : "nil"); - - Replaceall(wrap->code, "$body", lout); - // $lclass handling. - String *lclass = (String *) 0; - SwigType *parsed = Swig_cparse_type(Getattr(n, "tmap:ctype")); - // SwigType *cl_t = SwigType_typedef_resolve_all(parsed); - SwigType *cl_t = class_from_class_or_class_ref(parsed); - String *out_ffitype = compose_foreign_type(n, parsed); - String *deref_out_ffitype; - String *out_temp = Copy(parsed); - - if (SwigType_ispointer(out_temp)) { - SwigType_pop(out_temp); - deref_out_ffitype = compose_foreign_type(n, out_temp); - } else { - deref_out_ffitype = Copy(out_ffitype); - } - - Delete(out_temp); - - Delete(parsed); - - if (cl_t) { - lclass = lookup_defined_foreign_ltype(cl_t); - } - - int ff_foreign_ptr = 0; - if (!lclass) { - ff_foreign_ptr = 1; - lclass = NewStringf("ff:foreign-pointer"); - } -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "for output wrapping %s: type=%s, ctype=%s\n", Getattr(n, "name"), - Getattr(n, "type"), Swig_cparse_type(Getattr(n, "tmap:ctype"))); -#endif - - if (lclass) - Replaceall(wrap->code, "$lclass", lclass); - if (out_ffitype) - Replaceall(wrap->code, "$out_fftype", out_ffitype); - if (deref_out_ffitype) - Replaceall(wrap->code, "$*out_fftype", deref_out_ffitype); - - Replaceall(wrap->code, "$body", NewStringf("(swig-ff-call%s)", wrap->locals)); - String *ldestructor = Copy(lclass); - if (ff_foreign_ptr) - Replaceall(ldestructor, ldestructor, "cl::identity"); - else - Replaceall(ldestructor, ":type :class", ":type :destructor"); - Replaceall(wrap->code, "$ldestructor", ldestructor); - Delete(ldestructor); - - Printf(fcl, ")\n"); /* finish arg list */ - - ///////////////////////////////////////////////////// - // Lisp foreign call return type and optimizations // - ///////////////////////////////////////////////////// - Printf(fcl, " (:returning (%s %s)", compose_foreign_type(n, result_type), get_lisp_type(n, Getattr(n, "type"), Swig_cresult_name())); - - for (Iterator option = First(n); option.item; option = Next(option)) { - if (Strncmp("feature:ffargs:", option.key, 15)) - continue; - String *option_val = option.item; - String *option_name = NewString(Char(option.key) + 14); - Replaceall(option_name, "_", "-"); - - // TODO: varargs vs call-direct ? - Printf(fcl, "\n %s %s", option_name, option_val); - - Delete(option_name); - } - - Printf(fcl, ")\n %s)\n\n", wrap->code); - // Wrapper_print(wrap, stderr); - - Delete(result_type); - Delete(mangled_name); - Delete(pl); - DelWrapper(wrap); - -#ifdef ALLEGROCL_WRAP_DEBUG - Printf(stderr, "emit_defun: EXIT\n"); -#endif - - return SWIG_OK; -} - -int ALLEGROCL::functionWrapper(Node *n) { -#ifdef ALLEGROCL_DEBUG - Printf(stderr, "functionWrapper %s\n", Getattr(n,"name")); -#endif - - - ParmList *parms = CopyParmList(Getattr(n, "parms")); - Wrapper *f = NewWrapper(); - SwigType *t = Getattr(n, "type"); - String *name = Getattr(n, "name"); - - String *raw_return_type = Swig_typemap_lookup("ctype", n, "", 0); - SwigType *return_type = Swig_cparse_type(raw_return_type); - SwigType *resolved = SwigType_typedef_resolve_all(return_type); - int is_void_return = (Cmp(resolved, "void") == 0); - - Delete(resolved); - - if (!is_void_return) { - String *lresult_init = - NewStringf("= (%s)0", - SwigType_str(SwigType_strip_qualifiers(return_type),0)); - Wrapper_add_localv(f, "lresult", - SwigType_lstr(SwigType_ltype(return_type), "lresult"), - lresult_init, NIL); - Delete(lresult_init); - } - // Emit all of the local variables for holding arguments. - emit_parameter_variables(parms, f); - - // Attach the standard typemaps - Swig_typemap_attach_parms("ctype", parms, f); - Swig_typemap_attach_parms("lin", parms, f); - emit_attach_parmmaps(parms, f); - - String *mangled = mangle_name(n); - Node *overloaded = Getattr(n, "sym:overloaded"); - - // Parameter overloading - Setattr(n, "wrap:parms", parms); - Setattr(n, "wrap:name", mangled); - - if (overloaded) { - // emit warnings when overloading is impossible on the lisp side. - // basically Swig_overload_check(n), but with script_lang_wrapping - // set to true. - Delete(Swig_overload_rank(n, true)); - if (Getattr(n, "overload:ignore")) { - // if we're the last overload, make sure to force the emit - // of the rest of the overloads before we leave. - // Printf(stderr, "ignored overload %s(%p)\n", name, Getattr(n, "sym:nextSibling")); - if (!Getattr(n, "sym:nextSibling")) { - update_package_if_needed(n); - emit_buffered_defuns(n); - emit_dispatch_defun(n); - } - DelWrapper(f); - return SWIG_OK; - } - } - // Get number of required and total arguments - int num_arguments = emit_num_arguments(parms); - int gencomma = 0; - -#ifdef ALLEGROCL_DEBUG - Printf(stderr, "Walking parameters for %s '%s'\n", Getattr(n, "allegrocl:kind"), name); -#endif - // Now walk the function parameter list and generate code to get arguments - String *name_and_parms = NewStringf("%s (", mangled); - int i; - Parm *p; - for (i = 0, p = parms; i < num_arguments; i++) { - -#ifdef ALLEGROCL_DEBUG - String *temp1 = Getattr(p,"tmap:in"); - String *temp2 = Getattr(p,"tmap:in:numinputs"); - Printf(stderr," parm %d: %s, tmap:in='%s', tmap:in:numinputs='%s'\n", i, Getattr(p,"name"), temp1 ? temp1 : "", temp2 ? temp2 : ""); -#endif - - while (p && checkAttribute(p, "tmap:in:numinputs", "0")) { - p = Getattr(p, "tmap:in:next"); - } - - if (!p) - break; - - SwigType *c_parm_type = Swig_cparse_type(Getattr(p, "tmap:ctype")); - String *arg = NewStringf("l%s", Getattr(p, "lname")); - - // Emit parameter declaration - if (gencomma) - Printf(name_and_parms, ", "); - String *parm_decl = SwigType_str(c_parm_type, arg); - Printf(name_and_parms, "%s", parm_decl); -#ifdef ALLEGROCL_DEBUG - Printf(stderr, " param: %s\n", parm_decl); -#endif - Delete(parm_decl); - gencomma = 1; - - // Emit parameter conversion code - String *parm_code = Getattr(p, "tmap:in"); - //if (!parm_code) { - // Swig_warning(...); - // p = nextSibling(p); - /*} else */ { - // canThrow(n, "in", p); - Replaceall(parm_code, "$input", arg); - Setattr(p, "emit:input", arg); - Printf(f->code, "%s\n", parm_code); - p = Getattr(p, "tmap:in:next"); - } - - Delete(arg); - } - Printf(name_and_parms, ")"); - -#ifdef ALLEGROCL_DEBUG - Printf(stderr, " arity = %d(%d)\n", emit_num_lin_arguments(parms), emit_num_lin_arguments(Getattr(n,"wrap:parms"))); -#endif - - // Emit the function definition - String *signature = SwigType_str(return_type, name_and_parms); - Printf(f->def, "EXPORT %s {", signature); - if (CPlusPlus) - Printf(f->code, " try {\n"); - - String *actioncode = emit_action(n); - - String *tm = Swig_typemap_lookup_out("out", n, Swig_cresult_name(), f, actioncode); - if (!is_void_return) { - if (tm) { - Replaceall(tm, "$result", "lresult"); - Printf(f->code, "%s\n", tm); - Printf(f->code, " return lresult;\n"); - Delete(tm); - } else { - Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, - "Unable to use return type %s in function %s.\n", - SwigType_str(t, 0), name); - } - } - - /* See if there is any return cleanup code */ - if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); - Printf(f->code, "%s\n", tm); - Delete(tm); - } - - emit_return_variable(n, t, f); - - if (CPlusPlus) { - Printf(f->code, " } catch (...) {\n"); - if (!is_void_return) - Printf(f->code, " return (%s)0;\n", - SwigType_str(SwigType_strip_qualifiers(return_type),0)); - Printf(f->code, " }\n"); - } - Printf(f->code, "}\n"); - - /* print this when in C mode? make this a command-line arg? */ - if (Generate_Wrapper) - Wrapper_print(f, f_cxx_wrapper); - - String *f_buffer = NewString(""); - - emit_defun(n, f_buffer); - Setattr(n, "allegrocl:lisp-wrap", f_buffer); - - if (!overloaded || !Getattr(n, "sym:nextSibling")) { - update_package_if_needed(n); - emit_buffered_defuns(n); - // this is the last overload. - if (overloaded) { - emit_dispatch_defun(n); - } - } - - DelWrapper(f); - - return SWIG_OK; -} - -int ALLEGROCL::namespaceDeclaration(Node *n) { -#ifdef ALLEGROCL_DEBUG - Printf(stderr, "namespaceDecl: '%s'(%p) (fc=%p)\n", Getattr(n, "sym:name"), n, firstChild(n)); -#endif - - /* don't wrap a namespace with no contents. package bloat. - also, test-suite/namespace_class.i claims an unnamed namespace - is 'private' and should not be wrapped. Complying... - */ - if (Getattr(n,"unnamed") || !firstChild(n)) - return SWIG_OK; - - String *name = Getattr(n, "sym:name"); - - String *old_namespace = current_namespace; - if (Cmp(current_namespace, "") == 0) - current_namespace = NewStringf("%s", name); - else - current_namespace = NewStringf("%s::%s", current_namespace, name); - - if (!GetInt(defined_namespace_packages, current_namespace)) { - SetInt(defined_namespace_packages, current_namespace, 1); - String *lispy_namespace = listify_namespace(current_namespace); - Printf(f_clhead, "(swig-defpackage %s)\n", lispy_namespace); - Delete(lispy_namespace); - } - - emit_children(n); - - Delete(current_namespace); - current_namespace = old_namespace; - return SWIG_OK; -} - -int ALLEGROCL::constructorHandler(Node *n) { -#ifdef ALLEGROCL_DEBUG - Printf(stderr, "constructorHandler %s\n", Getattr(n, "name")); -#endif - // Swig_print_node(n); - Setattr(n, "allegrocl:kind", "constructor"); - Setattr(n, "allegrocl:old-sym:name", Getattr(n, "sym:name")); - - // Let SWIG generate a global forwarding function. - return Language::constructorHandler(n); -} - -int ALLEGROCL::destructorHandler(Node *n) { -#ifdef ALLEGROCL_DEBUG - Printf(stderr, "destructorHandler %s\n", Getattr(n, "name")); -#endif - - Setattr(n, "allegrocl:kind", "destructor"); - Setattr(n, "allegrocl:old-sym:name", Getattr(n, "sym:name")); - - // Let SWIG generate a global forwarding function. - return Language::destructorHandler(n); -} - -int ALLEGROCL::constantWrapper(Node *n) { -#ifdef ALLEGROCL_DEBUG - Printf(stderr, "constantWrapper %s\n", Getattr(n, "name")); -#endif - - if (Generate_Wrapper) { - // Setattr(n,"wrap:name",mangle_name(n, "ACLPP")); - String *const_type = Getattr(n, "type"); - - String *const_val = 0; - String *raw_const = Getattr(n, "value"); - - if (SwigType_type(const_type) == T_STRING) { - const_val = NewStringf("\"%s\"", raw_const); - } else if (SwigType_type(const_type) == T_CHAR) { - const_val = NewStringf("'%s'", raw_const); - } else { - const_val = Copy(raw_const); - } - - SwigType_add_qualifier(const_type, "const"); - - String *ppcname = NewStringf("ACLppc_%s", Getattr(n, "sym:name")); - // Printf(f_runtime, "static const %s = %s;\n", SwigType_lstr(const_type, ppcname), const_val); - Printf(f_runtime, "static %s = %s;\n", SwigType_lstr(const_type, ppcname), const_val); - - Setattr(n, "name", ppcname); - SetFlag(n, "feature:immutable"); - - Delete(const_val); - return variableWrapper(n); - } - - String *type = Getattr(n, "type"); - String *value = Getattr(n, "value"); - String *converted_value = convert_literal(value, type); - String *name = Getattr(n, "sym:name"); - - Setattr(n, "allegrocl:kind", "constant"); - Setattr(n, "allegrocl:old-sym:name", Getattr(n, "sym:name")); - -#if 0 - Printf(stdout, "constant %s is of type %s. value: %s\n", name, type, converted_value); -#endif - - if (converted_value) { - Printf(f_clwrap, "(swig-defconstant \"%s\" %s)\n", name, converted_value); - } else { - Swig_warning(WARN_LANG_DISCARD_CONST, Getfile(n), Getline(n), "Unable to parse constant value '%s'. Setting to NIL\n", value); - Printf(f_clwrap, "(swig-defconstant \"%s\" nil #| %s |#)\n", name, value); - } - - Delete(converted_value); - - return SWIG_OK; -} - -int ALLEGROCL::globalvariableHandler(Node *n) { -#ifdef ALLEGROCL_DEBUG - Printf(stderr, "globalvariableHandler %s\n", Getattr(n, "name")); -#endif - - if (Generate_Wrapper) - return Language::globalvariableHandler(n); - - // String *name = Getattr(n, "name"); - SwigType *type = Getattr(n, "type"); - SwigType *rtype = SwigType_typedef_resolve_all(type); - - if (SwigType_isclass(rtype)) { - SwigType_add_pointer(type); - SwigType_add_pointer(rtype); - } - - Printf(f_clwrap, "(swig-defvar \"%s\" \"%s\" :type %s)\n", - Getattr(n, "sym:name"), Getattr(n, "sym:name"), ((SwigType_isconst(type)) ? ":constant" : ":variable")); - - return SWIG_OK; -} - -int ALLEGROCL::variableWrapper(Node *n) { -#ifdef ALLEGROCL_DEBUG - Printf(stderr, "variableWrapper %s\n", Getattr(n, "name")); -#endif - Setattr(n, "allegrocl:kind", "variable"); - Setattr(n, "allegrocl:old-sym:name", Getattr(n, "sym:name")); - - // Let SWIG generate a get/set function pair. - if (Generate_Wrapper) - return Language::variableWrapper(n); - - String *name = Getattr(n, "name"); - SwigType *type = Getattr(n, "type"); - SwigType *ctype; - SwigType *rtype = SwigType_typedef_resolve_all(type); - - String *mangled_name = mangle_name(n); - - int pointer_added = 0; - - if (SwigType_isclass(rtype)) { - SwigType_add_pointer(type); - SwigType_add_pointer(rtype); - pointer_added = 1; - } - - ctype = SwigType_str(type, 0); - - // EXPORT ; - // = ; - Printf(f_runtime, "EXPORT %s %s;\n%s %s = %s%s;\n", ctype, mangled_name, ctype, mangled_name, (pointer_added ? "&" : ""), name); - - Printf(f_cl, "(swig-defvar \"%s\" :type %s)\n", mangled_name, ((SwigType_isconst(type)) ? ":constant" : ":variable")); - - Printf(stderr,"***\n"); - Delete(mangled_name); - -#ifdef ALLEGROCL_DEBUG - Printf(stderr, "DONE variable %s\n", Getattr(n, "name")); -#endif - - return SWIG_OK; -} - -int ALLEGROCL::memberfunctionHandler(Node *n) { -#ifdef ALLEGROCL_DEBUG - Printf(stderr, "memberfunctionHandler %s::%s\n", Getattr(parent_node_skipping_extends(n), "name"), Getattr(n, "name")); - Swig_print_node(n); -#endif - Setattr(n, "allegrocl:kind", "member function"); - Setattr(n, "allegrocl:old-sym:name", Getattr(n, "sym:name")); - - // Let SWIG generate a global forwarding function. - return Language::memberfunctionHandler(n); -} - -int ALLEGROCL::membervariableHandler(Node *n) { -#ifdef ALLEGROCL_DEBUG - Printf(stderr, "membervariableHandler %s::%s\n", Getattr(parent_node_skipping_extends(n), "name"), Getattr(n, "name")); -#endif - Setattr(n, "allegrocl:kind", "member variable"); - Setattr(n, "allegrocl:old-sym:name", Getattr(n, "sym:name")); - - // Let SWIG generate a get/set function pair. - return Language::membervariableHandler(n); -} - -int ALLEGROCL::typedefHandler(Node *n) { -#ifdef ALLEGROCL_TYPE_DEBUG - Printf(stderr, "In typedefHandler\n"); -#endif - - SwigType *typedef_type = Getattr(n,"type"); - // has the side-effect of noting any implicit - // template instantiations in type. - String *ff_type = compose_foreign_type(n, typedef_type); - - String *sym_name = Getattr(n, "sym:name"); - - String *name; - String *type_ref; - - if (in_class) { -#ifdef ALLEGROCL_TYPE_DEBUG - Printf(stderr, " typedef in class '%s'(%p)\n", Getattr(in_class, "sym:name"), in_class); -#endif - Setattr(n, "allegrocl:typedef:in-class", in_class); - - String *class_name = Getattr(in_class, "name"); - name = NewStringf("%s__%s", class_name, sym_name); - type_ref = NewStringf("%s::%s", class_name, sym_name); - Setattr(n, "allegrocl:in-class", in_class); - } else { - name = Copy(sym_name); - type_ref = Copy(Getattr(n, "name")); - } - - Setattr(n, "allegrocl:namespace", current_namespace); - - String *lookup = lookup_defined_foreign_type(typedef_type); - -#ifdef ALLEGROCL_TYPE_DEBUG - Printf(stderr, "** lookup='%s'(%p), typedef_type='%s', strcmp = '%d' strstr = '%d'\n", lookup, lookup, typedef_type, Strcmp(typedef_type,"void"), Strstr(ff_type,"__SWIGACL_FwdReference")); -#endif - - if(lookup || (!lookup && Strcmp(typedef_type,"void")) || - (!lookup && Strstr(ff_type,"__SWIGACL_FwdReference"))) { - add_defined_foreign_type(n, 0, type_ref, name); - } else { - add_forward_referenced_type(n); - } - -#ifdef ALLEGROCL_TYPE_DEBUG - Printf(stderr, "Out typedefHandler\n"); -#endif - - Delete(ff_type); - - return SWIG_OK; -} - -// forward referenced classes are added specially to defined_foreign_types -int ALLEGROCL::classforwardDeclaration(Node *n) { -#ifdef ALLEGROCL_DEBUG - Printf(stderr, "classforwardDeclaration %s\n", Getattr(n, "name")); -#endif - - add_forward_referenced_type(n); - return SWIG_OK; -} - -int ALLEGROCL::classHandler(Node *n) { -#ifdef ALLEGROCL_DEBUG - Printf(stderr, "classHandler %s::%s\n", current_namespace, Getattr(n, "sym:name")); -#endif - - int result; - - if (Generate_Wrapper) - result = cppClassHandler(n); - else - result = cClassHandler(n); - - return result; -} - -int ALLEGROCL::cClassHandler(Node *n) { -#ifdef ALLEGROCL_TYPE_DEBUG - Printf(stderr, "In cClassHandler\n"); -#endif - /* Add this structure to the known lisp types */ - // Printf(stderr, "Adding %s foreign type\n", name); - String *ns = listify_namespace(current_namespace); - - add_defined_foreign_type(n); - - Delete(ns); - -#ifdef ALLEGROCL_TYPE_DEBUG - Printf(stderr, "Out cClassHandler\n"); -#endif - - return SWIG_OK; -} - -int ALLEGROCL::cppClassHandler(Node *n) { -#ifdef ALLEGROCL_DEBUG - Printf(stderr, "cppClassHandler %s\n", Getattr(n, "name")); -#endif - - // String *name=Getattr(n, "sym:name"); - // String *kind = Getattr(n,"kind"); - - /* Template instantiation. - Careful. - SWIG does not create instantiations of templated classes whenever - it sees a templated class reference (say, as a return type, or - in a parameter list). - - The %template directive results in a templated class instantiation - that will actually be seen by :: classHandler(). - - In this case, we don't want to error if the type already exists; - the point is to force the creation of wrappers for the templated - class. - */ - String *templated = Getattr(n, "template"); - String *t_name; - // String *ns = listify_namespace(current_namespace); - - if (templated) { - t_name = namespaced_name(n); - } else { - t_name = Getattr(n, "name"); - } - - Setattr(n, "allegrocl:namespace", current_namespace); - - /* Add this structure to the known lisp types. - Class may contain references to the type currently being - defined */ - if (!templated || !lookup_defined_foreign_type(t_name)) { -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, "Adding %s foreign type\n", Getattr(n, "sym:name")); -#endif - add_defined_foreign_type(n); - } else { -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, "cppClassHand: type %s already exists. Assuming %%template instantiation for wrapping purposes.\n", Getattr(n, "sym:name")); -#endif - add_defined_foreign_type(n, 1); - } - - // Generate slot accessors, constructor, and destructor. - Node *prev_class = in_class; - in_class = n; - - Node *c; - // walk all member variables. -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, " MANUALLY walking class members... \n"); -#endif - for (c = firstChild(n); c; c = nextSibling(c)) { - // ping the types of all children--even protected and private - // so their types can be added to the linked_type_list. - SwigType *childType = NewStringf("%s%s", Getattr(c, "decl"), - Getattr(c, "type")); -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, "looking at child '%p' of type '%s' '%d'\n", c, childType, SwigType_isfunction(childType)); - // Swig_print_node(c); -#endif - if (!SwigType_isfunction(childType)) - Delete(compose_foreign_type(n, childType)); - - Delete(childType); - } -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, " MANUAL walk DONE.\n"); -#endif - - // this will walk all necessary methods. -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, " LANGUAGE walk of children...\n"); -#endif - Language::classHandler(n); -#ifdef ALLEGROCL_CLASS_DEBUG - Printf(stderr, " LANGUAGE walk DONE\n"); -#endif - in_class = prev_class; - - return SWIG_OK; -} - -int ALLEGROCL::emit_one(Node *n) { - // When the current package does not correspond with the current - // namespace we need to generate an IN-PACKAGE form, unless the - // current node is another namespace node. - if (Cmp(nodeType(n), "namespace") != 0 && Cmp(current_package, current_namespace) != 0) { - String *lispy_namespace = listify_namespace(current_namespace); - Printf(f_clwrap, "(swig-in-package %s)\n", lispy_namespace); - Delete(lispy_namespace); - Delete(current_package); - current_package = NewStringf("%s", current_namespace); - } - - Setattr(n, "allegrocl:package", current_package); - - return Language::emit_one(n); -} - -int ALLEGROCL::enumDeclaration(Node *n) { -#ifdef ALLEGROCL_DEBUG - Printf(stderr, "enumDeclaration %s\n", Getattr(n, "name")); -#endif - - if (getCurrentClass() && (cplus_mode != PUBLIC)) - return SWIG_NOWRAP; - - if (Getattr(n, "sym:name")) { - add_defined_foreign_type(n); - } - Node *c; - for (c = firstChild(n); c; c = nextSibling(c)) { - ALLEGROCL::enumvalueDeclaration(c); - // since we walk our own children, we need to add - // the current package ourselves. - Setattr(c, "allegrocl:package", current_package); - } - return SWIG_OK; -} - - -int ALLEGROCL::enumvalueDeclaration(Node *n) { -#ifdef ALLEGROCL_DEBUG - Printf(stderr, "enumvalueDeclaration %s\n", Getattr(n, "name")); -#endif - /* print this when in C mode? make this a command-line arg? */ - if (Generate_Wrapper) { - SwigType *enum_type = Copy(Getattr(n,"type")); - String *mangled_name = - mangle_name(n, "ACL_ENUM", - in_class ? Getattr(in_class,"name") : - current_namespace); - - SwigType_add_qualifier(enum_type,"const"); - - String *enum_decl = SwigType_str(enum_type, mangled_name); - Printf(f_cxx_wrapper, "EXPORT %s;\n", enum_decl); - Printf(f_cxx_wrapper, "%s = %s;\n", enum_decl, Getattr(n, "value")); - - Delete(mangled_name); - Delete(enum_type); - Delete(enum_decl); - } - return SWIG_OK; -} - -int ALLEGROCL::templateDeclaration(Node *n) { -#ifdef ALLEGROCL_DEBUG - Printf(stderr, "templateDeclaration %s\n", Getattr(n, "name")); -#endif - - String *type = Getattr(n, "templatetype"); - - // Printf(stderr, "tempDecl: %s %s\n", Getattr(n,"name"), - // type); - // Swig_print_node(n); - - if (!Strcmp(type, "cdecl")) { - SwigType *ty = NewStringf("%s%s", Getattr(n, "decl"), - Getattr(n, "type")); - Delete(ty); - } - - Delete(type); - - return SWIG_OK; -} - diff --git a/Source/Modules/allocate.cxx b/Source/Modules/allocate.cxx index 23683c385..7d567395c 100644 --- a/Source/Modules/allocate.cxx +++ b/Source/Modules/allocate.cxx @@ -779,6 +779,12 @@ Allocate(): if (Swig_storage_isstatic(n)) { Setattr(n, "cplus:staticbase", inclass); + } else if (Cmp(Getattr(n, "kind"), "variable") == 0) { + /* Check member variable to determine whether assignment is valid */ + if (SwigType_isreference(Getattr(n, "type"))) { + /* Can't assign a class with reference member data */ + Setattr(inclass, "allocate:noassign", "1"); + } } String *name = Getattr(n, "name"); diff --git a/Source/Modules/cffi.cxx b/Source/Modules/cffi.cxx index bf3338813..6333fa153 100644 --- a/Source/Modules/cffi.cxx +++ b/Source/Modules/cffi.cxx @@ -227,7 +227,7 @@ int CFFI::classHandler(Node *n) { int CFFI::constructorHandler(Node *n) { #ifdef CFFI_DEBUG Printf(stderr, "constructor %s\n", Getattr(n, "name")); - Printf(stderr, "constructor %s\n and %s and %s", Getattr(n, "kind"), Getattr(n, "sym:name"), Getattr(n, "allegrocl:old-sym:name")); + Printf(stderr, "constructor %s\n and %s", Getattr(n, "kind"), Getattr(n, "sym:name")); #endif Setattr(n, "cffi:constructorfunction", "1"); // Let SWIG generate a global forwarding function. @@ -426,7 +426,6 @@ void CFFI::cleanupFunction(Node *n, Wrapper *f, ParmList *parms) { if (GetFlag(n, "feature:new")) { String *tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0); if (tm) { - Replaceall(tm, "$source", Swig_cresult_name()); Printv(f->code, tm, "\n", NULL); Delete(tm); } @@ -546,7 +545,6 @@ int CFFI::functionWrapper(Node *n) { /* See if there is any return cleanup code */ String *tm = 0; if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); Printf(f->code, "%s\n", tm); Delete(tm); } diff --git a/Source/Modules/chicken.cxx b/Source/Modules/chicken.cxx deleted file mode 100644 index 76b6455e2..000000000 --- a/Source/Modules/chicken.cxx +++ /dev/null @@ -1,1535 +0,0 @@ -/* ----------------------------------------------------------------------------- - * This file is part of SWIG, which is licensed as a whole under version 3 - * (or any later version) of the GNU General Public License. Some additional - * terms also apply to certain portions of SWIG. The full details of the SWIG - * license and copyrights can be found in the LICENSE and COPYRIGHT files - * included with the SWIG source code as distributed by the SWIG developers - * and at http://www.swig.org/legal.html. - * - * chicken.cxx - * - * CHICKEN language module for SWIG. - * ----------------------------------------------------------------------------- */ - -#include "swigmod.h" - -#include - -static const char *usage = "\ -\ -CHICKEN Options (available with -chicken)\n\ - -closprefix - Prepend to all clos identifiers\n\ - -noclosuses - Do not (declare (uses ...)) in scheme file\n\ - -nocollection - Do not register pointers with chicken garbage\n\ - collector and export destructors\n\ - -nounit - Do not (declare (unit ...)) in scheme file\n\ - -proxy - Export TinyCLOS class definitions\n\ - -unhideprimitive - Unhide the primitive: symbols\n\ - -useclassprefix - Prepend the class name to all clos identifiers\n\ -\n"; - -static char *module = 0; -static const char *chicken_path = "chicken"; -static int num_methods = 0; - -static File *f_begin = 0; -static File *f_runtime = 0; -static File *f_header = 0; -static File *f_wrappers = 0; -static File *f_init = 0; -static String *chickentext = 0; -static String *closprefix = 0; -static String *swigtype_ptr = 0; - - -static String *f_sym_size = 0; - -/* some options */ -static int declare_unit = 1; -static int no_collection = 0; -static int clos_uses = 1; - -/* C++ Support + Clos Classes */ -static int clos = 0; -static String *c_class_name = 0; -static String *class_name = 0; -static String *short_class_name = 0; - -static int in_class = 0; -static int have_constructor = 0; -static bool exporting_destructor = false; -static bool exporting_constructor = false; -static String *constructor_name = 0; -static String *member_name = 0; - -/* sections of the .scm code */ -static String *scm_const_defs = 0; -static String *clos_class_defines = 0; -static String *clos_methods = 0; - -/* Some clos options */ -static int useclassprefix = 0; -static String *clossymnameprefix = 0; -static int hide_primitive = 1; -static Hash *primitive_names = 0; - -/* Used for overloading constructors */ -static int has_constructor_args = 0; -static List *constructor_arg_types = 0; -static String *constructor_dispatch = 0; - -static Hash *overload_parameter_lists = 0; - -class CHICKEN:public Language { -public: - - virtual void main(int argc, char *argv[]); - virtual int top(Node *n); - virtual int functionWrapper(Node *n); - virtual int variableWrapper(Node *n); - virtual int constantWrapper(Node *n); - virtual int classHandler(Node *n); - virtual int memberfunctionHandler(Node *n); - virtual int membervariableHandler(Node *n); - virtual int constructorHandler(Node *n); - virtual int destructorHandler(Node *n); - virtual int validIdentifier(String *s); - virtual int staticmembervariableHandler(Node *n); - virtual int staticmemberfunctionHandler(Node *n); - virtual int importDirective(Node *n); - -protected: - void addMethod(String *scheme_name, String *function); - /* Return true iff T is a pointer type */ - int isPointer(SwigType *t); - void dispatchFunction(Node *n); - - String *chickenNameMapping(String *, const_String_or_char_ptr ); - String *chickenPrimitiveName(String *); - - String *runtimeCode(); - String *defaultExternalRuntimeFilename(); - String *buildClosFunctionCall(List *types, const_String_or_char_ptr closname, const_String_or_char_ptr funcname); -}; - -/* ----------------------------------------------------------------------- - * swig_chicken() - Instantiate module - * ----------------------------------------------------------------------- */ - -static Language *new_swig_chicken() { - return new CHICKEN(); -} - -extern "C" { - Language *swig_chicken(void) { - return new_swig_chicken(); - } -} - -void CHICKEN::main(int argc, char *argv[]) { - int i; - - SWIG_library_directory(chicken_path); - - // Look for certain command line options - for (i = 1; i < argc; i++) { - if (argv[i]) { - if (strcmp(argv[i], "-help") == 0) { - fputs(usage, stdout); - SWIG_exit(0); - } else if (strcmp(argv[i], "-proxy") == 0) { - clos = 1; - Swig_mark_arg(i); - } else if (strcmp(argv[i], "-closprefix") == 0) { - if (argv[i + 1]) { - clossymnameprefix = NewString(argv[i + 1]); - Swig_mark_arg(i); - Swig_mark_arg(i + 1); - i++; - } else { - Swig_arg_error(); - } - } else if (strcmp(argv[i], "-useclassprefix") == 0) { - useclassprefix = 1; - Swig_mark_arg(i); - } else if (strcmp(argv[i], "-unhideprimitive") == 0) { - hide_primitive = 0; - Swig_mark_arg(i); - } else if (strcmp(argv[i], "-nounit") == 0) { - declare_unit = 0; - Swig_mark_arg(i); - } else if (strcmp(argv[i], "-noclosuses") == 0) { - clos_uses = 0; - Swig_mark_arg(i); - } else if (strcmp(argv[i], "-nocollection") == 0) { - no_collection = 1; - Swig_mark_arg(i); - } - } - } - - if (!clos) - hide_primitive = 0; - - // Add a symbol for this module - Preprocessor_define("SWIGCHICKEN 1", 0); - - // Set name of typemaps - - SWIG_typemap_lang("chicken"); - - // Read in default typemaps */ - SWIG_config_file("chicken.swg"); - allow_overloading(); -} - -int CHICKEN::top(Node *n) { - String *chicken_filename = NewString(""); - File *f_scm; - String *scmmodule; - - /* Initialize all of the output files */ - String *outfile = Getattr(n, "outfile"); - - f_begin = NewFile(outfile, "w", SWIG_output_files()); - if (!f_begin) { - FileErrorDisplay(outfile); - SWIG_exit(EXIT_FAILURE); - } - f_runtime = NewString(""); - f_init = NewString(""); - f_header = NewString(""); - f_wrappers = NewString(""); - chickentext = NewString(""); - closprefix = NewString(""); - f_sym_size = NewString(""); - primitive_names = NewHash(); - overload_parameter_lists = NewHash(); - - /* Register file targets with the SWIG file handler */ - Swig_register_filebyname("header", f_header); - Swig_register_filebyname("wrapper", f_wrappers); - Swig_register_filebyname("begin", f_begin); - Swig_register_filebyname("runtime", f_runtime); - Swig_register_filebyname("init", f_init); - - Swig_register_filebyname("chicken", chickentext); - Swig_register_filebyname("closprefix", closprefix); - - clos_class_defines = NewString(""); - clos_methods = NewString(""); - scm_const_defs = NewString(""); - - Swig_banner(f_begin); - - Printf(f_runtime, "\n\n#ifndef SWIGCHICKEN\n#define SWIGCHICKEN\n#endif\n\n"); - - if (no_collection) - Printf(f_runtime, "#define SWIG_CHICKEN_NO_COLLECTION 1\n"); - - Printf(f_runtime, "\n"); - - /* Set module name */ - module = Swig_copy_string(Char(Getattr(n, "name"))); - scmmodule = NewString(module); - Replaceall(scmmodule, "_", "-"); - - Printf(f_header, "#define SWIG_init swig_%s_init\n", module); - Printf(f_header, "#define SWIG_name \"%s\"\n", scmmodule); - - Printf(f_wrappers, "#ifdef __cplusplus\n"); - Printf(f_wrappers, "extern \"C\" {\n"); - Printf(f_wrappers, "#endif\n\n"); - - Language::top(n); - - SwigType_emit_type_table(f_runtime, f_wrappers); - - Printf(f_wrappers, "#ifdef __cplusplus\n"); - Printf(f_wrappers, "}\n"); - Printf(f_wrappers, "#endif\n"); - - Printf(f_init, "C_kontinue (continuation, ret);\n"); - Printf(f_init, "}\n\n"); - - Printf(f_init, "#ifdef __cplusplus\n"); - Printf(f_init, "}\n"); - Printf(f_init, "#endif\n"); - - Printf(chicken_filename, "%s%s.scm", SWIG_output_directory(), module); - if ((f_scm = NewFile(chicken_filename, "w", SWIG_output_files())) == 0) { - FileErrorDisplay(chicken_filename); - SWIG_exit(EXIT_FAILURE); - } - - Swig_banner_target_lang(f_scm, ";;"); - Printf(f_scm, "\n"); - - if (declare_unit) - Printv(f_scm, "(declare (unit ", scmmodule, "))\n\n", NIL); - Printv(f_scm, "(declare \n", - tab4, "(hide swig-init swig-init-return)\n", - tab4, "(foreign-declare \"C_extern void swig_", module, "_init(C_word,C_word,C_word) C_noret;\"))\n", NIL); - Printv(f_scm, "(define swig-init (##core#primitive \"swig_", module, "_init\"))\n", NIL); - Printv(f_scm, "(define swig-init-return (swig-init))\n\n", NIL); - - if (clos) { - //Printf (f_scm, "(declare (uses tinyclos))\n"); - //New chicken versions have tinyclos as an egg - Printf(f_scm, "(require-extension tinyclos)\n"); - Replaceall(closprefix, "$module", scmmodule); - Printf(f_scm, "%s\n", closprefix); - Printf(f_scm, "%s\n", clos_class_defines); - Printf(f_scm, "%s\n", clos_methods); - } else { - Printf(f_scm, "%s\n", scm_const_defs); - } - - Printf(f_scm, "%s\n", chickentext); - - Delete(f_scm); - - char buftmp[20]; - sprintf(buftmp, "%d", num_methods); - Replaceall(f_init, "$nummethods", buftmp); - Replaceall(f_init, "$symsize", f_sym_size); - - if (hide_primitive) - Replaceall(f_init, "$veclength", buftmp); - else - Replaceall(f_init, "$veclength", "0"); - - Delete(chicken_filename); - Delete(chickentext); - Delete(closprefix); - Delete(overload_parameter_lists); - - Delete(clos_class_defines); - Delete(clos_methods); - Delete(scm_const_defs); - - /* Close all of the files */ - Delete(primitive_names); - Delete(scmmodule); - Dump(f_runtime, f_begin); - Dump(f_header, f_begin); - Dump(f_wrappers, f_begin); - Wrapper_pretty_print(f_init, f_begin); - Delete(f_header); - Delete(f_wrappers); - Delete(f_sym_size); - Delete(f_init); - Delete(f_runtime); - Delete(f_begin); - return SWIG_OK; -} - -int CHICKEN::functionWrapper(Node *n) { - - String *name = Getattr(n, "name"); - String *iname = Getattr(n, "sym:name"); - SwigType *d = Getattr(n, "type"); - ParmList *l = Getattr(n, "parms"); - - Parm *p; - int i; - String *wname; - Wrapper *f; - String *mangle = NewString(""); - String *get_pointers; - String *cleanup; - String *argout; - String *tm; - String *overname = 0; - String *declfunc = 0; - String *scmname; - bool any_specialized_arg = false; - List *function_arg_types = NewList(); - - int num_required; - int num_arguments; - int have_argout; - - Printf(mangle, "\"%s\"", SwigType_manglestr(d)); - - if (Getattr(n, "sym:overloaded")) { - overname = Getattr(n, "sym:overname"); - } else { - if (!addSymbol(iname, n)) - return SWIG_ERROR; - } - - f = NewWrapper(); - wname = NewString(""); - get_pointers = NewString(""); - cleanup = NewString(""); - argout = NewString(""); - declfunc = NewString(""); - scmname = NewString(iname); - Replaceall(scmname, "_", "-"); - - /* Local vars */ - Wrapper_add_local(f, "resultobj", "C_word resultobj"); - - /* Write code to extract function parameters. */ - emit_parameter_variables(l, f); - - /* Attach the standard typemaps */ - emit_attach_parmmaps(l, f); - Setattr(n, "wrap:parms", l); - - /* Get number of required and total arguments */ - num_arguments = emit_num_arguments(l); - num_required = emit_num_required(l); - - Append(wname, Swig_name_wrapper(iname)); - if (overname) { - Append(wname, overname); - } - // Check for interrupts - Printv(f->code, "C_trace(\"", scmname, "\");\n", NIL); - - Printv(f->def, "static ", "void ", wname, " (C_word argc, C_word closure, C_word continuation", NIL); - Printv(declfunc, "void ", wname, "(C_word,C_word,C_word", NIL); - - /* Generate code for argument marshalling */ - for (i = 0, p = l; i < num_arguments; i++) { - - while (checkAttribute(p, "tmap:in:numinputs", "0")) { - p = Getattr(p, "tmap:in:next"); - } - - SwigType *pt = Getattr(p, "type"); - String *ln = Getattr(p, "lname"); - - Printf(f->def, ", C_word scm%d", i + 1); - Printf(declfunc, ",C_word"); - - /* Look for an input typemap */ - if ((tm = Getattr(p, "tmap:in"))) { - String *parse = Getattr(p, "tmap:in:parse"); - if (!parse) { - String *source = NewStringf("scm%d", i + 1); - Replaceall(tm, "$source", source); - Replaceall(tm, "$target", ln); - Replaceall(tm, "$input", source); - Setattr(p, "emit:input", source); /* Save the location of - the object */ - - if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) { - Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); - } else { - Replaceall(tm, "$disown", "0"); - } - - if (i >= num_required) - Printf(get_pointers, "if (argc-2>%i && (%s)) {\n", i, source); - Printv(get_pointers, tm, "\n", NIL); - if (i >= num_required) - Printv(get_pointers, "}\n", NIL); - - if (clos) { - if (i < num_required) { - if (strcmp("void", Char(pt)) != 0) { - Node *class_node = 0; - String *clos_code = Getattr(p, "tmap:in:closcode"); - class_node = classLookup(pt); - if (clos_code && class_node) { - String *class_name = NewStringf("<%s>", Getattr(class_node, "sym:name")); - Replaceall(class_name, "_", "-"); - Append(function_arg_types, class_name); - Append(function_arg_types, Copy(clos_code)); - any_specialized_arg = true; - Delete(class_name); - } else { - Append(function_arg_types, ""); - Append(function_arg_types, "$input"); - } - } - } - } - Delete(source); - } - - p = Getattr(p, "tmap:in:next"); - continue; - } else { - Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0)); - break; - } - } - - /* finish argument marshalling */ - - Printf(f->def, ") {"); - Printf(declfunc, ")"); - - if (num_required != num_arguments) { - Append(function_arg_types, "^^##optional$$"); - } - - /* First check the number of arguments is correct */ - if (num_arguments != num_required) - Printf(f->code, "if (argc-2<%i || argc-2>%i) C_bad_argc(argc,%i);\n", num_required, num_arguments, num_required + 2); - else - Printf(f->code, "if (argc!=%i) C_bad_argc(argc,%i);\n", num_arguments + 2, num_arguments + 2); - - /* Now piece together the first part of the wrapper function */ - Printv(f->code, get_pointers, NIL); - - /* Insert constraint checking code */ - for (p = l; p;) { - if ((tm = Getattr(p, "tmap:check"))) { - Replaceall(tm, "$target", Getattr(p, "lname")); - Printv(f->code, tm, "\n", NIL); - p = Getattr(p, "tmap:check:next"); - } else { - p = nextSibling(p); - } - } - - /* Insert cleanup code */ - for (p = l; p;) { - if ((tm = Getattr(p, "tmap:freearg"))) { - Replaceall(tm, "$source", Getattr(p, "lname")); - Printv(cleanup, tm, "\n", NIL); - p = Getattr(p, "tmap:freearg:next"); - } else { - p = nextSibling(p); - } - } - - /* Insert argument output code */ - have_argout = 0; - for (p = l; p;) { - if ((tm = Getattr(p, "tmap:argout"))) { - - if (!have_argout) { - have_argout = 1; - // Print initial argument output code - Printf(argout, "SWIG_Chicken_SetupArgout\n"); - } - - Replaceall(tm, "$source", Getattr(p, "lname")); - Replaceall(tm, "$target", "resultobj"); - Replaceall(tm, "$arg", Getattr(p, "emit:input")); - Replaceall(tm, "$input", Getattr(p, "emit:input")); - Printf(argout, "%s", tm); - p = Getattr(p, "tmap:argout:next"); - } else { - p = nextSibling(p); - } - } - - Setattr(n, "wrap:name", wname); - - /* Emit the function call */ - String *actioncode = emit_action(n); - - /* Return the function value */ - if ((tm = Swig_typemap_lookup_out("out", n, Swig_cresult_name(), f, actioncode))) { - Replaceall(tm, "$source", Swig_cresult_name()); - Replaceall(tm, "$target", "resultobj"); - Replaceall(tm, "$result", "resultobj"); - if (GetFlag(n, "feature:new")) { - Replaceall(tm, "$owner", "1"); - } else { - Replaceall(tm, "$owner", "0"); - } - - Printf(f->code, "%s", tm); - - if (have_argout) - Printf(f->code, "\nSWIG_APPEND_VALUE(resultobj);\n"); - - } else { - Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(d, 0), name); - } - emit_return_variable(n, d, f); - - /* Insert the argument output code */ - Printv(f->code, argout, NIL); - - /* Output cleanup code */ - Printv(f->code, cleanup, NIL); - - /* Look to see if there is any newfree cleanup code */ - if (GetFlag(n, "feature:new")) { - if ((tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); - Printf(f->code, "%s\n", tm); - } - } - - /* See if there is any return cleanup code */ - if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); - Printf(f->code, "%s\n", tm); - } - - - if (have_argout) { - Printf(f->code, "C_kontinue(continuation,C_SCHEME_END_OF_LIST);\n"); - } else { - if (exporting_constructor && clos && hide_primitive) { - /* Don't return a proxy, the wrapped CLOS class is the proxy */ - Printf(f->code, "C_kontinue(continuation,resultobj);\n"); - } else { - // make the continuation the proxy creation function, if one exists - Printv(f->code, "{\n", - "C_word func;\n", - "SWIG_Chicken_FindCreateProxy(func, resultobj)\n", - "if (C_swig_is_closurep(func))\n", - " ((C_proc4)(void *)C_block_item(func, 0))(4,func,continuation,resultobj,C_SCHEME_FALSE);\n", - "else\n", " C_kontinue(continuation, resultobj);\n", "}\n", NIL); - } - } - - /* Error handling code */ -#ifdef USE_FAIL - Printf(f->code, "fail:\n"); - Printv(f->code, cleanup, NIL); - Printf(f->code, "swig_panic (\"failure in " "'$symname' SWIG function wrapper\");\n"); -#endif - Printf(f->code, "}\n"); - - /* Substitute the cleanup code */ - Replaceall(f->code, "$cleanup", cleanup); - - /* Substitute the function name */ - Replaceall(f->code, "$symname", iname); - Replaceall(f->code, "$result", "resultobj"); - - /* Dump the function out */ - Printv(f_wrappers, "static ", declfunc, " C_noret;\n", NIL); - Wrapper_print(f, f_wrappers); - - /* Now register the function with the interpreter. */ - if (!Getattr(n, "sym:overloaded")) { - if (exporting_destructor && !no_collection) { - Printf(f_init, "((swig_chicken_clientdata *)(SWIGTYPE%s->clientdata))->destroy = (swig_chicken_destructor) %s;\n", swigtype_ptr, wname); - } else { - addMethod(scmname, wname); - } - - /* Only export if we are not in a class, or if in a class memberfunction */ - if (!in_class || member_name) { - String *method_def; - String *clos_name; - if (in_class) - clos_name = NewString(member_name); - else - clos_name = chickenNameMapping(scmname, ""); - - if (!any_specialized_arg) { - method_def = NewString(""); - Printv(method_def, "(define ", clos_name, " ", chickenPrimitiveName(scmname), ")", NIL); - } else { - method_def = buildClosFunctionCall(function_arg_types, clos_name, chickenPrimitiveName(scmname)); - } - Printv(clos_methods, method_def, "\n", NIL); - Delete(clos_name); - Delete(method_def); - } - - if (have_constructor && !has_constructor_args && any_specialized_arg) { - has_constructor_args = 1; - constructor_arg_types = Copy(function_arg_types); - } - } else { - /* add function_arg_types to overload hash */ - List *flist = Getattr(overload_parameter_lists, scmname); - if (!flist) { - flist = NewList(); - Setattr(overload_parameter_lists, scmname, flist); - } - - Append(flist, Copy(function_arg_types)); - - if (!Getattr(n, "sym:nextSibling")) { - dispatchFunction(n); - } - } - - - Delete(wname); - Delete(get_pointers); - Delete(cleanup); - Delete(declfunc); - Delete(mangle); - Delete(function_arg_types); - DelWrapper(f); - return SWIG_OK; -} - -int CHICKEN::variableWrapper(Node *n) { - char *name = GetChar(n, "name"); - char *iname = GetChar(n, "sym:name"); - SwigType *t = Getattr(n, "type"); - ParmList *l = Getattr(n, "parms"); - - String *wname = NewString(""); - String *mangle = NewString(""); - String *tm; - String *tm2 = NewString(""); - String *argnum = NewString("0"); - String *arg = NewString("argv[0]"); - Wrapper *f; - String *overname = 0; - String *scmname; - - scmname = NewString(iname); - Replaceall(scmname, "_", "-"); - - Printf(mangle, "\"%s\"", SwigType_manglestr(t)); - - if (Getattr(n, "sym:overloaded")) { - overname = Getattr(n, "sym:overname"); - } else { - if (!addSymbol(iname, n)) - return SWIG_ERROR; - } - - f = NewWrapper(); - - /* Attach the standard typemaps */ - emit_attach_parmmaps(l, f); - Setattr(n, "wrap:parms", l); - - // evaluation function names - Append(wname, Swig_name_wrapper(iname)); - if (overname) { - Append(wname, overname); - } - Setattr(n, "wrap:name", wname); - - // Check for interrupts - Printv(f->code, "C_trace(\"", scmname, "\");\n", NIL); - - if (1 || (SwigType_type(t) != T_USER) || (isPointer(t))) { - - Printv(f->def, "static ", "void ", wname, "(C_word, C_word, C_word, C_word) C_noret;\n", NIL); - Printv(f->def, "static " "void ", wname, "(C_word argc, C_word closure, " "C_word continuation, C_word value) {\n", NIL); - - Wrapper_add_local(f, "resultobj", "C_word resultobj"); - - Printf(f->code, "if (argc!=2 && argc!=3) C_bad_argc(argc,2);\n"); - - /* Check for a setting of the variable value */ - if (!GetFlag(n, "feature:immutable")) { - Printf(f->code, "if (argc > 2) {\n"); - if ((tm = Swig_typemap_lookup("varin", n, name, 0))) { - Replaceall(tm, "$source", "value"); - Replaceall(tm, "$target", name); - Replaceall(tm, "$input", "value"); - /* Printv(f->code, tm, "\n",NIL); */ - emit_action_code(n, f->code, tm); - } else { - Swig_warning(WARN_TYPEMAP_VARIN_UNDEF, input_file, line_number, "Unable to set variable of type %s.\n", SwigType_str(t, 0)); - } - Printf(f->code, "}\n"); - } - - String *varname; - if (SwigType_istemplate((char *) name)) { - varname = SwigType_namestr((char *) name); - } else { - varname = name; - } - - // Now return the value of the variable - regardless - // of evaluating or setting. - if ((tm = Swig_typemap_lookup("varout", n, name, 0))) { - Replaceall(tm, "$source", varname); - Replaceall(tm, "$varname", varname); - Replaceall(tm, "$target", "resultobj"); - Replaceall(tm, "$result", "resultobj"); - /* Printf(f->code, "%s\n", tm); */ - emit_action_code(n, f->code, tm); - } else { - Swig_warning(WARN_TYPEMAP_VAROUT_UNDEF, input_file, line_number, "Unable to read variable of type %s\n", SwigType_str(t, 0)); - } - - Printv(f->code, "{\n", - "C_word func;\n", - "SWIG_Chicken_FindCreateProxy(func, resultobj)\n", - "if (C_swig_is_closurep(func))\n", - " ((C_proc4)(void *)C_block_item(func, 0))(4,func,continuation,resultobj,C_SCHEME_FALSE);\n", - "else\n", " C_kontinue(continuation, resultobj);\n", "}\n", NIL); - - /* Error handling code */ -#ifdef USE_FAIL - Printf(f->code, "fail:\n"); - Printf(f->code, "swig_panic (\"failure in " "'%s' SWIG wrapper\");\n", proc_name); -#endif - Printf(f->code, "}\n"); - - Wrapper_print(f, f_wrappers); - - /* Now register the variable with the interpreter. */ - addMethod(scmname, wname); - - if (!in_class || member_name) { - String *clos_name; - if (in_class) - clos_name = NewString(member_name); - else - clos_name = chickenNameMapping(scmname, ""); - - Node *class_node = classLookup(t); - String *clos_code = Getattr(n, "tmap:varin:closcode"); - if (class_node && clos_code && !GetFlag(n, "feature:immutable")) { - Replaceall(clos_code, "$input", "(car lst)"); - Printv(clos_methods, "(define (", clos_name, " . lst) (if (null? lst) (", chickenPrimitiveName(scmname), ") (", - chickenPrimitiveName(scmname), " ", clos_code, ")))\n", NIL); - } else { - /* Simply re-export the procedure */ - if (GetFlag(n, "feature:immutable") && GetFlag(n, "feature:constasvar")) { - Printv(clos_methods, "(define ", clos_name, " (", chickenPrimitiveName(scmname), "))\n", NIL); - Printv(scm_const_defs, "(set! ", scmname, " (", scmname, "))\n", NIL); - } else { - Printv(clos_methods, "(define ", clos_name, " ", chickenPrimitiveName(scmname), ")\n", NIL); - } - } - Delete(clos_name); - } - } else { - Swig_warning(WARN_TYPEMAP_VAR_UNDEF, input_file, line_number, "Unsupported variable type %s (ignored).\n", SwigType_str(t, 0)); - } - - Delete(wname); - Delete(argnum); - Delete(arg); - Delete(tm2); - Delete(mangle); - DelWrapper(f); - return SWIG_OK; -} - -/* ------------------------------------------------------------ - * constantWrapper() - * ------------------------------------------------------------ */ - -int CHICKEN::constantWrapper(Node *n) { - - char *name = GetChar(n, "name"); - char *iname = GetChar(n, "sym:name"); - SwigType *t = Getattr(n, "type"); - ParmList *l = Getattr(n, "parms"); - String *value = Getattr(n, "value"); - - String *proc_name = NewString(""); - String *wname = NewString(""); - String *mangle = NewString(""); - String *tm; - String *tm2 = NewString(""); - String *source = NewString(""); - String *argnum = NewString("0"); - String *arg = NewString("argv[0]"); - Wrapper *f; - String *overname = 0; - String *scmname; - String *rvalue; - SwigType *nctype; - - scmname = NewString(iname); - Replaceall(scmname, "_", "-"); - - Printf(source, "swig_const_%s", iname); - Replaceall(source, "::", "__"); - - Printf(mangle, "\"%s\"", SwigType_manglestr(t)); - - if (Getattr(n, "sym:overloaded")) { - overname = Getattr(n, "sym:overname"); - } else { - if (!addSymbol(iname, n)) - return SWIG_ERROR; - } - - Append(wname, Swig_name_wrapper(iname)); - if (overname) { - Append(wname, overname); - } - - nctype = NewString(t); - if (SwigType_isconst(nctype)) { - Delete(SwigType_pop(nctype)); - } - - bool is_enum_item = (Cmp(nodeType(n), "enumitem") == 0); - if (SwigType_type(nctype) == T_STRING) { - rvalue = NewStringf("\"%s\"", value); - } else if (SwigType_type(nctype) == T_CHAR && !is_enum_item) { - rvalue = NewStringf("\'%s\'", value); - } else { - rvalue = NewString(value); - } - - /* Special hook for member pointer */ - if (SwigType_type(t) == T_MPOINTER) { - Printf(f_header, "static %s = %s;\n", SwigType_str(t, source), rvalue); - } else { - if ((tm = Swig_typemap_lookup("constcode", n, name, 0))) { - Replaceall(tm, "$source", rvalue); - Replaceall(tm, "$target", source); - Replaceall(tm, "$result", source); - Replaceall(tm, "$value", rvalue); - Printf(f_header, "%s\n", tm); - } else { - Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value.\n"); - return SWIG_NOWRAP; - } - } - - f = NewWrapper(); - - /* Attach the standard typemaps */ - emit_attach_parmmaps(l, f); - Setattr(n, "wrap:parms", l); - - // evaluation function names - - // Check for interrupts - Printv(f->code, "C_trace(\"", scmname, "\");\n", NIL); - - if (1 || (SwigType_type(t) != T_USER) || (isPointer(t))) { - - Setattr(n, "wrap:name", wname); - Printv(f->def, "static ", "void ", wname, "(C_word, C_word, C_word) C_noret;\n", NIL); - - Printv(f->def, "static ", "void ", wname, "(C_word argc, C_word closure, " "C_word continuation) {\n", NIL); - - Wrapper_add_local(f, "resultobj", "C_word resultobj"); - - Printf(f->code, "if (argc!=2) C_bad_argc(argc,2);\n"); - - // Return the value of the variable - if ((tm = Swig_typemap_lookup("varout", n, name, 0))) { - - Replaceall(tm, "$source", source); - Replaceall(tm, "$varname", source); - Replaceall(tm, "$target", "resultobj"); - Replaceall(tm, "$result", "resultobj"); - /* Printf(f->code, "%s\n", tm); */ - emit_action_code(n, f->code, tm); - } else { - Swig_warning(WARN_TYPEMAP_VAROUT_UNDEF, input_file, line_number, "Unable to read variable of type %s\n", SwigType_str(t, 0)); - } - - Printv(f->code, "{\n", - "C_word func;\n", - "SWIG_Chicken_FindCreateProxy(func, resultobj)\n", - "if (C_swig_is_closurep(func))\n", - " ((C_proc4)(void *)C_block_item(func, 0))(4,func,continuation,resultobj,C_SCHEME_FALSE);\n", - "else\n", " C_kontinue(continuation, resultobj);\n", "}\n", NIL); - - /* Error handling code */ -#ifdef USE_FAIL - Printf(f->code, "fail:\n"); - Printf(f->code, "swig_panic (\"failure in " "'%s' SWIG wrapper\");\n", proc_name); -#endif - Printf(f->code, "}\n"); - - Wrapper_print(f, f_wrappers); - - /* Now register the variable with the interpreter. */ - addMethod(scmname, wname); - - if (!in_class || member_name) { - String *clos_name; - if (in_class) - clos_name = NewString(member_name); - else - clos_name = chickenNameMapping(scmname, ""); - if (GetFlag(n, "feature:constasvar")) { - Printv(clos_methods, "(define ", clos_name, " (", chickenPrimitiveName(scmname), "))\n", NIL); - Printv(scm_const_defs, "(set! ", scmname, " (", scmname, "))\n", NIL); - } else { - Printv(clos_methods, "(define ", clos_name, " ", chickenPrimitiveName(scmname), ")\n", NIL); - } - Delete(clos_name); - } - - } else { - Swig_warning(WARN_TYPEMAP_VAR_UNDEF, input_file, line_number, "Unsupported variable type %s (ignored).\n", SwigType_str(t, 0)); - } - - Delete(wname); - Delete(nctype); - Delete(proc_name); - Delete(argnum); - Delete(arg); - Delete(tm2); - Delete(mangle); - Delete(source); - Delete(rvalue); - DelWrapper(f); - return SWIG_OK; -} - -int CHICKEN::classHandler(Node *n) { - /* Create new strings for building up a wrapper function */ - have_constructor = 0; - constructor_dispatch = 0; - constructor_name = 0; - - c_class_name = NewString(Getattr(n, "sym:name")); - class_name = NewString(""); - short_class_name = NewString(""); - Printv(class_name, "<", c_class_name, ">", NIL); - Printv(short_class_name, c_class_name, NIL); - Replaceall(class_name, "_", "-"); - Replaceall(short_class_name, "_", "-"); - - if (!addSymbol(class_name, n)) - return SWIG_ERROR; - - /* Handle inheritance */ - String *base_class = NewString(""); - List *baselist = Getattr(n, "bases"); - if (baselist && Len(baselist)) { - Iterator base = First(baselist); - while (base.item) { - if (!Getattr(base.item, "feature:ignore")) - Printv(base_class, "<", Getattr(base.item, "sym:name"), "> ", NIL); - base = Next(base); - } - } - - Replaceall(base_class, "_", "-"); - - String *scmmod = NewString(module); - Replaceall(scmmod, "_", "-"); - - Printv(clos_class_defines, "(define ", class_name, "\n", " (make 'name \"", short_class_name, "\"\n", NIL); - Delete(scmmod); - - if (Len(base_class)) { - Printv(clos_class_defines, " 'direct-supers (list ", base_class, ")\n", NIL); - } else { - Printv(clos_class_defines, " 'direct-supers (list )\n", NIL); - } - - Printf(clos_class_defines, " 'direct-slots (list 'swig-this\n"); - - String *mangled_classname = Swig_name_mangle(Getattr(n, "sym:name")); - - SwigType *ct = NewStringf("p.%s", Getattr(n, "name")); - swigtype_ptr = SwigType_manglestr(ct); - - Printf(f_runtime, "static swig_chicken_clientdata _swig_chicken_clientdata%s = { 0 };\n", mangled_classname); - Printv(f_init, "SWIG_TypeClientData(SWIGTYPE", swigtype_ptr, ", (void *) &_swig_chicken_clientdata", mangled_classname, ");\n", NIL); - SwigType_remember(ct); - - /* Emit all of the members */ - - in_class = 1; - Language::classHandler(n); - in_class = 0; - - Printf(clos_class_defines, ")))\n\n"); - - if (have_constructor) { - Printv(clos_methods, "(define-method (initialize (obj ", class_name, ") initargs)\n", " (swig-initialize obj initargs ", NIL); - if (constructor_arg_types) { - String *initfunc_name = NewStringf("%s@@SWIG@initmethod", class_name); - String *func_call = buildClosFunctionCall(constructor_arg_types, initfunc_name, chickenPrimitiveName(constructor_name)); - Printf(clos_methods, "%s)\n)\n", initfunc_name); - Printf(clos_methods, "(declare (hide %s))\n", initfunc_name); - Printf(clos_methods, "%s\n", func_call); - Delete(func_call); - Delete(initfunc_name); - Delete(constructor_arg_types); - constructor_arg_types = 0; - } else if (constructor_dispatch) { - Printf(clos_methods, "%s)\n)\n", constructor_dispatch); - Delete(constructor_dispatch); - constructor_dispatch = 0; - } else { - Printf(clos_methods, "%s)\n)\n", chickenPrimitiveName(constructor_name)); - } - Delete(constructor_name); - constructor_name = 0; - } else { - Printv(clos_methods, "(define-method (initialize (obj ", class_name, ") initargs)\n", " (swig-initialize obj initargs (lambda x #f)))\n", NIL); - } - - /* export class initialization function */ - if (clos) { - String *funcname = NewString(mangled_classname); - Printf(funcname, "_swig_chicken_setclosclass"); - String *closfuncname = NewString(funcname); - Replaceall(closfuncname, "_", "-"); - - Printv(f_wrappers, "static void ", funcname, "(C_word,C_word,C_word,C_word) C_noret;\n", - "static void ", funcname, "(C_word argc, C_word closure, C_word continuation, C_word cl) {\n", - " C_trace(\"", funcname, "\");\n", - " if (argc!=3) C_bad_argc(argc,3);\n", - " swig_chicken_clientdata *cdata = (swig_chicken_clientdata *) SWIGTYPE", swigtype_ptr, "->clientdata;\n", - " cdata->gc_proxy_create = CHICKEN_new_gc_root();\n", - " CHICKEN_gc_root_set(cdata->gc_proxy_create, cl);\n", " C_kontinue(continuation, C_SCHEME_UNDEFINED);\n", "}\n", NIL); - addMethod(closfuncname, funcname); - - Printv(clos_methods, "(", chickenPrimitiveName(closfuncname), " (lambda (x lst) (if lst ", - "(cons (make ", class_name, " 'swig-this x) lst) ", "(make ", class_name, " 'swig-this x))))\n\n", NIL); - Delete(closfuncname); - Delete(funcname); - } - - Delete(mangled_classname); - Delete(swigtype_ptr); - swigtype_ptr = 0; - - Delete(class_name); - Delete(short_class_name); - Delete(c_class_name); - class_name = 0; - short_class_name = 0; - c_class_name = 0; - - return SWIG_OK; -} - -int CHICKEN::memberfunctionHandler(Node *n) { - String *iname = Getattr(n, "sym:name"); - String *proc = NewString(iname); - Replaceall(proc, "_", "-"); - - member_name = chickenNameMapping(proc, short_class_name); - Language::memberfunctionHandler(n); - Delete(member_name); - member_name = NULL; - Delete(proc); - - return SWIG_OK; -} - -int CHICKEN::staticmemberfunctionHandler(Node *n) { - String *iname = Getattr(n, "sym:name"); - String *proc = NewString(iname); - Replaceall(proc, "_", "-"); - - member_name = NewStringf("%s-%s", short_class_name, proc); - Language::staticmemberfunctionHandler(n); - Delete(member_name); - member_name = NULL; - Delete(proc); - - return SWIG_OK; -} - -int CHICKEN::membervariableHandler(Node *n) { - String *iname = Getattr(n, "sym:name"); - //String *pb = SwigType_typedef_resolve_all(SwigType_base(Getattr(n, "type"))); - - Language::membervariableHandler(n); - - String *proc = NewString(iname); - Replaceall(proc, "_", "-"); - - //Node *class_node = Swig_symbol_clookup(pb, Getattr(n, "sym:symtab")); - Node *class_node = classLookup(Getattr(n, "type")); - - //String *getfunc = NewStringf("%s-%s-get", short_class_name, proc); - //String *setfunc = NewStringf("%s-%s-set", short_class_name, proc); - String *getfunc = Swig_name_get(NSPACE_TODO, Swig_name_member(NSPACE_TODO, c_class_name, iname)); - Replaceall(getfunc, "_", "-"); - String *setfunc = Swig_name_set(NSPACE_TODO, Swig_name_member(NSPACE_TODO, c_class_name, iname)); - Replaceall(setfunc, "_", "-"); - - Printv(clos_class_defines, " (list '", proc, " ':swig-virtual ':swig-get ", chickenPrimitiveName(getfunc), NIL); - - if (!GetFlag(n, "feature:immutable")) { - if (class_node) { - Printv(clos_class_defines, " ':swig-set (lambda (x y) (", chickenPrimitiveName(setfunc), " x (slot-ref y 'swig-this))))\n", NIL); - } else { - Printv(clos_class_defines, " ':swig-set ", chickenPrimitiveName(setfunc), ")\n", NIL); - } - } else { - Printf(clos_class_defines, ")\n"); - } - - Delete(proc); - Delete(setfunc); - Delete(getfunc); - return SWIG_OK; -} - -int CHICKEN::staticmembervariableHandler(Node *n) { - String *iname = Getattr(n, "sym:name"); - String *proc = NewString(iname); - Replaceall(proc, "_", "-"); - - member_name = NewStringf("%s-%s", short_class_name, proc); - Language::staticmembervariableHandler(n); - Delete(member_name); - member_name = NULL; - Delete(proc); - - return SWIG_OK; -} - -int CHICKEN::constructorHandler(Node *n) { - have_constructor = 1; - has_constructor_args = 0; - - - exporting_constructor = true; - Language::constructorHandler(n); - exporting_constructor = false; - - has_constructor_args = 1; - - String *iname = Getattr(n, "sym:name"); - constructor_name = Swig_name_construct(NSPACE_TODO, iname); - Replaceall(constructor_name, "_", "-"); - return SWIG_OK; -} - -int CHICKEN::destructorHandler(Node *n) { - - if (no_collection) - member_name = NewStringf("delete-%s", short_class_name); - - exporting_destructor = true; - Language::destructorHandler(n); - exporting_destructor = false; - - if (no_collection) { - Delete(member_name); - member_name = NULL; - } - - return SWIG_OK; -} - -int CHICKEN::importDirective(Node *n) { - String *modname = Getattr(n, "module"); - if (modname && clos_uses) { - - // Find the module node for this imported module. It should be the - // first child but search just in case. - Node *mod = firstChild(n); - while (mod && Strcmp(nodeType(mod), "module") != 0) - mod = nextSibling(mod); - - if (mod) { - String *name = Getattr(mod, "name"); - if (name) { - Printf(closprefix, "(declare (uses %s))\n", name); - } - } - } - - return Language::importDirective(n); -} - -String *CHICKEN::buildClosFunctionCall(List *types, const_String_or_char_ptr closname, const_String_or_char_ptr funcname) { - String *method_signature = NewString(""); - String *func_args = NewString(""); - String *func_call = NewString(""); - - Iterator arg_type; - int arg_count = 0; - int optional_arguments = 0; - - for (arg_type = First(types); arg_type.item; arg_type = Next(arg_type)) { - if (Strcmp(arg_type.item, "^^##optional$$") == 0) { - optional_arguments = 1; - } else { - Printf(method_signature, " (arg%i %s)", arg_count, arg_type.item); - arg_type = Next(arg_type); - if (!arg_type.item) - break; - - String *arg = NewStringf("arg%i", arg_count); - String *access_arg = Copy(arg_type.item); - - Replaceall(access_arg, "$input", arg); - Printf(func_args, " %s", access_arg); - - Delete(arg); - Delete(access_arg); - } - arg_count++; - } - - if (optional_arguments) { - Printf(func_call, "(define-method (%s %s . args) (apply %s %s args))", closname, method_signature, funcname, func_args); - } else { - Printf(func_call, "(define-method (%s %s) (%s %s))", closname, method_signature, funcname, func_args); - } - - Delete(method_signature); - Delete(func_args); - - return func_call; -} - -extern "C" { - - /* compares based on non-primitive names */ - static int compareTypeListsHelper(const DOH *a, const DOH *b, int opt_equal) { - List *la = (List *) a; - List *lb = (List *) b; - - Iterator ia = First(la); - Iterator ib = First(lb); - - while (ia.item && ib.item) { - int ret = Strcmp(ia.item, ib.item); - if (ret) - return ret; - ia = Next(Next(ia)); - ib = Next(Next(ib)); - } if (opt_equal && ia.item && Strcmp(ia.item, "^^##optional$$") == 0) - return 0; - if (ia.item) - return -1; - if (opt_equal && ib.item && Strcmp(ib.item, "^^##optional$$") == 0) - return 0; - if (ib.item) - return 1; - - return 0; - } - - static int compareTypeLists(const DOH *a, const DOH *b) { - return compareTypeListsHelper(a, b, 0); - } -} - -void CHICKEN::dispatchFunction(Node *n) { - /* Last node in overloaded chain */ - - int maxargs; - String *tmp = NewString(""); - String *dispatch = Swig_overload_dispatch(n, "%s (2+$numargs,closure," "continuation$commaargs);", &maxargs); - - /* Generate a dispatch wrapper for all overloaded functions */ - - Wrapper *f = NewWrapper(); - String *iname = Getattr(n, "sym:name"); - String *wname = NewString(""); - String *scmname = NewString(iname); - Replaceall(scmname, "_", "-"); - - Append(wname, Swig_name_wrapper(iname)); - - Printv(f->def, "static void real_", wname, "(C_word, C_word, C_word, C_word) C_noret;\n", NIL); - - Printv(f->def, "static void real_", wname, "(C_word oldargc, C_word closure, C_word continuation, C_word args) {", NIL); - - Wrapper_add_local(f, "argc", "int argc"); - Printf(tmp, "C_word argv[%d]", maxargs + 1); - Wrapper_add_local(f, "argv", tmp); - Wrapper_add_local(f, "ii", "int ii"); - Wrapper_add_local(f, "t", "C_word t = args"); - Printf(f->code, "if (!C_swig_is_list (args)) {\n"); - Printf(f->code, " swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, " "\"Argument #1 must be a list of overloaded arguments\");\n"); - Printf(f->code, "}\n"); - Printf(f->code, "argc = C_unfix (C_i_length (args));\n"); - Printf(f->code, "for (ii = 0; (ii < argc) && (ii < %d); ii++, t = C_block_item (t, 1)) {\n", maxargs); - Printf(f->code, "argv[ii] = C_block_item (t, 0);\n"); - Printf(f->code, "}\n"); - - Printv(f->code, dispatch, "\n", NIL); - Printf(f->code, "swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE," "\"No matching function for overloaded '%s'\");\n", iname); - Printv(f->code, "}\n", NIL); - Wrapper_print(f, f_wrappers); - addMethod(scmname, wname); - - DelWrapper(f); - f = NewWrapper(); - - /* varargs */ - Printv(f->def, "void ", wname, "(C_word, C_word, C_word, ...) C_noret;\n", NIL); - Printv(f->def, "void ", wname, "(C_word c, C_word t0, C_word t1, ...) {", NIL); - Printv(f->code, - "C_word t2;\n", - "va_list v;\n", - "C_word *a, c2 = c;\n", - "C_save_rest (t1, c2, 2);\n", "a = C_alloc((c-2)*3);\n", "t2 = C_restore_rest (a, C_rest_count (0));\n", "real_", wname, " (3, t0, t1, t2);\n", NIL); - Printv(f->code, "}\n", NIL); - Wrapper_print(f, f_wrappers); - - /* Now deal with overloaded function when exporting clos */ - if (clos) { - List *flist = Getattr(overload_parameter_lists, scmname); - if (flist) { - Delattr(overload_parameter_lists, scmname); - - SortList(flist, compareTypeLists); - - String *clos_name; - if (have_constructor && !has_constructor_args) { - has_constructor_args = 1; - constructor_dispatch = NewStringf("%s@SWIG@new@dispatch", short_class_name); - clos_name = Copy(constructor_dispatch); - Printf(clos_methods, "(declare (hide %s))\n", clos_name); - } else if (in_class) - clos_name = NewString(member_name); - else - clos_name = chickenNameMapping(scmname, ""); - - Iterator f; - List *prev = 0; - int all_primitive = 1; - - /* first check for duplicates and an empty call */ - String *newlist = NewList(); - for (f = First(flist); f.item; f = Next(f)) { - /* check if cur is a duplicate of prev */ - if (prev && compareTypeListsHelper(f.item, prev, 1) == 0) { - Delete(f.item); - } else { - Append(newlist, f.item); - prev = f.item; - Iterator j; - for (j = First(f.item); j.item; j = Next(j)) { - if (Strcmp(j.item, "^^##optional$$") != 0 && Strcmp(j.item, "") != 0) - all_primitive = 0; - } - } - } - Delete(flist); - flist = newlist; - - if (all_primitive) { - Printf(clos_methods, "(define %s %s)\n", clos_name, chickenPrimitiveName(scmname)); - } else { - for (f = First(flist); f.item; f = Next(f)) { - /* now export clos code for argument */ - String *func_call = buildClosFunctionCall(f.item, clos_name, chickenPrimitiveName(scmname)); - Printf(clos_methods, "%s\n", func_call); - Delete(f.item); - Delete(func_call); - } - } - - Delete(clos_name); - Delete(flist); - } - } - - DelWrapper(f); - Delete(dispatch); - Delete(tmp); - Delete(wname); -} - -int CHICKEN::isPointer(SwigType *t) { - return SwigType_ispointer(SwigType_typedef_resolve_all(t)); -} - -void CHICKEN::addMethod(String *scheme_name, String *function) { - String *sym = NewString(""); - if (clos) { - Append(sym, "primitive:"); - } - Append(sym, scheme_name); - - /* add symbol to Chicken internal symbol table */ - if (hide_primitive) { - Printv(f_init, "{\n", - " C_word *p0 = a;\n", " *(a++)=C_CLOSURE_TYPE|1;\n", " *(a++)=(C_word)", function, ";\n", " C_mutate(return_vec++, (C_word)p0);\n", "}\n", NIL); - } else { - Printf(f_sym_size, "+C_SIZEOF_INTERNED_SYMBOL(%d)", Len(sym)); - Printf(f_init, "sym = C_intern (&a, %d, \"%s\");\n", Len(sym), sym); - Printv(f_init, "C_mutate ((C_word*)sym+1, (*a=C_CLOSURE_TYPE|1, a[1]=(C_word)", function, ", tmp=(C_word)a, a+=2, tmp));\n", NIL); - } - - if (hide_primitive) { - Setattr(primitive_names, scheme_name, NewStringf("(vector-ref swig-init-return %i)", num_methods)); - } else { - Setattr(primitive_names, scheme_name, Copy(sym)); - } - - num_methods++; - - Delete(sym); -} - -String *CHICKEN::chickenPrimitiveName(String *name) { - String *value = Getattr(primitive_names, name); - if (value) - return value; - else { - Swig_error(input_file, line_number, "Internal Error: attempting to reference non-existent primitive name %s\n", name); - return NewString("#f"); - } -} - -int CHICKEN::validIdentifier(String *s) { - char *c = Char(s); - /* Check whether we have an R5RS identifier. */ - /* --> * | */ - /* --> | */ - if (!(isalpha(*c) || (*c == '!') || (*c == '$') || (*c == '%') - || (*c == '&') || (*c == '*') || (*c == '/') || (*c == ':') - || (*c == '<') || (*c == '=') || (*c == '>') || (*c == '?') - || (*c == '^') || (*c == '_') || (*c == '~'))) { - /* --> + | - | ... */ - if ((strcmp(c, "+") == 0) - || strcmp(c, "-") == 0 || strcmp(c, "...") == 0) - return 1; - else - return 0; - } - /* --> | | */ - while (*c) { - if (!(isalnum(*c) || (*c == '!') || (*c == '$') || (*c == '%') - || (*c == '&') || (*c == '*') || (*c == '/') || (*c == ':') - || (*c == '<') || (*c == '=') || (*c == '>') || (*c == '?') - || (*c == '^') || (*c == '_') || (*c == '~') || (*c == '+') - || (*c == '-') || (*c == '.') || (*c == '@'))) - return 0; - c++; - } - return 1; -} - - /* ------------------------------------------------------------ - * closNameMapping() - * Maps the identifier from C++ to the CLOS based on command - * line parameters and such. - * If class_name = "" that means the mapping is for a function or - * variable not attached to any class. - * ------------------------------------------------------------ */ -String *CHICKEN::chickenNameMapping(String *name, const_String_or_char_ptr class_name) { - String *n = NewString(""); - - if (Strcmp(class_name, "") == 0) { - // not part of a class, so no class name to prefix - if (clossymnameprefix) { - Printf(n, "%s%s", clossymnameprefix, name); - } else { - Printf(n, "%s", name); - } - } else { - if (useclassprefix) { - Printf(n, "%s-%s", class_name, name); - } else { - if (clossymnameprefix) { - Printf(n, "%s%s", clossymnameprefix, name); - } else { - Printf(n, "%s", name); - } - } - } - return n; -} - -String *CHICKEN::runtimeCode() { - String *s = Swig_include_sys("chickenrun.swg"); - if (!s) { - Printf(stderr, "*** Unable to open 'chickenrun.swg'\n"); - s = NewString(""); - } - return s; -} - -String *CHICKEN::defaultExternalRuntimeFilename() { - return NewString("swigchickenrun.h"); -} diff --git a/Source/Modules/clisp.cxx b/Source/Modules/clisp.cxx deleted file mode 100644 index d7f197197..000000000 --- a/Source/Modules/clisp.cxx +++ /dev/null @@ -1,515 +0,0 @@ -/* ----------------------------------------------------------------------------- - * This file is part of SWIG, which is licensed as a whole under version 3 - * (or any later version) of the GNU General Public License. Some additional - * terms also apply to certain portions of SWIG. The full details of the SWIG - * license and copyrights can be found in the LICENSE and COPYRIGHT files - * included with the SWIG source code as distributed by the SWIG developers - * and at http://www.swig.org/legal.html. - * - * clisp.cxx - * - * clisp language module for SWIG. - * ----------------------------------------------------------------------------- */ - -#include "swigmod.h" - -static const char *usage = "\ -CLISP Options (available with -clisp)\n\ - -extern-all - Create clisp definitions for all the functions and\n\ - global variables otherwise only definitions for\n\ - externed functions and variables are created.\n\ - -generate-typedef - Use def-c-type to generate shortcuts according to the\n\ - typedefs in the input.\n\ -"; - -class CLISP:public Language { -public: - File *f_cl; - String *module; - virtual void main(int argc, char *argv[]); - virtual int top(Node *n); - virtual int functionWrapper(Node *n); - virtual int variableWrapper(Node *n); - virtual int constantWrapper(Node *n); - virtual int classDeclaration(Node *n); - virtual int enumDeclaration(Node *n); - virtual int typedefHandler(Node *n); - List *entries; -private: - String *get_ffi_type(Node *n, SwigType *ty); - String *convert_literal(String *num_param, String *type); - String *strip_parens(String *string); - int extern_all_flag; - int generate_typedef_flag; - int is_function; -}; - -void CLISP::main(int argc, char *argv[]) { - int i; - - Preprocessor_define("SWIGCLISP 1", 0); - SWIG_library_directory("clisp"); - SWIG_config_file("clisp.swg"); - generate_typedef_flag = 0; - extern_all_flag = 0; - - for (i = 1; i < argc; i++) { - if (!strcmp(argv[i], "-help")) { - Printf(stdout, "%s\n", usage); - } else if ((Strcmp(argv[i], "-extern-all") == 0)) { - extern_all_flag = 1; - Swig_mark_arg(i); - } else if ((Strcmp(argv[i], "-generate-typedef") == 0)) { - generate_typedef_flag = 1; - Swig_mark_arg(i); - } - } -} - -int CLISP::top(Node *n) { - - File *f_null = NewString(""); - module = Getattr(n, "name"); - String *output_filename; - entries = NewList(); - - /* Get the output file name */ - String *outfile = Getattr(n, "outfile"); - - if (!outfile) { - Printf(stderr, "Unable to determine outfile\n"); - SWIG_exit(EXIT_FAILURE); - } - - output_filename = NewStringf("%s%s.lisp", SWIG_output_directory(), module); - - f_cl = NewFile(output_filename, "w+", SWIG_output_files()); - if (!f_cl) { - FileErrorDisplay(output_filename); - SWIG_exit(EXIT_FAILURE); - } - - Swig_register_filebyname("header", f_null); - Swig_register_filebyname("begin", f_null); - Swig_register_filebyname("runtime", f_null); - Swig_register_filebyname("wrapper", f_null); - - String *header = NewString(""); - - Swig_banner_target_lang(header, ";;"); - - Printf(header, "\n(defpackage :%s\n (:use :common-lisp :ffi)", module); - - Language::top(n); - - Iterator i; - - long len = Len(entries); - if (len > 0) { - Printf(header, "\n (:export"); - } - //else nothing to export - - for (i = First(entries); i.item; i = Next(i)) { - Printf(header, "\n\t:%s", i.item); - } - - if (len > 0) { - Printf(header, ")"); - } - - Printf(header, ")\n"); - Printf(header, "\n(in-package :%s)\n", module); - Printf(header, "\n(default-foreign-language :stdc)\n"); - - len = Tell(f_cl); - - Printf(f_cl, "%s", header); - - long end = Tell(f_cl); - - for (len--; len >= 0; len--) { - end--; - (void)Seek(f_cl, len, SEEK_SET); - int ch = Getc(f_cl); - (void)Seek(f_cl, end, SEEK_SET); - Putc(ch, f_cl); - } - - Seek(f_cl, 0, SEEK_SET); - Write(f_cl, Char(header), Len(header)); - - Delete(f_cl); - - return SWIG_OK; -} - - -int CLISP::functionWrapper(Node *n) { - is_function = 1; - String *storage = Getattr(n, "storage"); - if (!extern_all_flag && (!storage || (!Swig_storage_isextern(n) && !Swig_storage_isexternc(n)))) - return SWIG_OK; - - String *func_name = Getattr(n, "sym:name"); - - ParmList *pl = Getattr(n, "parms"); - - int argnum = 0, first = 1; - - Printf(f_cl, "\n(ffi:def-call-out %s\n\t(:name \"%s\")\n", func_name, func_name); - - Append(entries, func_name); - - if (ParmList_len(pl) != 0) { - Printf(f_cl, "\t(:arguments "); - } - for (Parm *p = pl; p; p = nextSibling(p), argnum++) { - - String *argname = Getattr(p, "name"); - // SwigType *argtype; - - String *ffitype = get_ffi_type(n, Getattr(p, "type")); - - int tempargname = 0; - - if (!argname) { - argname = NewStringf("arg%d", argnum); - tempargname = 1; - } - - if (!first) { - Printf(f_cl, "\n\t\t"); - } - Printf(f_cl, "(%s %s)", argname, ffitype); - first = 0; - - Delete(ffitype); - - if (tempargname) - Delete(argname); - } - if (ParmList_len(pl) != 0) { - Printf(f_cl, ")\n"); /* finish arg list */ - } - String *ffitype = get_ffi_type(n, Getattr(n, "type")); - if (Strcmp(ffitype, "NIL")) { //when return type is not nil - Printf(f_cl, "\t(:return-type %s)\n", ffitype); - } - Printf(f_cl, "\t(:library +library-name+))\n"); - - return SWIG_OK; -} - - -int CLISP::constantWrapper(Node *n) { - is_function = 0; - String *type = Getattr(n, "type"); - String *converted_value = convert_literal(Getattr(n, "value"), type); - String *name = Getattr(n, "sym:name"); - - Printf(f_cl, "\n(defconstant %s %s)\n", name, converted_value); - Append(entries, name); - Delete(converted_value); - - return SWIG_OK; -} - -int CLISP::variableWrapper(Node *n) { - is_function = 0; - String *storage = Getattr(n, "storage"); - - if (!extern_all_flag && (!storage || (!Swig_storage_isextern(n) && !Swig_storage_isexternc(n)))) - return SWIG_OK; - - String *var_name = Getattr(n, "sym:name"); - String *lisp_type = get_ffi_type(n, Getattr(n, "type")); - Printf(f_cl, "\n(ffi:def-c-var %s\n (:name \"%s\")\n (:type %s)\n", var_name, var_name, lisp_type); - Printf(f_cl, "\t(:library +library-name+))\n"); - Append(entries, var_name); - - Delete(lisp_type); - return SWIG_OK; -} - -int CLISP::typedefHandler(Node *n) { - if (generate_typedef_flag) { - is_function = 0; - Printf(f_cl, "\n(ffi:def-c-type %s %s)\n", Getattr(n, "name"), get_ffi_type(n, Getattr(n, "type"))); - } - - return Language::typedefHandler(n); -} - -int CLISP::enumDeclaration(Node *n) { - if (getCurrentClass() && (cplus_mode != PUBLIC)) - return SWIG_NOWRAP; - - is_function = 0; - String *name = Getattr(n, "sym:name"); - - Printf(f_cl, "\n(ffi:def-c-enum %s ", name); - - for (Node *c = firstChild(n); c; c = nextSibling(c)) { - - String *slot_name = Getattr(c, "name"); - String *value = Getattr(c, "enumvalue"); - - Printf(f_cl, "(%s %s)", slot_name, value); - - Append(entries, slot_name); - - Delete(value); - } - - Printf(f_cl, ")\n"); - return SWIG_OK; -} - - -// Includes structs -int CLISP::classDeclaration(Node *n) { - is_function = 0; - String *name = Getattr(n, "sym:name"); - String *kind = Getattr(n, "kind"); - - if (Strcmp(kind, "struct")) { - Printf(stderr, "Don't know how to deal with %s kind of class yet.\n", kind); - Printf(stderr, " (name: %s)\n", name); - SWIG_exit(EXIT_FAILURE); - } - - - Printf(f_cl, "\n(ffi:def-c-struct %s", name); - - Append(entries, NewStringf("make-%s", name)); - - for (Node *c = firstChild(n); c; c = nextSibling(c)) { - - if (Strcmp(nodeType(c), "cdecl")) { - Printf(stderr, "Structure %s has a slot that we can't deal with.\n", name); - Printf(stderr, "nodeType: %s, name: %s, type: %s\n", nodeType(c), Getattr(c, "name"), Getattr(c, "type")); - SWIG_exit(EXIT_FAILURE); - } - - String *temp = Copy(Getattr(c, "decl")); - if (temp) { - Append(temp, Getattr(c, "type")); //appending type to the end, otherwise wrong type - String *lisp_type = get_ffi_type(n, temp); - Delete(temp); - - String *slot_name = Getattr(c, "sym:name"); - Printf(f_cl, "\n\t(%s %s)", slot_name, lisp_type); - - Append(entries, NewStringf("%s-%s", name, slot_name)); - - Delete(lisp_type); - } - } - - Printf(f_cl, ")\n"); - - /* Add this structure to the known lisp types */ - //Printf(stdout, "Adding %s foreign type\n", name); - // add_defined_foreign_type(name); - - return SWIG_OK; -} - -/* utilities */ -/* returns new string w/ parens stripped */ -String *CLISP::strip_parens(String *string) { - char *s = Char(string), *p; - int len = Len(string); - String *res; - - if (len == 0 || s[0] != '(' || s[len - 1] != ')') { - return NewString(string); - } - - p = (char *) malloc(len - 2 + 1); - if (!p) { - Printf(stderr, "Malloc failed\n"); - SWIG_exit(EXIT_FAILURE); - } - - strncpy(p, s + 1, len - 1); - p[len - 2] = 0; /* null terminate */ - - res = NewString(p); - free(p); - - return res; -} - -String *CLISP::convert_literal(String *num_param, String *type) { - String *num = strip_parens(num_param), *res; - char *s = Char(num); - - /* Make sure doubles use 'd' instead of 'e' */ - if (!Strcmp(type, "double")) { - String *updated = Copy(num); - if (Replace(updated, "e", "d", DOH_REPLACE_ANY) > 1) { - Printf(stderr, "Weird!! number %s looks invalid.\n", num); - SWIG_exit(EXIT_FAILURE); - } - Delete(num); - return updated; - } - - if (SwigType_type(type) == T_CHAR) { - /* Use CL syntax for character literals */ - return NewStringf("#\\%s", num_param); - } else if (SwigType_type(type) == T_STRING) { - /* Use CL syntax for string literals */ - return NewStringf("\"%s\"", num_param); - } - - if (Len(num) < 2 || s[0] != '0') { - return num; - } - - /* octal or hex */ - - res = NewStringf("#%c%s", s[1] == 'x' ? 'x' : 'o', s + 2); - Delete(num); - - return res; -} - -String *CLISP::get_ffi_type(Node *n, SwigType *ty) { - Node *node = NewHash(); - Setattr(node, "type", ty); - Setfile(node, Getfile(n)); - Setline(node, Getline(n)); - const String *tm = Swig_typemap_lookup("in", node, "", 0); - Delete(node); - - if (tm) { - return NewString(tm); - } else if (SwigType_ispointer(ty)) { - SwigType *cp = Copy(ty); - SwigType_del_pointer(cp); - String *inner_type = get_ffi_type(n, cp); - - if (SwigType_isfunction(cp)) { - return inner_type; - } - - SwigType *base = SwigType_base(ty); - String *base_name = SwigType_str(base, 0); - - String *str; - if (!Strcmp(base_name, "int") || !Strcmp(base_name, "float") || !Strcmp(base_name, "short") - || !Strcmp(base_name, "double") || !Strcmp(base_name, "long") || !Strcmp(base_name, "char")) { - - str = NewStringf("(ffi:c-ptr %s)", inner_type); - } else { - str = NewStringf("(ffi:c-pointer %s)", inner_type); - } - Delete(base_name); - Delete(base); - Delete(cp); - Delete(inner_type); - return str; - } else if (SwigType_isarray(ty)) { - SwigType *cp = Copy(ty); - String *array_dim = SwigType_array_getdim(ty, 0); - - if (!Strcmp(array_dim, "")) { //dimension less array convert to pointer - Delete(array_dim); - SwigType_del_array(cp); - SwigType_add_pointer(cp); - String *str = get_ffi_type(n, cp); - Delete(cp); - return str; - } else { - SwigType_pop_arrays(cp); - String *inner_type = get_ffi_type(n, cp); - Delete(cp); - - int ndim = SwigType_array_ndim(ty); - String *dimension; - if (ndim == 1) { - dimension = array_dim; - } else { - dimension = array_dim; - for (int i = 1; i < ndim; i++) { - array_dim = SwigType_array_getdim(ty, i); - Append(dimension, " "); - Append(dimension, array_dim); - Delete(array_dim); - } - String *temp = dimension; - dimension = NewStringf("(%s)", dimension); - Delete(temp); - } - String *str; - if (is_function) - str = NewStringf("(ffi:c-ptr (ffi:c-array %s %s))", inner_type, dimension); - else - str = NewStringf("(ffi:c-array %s %s)", inner_type, dimension); - - Delete(inner_type); - Delete(dimension); - return str; - } - } else if (SwigType_isfunction(ty)) { - SwigType *cp = Copy(ty); - SwigType *fn = SwigType_pop_function(cp); - String *args = NewString(""); - ParmList *pl = SwigType_function_parms(fn, n); - if (ParmList_len(pl) != 0) { - Printf(args, "(:arguments "); - } - int argnum = 0, first = 1; - for (Parm *p = pl; p; p = nextSibling(p), argnum++) { - String *argname = Getattr(p, "name"); - SwigType *argtype = Getattr(p, "type"); - String *ffitype = get_ffi_type(n, argtype); - - int tempargname = 0; - - if (!argname) { - argname = NewStringf("arg%d", argnum); - tempargname = 1; - } - if (!first) { - Printf(args, "\n\t\t"); - } - Printf(args, "(%s %s)", argname, ffitype); - first = 0; - Delete(ffitype); - if (tempargname) - Delete(argname); - } - if (ParmList_len(pl) != 0) { - Printf(args, ")\n"); /* finish arg list */ - } - String *ffitype = get_ffi_type(n, cp); - String *str = NewStringf("(ffi:c-function %s \t\t\t\t(:return-type %s))", args, ffitype); - Delete(fn); - Delete(args); - Delete(cp); - Delete(ffitype); - return str; - } - String *str = SwigType_str(ty, 0); - if (str) { - char *st = Strstr(str, "struct"); - if (st) { - st += 7; - return NewString(st); - } - char *cl = Strstr(str, "class"); - if (cl) { - cl += 6; - return NewString(cl); - } - } - return str; -} - -extern "C" Language *swig_clisp(void) { - return new CLISP(); -} diff --git a/Source/Modules/csharp.cxx b/Source/Modules/csharp.cxx index 27cc65b32..edb79e13e 100644 --- a/Source/Modules/csharp.cxx +++ b/Source/Modules/csharp.cxx @@ -901,8 +901,6 @@ public: // Get typemap for this argument if ((tm = Getattr(p, "tmap:in"))) { canThrow(n, "in", p); - Replaceall(tm, "$source", arg); /* deprecated */ - Replaceall(tm, "$target", ln); /* deprecated */ Replaceall(tm, "$arg", arg); /* deprecated? */ Replaceall(tm, "$input", arg); Setattr(p, "emit:input", arg); @@ -921,7 +919,6 @@ public: for (p = l; p;) { if ((tm = Getattr(p, "tmap:check"))) { canThrow(n, "check", p); - Replaceall(tm, "$target", Getattr(p, "lname")); /* deprecated */ Replaceall(tm, "$arg", Getattr(p, "emit:input")); /* deprecated? */ Replaceall(tm, "$input", Getattr(p, "emit:input")); Printv(f->code, tm, "\n", NIL); @@ -935,7 +932,6 @@ public: for (p = l; p;) { if ((tm = Getattr(p, "tmap:freearg"))) { canThrow(n, "freearg", p); - Replaceall(tm, "$source", Getattr(p, "emit:input")); /* deprecated */ Replaceall(tm, "$arg", Getattr(p, "emit:input")); /* deprecated? */ Replaceall(tm, "$input", Getattr(p, "emit:input")); Printv(cleanup, tm, "\n", NIL); @@ -949,8 +945,6 @@ public: for (p = l; p;) { if ((tm = Getattr(p, "tmap:argout"))) { canThrow(n, "argout", p); - Replaceall(tm, "$source", Getattr(p, "emit:input")); /* deprecated */ - Replaceall(tm, "$target", Getattr(p, "lname")); /* deprecated */ Replaceall(tm, "$arg", Getattr(p, "emit:input")); /* deprecated? */ Replaceall(tm, "$result", "jresult"); Replaceall(tm, "$input", Getattr(p, "emit:input")); @@ -982,8 +976,6 @@ public: /* Return value if necessary */ if ((tm = Swig_typemap_lookup_out("out", n, Swig_cresult_name(), f, actioncode))) { canThrow(n, "out", n); - Replaceall(tm, "$source", Swig_cresult_name()); /* deprecated */ - Replaceall(tm, "$target", "jresult"); /* deprecated */ Replaceall(tm, "$result", "jresult"); if (GetFlag(n, "feature:new")) @@ -1011,7 +1003,6 @@ public: if (GetFlag(n, "feature:new")) { if ((tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0))) { canThrow(n, "newfree", n); - Replaceall(tm, "$source", Swig_cresult_name()); /* deprecated */ Printf(f->code, "%s\n", tm); } } @@ -1020,7 +1011,6 @@ public: if (!native_function_flag) { if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { canThrow(n, "ret", n); - Replaceall(tm, "$source", Swig_cresult_name()); /* deprecated */ Printf(f->code, "%s\n", tm); } } @@ -2050,7 +2040,8 @@ public: void emitInterfaceDeclaration(Node *n, String *interface_name, File *f_interface) { Printv(f_interface, typemapLookup(n, "csimports", Getattr(n, "classtypeobj"), WARN_NONE), "\n", NIL); - Printf(f_interface, "public interface %s", interface_name); + Printv(f_interface, typemapLookup(n, "csinterfacemodifiers", Getattr(n, "classtypeobj"), WARN_CSHARP_TYPEMAP_INTERFACEMODIFIERS_UNDEF), NIL); + Printf(f_interface, " %s", interface_name); if (List *baselist = Getattr(n, "bases")) { String *bases = 0; for (Iterator base = First(baselist); base.item; base = Next(base)) { diff --git a/Source/Modules/directors.cxx b/Source/Modules/directors.cxx index a91d5fd9a..196974792 100644 --- a/Source/Modules/directors.cxx +++ b/Source/Modules/directors.cxx @@ -160,7 +160,7 @@ String *Swig_method_decl(SwigType *return_base_type, SwigType *decl, const_Strin SwigType *rettype_stripped = SwigType_strip_qualifiers(rettype); String *rtype = SwigType_str(rettype, 0); Append(result, rtype); - if (SwigType_issimple(rettype_stripped) && return_base_type) + if ((SwigType_issimple(rettype_stripped) && return_base_type) || SwigType_isqualifier(rettype)) Append(result, " "); Delete(rtype); Delete(rettype_stripped); @@ -175,10 +175,6 @@ String *Swig_method_decl(SwigType *return_base_type, SwigType *decl, const_Strin if (qualifiers) Printv(result, " ", qualifiers, NIL); - // Reformat result to how it has been historically - Replaceall(result, ",", ", "); - Replaceall(result, "=", " = "); - Delete(args_string); Delete(popped_decl); Delete(qualifiers); diff --git a/Source/Modules/emit.cxx b/Source/Modules/emit.cxx index 7a4c2dcfb..edfa57ccd 100644 --- a/Source/Modules/emit.cxx +++ b/Source/Modules/emit.cxx @@ -74,7 +74,6 @@ void emit_parameter_variables(ParmList *l, Wrapper *f) { while (p) { tm = Getattr(p, "tmap:arginit"); if (tm) { - Replace(tm, "$target", Getattr(p, "lname"), DOH_REPLACE_ANY); Printv(f->code, tm, "\n", NIL); p = Getattr(p, "tmap:arginit:next"); } else { @@ -87,7 +86,6 @@ void emit_parameter_variables(ParmList *l, Wrapper *f) { while (p) { tm = Getattr(p, "tmap:default"); if (tm) { - Replace(tm, "$target", Getattr(p, "lname"), DOH_REPLACE_ANY); Printv(f->code, tm, "\n", NIL); p = Getattr(p, "tmap:default:next"); } else { @@ -116,7 +114,6 @@ void emit_attach_parmmaps(ParmList *l, Wrapper *f) { while (p) { String *tm = Getattr(p, "tmap:in"); if (tm && checkAttribute(p, "tmap:in:numinputs", "0")) { - Replaceall(tm, "$target", Getattr(p, "lname")); Printv(f->code, tm, "\n", NIL); np = Getattr(p, "tmap:in:next"); while (p && (p != np)) { diff --git a/Source/Modules/go.cxx b/Source/Modules/go.cxx index 0163f71df..f97e7ee20 100644 --- a/Source/Modules/go.cxx +++ b/Source/Modules/go.cxx @@ -115,8 +115,6 @@ 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. @@ -137,7 +135,6 @@ class GO:public Language { /* Output files */ File *f_c_begin; File *f_go_begin; - File *f_gc_begin; /* Output fragments */ File *f_c_runtime; @@ -151,9 +148,6 @@ class GO:public Language { 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; @@ -201,7 +195,6 @@ class GO:public Language { public: GO():package(NULL), module(NULL), - cgo_flag(true), gccgo_flag(false), go_prefix(NULL), prefix_option(NULL), @@ -212,7 +205,6 @@ public: intgo_type_size(0), f_c_begin(NULL), f_go_begin(NULL), - f_gc_begin(NULL), f_c_runtime(NULL), f_c_header(NULL), f_c_wrappers(NULL), @@ -224,9 +216,6 @@ public: 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), @@ -256,6 +245,7 @@ private: SWIG_library_directory("go"); bool display_help = false; + bool saw_nocgo_flag = false; // Process command line options. for (int i = 1; i < argc; i++) { @@ -271,10 +261,9 @@ private: } } else if (strcmp(argv[i], "-cgo") == 0) { Swig_mark_arg(i); - cgo_flag = true; } else if (strcmp(argv[i], "-no-cgo") == 0) { Swig_mark_arg(i); - cgo_flag = false; + saw_nocgo_flag = true; } else if (strcmp(argv[i], "-gccgo") == 0) { Swig_mark_arg(i); gccgo_flag = true; @@ -346,6 +335,11 @@ private: } } + if (saw_nocgo_flag) { + Printf(stderr, "SWIG -go: -no-cgo option is no longer supported\n"); + SWIG_exit(EXIT_FAILURE); + } + if (gccgo_flag && !pkgpath_option && !prefix_option) { prefix_option = NewString("go"); } @@ -353,10 +347,6 @@ 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); } @@ -458,12 +448,6 @@ private: String *go_filename = NewString(""); Printf(go_filename, "%s%s.go", SWIG_output_directory(), module); - String *gc_filename = NULL; - if (!gccgo_flag) { - gc_filename = NewString(""); - Printf(gc_filename, "%s%s_gc.c", SWIG_output_directory(), module); - } - // Generate a unique ID based on a hash of the SWIG input. swig_uint64 hash = {0, 0}; FILE *swig_input = Swig_open(swig_filename); @@ -504,14 +488,6 @@ private: SWIG_exit(EXIT_FAILURE); } - if (!gccgo_flag && !cgo_flag) { - f_gc_begin = NewFile(gc_filename, "w", SWIG_output_files()); - if (!f_gc_begin) { - FileErrorDisplay(gc_filename); - SWIG_exit(EXIT_FAILURE); - } - } - f_c_runtime = NewString(""); f_c_header = NewString(""); f_c_wrappers = NewString(""); @@ -522,15 +498,8 @@ private: f_go_header = NewString(""); f_go_wrappers = NewString(""); 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(""); - } + f_cgo_comment = NewString(""); + f_cgo_comment_typedefs = NewString(""); Swig_register_filebyname("begin", f_c_begin); Swig_register_filebyname("runtime", f_c_runtime); @@ -545,16 +514,8 @@ private: Swig_register_filebyname("go_header", f_go_header); Swig_register_filebyname("go_wrapper", f_go_wrappers); 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_register_filebyname("cgo_comment", f_cgo_comment); + Swig_register_filebyname("cgo_comment_typedefs", f_cgo_comment_typedefs); Swig_banner(f_c_begin); if (CPlusPlus) { @@ -587,34 +548,18 @@ private: Swig_banner(f_go_begin); Printf(f_go_begin, "\n// source: %s\n", swig_filename); - 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); - } + Printv(f_cgo_comment_typedefs, "/*\n", NULL); - 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); - } + // 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", getModuleName(package)); - 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"); - Printf(f_go_runtime, "func SwigCgocallBackDone()\n\n"); - } - // All the C++ wrappers should be extern "C". Printv(f_c_wrappers, "#ifdef __cplusplus\n", "extern \"C\" {\n", "#endif\n\n", NULL); @@ -686,21 +631,45 @@ 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); + // 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); + + bool need_panic = false; + if (Strstr(f_c_runtime, "SWIG_contract_assert(") != 0 || Strstr(f_c_wrappers, "SWIG_contract_assert(") != 0) { + Printv(f_c_begin, "\n#define SWIG_contract_assert(expr, msg) if (!(expr)) { _swig_gopanic(msg); } else\n\n", NULL); + need_panic = true; + } + + if (!gccgo_flag && (need_panic || Strstr(f_c_runtime, "_swig_gopanic") != 0 || Strstr(f_c_wrappers, "_swig_gopanic") != 0)) { + Printv(f_go_header, "//export cgo_panic_", unique_id, "\n", NULL); + Printv(f_go_header, "func cgo_panic_", unique_id, "(p *byte) {\n", NULL); + Printv(f_go_header, "\ts := (*[1024]byte)(unsafe.Pointer(p))[:]\n", NULL); + Printv(f_go_header, "\tfor i, b := range s {\n", NULL); + Printv(f_go_header, "\t\tif b == 0 {\n", NULL); + Printv(f_go_header, "\t\t\tpanic(string(s[:i]))\n", NULL); + Printv(f_go_header, "\t\t}\n", NULL); + Printv(f_go_header, "\t}\n", NULL); + Printv(f_go_header, "\tpanic(string(s))\n", NULL); + Printv(f_go_header, "}\n\n", NULL); + + Printv(f_c_begin, "\nextern\n", NULL); + Printv(f_c_begin, "#ifdef __cplusplus\n", NULL); + Printv(f_c_begin, " \"C\"\n", NULL); + Printv(f_c_begin, "#endif\n", NULL); + Printv(f_c_begin, " void cgo_panic_", unique_id, "(const char*);\n", NULL); + Printv(f_c_begin, "static void _swig_gopanic(const char *p) {\n", NULL); + Printv(f_c_begin, " cgo_panic_", unique_id, "(p);\n", NULL); + Printv(f_c_begin, "}\n\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_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); @@ -708,12 +677,6 @@ private: 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); - } - Delete(f_c_runtime); Delete(f_c_header); Delete(f_c_wrappers); @@ -723,21 +686,10 @@ private: Delete(f_go_header); Delete(f_go_wrappers); 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_cgo_comment); + Delete(f_cgo_comment_typedefs); Delete(f_c_begin); Delete(f_go_begin); - if (!gccgo_flag && !cgo_flag) { - Delete(f_gc_begin); - } return SWIG_OK; } @@ -952,7 +904,7 @@ private: ParmList *parms = Getattr(n, "parms"); Setattr(n, "wrap:parms", parms); - int r = makeWrappers(n, name, go_name, overname, wname, NULL, parms, result, is_static); + int r = makeWrappers(n, go_name, overname, wname, NULL, parms, result, is_static); if (r != SWIG_OK) { return r; } @@ -1010,7 +962,6 @@ private: * * Write out the various function wrappers. * n: The function we are emitting. - * name: The function name. * go_name: The name of the function in Go. * overname: The overload string for overloaded function. * wname: The SWIG wrapped name--the name of the C function. @@ -1021,38 +972,15 @@ private: * is_static: Whether this is a static method or member. * ---------------------------------------------------------------------- */ - int makeWrappers(Node *n, String *name, String *go_name, String *overname, String *wname, List *base, ParmList *parms, SwigType *result, bool is_static) { + int makeWrappers(Node *n, String *go_name, String *overname, String *wname, List *base, ParmList *parms, SwigType *result, bool is_static) { assert(result); int ret = SWIG_OK; - if (cgo_flag) { - int r = makeCgoWrappers(n, go_name, overname, wname, base, parms, result, is_static); - if (r != SWIG_OK) { - ret = r; - } - } else { - int r = goFunctionWrapper(n, name, go_name, overname, wname, base, parms, result, is_static); - if (r != SWIG_OK) { - 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; - } - } + int r = makeCgoWrappers(n, go_name, overname, wname, base, parms, result, is_static); + if (r != SWIG_OK) { + ret = r; } if (class_methods) { @@ -1618,415 +1546,6 @@ private: return SWIG_OK; } - /* ---------------------------------------------------------------------- - * goFunctionWrapper() - * - * Write out a function wrapper in Go. When not implementing a - * method, the actual code is all in C; here we just declare the C - * function. When implementing a method, we have to call the C - * function, because it will have a different name. If base is not - * NULL, then we are being called to forward a virtual method to a - * base class. - * ---------------------------------------------------------------------- */ - - int goFunctionWrapper(Node *n, String *name, String *go_name, String *overname, String *wname, List *base, ParmList *parms, SwigType *result, bool is_static) { - Wrapper *dummy = initGoTypemaps(parms); - - int parm_count = emit_num_arguments(parms); - int required_count = emit_num_required(parms); - - String *receiver = class_receiver; - if (receiver && is_static) { - receiver = NULL; - } - - String *nodetype = Getattr(n, "nodeType"); - bool is_constructor = Cmp(nodetype, "constructor") == 0; - bool is_destructor = Cmp(nodetype, "destructor") == 0; - if (is_constructor || is_destructor) { - assert(class_receiver); - assert(!base); - receiver = NULL; - } - - Swig_save("cgoGoWrapper", n, "type", "tmap:goout", NULL); - Setattr(n, "type", result); - - String *goout = goTypemapLookup("goout", n, "swig_r"); - - Swig_restore(n); - - bool add_to_interface = (interfaces && !is_constructor && !is_destructor && !is_static && !overname && checkFunctionVisibility(n, NULL)); - - bool needs_wrapper = (gccgo_flag || receiver || is_constructor || is_destructor || parm_count > required_count); - - bool has_goout = false; - if (goout) { - has_goout = true; - } - - // 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. - Parm *p = parms; - for (int i = 0; i < parm_count; ++i) { - p = getParm(p); - String *ty = Getattr(p, "type"); - if (goGetattr(p, "tmap:goargout")) { - has_goout = true; - needs_wrapper = true; - } else if (goTypeIsInterface(p, ty) || goGetattr(p, "tmap:goin")) { - needs_wrapper = true; - } - - if (paramNeedsEscape(p)) { - needs_wrapper = true; - } - - p = nextParm(p); - } - if (goTypeIsInterface(n, result) || goout != NULL) { - needs_wrapper = true; - } - - if (!gccgo_flag) { - Printv(f_go_wrappers, "var ", wname, " unsafe.Pointer\n\n", NULL); - } - - // If this is a method, first declare the C function we will call. - // If we do not need a wrapper, then we will only be writing a - // declaration. - String *wrapper_name = NULL; - if (needs_wrapper) { - wrapper_name = buildGoWrapperName(name, overname); - - if (gccgo_flag) { - Printv(f_go_wrappers, "//extern ", go_prefix, "_", wname, "\n", NULL); - } - - bool arg = false; - Printv(f_go_wrappers, "func ", wrapper_name, "(", NULL); - if (parm_count > required_count) { - Printv(f_go_wrappers, argName(&arg), " int", NULL); - } - Parm *p = getParm(parms); - int i = 0; - if (is_destructor) { - if (parm_count > required_count) { - Printv(f_go_wrappers, ", ", NULL); - } - Printv(f_go_wrappers, argName(&arg), " uintptr", NULL); - ++i; - p = nextParm(p); - } else if (receiver && (base || !is_constructor)) { - if (parm_count > required_count) { - Printv(f_go_wrappers, ", ", NULL); - } - Printv(f_go_wrappers, argName(&arg), " ", receiver, NULL); - if (!base) { - ++i; - p = nextParm(p); - } - } - for (; i < parm_count; ++i) { - p = getParm(p); - if (i > 0 || (base && receiver) || parm_count > required_count) { - Printv(f_go_wrappers, ", ", NULL); - } - String *tm = goWrapperType(p, Getattr(p, "type"), false); - Printv(f_go_wrappers, argName(&arg), " ", tm, NULL); - Delete(tm); - p = nextParm(p); - } - Printv(f_go_wrappers, ")", NULL); - if (is_constructor) { - Printv(f_go_wrappers, " (", argName(&arg), " ", class_receiver, ")", NULL); - } else { - if (SwigType_type(result) != T_VOID) { - String *tm = goWrapperType(n, result, true); - Printv(f_go_wrappers, " (", argName(&arg), " ", tm, ")", NULL); - Delete(tm); - } - } - - if (!gccgo_flag) { - Printv(f_go_wrappers, " {\n", NULL); - if (arg) { - Printv(f_go_wrappers, "\t_swig_p := uintptr(unsafe.Pointer(&base))\n", NULL); - } else { - Printv(f_go_wrappers, "\tvar _swig_p uintptr\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); - } - - // Start defining the Go function. - - if (!needs_wrapper && gccgo_flag) { - Printv(f_go_wrappers, "//extern ", go_prefix, "_", wname, "\n", NULL); - } - - Printv(f_go_wrappers, "func ", NULL); - - p = parms; - int pi = 0; - - // Add the receiver if this is a method. - String *first = NULL; - if (receiver) { - Printv(f_go_wrappers, "(", NULL); - if (base && receiver) { - Printv(f_go_wrappers, "_swig_base", NULL); - if (first == NULL) { - first = NewString("_swig_base"); - } - } else { - Printv(f_go_wrappers, Getattr(p, "lname"), NULL); - if (first == NULL) { - first = Copy(Getattr(p, "lname")); - } - p = nextParm(p); - ++pi; - } - Printv(f_go_wrappers, " ", receiver, ") ", NULL); - } - - Printv(f_go_wrappers, go_name, NULL); - if (overname) { - Printv(f_go_wrappers, overname, NULL); - } - Printv(f_go_wrappers, "(", NULL); - - // If we are doing methods, add this function to the interface. - if (add_to_interface) { - Printv(interfaces, "\t", go_name, "(", NULL); - } - - // Write out the parameters to both the function definition and - // the interface. - - String *parm_print = NewString(""); - - for (; pi < parm_count; ++pi) { - p = getParm(p); - if (pi == 0 && is_destructor) { - String *cl = exportedName(class_name); - Printv(parm_print, Getattr(p, "lname"), " ", cl, NULL); - if (first == NULL) { - first = Copy(Getattr(p, "lname")); - } - Delete(cl); - } else { - if (pi > (receiver && !base ? 1 : 0)) { - Printv(parm_print, ", ", NULL); - } - if (pi >= required_count) { - Printv(parm_print, "_swig_args ...interface{}", NULL); - if (first == NULL) { - first = NewString("_swig_args"); - } - break; - } - Printv(parm_print, Getattr(p, "lname"), " ", NULL); - if (first == NULL) { - first = Copy(Getattr(p, "lname")); - } - 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 (is_constructor) { - String *cl = exportedName(class_name); - Printv(parm_print, " (_swig_ret ", cl, ")", NULL); - if (first == NULL) { - first = NewString("_swig_ret"); - } - Delete(cl); - } else { - if (SwigType_type(result) != T_VOID) { - String *tm = goType(n, result); - Printv(parm_print, " (_swig_ret ", tm, ")", NULL); - if (first == NULL) { - first = NewString("_swig_ret"); - } - Delete(tm); - } - } - - Printv(f_go_wrappers, parm_print, NULL); - if (add_to_interface) { - Printv(interfaces, parm_print, "\n", NULL); - } - - // If this is a wrapper, we need to actually call the C function. - if (needs_wrapper) { - Printv(f_go_wrappers, " {\n", NULL); - - if (parm_count > required_count) { - Parm *p = 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(""); - - bool need_return_var = SwigType_type(result) != T_VOID && ((gccgo_flag && is_constructor) || has_goout); - if (need_return_var) { - Printv(f_go_wrappers, "\tvar swig_r ", NULL); - if (is_constructor) { - String *cl = exportedName(class_name); - Printv(f_go_wrappers, cl, NULL); - Delete(cl); - } else { - Printv(f_go_wrappers, goImType(n, result), NULL); - } - Printv(f_go_wrappers, "\n", NULL); - } - - if (gccgo_flag) { - if (has_goout || is_constructor) { - Printv(call, "\tfunc() {\n", NULL); - } - Printv(call, "\tdefer SwigCgocallDone()\n", NULL); - Printv(call, "\tSwigCgocall()\n", NULL); - } - - Printv(call, "\t", NULL); - if (SwigType_type(result) != T_VOID) { - if (need_return_var) { - Printv(call, "swig_r = ", NULL); - } else { - Printv(call, "return ", NULL); - } - } - - Printv(call, wrapper_name, "(", NULL); - - if (parm_count > required_count) { - Printv(call, "len(_swig_args)", NULL); - } - - if (base && receiver) { - if (parm_count > required_count) { - Printv(call, ", ", NULL); - } - Printv(call, "_swig_base", NULL); - } - - Parm *p = parms; - for (int i = 0; i < parm_count; ++i) { - p = getParm(p); - if (i > 0 || (base && receiver) - || parm_count > required_count) { - Printv(call, ", ", NULL); - } - - SwigType *pt = Getattr(p, "type"); - String *ln = Getattr(p, "lname"); - - String *goin = goGetattr(p, "tmap:goin"); - if (goin == NULL) { - Printv(call, ln, NULL); - if ((i == 0 && is_destructor) || ((i > 0 || !receiver || base || is_constructor) && goTypeIsInterface(p, pt))) { - Printv(call, ".Swigcptr()", NULL); - } - Setattr(p, "emit:goinput", ln); - } else { - String *ivar = NewString(""); - Printf(ivar, "_swig_i_%d", i); - 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); - Printv(call, ivar, NULL); - Setattr(p, "emit:goinput", ivar); - } - - // If the parameter has an argout or freearg typemap, make - // sure that it escapes. - if (paramNeedsEscape(p)) { - 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); - } - Printv(call, ")\n", NULL); - - if (gccgo_flag && (has_goout || is_constructor)) { - Printv(call, "\t}()\n", NULL); - } - - Printv(f_go_wrappers, call, NULL); - Delete(call); - - goargout(parms); - - if (need_return_var) { - if (goout == NULL) { - Printv(f_go_wrappers, "\treturn swig_r\n", NULL); - } else { - String *tm = goType(n, result); - Printv(f_go_wrappers, "\tvar swig_r_1 ", tm, "\n", NULL); - 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", NULL); - } else if (!gccgo_flag) { - // We don't need a wrapper. If we're using gccgo, the function - // declaration is all we need--it has a //extern comment to - // GCC-compiled wrapper. If we're not using gccgo, we need to - // call the GCC-compiled wrapper here. - Printv(f_go_wrappers, " {\n", NULL); - if (first == NULL) { - Printv(f_go_wrappers, "\tvar _swig_p uintptr\n", NULL); - } else { - Printv(f_go_wrappers, "\t_swig_p := uintptr(unsafe.Pointer(&", first, "))\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", NULL); - - Delete(wrapper_name); - DelWrapper(dummy); - - return SWIG_OK; - } - /* ---------------------------------------------------------------------- * initGoTypemaps() * @@ -2055,362 +1574,6 @@ private: return dummy; } - /* ---------------------------------------------------------------------- - * argName() - * - * A helper for goFunctionWrapper to output the first argument name - * as "base" and all others as "_". - * ---------------------------------------------------------------------- */ - - const char *argName(bool *arg) { - if (*arg) { - return "_"; - } - *arg = true; - return "base"; - } - - /* ---------------------------------------------------------------------- - * paramNeedsEscape() - * - * A helper for goFunctionWrapper that returns whether a parameter - * 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 point into the stack, which means that - * it needs to escape. - * ---------------------------------------------------------------------- */ - bool paramNeedsEscape(Parm *p) { - String *argout = Getattr(p, "tmap:argout"); - String *freearg = Getattr(p, "tmap:freearg"); - if ((!argout || Len(argout) == 0) && (!freearg || Len(freearg) == 0)) { - return false; - } - // If a C++ type is represented as an interface type in Go, then - // we don't care whether it escapes, because we know that the - // pointer is a C++ pointer. - if (goTypeIsInterface(p, Getattr(p, "type"))) { - return false; - } - return true; - } - - /* ---------------------------------------------------------------------- - * gcFunctionWrapper() - * - * This is used for 6g/8g, not for gccgo. Write out the function - * redirector that will be compiled with 6c/8c. This used to write - * out a real function wrapper, but that has moved into Go code. - * ---------------------------------------------------------------------- */ - - int gcFunctionWrapper(String *wname) { - Wrapper *f = NewWrapper(); - - Printv(f->def, "#pragma dynimport ", wname, " ", wname, " \"\"\n", NULL); - Printv(f->def, "#pragma cgo_import_static ", wname, "\n", NULL); - Printv(f->def, "extern void ", wname, "(void*);\n", NULL); - // Declare this as a uintptr, since it is not a pointer into the - // Go heap. - // \xc2\xb7 is UTF-8 for U+00B7 which is Unicode 'Middle Dot' - Printv(f->def, "uintptr \xc2\xb7", wname, " = (uintptr)", wname, ";\n", NULL); - - Wrapper_print(f, f_gc_wrappers); - - DelWrapper(f); - - return SWIG_OK; - } - - /* ---------------------------------------------------------------------- - * gccFunctionWrapper() - * - * This is used for 6g/8g, not for gccgo. Write out the function - * wrapper which will be compiled with gcc. If the base parameter - * is not NULL, this is calls the base class method rather than - * executing the SWIG wrapper code. - * ---------------------------------------------------------------------- */ - - int gccFunctionWrapper(Node *n, List *base, String *wname, ParmList *parms, SwigType *result) { - Wrapper *f = NewWrapper(); - - Swig_save("gccFunctionWrapper", n, "parms", NULL); - - Parm *base_parm = NULL; - if (base && !isStatic(n)) { - SwigType *base_type = Copy(getClassType()); - SwigType_add_pointer(base_type); - base_parm = NewParm(base_type, NewString("arg1"), 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); - bool needs_swigargs = false; - - emit_return_variable(n, result, f); - - // Start the function definition. - - Printv(f->def, "void\n", wname, "(void *swig_v)\n", "{\n", NULL); - - // The single function parameter is a pointer to the real argument - // values. Define the structure that it points to. - - String *swigargs = NewString("\tstruct swigargs {\n"); - - if (parm_count > required_count) { - needs_swigargs = true; - Printv(swigargs, "\t\tintgo _swig_optargc;\n", NULL); - } - - Parm *p = parms; - for (int i = 0; i < parm_count; ++i) { - p = getParm(p); - - String *ln = Getattr(p, "lname"); - SwigType *pt = Getattr(p, "type"); - String *ct = gcCTypeForGoValue(p, pt, ln); - Printv(swigargs, "\t\t\t", ct, ";\n", NULL); - needs_swigargs = true; - Delete(ct); - - String *gn = NewStringf("_swig_go_%d", i); - ct = gcCTypeForGoValue(p, pt, gn); - Setattr(p, "emit:input", gn); - Wrapper_add_local(f, gn, ct); - Delete(ct); - - p = nextParm(p); - } - if (SwigType_type(result) != T_VOID) { - Printv(swigargs, "\t\tlong : 0;\n", NULL); - String *ln = NewString(Swig_cresult_name()); - String *ct = gcCTypeForGoValue(n, result, ln); - Delete(ln); - Printv(swigargs, "\t\t", ct, ";\n", NULL); - needs_swigargs = true; - Delete(ct); - - ln = NewString("_swig_go_result"); - ct = gcCTypeForGoValue(n, result, ln); - Wrapper_add_local(f, "_swig_go_result", ct); - Delete(ct); - Delete(ln); - } - Printv(swigargs, "\t} SWIGSTRUCTPACKED *swig_a = (struct swigargs *) swig_v;\n", NULL); - - // Copy the input arguments out of the structure into the Go local - // variables. - p = parms; - for (int i = 0; i < parm_count; ++i) { - p = getParm(p); - String *ln = Getattr(p, "lname"); - String *gn = Getattr(p, "emit:input"); - Printv(f->code, "\t", gn, " = swig_a->", ln, ";\n", NULL); - p = nextParm(p); - } - - // 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 *gn = Getattr(p, "emit:input"); - Replaceall(tm, "$input", gn); - if (i < required_count) { - Printv(f->code, "\t", tm, "\n", NULL); - } else { - Printf(f->code, "\tif (swig_a->_swig_optargc > %d) {\n", i - required_count); - Printv(f->code, "\t\t", tm, "\n", NULL); - Printv(f->code, "\t}\n", NULL); - } - Delete(tm); - } - p = nextParm(p); - } - - Printv(f->code, "\n", NULL); - - // Do the real work of the function. - - checkConstraints(parms, f); - - emitGoAction(n, base, parms, result, f); - - argout(parms, f); - - cleanupFunction(n, f, parms); - - if (needs_swigargs) - { - Printv(f->locals, swigargs, NULL); - } - - Printv(f->code, "}\n", NULL); - - Wrapper_print(f, f_c_wrappers); - - Swig_restore(n); - - Delete(swigargs); - DelWrapper(f); - Delete(base_parm); - - return SWIG_OK; - } - - /* ---------------------------------------------------------------------- - * gccgoFunctionWrapper() - * - * This is used for gccgo, not 6g/8g. Write out the function - * wrapper which will be compiled with gcc. If the base parameter - * is not NULL, this is calls the base class method rather than - * executing the SWIG wrapper code. - * ---------------------------------------------------------------------- */ - - int gccgoFunctionWrapper(Node *n, List *base, String *wname, ParmList *parms, SwigType *result) { - Wrapper *f = NewWrapper(); - - Swig_save("gccgoFunctionWrapper", n, "parms", NULL); - - Parm *base_parm = NULL; - if (base && !isStatic(n)) { - SwigType *base_type = Copy(getClassType()); - SwigType_add_pointer(base_type); - base_parm = NewParm(base_type, NewString("arg1"), 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(n, result, f); - - // Start the function definition. - - String *fnname = NewString(""); - Printv(fnname, "go_", wname, "(", NULL); - - if (parm_count > required_count) { - Printv(fnname, "intgo _swig_optargc", NULL); - } - - Parm *p = parms; - for (int i = 0; i < parm_count; ++i) { - p = getParm(p); - SwigType *pt = Copy(Getattr(p, "type")); - if (SwigType_isarray(pt)) { - SwigType_del_array(pt); - SwigType_add_pointer(pt); - } - String *pn = NewString("g"); - Append(pn, Getattr(p, "lname")); - String *ct = gccgoCTypeForGoValue(p, pt, pn); - if (i > 0 || parm_count > required_count) { - Printv(fnname, ", ", NULL); - } - Printv(fnname, ct, NULL); - Delete(ct); - Delete(pn); - Delete(pt); - p = nextParm(p); - } - - Printv(fnname, ")", NULL); - - String *fndef = NewString(""); - if (SwigType_type(result) == T_VOID) { - Printv(fndef, "void ", fnname, NULL); - } else { - String *ct = gccgoCTypeForGoValue(n, result, fnname); - Printv(fndef, ct, NULL); - Delete(ct); - } - - Printv(f->def, fndef, " __asm__(\"", go_prefix, "_", wname, "\");\n", NULL); - - Printv(f->def, fndef, " {\n", NULL); - - Delete(fnname); - Delete(fndef); - - if (SwigType_type(result) != T_VOID) { - String *ln = NewString("_swig_go_result"); - String *ct = gccgoCTypeForGoValue(n, result, ln); - Wrapper_add_local(f, "_swig_go_result", ct); - Delete(ct); - Delete(ln); - } - - // Copy the parameters into the variables which hold their values, - // applying appropriate transformations. - - 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 { - String *ln = Getattr(p, "lname"); - String *pn = NewString("g"); - Append(pn, ln); - tm = Copy(tm); - Replaceall(tm, "$input", pn); - Setattr(p, "emit:input", pn); - if (i < required_count) { - Printv(f->code, " ", tm, "\n", NULL); - } else { - Printf(f->code, " if (_swig_optargc > %d) {\n", i - required_count); - Printv(f->code, " ", tm, "\n", NULL); - Printv(f->code, " }\n", NULL); - } - Delete(tm); - } - - p = nextParm(p); - } - - Printv(f->code, "\n", NULL); - - // Do the real work of the function. - - checkConstraints(parms, f); - - emitGoAction(n, base, parms, result, f); - - argout(parms, f); - - cleanupFunction(n, f, parms); - - if (SwigType_type(result) != T_VOID) { - Printv(f->code, " return _swig_go_result;\n", NULL); - } - - Printv(f->code, "}\n", NULL); - - Wrapper_print(f, f_c_wrappers); - - Swig_restore(n); - - DelWrapper(f); - Delete(base_parm); - - return SWIG_OK; - } - /* ----------------------------------------------------------------------- * checkConstraints() * @@ -2442,10 +1605,6 @@ private: * ----------------------------------------------------------------------- */ void emitGoAction(Node *n, List *base, ParmList *parms, SwigType *result, Wrapper *f) { - 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); - } String *actioncode; if (!base || isStatic(n)) { Swig_director_emit_dynamic_cast(n, f); @@ -2455,9 +1614,6 @@ private: actioncode = NewString(""); String *current = NewString(""); - if (!gccgo_flag && !cgo_flag) { - Printv(current, "swig_a->", NULL); - } Printv(current, Getattr(parms, "lname"), NULL); int vc = 0; @@ -2493,14 +1649,6 @@ private: Delete(tm); } - 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. - Printv(f->code, "\tswig_a = (struct swigargs*)((char*)swig_a + (_swig_topofstack() - swig_stktop));\n", NULL); - Printv(f->code, "\tswig_a->", Swig_cresult_name(), " = ", "_swig_go_result;\n", NULL); - } - Swig_restore(n); } @@ -2553,26 +1701,23 @@ private: } } - // 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); + // 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. + 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); } } @@ -2615,7 +1760,6 @@ private: if (GetFlag(n, "feature:new")) { String *tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0); if (tm) { - Replaceall(tm, "$source", Swig_cresult_name()); Printv(f->code, tm, "\n", NULL); Delete(tm); } @@ -2627,7 +1771,6 @@ private: /* See if there is any return cleanup code */ String *tm; if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); Printf(f->code, "%s\n", tm); Delete(tm); } @@ -2895,7 +2038,7 @@ private: Append(wname, unique_id); Setattr(n, "wrap:name", wname); - int r = makeWrappers(n, sname, go_name, NULL, wname, NULL, NULL, type, true); + int r = makeWrappers(n, go_name, NULL, wname, NULL, NULL, type, true); if (r != SWIG_OK) { return r; @@ -3208,7 +2351,7 @@ private: } } - int r = makeWrappers(method, name, go_name, overname, wname, bases, Getattr(method, "parms"), result, is_static); + int r = makeWrappers(method, go_name, overname, wname, bases, Getattr(method, "parms"), result, is_static); Swig_restore(method); @@ -3283,7 +2426,7 @@ private: Append(wname, unique_id); ParmList *parms = NewParm(vt, var_name, var); String *result = NewString("void"); - int r = makeWrappers(var, mname_set, go_name, NULL, wname, bases, parms, result, false); + int r = makeWrappers(var, go_name, NULL, wname, bases, parms, result, false); if (r != SWIG_OK) { return r; } @@ -3312,7 +2455,7 @@ private: String *wname = Swig_name_wrapper(mname_get); Append(wname, unique_id); - int r = makeWrappers(var, mname_get, go_name, NULL, wname, bases, NULL, vt, false); + int r = makeWrappers(var, go_name, NULL, wname, bases, NULL, vt, false); if (r != SWIG_OK) { return r; } @@ -3428,8 +2571,7 @@ private: SwigType *result = Copy(Getattr(b.item, "classtypeobj")); SwigType_add_pointer(result); - int r = makeWrappers(n, name, go_name, NULL, wname, NULL, parm, result, - false); + int r = makeWrappers(n, go_name, NULL, wname, NULL, parm, result, false); if (r != SWIG_OK) { return r; } @@ -3677,50 +2819,17 @@ private: } if (!is_ignored) { - if (cgo_flag) { - Printv(f_cgo_comment, "extern uintptr_t ", wname, "(int", NULL); + Printv(f_cgo_comment, "extern uintptr_t ", wname, "(int", 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 { - // 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); + 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); // Write out the Go function that calls the wrapper. @@ -3740,19 +2849,10 @@ private: Printv(f_go_wrappers, "\tp := &", director_struct_name, "{0, v}\n", NULL); - if (gccgo_flag && !cgo_flag) { - Printv(f_go_wrappers, "\tdefer SwigCgocallDone()\n", NULL); - Printv(f_go_wrappers, "\tSwigCgocall()\n", 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(call, go_type_name, "(C.", wname, "(C.int(swigDirectorAdd(p))", NULL); p = parms; for (int i = 0; i < parm_count; ++i) { @@ -3783,25 +2883,19 @@ private: 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); + 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, ivar, NULL); + Printv(call, "C.", ct, "(", ivar, ")", NULL); } + Delete(ct); + p = nextParm(p); } - Printv(call, ")", NULL); - if (cgo_flag) { - Printv(call, ")", NULL); - } + Printv(call, "))", NULL); Printv(f_go_wrappers, call, "\n", NULL); @@ -3839,39 +2933,23 @@ private: Printv(action, ");", NULL); Setattr(n, "wrap:action", action); - if (cgo_flag) { - cgoWrapperInfo info; + 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; + 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; - } - r = gccFunctionWrapper(n, NULL, wname, first_parm, result); - if (r != SWIG_OK) { - return r; - } - } else { - int r = gccgoFunctionWrapper(n, NULL, wname, first_parm, result); - if (r != SWIG_OK) { - return r; - } + int r = cgoGccWrapper(&info); + if (r != SWIG_OK) { + return r; } Swig_restore(n); @@ -3960,7 +3038,7 @@ private: Setattr(n, "wrap:parms", parms); String *result = NewString("void"); - int r = makeWrappers(n, fnname, fnname, NULL, wname, NULL, parms, result, isStatic(n)); + int r = makeWrappers(n, fnname, NULL, wname, NULL, parms, result, isStatic(n)); if (r != SWIG_OK) { return r; } @@ -4025,65 +3103,9 @@ private: * makeDirectorDestructorWrapper * * Emit the function wrapper for the destructor of a director class. - * This writes director_sig to f_c_directors and leaves the function - * unfinished. * ------------------------------------------------------------ */ 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, "(intgo) __asm__(\"", go_prefix, ".", go_name, "\");\n", NULL); - } - - Printv(f_c_directors, director_sig, NULL); - - if (!gccgo_flag) { - Printv(f_c_directors, " struct { intgo p; } SWIGSTRUCTPACKED 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); - - Printv(f_gc_wrappers, "#pragma dynexport ", wname, " ", wname, "\n", NULL); - Printv(f_gc_wrappers, "#pragma cgo_export_static ", wname, " ", wname, "\n", NULL); - Printv(f_gc_wrappers, "#pragma textflag 7\n", NULL); - Printv(f_gc_wrappers, "extern void \xc2\xb7", go_name, "();\n", NULL); - Printv(f_gc_wrappers, "void\n", NULL); - Printv(f_gc_wrappers, wname, "(void *a, int32 n)\n", NULL); - Printv(f_gc_wrappers, "{\n", NULL); - Printv(f_gc_wrappers, "\truntime\xc2\xb7" "cgocallback(\xc2\xb7", go_name, ", a, n);\n", NULL); - Printv(f_gc_wrappers, "}\n\n", NULL); - } else { - Printv(f_c_directors, " ", wname, "(go_val);\n", NULL); - } - - 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); @@ -4115,6 +3137,7 @@ private: String *name = Getattr(n, "sym:name"); if (!name) { assert(is_ignored); + (void)is_ignored; name = Getattr(n, "name"); } @@ -4252,9 +3275,7 @@ private: if (overname) { Append(callback_name, overname); } - if (cgo_flag) { - Append(callback_name, unique_id); - } + Append(callback_name, unique_id); String *upcall_name = Copy(director_struct_name); Append(upcall_name, "_upcall_"); @@ -4315,68 +3336,28 @@ private: Printv(f_go_wrappers, "}\n\n", NULL); if (!GetFlag(n, "abstract")) { - if (cgo_flag) { - Printv(f_cgo_comment, "extern ", NULL); + Printv(f_cgo_comment, "extern ", 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); + if (SwigType_type(result) == T_VOID) { + Printv(f_cgo_comment, "void", NULL); } else { - // 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); + 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); } // Define the method on the director class in Go. @@ -4435,73 +3416,36 @@ private: String *ret_type = NULL; bool memcpy_ret = false; String *wt = NULL; - bool has_goout = false; String *goout = NULL; if (SwigType_type(result) != T_VOID) { 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; - } + bool c_struct_type; + Delete(cgoTypeForGoValue(n, result, &c_struct_type)); + if (c_struct_type) { + memcpy_ret = true; } } - p = parms; - for (int i = 0; i < parm_count; ++i) { - p = getParm(p); - if (goGetattr(p, "tmap:goargout")) { - has_goout = true; - } - p = nextParm(p); - } - String *call = NewString(""); - if (gccgo_flag && !cgo_flag) { - if (has_goout) { - Printv(call, "\tfunc() {\n", NULL); - } - Printv(call, "\tdefer SwigCgocallDone()\n", NULL); - Printv(call, "\tSwigCgocall()\n", NULL); - } - Printv(call, "\t", NULL); if (SwigType_type(result) != T_VOID) { if (memcpy_ret) { Printv(call, "swig_r_p := ", NULL); } else { - Printv(call, "swig_r = ", NULL); - if (cgo_flag) { - Printv(call, "(", ret_type, ")(", NULL); - } + Printv(call, "swig_r = (", ret_type, ")(", NULL); } - if (cgo_flag && goTypeIsInterface(n, result)) { + if (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, "C.", upcall_wname, "(C.uintptr_t(swig_p.", + go_type_name, ")", NULL); p = parms; for (int i = 0; i < parm_count; ++i) { @@ -4534,16 +3478,12 @@ private: 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); - } + 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, ivar, NULL); + Printv(call, "C.", ct, "(", ivar, ")", NULL); } p = nextParm(p); @@ -4551,19 +3491,13 @@ private: Printv(call, ")", NULL); - if (gccgo_flag && !cgo_flag && has_goout) { - Printv(call, "\n\t}()", NULL); + if (wt) { + // Close the type conversion to the wrapper type. + Printv(call, ")", 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); - } + if (SwigType_type(result) != T_VOID && !memcpy_ret) { + // Close the type conversion of the return value. + Printv(call, ")", NULL); } Printv(call, "\n", NULL); @@ -4677,41 +3611,23 @@ private: Printv(action, ");", NULL); Setattr(n, "wrap:action", action); - if (cgo_flag) { - cgoWrapperInfo info; + 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; + 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); - if (r != SWIG_OK) { - return r; - } - r = gccFunctionWrapper(n, NULL, upcall_wname, first_parm, result); - if (r != SWIG_OK) { - return r; - } - } else { - int r = gccgoFunctionWrapper(n, NULL, upcall_wname, first_parm, result); - if (r != SWIG_OK) { - return r; - } + int r = cgoGccWrapper(&info); + if (r != SWIG_OK) { + return r; } Delete(first_type); @@ -4756,54 +3672,30 @@ private: 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; - } + bool c_struct_type; + Delete(cgoTypeForGoValue(n, result, &c_struct_type)); + if (c_struct_type) { + memcpy_ret = true; } } String *call = NewString(""); - if (gccgo_flag && !cgo_flag) { - if (goout != NULL) { - Printv(call, "\tfunc() {\n", NULL); - } - Printv(call, "\tdefer SwigCgocallDone()\n", NULL); - Printv(call, "\tSwigCgocall()\n", NULL); - } - Printv(call, "\t", NULL); if (SwigType_type(result) != T_VOID) { if (memcpy_ret) { Printv(call, "swig_r_p := ", NULL); } else { - Printv(call, "swig_r = ", NULL); - if (cgo_flag) { - Printv(call, "(", ret_type, ")(", NULL); - } + Printv(call, "swig_r = (", ret_type, ")(", NULL); } - if (cgo_flag && goTypeIsInterface(n, result)) { + if (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, "C.", upcall_wname, "(C.uintptr_t(p.(*", + director_struct_name, ").", go_type_name, ")", NULL); p = parms; for (int i = 0; i < parm_count; ++i) { @@ -4834,16 +3726,12 @@ private: 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); - } + 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, ivar, NULL); + Printv(call, "C.", ct, "(", ivar, ")", NULL); } Delete(ln); @@ -4853,19 +3741,13 @@ private: Printv(call, ")", NULL); - if (gccgo_flag && !cgo_flag && goout != NULL) { - Printv(call, "\n\t}()", NULL); + if (wt) { + // Close the type conversion to the wrapper type. + Printv(call, ")", 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); - } + if (SwigType_type(result) != T_VOID && !memcpy_ret) { + // Close the type conversion of the return value. + Printv(call, ")", NULL); } Printv(call, "\n", NULL); @@ -4905,11 +3787,8 @@ private: // The Go function which invokes the method. This is called by // the C++ method on the director class. - if (cgo_flag) { - Printv(f_go_wrappers, "//export ", callback_name, "\n", NULL); - } - - Printv(f_go_wrappers, "func ", callback_name, "(swig_c int", NULL); + Printv(f_go_wrappers, "//export ", callback_name, "\n", + "func ", callback_name, "(swig_c int", NULL); p = parms; for (int i = 0; i < parm_count; ++i) { @@ -5015,23 +3894,11 @@ private: } Printv(call, "\n", NULL); - if (gccgo_flag && !cgo_flag) { - if (goout != NULL) { - Printv(f_go_wrappers, "\tfunc() {\n", NULL); - } - Printv(f_go_wrappers, "\tSwigCgocallBack()\n", NULL); - 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 && !cgo_flag && goout != NULL) { - Printv(f_go_wrappers, "\t}()\n", NULL); - } - if (SwigType_type(result) != T_VOID) { if (goout == NULL) { Printv(f_go_wrappers, "\treturn swig_r\n", NULL); @@ -5133,241 +4000,6 @@ 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"); - - String *callback_wname = Swig_name_wrapper(callback_name); - Append(callback_wname, unique_id); - - if (!gccgo_flag) { - Printv(f_c_directors, "extern \"C\" void ", callback_wname, "(void*, int);\n", NULL); - } else { - Printv(f_c_directors, "extern \"C\" ", NULL); - - String *fnname = NewString(""); - Printv(fnname, callback_wname, "(int", NULL); - - Parm *p = parms; - while (p) { - while (checkAttribute(p, "tmap:directorin:numinputs", "0")) { - p = Getattr(p, "tmap:directorin:next"); - } - String *cg = gccgoCTypeForGoValue(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 = gccgoCTypeForGoValue(n, result, fnname); - Printv(f_c_directors, tm, NULL); - Delete(tm); - } - - Delete(fnname); - - Printv(f_c_directors, " __asm__(\"", go_prefix, ".", callback_name, "\");\n", NULL); - } - - if (!gccgo_flag) { - Printv(w->code, " struct {\n", NULL); - Printv(w->code, " intgo go_val;\n", NULL); - - Parm *p = parms; - while (p) { - while (checkAttribute(p, "tmap:directorin:numinputs", "0")) { - p = Getattr(p, "tmap:directorin:next"); - } - String *ln = Getattr(p, "lname"); - String *cg = gcCTypeForGoValue(p, Getattr(p, "type"), ln); - Printv(w->code, " ", cg, ";\n", NULL); - Delete(cg); - p = Getattr(p, "tmap:directorin:next"); - } - if (SwigType_type(result) != T_VOID) { - Printv(w->code, " long : 0;\n", NULL); - String *rname = NewString(Swig_cresult_name()); - String *cg = gcCTypeForGoValue(n, result, rname); - Printv(w->code, " ", cg, ";\n", NULL); - Delete(cg); - Delete(rname); - } - - Printv(w->code, " } SWIGSTRUCTPACKED swig_a;\n", NULL); - Printv(w->code, " swig_a.go_val = go_val;\n", NULL); - - p = parms; - while (p) { - while (checkAttribute(p, "tmap:directorin:numinputs", "0")) { - p = Getattr(p, "tmap:directorin:next"); - } - String *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); - String *ln = Getattr(p, "lname"); - String *input = NewString(""); - Printv(input, "swig_a.", ln, NULL); - Setattr(p, "emit:directorinput", input); - Replaceall(tm, "$input", input); - Replaceall(tm, "$owner", "0"); - Delete(input); - Printv(w->code, "\t", tm, "\n", NULL); - Delete(tm); - } - p = Getattr(p, "tmap:directorin:next"); - } - - Printv(w->code, " crosscall2(", callback_wname, ", &swig_a, (int) sizeof swig_a);\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", NIL); - 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 { - static const String *swig_a_result = NewStringf("swig_a.%s", Swig_cresult_name()); - Replaceall(tm, "$input", swig_a_result); - 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); - } - - // The C wrapper code which calls the Go function. - Printv(f_gc_wrappers, "#pragma dynexport ", callback_wname, " ", callback_wname, "\n", NULL); - Printv(f_gc_wrappers, "#pragma cgo_export_static ", callback_wname, " ", callback_wname, "\n", NULL); - Printv(f_gc_wrappers, "#pragma textflag 7\n", NULL); - Printv(f_gc_wrappers, "extern void \xc2\xb7", callback_name, "();\n", NULL); - Printv(f_gc_wrappers, "void\n", NULL); - Printv(f_gc_wrappers, callback_wname, "(void *a, int32 n)\n", NULL); - Printv(f_gc_wrappers, "{\n", NULL); - Printv(f_gc_wrappers, "\truntime\xc2\xb7" "cgocallback(\xc2\xb7", callback_name, ", a, n);\n", NULL); - Printv(f_gc_wrappers, "}\n\n", NULL); - } else { - if (SwigType_type(result) != T_VOID) { - String *r = NewString(Swig_cresult_name()); - String *tm = gccgoCTypeForGoValue(n, result, r); - Wrapper_add_local(w, r, tm); - Delete(tm); - Delete(r); - } - - String *args = NewString(""); - - Parm *p = parms; - while (p) { - while (checkAttribute(p, "tmap:directorin:numinputs", "0")) { - p = Getattr(p, "tmap:directorin:next"); - } - - String *pn = NewString("g"); - Append(pn, Getattr(p, "lname")); - Setattr(p, "emit:directorinput", pn); - - String *tm = gccgoCTypeForGoValue(n, 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_wname, "(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", NIL); - 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 { - 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); - } - } - - 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"); @@ -6085,6 +4717,7 @@ private: } bool r = addSymbol(name, n, scope) ? true : false; assert(r); + (void)r; return true; } @@ -6593,10 +5226,14 @@ private: } } - if (Getattr(undefined_types, ty) && !Getattr(defined_types, ty)) { + String* go_type = goType(n, ty); + + if (Getattr(undefined_types, ty) && !Getattr(defined_types, go_type)) { + Delete(go_type); return goWrapperType(n, type, true); } + Delete(go_type); return goType(n, type); } diff --git a/Source/Modules/guile.cxx b/Source/Modules/guile.cxx index 461c69e50..d7d3da8fc 100644 --- a/Source/Modules/guile.cxx +++ b/Source/Modules/guile.cxx @@ -719,7 +719,6 @@ public: sprintf(source, "argv[%d]", i); else sprintf(source, "s_%d", i); - String *target = Getattr(p, "lname"); if (!args_passed_as_array) { if (i != 0) @@ -730,8 +729,6 @@ public: Printf(f->code, " if (%s != SCM_UNDEFINED) {\n", source); } if ((tm = Getattr(p, "tmap:in"))) { - Replaceall(tm, "$source", source); - Replaceall(tm, "$target", target); Replaceall(tm, "$input", source); Setattr(p, "emit:input", source); Printv(f->code, tm, "\n", NIL); @@ -794,7 +791,6 @@ public: /* Insert constraint checking code */ for (p = l; p;) { if ((tm = Getattr(p, "tmap:check"))) { - Replaceall(tm, "$target", Getattr(p, "lname")); Printv(f->code, tm, "\n", NIL); p = Getattr(p, "tmap:check:next"); } else { @@ -807,8 +803,6 @@ public: String *returns_argout = NewString(""); for (p = l; p;) { if ((tm = Getattr(p, "tmap:argout"))) { - Replaceall(tm, "$source", Getattr(p, "lname")); - Replaceall(tm, "$target", Getattr(p, "lname")); Replaceall(tm, "$arg", Getattr(p, "emit:input")); Replaceall(tm, "$input", Getattr(p, "emit:input")); Printv(outarg, tm, "\n", NIL); @@ -828,7 +822,6 @@ public: /* Insert cleanup code */ for (p = l; p;) { if ((tm = Getattr(p, "tmap:freearg"))) { - Replaceall(tm, "$target", Getattr(p, "lname")); Replaceall(tm, "$input", Getattr(p, "emit:input")); Printv(cleanup, tm, "\n", NIL); p = Getattr(p, "tmap:freearg:next"); @@ -859,8 +852,6 @@ public: // Now have return value, figure out what to do with it. if ((tm = Swig_typemap_lookup_out("out", n, Swig_cresult_name(), f, actioncode))) { Replaceall(tm, "$result", "gswig_result"); - Replaceall(tm, "$target", "gswig_result"); - Replaceall(tm, "$source", Swig_cresult_name()); if (GetFlag(n, "feature:new")) Replaceall(tm, "$owner", "1"); else @@ -898,13 +889,11 @@ public: if (GetFlag(n, "feature:new")) { if ((tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); Printv(f->code, tm, "\n", NIL); } } // Free any memory allocated by the function being wrapped.. if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); Printv(f->code, tm, "\n", NIL); } // Wrap things up (in a manner of speaking) @@ -1141,9 +1130,7 @@ public: /* Check for a setting of the variable value */ Printf(f->code, "if (s_0 != SCM_UNDEFINED) {\n"); if ((tm = Swig_typemap_lookup("varin", n, name, 0))) { - Replaceall(tm, "$source", "s_0"); Replaceall(tm, "$input", "s_0"); - Replaceall(tm, "$target", name); /* Printv(f->code,tm,"\n",NIL); */ emit_action_code(n, f->code, tm); } else { @@ -1155,8 +1142,6 @@ public: // of evaluating or setting) if ((tm = Swig_typemap_lookup("varout", n, name, 0))) { - Replaceall(tm, "$source", name); - Replaceall(tm, "$target", "gswig_result"); Replaceall(tm, "$result", "gswig_result"); /* Printv(f->code,tm,"\n",NIL); */ emit_action_code(n, f->code, tm); @@ -1334,9 +1319,7 @@ public: // See if there's a typemap if ((tm = Swig_typemap_lookup("constant", n, name, 0))) { - Replaceall(tm, "$source", value); Replaceall(tm, "$value", value); - Replaceall(tm, "$target", name); Printv(f_header, tm, "\n", NIL); } else { // Create variable and assign it a value diff --git a/Source/Modules/java.cxx b/Source/Modules/java.cxx index 7734c6471..444fe02d1 100644 --- a/Source/Modules/java.cxx +++ b/Source/Modules/java.cxx @@ -196,7 +196,7 @@ public: String *name = Getattr(n, "name") ? Getattr(n, "name") : NewString(""); Swig_warning(WARN_JAVA_NSPACE_WITHOUT_PACKAGE, Getfile(n), Getline(n), "The nspace feature is used on '%s' without -package. " - "The generated code may not compile as Java does not support types declared in a named package accessing types declared in an unnamed package.\n", name); + "The generated code may not compile as Java does not support types declared in a named package accessing types declared in an unnamed package.\n", SwigType_namestr(name)); } } @@ -1001,8 +1001,6 @@ public: // Get typemap for this argument if ((tm = Getattr(p, "tmap:in"))) { addThrows(n, "tmap:in", p); - Replaceall(tm, "$source", arg); /* deprecated */ - Replaceall(tm, "$target", ln); /* deprecated */ Replaceall(tm, "$arg", arg); /* deprecated? */ Replaceall(tm, "$input", arg); Setattr(p, "emit:input", arg); @@ -1027,7 +1025,6 @@ public: for (p = l; p;) { if ((tm = Getattr(p, "tmap:check"))) { addThrows(n, "tmap:check", p); - Replaceall(tm, "$target", Getattr(p, "lname")); /* deprecated */ Replaceall(tm, "$arg", Getattr(p, "emit:input")); /* deprecated? */ Replaceall(tm, "$input", Getattr(p, "emit:input")); Printv(f->code, tm, "\n", NIL); @@ -1041,7 +1038,6 @@ public: for (p = l; p;) { if ((tm = Getattr(p, "tmap:freearg"))) { addThrows(n, "tmap:freearg", p); - Replaceall(tm, "$source", Getattr(p, "emit:input")); /* deprecated */ Replaceall(tm, "$arg", Getattr(p, "emit:input")); /* deprecated? */ Replaceall(tm, "$input", Getattr(p, "emit:input")); Printv(cleanup, tm, "\n", NIL); @@ -1055,8 +1051,6 @@ public: for (p = l; p;) { if ((tm = Getattr(p, "tmap:argout"))) { addThrows(n, "tmap:argout", p); - Replaceall(tm, "$source", Getattr(p, "emit:input")); /* deprecated */ - Replaceall(tm, "$target", Getattr(p, "lname")); /* deprecated */ Replaceall(tm, "$arg", Getattr(p, "emit:input")); /* deprecated? */ Replaceall(tm, "$result", "jresult"); Replaceall(tm, "$input", Getattr(p, "emit:input")); @@ -1090,8 +1084,6 @@ public: /* Return value if necessary */ if ((tm = Swig_typemap_lookup_out("out", n, Swig_cresult_name(), f, actioncode))) { addThrows(n, "tmap:out", n); - Replaceall(tm, "$source", Swig_cresult_name()); /* deprecated */ - Replaceall(tm, "$target", "jresult"); /* deprecated */ Replaceall(tm, "$result", "jresult"); if (GetFlag(n, "feature:new")) @@ -1118,7 +1110,6 @@ public: if (GetFlag(n, "feature:new")) { if ((tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0))) { addThrows(n, "tmap:newfree", n); - Replaceall(tm, "$source", Swig_cresult_name()); /* deprecated */ Printf(f->code, "%s\n", tm); } } @@ -1127,7 +1118,6 @@ public: if (!native_function_flag) { if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { addThrows(n, "tmap:ret", n); - Replaceall(tm, "$source", Swig_cresult_name()); /* deprecated */ Printf(f->code, "%s\n", tm); } } @@ -2145,7 +2135,8 @@ public: } Printv(f_interface, typemapLookup(n, "javaimports", Getattr(n, "classtypeobj"), WARN_NONE), "\n", NIL); - Printf(f_interface, "public interface %s", interface_name); + Printv(f_interface, typemapLookup(n, "javainterfacemodifiers", Getattr(n, "classtypeobj"), WARN_JAVA_TYPEMAP_INTERFACEMODIFIERS_UNDEF), NIL); + Printf(f_interface, " %s", interface_name); if (List *baselist = Getattr(n, "bases")) { String *bases = 0; for (Iterator base = First(baselist); base.item; base = Next(base)) { @@ -4835,34 +4826,27 @@ public: // .'s to delimit namespaces, so we need to replace those with /'s Replace(internal_classname, NSPACE_SEPARATOR, "/", DOH_REPLACE_ANY); - Wrapper_add_localv(w, "baseclass", "static jclass baseclass", "= 0", NIL); Printf(w->def, "void %s::swig_connect_director(JNIEnv *jenv, jobject jself, jclass jcls, bool swig_mem_own, bool weak_global) {", director_classname); + Printf(w->def, "static jclass baseclass = swig_new_global_ref(jenv, \"%s\");\n", internal_classname); + Printf(w->def, "if (!baseclass) return;\n"); + if (first_class_dmethod != curr_class_dmethod) { - Printf(w->def, "static struct {\n"); - Printf(w->def, "const char *mname;\n"); - Printf(w->def, "const char *mdesc;\n"); - Printf(w->def, "jmethodID base_methid;\n"); - Printf(w->def, "} methods[] = {\n"); + Printf(w->def, "static SwigDirectorMethod methods[] = {\n"); for (int i = first_class_dmethod; i < curr_class_dmethod; ++i) { UpcallData *udata = Getitem(dmethods_seq, i); - Printf(w->def, "{ \"%s\", \"%s\", NULL }", Getattr(udata, "method"), Getattr(udata, "fdesc")); + Printf(w->def, "SwigDirectorMethod(jenv, baseclass, \"%s\", \"%s\")", Getattr(udata, "method"), Getattr(udata, "fdesc")); if (i != curr_class_dmethod - 1) Putc(',', w->def); Putc('\n', w->def); } - Printf(w->def, "};\n"); + Printf(w->def, "};"); } Printf(w->code, "if (swig_set_self(jenv, jself, swig_mem_own, weak_global)) {\n"); - Printf(w->code, "if (!baseclass) {\n"); - Printf(w->code, "baseclass = jenv->FindClass(\"%s\");\n", internal_classname); - Printf(w->code, "if (!baseclass) return;\n"); - Printf(w->code, "baseclass = (jclass) jenv->NewGlobalRef(baseclass);\n"); - Printf(w->code, "}\n"); int n_methods = curr_class_dmethod - first_class_dmethod; @@ -4877,12 +4861,8 @@ public: /* Emit the code to look up the class's methods, initialize the override array */ - Printf(w->code, "bool derived = (jenv->IsSameObject(baseclass, jcls) ? false : true);\n"); - Printf(w->code, "for (int i = 0; i < %d; ++i) {\n", n_methods); - Printf(w->code, " if (!methods[i].base_methid) {\n"); - Printf(w->code, " methods[i].base_methid = jenv->GetMethodID(baseclass, methods[i].mname, methods[i].mdesc);\n"); - Printf(w->code, " if (!methods[i].base_methid) return;\n"); - Printf(w->code, " }\n"); + Printf(w->code, " bool derived = (jenv->IsSameObject(baseclass, jcls) ? false : true);\n"); + Printf(w->code, " for (int i = 0; i < %d; ++i) {\n", n_methods); // Generally, derived classes have a mix of overridden and // non-overridden methods and it is worth making a GetMethodID // check during initialization to determine if each method is @@ -4902,8 +4882,8 @@ public: } else { Printf(w->code, " swig_override[i] = false;\n"); Printf(w->code, " if (derived) {\n"); - Printf(w->code, " jmethodID methid = jenv->GetMethodID(jcls, methods[i].mname, methods[i].mdesc);\n"); - Printf(w->code, " swig_override[i] = (methid != methods[i].base_methid);\n"); + Printf(w->code, " jmethodID methid = jenv->GetMethodID(jcls, methods[i].name, methods[i].desc);\n"); + Printf(w->code, " swig_override[i] = methods[i].methid && (methid != methods[i].methid);\n"); Printf(w->code, " jenv->ExceptionClear();\n"); Printf(w->code, " }\n"); } diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index d2b33b1b4..01b577e20 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -166,7 +166,7 @@ public: */ virtual int exitClass(Node *) { return SWIG_OK; - }; + } /** * Invoked at the beginning of the variableHandler. @@ -178,7 +178,7 @@ public: */ virtual int exitVariable(Node *) { return SWIG_OK; - }; + } /** * Invoked at the beginning of the functionHandler. @@ -190,7 +190,7 @@ public: */ virtual int exitFunction(Node *) { return SWIG_OK; - }; + } /** * Invoked by functionWrapper callback after call to Language::functionWrapper. @@ -727,7 +727,7 @@ Node *JSEmitter::getBaseClass(Node *n) { /* ----------------------------------------------------------------------------- * JSEmitter::emitWrapperFunction() : dispatches emitter functions. * - * This allows to have small sized, dedicated emitting functions. + * This allows having small sized, dedicated emitting functions. * All state dependent branching is done here. * ----------------------------------------------------------------------------- */ @@ -994,7 +994,7 @@ int JSEmitter::emitDtor(Node *n) { { SWIG_PRV_DATA* t = (SWIG_PRV_DATA*)JSObjectGetPrivate(thisObject); if(t && t->swigCMemOwn) free ((${type}*)t->swigCObject); - if(t) free(t); + free(t); } %} @@ -1007,7 +1007,7 @@ int JSEmitter::emitDtor(Node *n) { ${type}* arg1 = (${type}*)t->swigCObject; ${destructor_action} } - if(t) free(t); + free(t); Based on what I saw in the Lua and Ruby modules, I use Getattr(n, "wrap:action") to decide if the user has a preferred destructor action. @@ -1143,7 +1143,7 @@ int JSEmitter::emitConstant(Node *n) { String *rawval = Getattr(n, "rawval"); String *value = rawval ? rawval : Getattr(n, "value"); - // HACK: forcing usage of cppvalue for v8 (which turned out to fix typdef_struct.i, et. al) + // HACK: forcing usage of cppvalue for v8 (which turned out to fix typedef_struct.i, et. al) if (State::IsSet(state.globals(FORCE_CPP)) && Getattr(n, "cppvalue") != NULL) { value = Getattr(n, "cppvalue"); } @@ -1255,7 +1255,7 @@ int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { // Note: this dispatcher function gets called after the last overloaded function has been created. // At this time, n.wrap:name contains the name of the last wrapper function. // To get a valid function name for the dispatcher function we take the last wrapper name and - // substract the extension "sym:overname", + // subtract the extension "sym:overname", String *wrap_name = NewString(Getattr(n, "wrap:name")); String *overname = Getattr(n, "sym:overname"); @@ -1575,7 +1575,8 @@ void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Ma Printf(arg, "argv[%d]", i); break; default: - throw "Illegal state."; + Printf(stderr, "Illegal MarshallingMode."); + SWIG_exit(EXIT_FAILURE); } tm = emitInputTypemap(n, p, wrapper, arg); Delete(arg); @@ -2212,7 +2213,8 @@ void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Mar Printf(arg, "args[%d]", i); break; default: - throw "Illegal state."; + Printf(stderr, "Illegal MarshallingMode."); + SWIG_exit(EXIT_FAILURE); } tm = emitInputTypemap(n, p, wrapper, arg); diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index f7979b611..196ff47a9 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -722,18 +722,18 @@ int Language::typemapDirective(Node *n) { String *code = Getattr(n, "code"); Parm *kwargs = Getattr(n, "kwargs"); Node *items = firstChild(n); - static int namewarn = 0; + static int nameerror = 0; if (code && (Strstr(code, "$source") || (Strstr(code, "$target")))) { - Swig_warning(WARN_TYPEMAP_SOURCETARGET, Getfile(n), Getline(n), "Deprecated typemap feature ($source/$target).\n"); - if (!namewarn) { - Swig_warning(WARN_TYPEMAP_SOURCETARGET, Getfile(n), Getline(n), "The use of $source and $target in a typemap declaration is deprecated.\n\ + Swig_error(Getfile(n), Getline(n), "Obsolete typemap feature ($source/$target).\n"); + if (!nameerror) { + Swig_error(Getfile(n), Getline(n), "The use of $source and $target in a typemap declaration is no longer supported.\n\ For typemaps related to argument input (in,ignore,default,arginit,check), replace\n\ $source by $input and $target by $1. For typemaps related to return values (out,\n\ argout,ret,except), replace $source by $1 and $target by $result. See the file\n\ Doc/Manual/Typemaps.html for complete details.\n"); - namewarn = 1; + nameerror = 1; } } @@ -1320,16 +1320,21 @@ int Language::staticmemberfunctionHandler(Node *n) { Delete(mrename); mrename = mangled; - if (Getattr(n, "sym:overloaded") && code) { - Append(cname, Getattr(defaultargs ? defaultargs : n, "sym:overname")); - } + if (code) { + // See Swig_MethodToFunction() for the explanation of this code. + if (Getattr(n, "sym:overloaded")) { + Append(cname, Getattr(defaultargs ? defaultargs : n, "sym:overname")); + } else { + Append(cname, "__SWIG"); + } - if (!defaultargs && code) { - /* Hmmm. An added static member. We have to create a little wrapper for this */ - String *mangled_cname = Swig_name_mangle(cname); - Swig_add_extension_code(n, mangled_cname, parms, type, code, CPlusPlus, 0); - Setattr(n, "extendname", mangled_cname); - Delete(mangled_cname); + if (!defaultargs) { + /* Hmmm. An added static member. We have to create a little wrapper for this */ + String *mangled_cname = Swig_name_mangle(cname); + Swig_add_extension_code(n, mangled_cname, parms, type, code, CPlusPlus, 0); + Setattr(n, "extendname", mangled_cname); + Delete(mangled_cname); + } } } @@ -1481,8 +1486,6 @@ int Language::membervariableHandler(Node *n) { } else { String *pname0 = Swig_cparm_name(0, 0); String *pname1 = Swig_cparm_name(0, 1); - Replace(tm, "$source", pname1, DOH_REPLACE_ANY); - Replace(tm, "$target", target, DOH_REPLACE_ANY); Replace(tm, "$input", pname1, DOH_REPLACE_ANY); Replace(tm, "$self", pname0, DOH_REPLACE_ANY); Setattr(n, "wrap:action", tm); @@ -3049,8 +3052,6 @@ int Language::variableWrapper(Node *n) { } } else { String *pname0 = Swig_cparm_name(0, 0); - Replace(tm, "$source", pname0, DOH_REPLACE_ANY); - Replace(tm, "$target", name, DOH_REPLACE_ANY); Replace(tm, "$input", pname0, DOH_REPLACE_ANY); Setattr(n, "wrap:action", tm); Delete(tm); diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 188b11c2b..f92c14cb2 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -50,7 +50,7 @@ /**** Diagnostics: With the #define REPORT(), you can change the amount of diagnostics given This helps me search the parse tree & figure out what is going on inside SWIG - (because its not clear or documented) + (because it's not clear or documented) */ #define REPORT(T,D) // no info: //#define REPORT(T,D) {Printf(stdout,T"\n");} // only title @@ -435,7 +435,7 @@ public: /* NEW LANGUAGE NOTE:*********************************************** This is it! you get this one right, and most of your work is done - but its going to take some file to get it working right + but it's going to take some file to get it working right quite a bit of this is generally boilerplate code (or stuff I don't understand) that which matters will have extra added comments @@ -613,13 +613,9 @@ public: } SwigType *pt = Getattr(p, "type"); - String *ln = Getattr(p, "lname"); - /* Look for an input typemap */ sprintf(source, "%d", i + 1); if ((tm = Getattr(p, "tmap:in"))) { - Replaceall(tm, "$source", source); - Replaceall(tm, "$target", ln); Replaceall(tm, "$input", source); Setattr(p, "emit:input", source); if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) { @@ -678,7 +674,6 @@ public: /* Insert constraint checking code */ for (p = l; p;) { if ((tm = Getattr(p, "tmap:check"))) { - Replaceall(tm, "$target", Getattr(p, "lname")); Printv(f->code, tm, "\n", NIL); p = Getattr(p, "tmap:check:next"); } else { @@ -690,7 +685,6 @@ public: String *cleanup = NewString(""); for (p = l; p;) { if ((tm = Getattr(p, "tmap:freearg"))) { - Replaceall(tm, "$source", Getattr(p, "lname")); Printv(cleanup, tm, "\n", NIL); p = Getattr(p, "tmap:freearg:next"); } else { @@ -709,8 +703,6 @@ public: // returnval+=GetInt(p,"tmap:argout:numoutputs"); // } // else returnval++; - Replaceall(tm, "$source", Getattr(p, "lname")); - Replaceall(tm, "$target", Swig_cresult_name()); Replaceall(tm, "$arg", Getattr(p, "emit:input")); Replaceall(tm, "$input", Getattr(p, "emit:input")); Printv(outarg, tm, "\n", NIL); @@ -740,7 +732,6 @@ public: // returnval+=GetInt(tm,"numoutputs"); // } // else returnval++; - Replaceall(tm, "$source", Swig_cresult_name()); if (GetFlag(n, "feature:new")) { Replaceall(tm, "$owner", "1"); } else { @@ -762,14 +753,12 @@ public: /* Look to see if there is any newfree cleanup code */ if (GetFlag(n, "feature:new")) { if ((tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); Printf(f->code, "%s\n", tm); } } /* See if there is any return cleanup code */ if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); Printf(f->code, "%s\n", tm); } @@ -1002,6 +991,7 @@ public: // REPORT("variableWrapper", n); String *lua_name = Getattr(n, "lua:name"); assert(lua_name); + (void)lua_name; current[VARIABLE] = true; // let SWIG generate the wrappers int result = Language::variableWrapper(n); @@ -1073,14 +1063,10 @@ public: } if ((tm = Swig_typemap_lookup("consttab", n, name, 0))) { - Replaceall(tm, "$source", value); - Replaceall(tm, "$target", lua_name); Replaceall(tm, "$value", value); Replaceall(tm, "$nsname", nsname); registerConstant(luaCurrentSymbolNSpace(), tm); } else if ((tm = Swig_typemap_lookup("constcode", n, name, 0))) { - Replaceall(tm, "$source", value); - Replaceall(tm, "$target", lua_name); Replaceall(tm, "$value", value); Replaceall(tm, "$nsname", nsname); Printf(f_init, "%s\n", tm); @@ -1109,8 +1095,6 @@ public: Setattr(n_v2, "sym:name", lua_name_v2); tm_v2 = Swig_typemap_lookup("consttab", n_v2, name, 0); if (tm_v2) { - Replaceall(tm_v2, "$source", value); - Replaceall(tm_v2, "$target", lua_name_v2); Replaceall(tm_v2, "$value", value); Replaceall(tm_v2, "$nsname", nsname); registerConstant(getNSpace(), tm_v2); @@ -1122,8 +1106,6 @@ public: Swig_restore(n); return SWIG_ERROR; } - Replaceall(tm_v2, "$source", value); - Replaceall(tm_v2, "$target", lua_name_v2); Replaceall(tm_v2, "$value", value); Replaceall(tm_v2, "$nsname", nsname); Printf(f_init, "%s\n", tm_v2); @@ -2071,8 +2053,8 @@ public: if (GetFlag(carrays_hash, "lua:class_instance")) { String *static_cls = Getattr(carrays_hash, "lua:class_instance:static_hash"); assert(static_cls); - // static_cls is swig_lua_namespace. This structure can't be use with eLua(LTR) - // Instead structure describing its methods isused + // static_cls is swig_lua_namespace. This structure can't be used with eLua(LTR) + // Instead a structure describing its methods is used String *static_cls_cname = Getattr(static_cls, "methods:name"); assert(static_cls_cname); Printv(metatable_tab, tab4, "{LSTRKEY(\".static\"), LROVAL(", static_cls_cname, ")},\n", NIL); @@ -2243,36 +2225,6 @@ public: }; -/* NEW LANGUAGE NOTE:*********************************************** - in order to add you language into swig, you need to make the following changes: - - write this file (obviously) - - add into the makefile (not 100% clear on how to do this) - - edit swigmain.cxx to add your module - -near the top of swigmain.cxx, look for this code & add you own codes -======= begin change ========== -extern "C" { - Language *swig_tcl(void); - Language *swig_python(void); - //etc,etc,etc... - Language *swig_lua(void); // this is my code -} - - //etc,etc,etc... - -swig_module modules[] = { - {"-guile", swig_guile, "Guile"}, - {"-java", swig_java, "Java"}, - //etc,etc,etc... - {"-lua", swig_lua, "Lua"}, // this is my code - {NULL, NULL, NULL} // this must come at the end of the list -}; -======= end change ========== - -This is all that is needed - -NEW LANGUAGE NOTE:END ************************************************/ - /* ----------------------------------------------------------------------------- * swig_lua() - Instantiate module * ----------------------------------------------------------------------------- */ diff --git a/Source/Modules/main.cxx b/Source/Modules/main.cxx index d8f2ab6b4..ebd788d35 100644 --- a/Source/Modules/main.cxx +++ b/Source/Modules/main.cxx @@ -137,7 +137,7 @@ static const char *usage4 = (const char *) "\ -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\ + -pcreversion - Display PCRE2 version information\n\ -small - Compile in virtual elimination and compact mode\n\ -swiglib - Report location of SWIG library and exit\n\ -templatereduce - Reduce all the typedefs in templates\n\ @@ -477,7 +477,10 @@ static void getoptions(int argc, char *argv[]) { Swig_mark_arg(i); } else if (strncmp(argv[i], "-D", 2) == 0) { String *d = NewString(argv[i] + 2); - Replace(d, "=", " ", DOH_REPLACE_ANY | DOH_REPLACE_FIRST); + if (Replace(d, "=", " ", DOH_REPLACE_FIRST) == 0) { + // Match C preprocessor behaviour whereby -DFOO sets FOO=1. + Append(d, " 1"); + } Preprocessor_define((DOH *) d, 0); Delete(d); // Create a symbol diff --git a/Source/Modules/modula3.cxx b/Source/Modules/modula3.cxx deleted file mode 100644 index c606845ea..000000000 --- a/Source/Modules/modula3.cxx +++ /dev/null @@ -1,3931 +0,0 @@ -/* ----------------------------------------------------------------------------- - * This file is part of SWIG, which is licensed as a whole under version 3 - * (or any later version) of the GNU General Public License. Some additional - * terms also apply to certain portions of SWIG. The full details of the SWIG - * license and copyrights can be found in the LICENSE and COPYRIGHT files - * included with the SWIG source code as distributed by the SWIG developers - * and at http://www.swig.org/legal.html. - * - * modula3.cxx - * - * Modula3 language module for SWIG. - * ----------------------------------------------------------------------------- */ - -/* - Text formatted with - indent -sob -br -ce -nut -npsl -*/ - -/* - Report: - - It's not a good concept to use member variables or global variables - for passing parameters to functions. - It's not a good concept to use functions of superclasses for specific services. - E.g. For SWIG this means: Generating accessor functions for member variables - is the most common but no general task to be processed in membervariableHandler. - Better provide a service function which generates accessor function code - and equip this service function with all parameters needed for input (parse node) - and output (generated code). - - How can I make globalvariableHandler not to generate - interface functions to two accessor functions - (that don't exist) ? - - How can I generate a typemap that turns every C reference argument into - its Modula 3 counterpart, that is - void test(Complex &z); - PROCEDURE test(VAR z:Complex); - - neither $*n_mangle nor $*n_type nor $*n_ltype return the type without - pointer converted to Modula3 equivalent, - $*n_mangle is the variant closest to what I expect - - using a typemap like - typemap(m3wrapintype) int * %{VAR $1_name: INTEGER%} - has the advantages: - - one C parameter can be turned into multiple M3 parameters - - the argument can be renamed - - using typemaps like - typemap(m3wrapinmode) int * "VAR" - typemap(m3wrapintype) int * "INTEGER" - has the advantages: - - multiple parameters with same type and default value can be bundled - - more conform to the other language modules - - Where takes the reduction of multi-typemaps place? - How can I preserve all parameters for functions of the intermediary class? - The answer is Getattrs(n,"tmap:m3rawintype:next") - - Char() can be used to transform a String to (char *) - which can be used for output with printf - - What is the while (checkAttribute()) loop in functionWrapper good for? - Appearently for skipping (numinputs=0) typemaps. - - SWIGTYPE const * - typemap is ignored, whereas - SWIGTYPE * - typemap is invoked, why? - Had it been (const SWIGTYPE *) instead? - - enumeration items should definitely be equipped - with its plain numerical value - One could add tag 'numvalue' in CParse/parser.y, - but it is still possible that someone declares an - enumeration using a symbolic constant. - I have quickly hacked - that the successive number is assigned - if "enumvalue" has suffix "+1". - The ultimate solution would be to generate a C program - which includes the header and outputs all constants. - This program might be compiled and run - by 'make' or by SWIG and the resulting output is fed back to SWIG. - - It's a bad idea to interpret feature value "" - 'disable feature' because the value "" - might be sensible in case of feature:modula3:oldprefix. - - What's the difference between "sym:name" and "name" ? - "name" is the original name and - "sym:name" is probably modified by the user using %rename - - Is it possible for 'configure' to find out if m3pp is installed - and to invoke it for generated Modula3 files? - - It would be better to separate an arguments purpose and its name, - because an output variable with name "OUTPUT" is not very descriptive. - In case of PLPlot this could be solved by typedefs - that assign special purposes to the array types. - - Can one interpret $n_basetype as the identifier matched with SWIGTYPE ? - - SWIG's odds: - - arguments of type (Node *) for SWIG functions - should be most often better (const Node *): - Swig_symbol_qualified, Getattr, nodeType, parentNode - - unique identifier style instead of - NewString, Getattr, firstChild - - 'class'.name is qualified, - 'enum'.name and 'enumitem'.name is not - - Swig_symbol_qualified() returns NIL for enumeration nodes - - - Is there a function that creates a C representation of a SWIG type string? - - ToDo: - - create WeakRefs only for resources returned by function marked with %newobject - -> part of output conversion - - clean typemap conception - - should a multi-typemap for m3wrapouttype skip the corresponding input parameters? - when yes - How to handle inout-arguments? In this case like in-argument. - - C++ classes - - C++ exceptions - - allow for moving RECORD and OBJECT definitions - to separate files, with the main type called T - - call-back functions - - special option: fast access to class members by pointer arithmetic, - member offsets can be determined by a C++ program that print them. - - emit enumeration definitions when its first item is declared, - currently enumerations are emitted at the beginning of the file - - Done: - - addThrow should convert the typemap by itself - - not possible because routine for attaching mapped types to parameter nodes - won't work for the function node - - turning error codes into exceptions - -> part of output value checking - - create WeakRefs for resources allocated by the library - -> part of output conversion - - TRY..FINALLY..END; can be omitted - - if there is no m3wrapfreearg - - no exception can be raised in the body (empty RAISES) list -*/ - -#include "swigmod.h" - -#include // for INT_MAX -#include - -#define USAGE_ARG_DIR "m3wrapargdir typemap expect values: in, out, inout\n" - -class MODULA3:public Language { -public: - enum block_type { no_block, constant, variable, blocktype, revelation }; - -private: - struct M3File { - String *f; - Hash *import; - block_type bt; - /* VC++ 6 doesn't allow the access to 'no_block' - if it is a private member of MODULA3 class */ - M3File():f(NewString("")), import(NewHash()), bt(no_block) { - } - ~M3File() { - Delete(f); - Delete(import); - } - - /* ----------------------------------------------------------------------------- - * enterBlock() - * - * Make sure that a given declaration is written to the right declaration block, - * that is constants are written after "CONST" and so on ... - * ----------------------------------------------------------------------------- */ - void enterBlock(block_type newbt) { - static const char *ident[] = { "", "\nCONST\n", "\nVAR\n", "\nTYPE\n", "\nREVEAL\n" }; -#ifdef DEBUG - if ((bt < 0) || (4 < bt)) { - printf("bt %d out of range\n", bt); - } -#endif - if (newbt != bt) { - Append(f, ident[newbt]); - bt = newbt; - } - } - - }; - - static const char *usage; - const String *empty_string; - - Hash *swig_types_hash; - File *f_begin; - File *f_runtime; - File *f_header; - File *f_wrappers; - File *f_init; - - bool proxy_flag; // Flag for generating proxy classes - bool have_default_constructor_flag; - bool native_function_flag; // Flag for when wrapping a native function - bool enum_constant_flag; // Flag for when wrapping an enum or constant - bool static_flag; // Flag for when wrapping a static functions or member variables - bool variable_wrapper_flag; // Flag for when wrapping a nonstatic member variable - bool wrapping_member_flag; // Flag for when wrapping a member variable/enum/const - bool global_variable_flag; // Flag for when wrapping a global variable - bool old_variable_names; // Flag for old style variable names in the intermediary class - bool unsafe_module; - - String *m3raw_name; // raw interface name - M3File m3raw_intf; // raw interface - M3File m3raw_impl; // raw implementation (usually empty) - String *m3wrap_name; // wrapper module - M3File m3wrap_intf; - M3File m3wrap_impl; - String *m3makefile; - String *targetlibrary; - String *proxy_class_def; - String *proxy_class_code; - String *proxy_class_name; - String *variable_name; //Name of a variable being wrapped - String *variable_type; //Type of this variable - Hash *enumeration_coll; //Collection of all enumerations. - /* The items are nodes with members: - "items" - hash of with key 'itemname' and content 'itemvalue' - "max" - maximum value in item list - */ - String *constant_values; - String *constantfilename; - String *renamefilename; - String *typemapfilename; - String *m3raw_imports; //intermediary class imports from %pragma - String *module_imports; //module imports from %pragma - String *m3raw_baseclass; //inheritance for intermediary class class from %pragma - String *module_baseclass; //inheritance for module class from %pragma - String *m3raw_interfaces; //interfaces for intermediary class class from %pragma - String *module_interfaces; //interfaces for module class from %pragma - String *m3raw_class_modifiers; //class modifiers for intermediary class overridden by %pragma - String *m3wrap_modifiers; //class modifiers for module class overridden by %pragma - String *upcasts_code; //C++ casts for inheritance hierarchies C++ code - String *m3raw_cppcasts_code; //C++ casts up inheritance hierarchies intermediary class code - String *destructor_call; //C++ destructor call if any - String *outfile; - - enum type_additions { none, pointer, reference }; - -public: - - /* ----------------------------------------------------------------------------- - * MODULA3() - * ----------------------------------------------------------------------------- */ - -MODULA3(): - empty_string(NewString("")), - swig_types_hash(NULL), - f_begin(NULL), - f_runtime(NULL), - f_header(NULL), - f_wrappers(NULL), - f_init(NULL), - proxy_flag(true), - have_default_constructor_flag(false), - native_function_flag(false), - enum_constant_flag(false), - static_flag(false), - variable_wrapper_flag(false), - wrapping_member_flag(false), - global_variable_flag(false), - old_variable_names(false), - unsafe_module(false), - m3raw_name(NULL), - m3raw_intf(), - m3raw_impl(), - m3wrap_name(NULL), - m3wrap_intf(), - m3wrap_impl(), - m3makefile(NULL), - targetlibrary(NULL), - proxy_class_def(NULL), - proxy_class_code(NULL), - proxy_class_name(NULL), - variable_name(NULL), - variable_type(NULL), - enumeration_coll(NULL), - constant_values(NULL), - constantfilename(NULL), - renamefilename(NULL), - typemapfilename(NULL), - m3raw_imports(NULL), - module_imports(NULL), - m3raw_baseclass(NULL), - module_baseclass(NULL), - m3raw_interfaces(NULL), - module_interfaces(NULL), - m3raw_class_modifiers(NULL), - m3wrap_modifiers(NULL), - upcasts_code(NULL), - m3raw_cppcasts_code(NULL), - destructor_call(NULL), - outfile(NULL) { - } - - /************** some utility functions ***************/ - - /* ----------------------------------------------------------------------------- - * getMappedType() - * - * Return the type of 'p' mapped by 'map'. - * Print a standard warning if 'p' can't be mapped. - * ----------------------------------------------------------------------------- */ - - String *getMappedType(Node *p, const char *map) { - String *mapattr = NewString("tmap:"); - Append(mapattr, map); - - String *tm = Getattr(p, mapattr); - if (tm == NIL) { - Swig_warning(WARN_MODULA3_TYPEMAP_TYPE_UNDEF, input_file, line_number, - "No '%s' typemap defined for type '%s'\n", map, SwigType_str(Getattr(p, "type"), 0)); - } - Delete(mapattr); - return tm; - } - - /* ----------------------------------------------------------------------------- - * getMappedTypeNew() - * - * Similar to getMappedType but uses Swig_type_lookup_new. - * ----------------------------------------------------------------------------- */ - - String *getMappedTypeNew(Node *n, const char *map, const char *lname = "", bool warn = true) { - String *tm = Swig_typemap_lookup(map, n, lname, 0); - if ((tm == NIL) && warn) { - Swig_warning(WARN_MODULA3_TYPEMAP_TYPE_UNDEF, input_file, line_number, - "No '%s' typemap defined for type '%s'\n", map, SwigType_str(Getattr(n, "type"), 0)); - } - return tm; - } - - /* ----------------------------------------------------------------------------- - * attachMappedType() - * - * Obtain the type mapped by 'map' and attach it to the node - * ----------------------------------------------------------------------------- */ - - void attachMappedType(Node *n, const char *map, const char *lname = "") { - String *tm = Swig_typemap_lookup(map, n, lname, 0); - if (tm != NIL) { - String *attr = NewStringf("tmap:%s", map); - Setattr(n, attr, tm); - Delete(attr); - } - } - - /* ----------------------------------------------------------------------------- - * skipIgnored() - * - * Skip all parameters that have 'numinputs=0' - * with respect to a given typemap. - * ----------------------------------------------------------------------------- */ - - Node *skipIgnored(Node *p, const char *map) { - String *niattr = NewStringf("tmap:%s:numinputs", map); - String *nextattr = NewStringf("tmap:%s:next", map); - - while ((p != NIL) && checkAttribute(p, niattr, "0")) { - p = Getattr(p, nextattr); - } - - Delete(nextattr); - Delete(niattr); - return p; - } - - /* ----------------------------------------------------------------------------- - * isInParam() - * isOutParam() - * - * Check if the parameter is intended for input or for output. - * ----------------------------------------------------------------------------- */ - - bool isInParam(Node *p) { - String *dir = Getattr(p, "tmap:m3wrapargdir"); -//printf("dir for %s: %s\n", Char(Getattr(p,"name")), Char(dir)); - if ((dir == NIL) || (Strcmp(dir, "in") == 0) - || (Strcmp(dir, "inout") == 0)) { - return true; - } else if (Strcmp(dir, "out") == 0) { - return false; - } else { - printf("%s", USAGE_ARG_DIR); - return false; - } - } - - bool isOutParam(Node *p) { - String *dir = Getattr(p, "tmap:m3wrapargdir"); - if ((dir == NIL) || (Strcmp(dir, "in") == 0)) { - return false; - } else if ((Strcmp(dir, "out") == 0) || (Strcmp(dir, "inout") == 0)) { - return true; - } else { - printf("%s", USAGE_ARG_DIR); - return false; - } - } - - /* ----------------------------------------------------------------------------- - * printAttrs() - * - * For debugging: Show all attributes of a node and their values. - * ----------------------------------------------------------------------------- */ - void printAttrs(Node *n) { - Iterator it; - for (it = First(n); it.key != NIL; it = Next(it)) { - printf("%s = %s\n", Char(it.key), Char(Getattr(n, it.key))); - } - } - - /* ----------------------------------------------------------------------------- - * hasPrefix() - * - * Check if a string have a given prefix. - * ----------------------------------------------------------------------------- */ - bool hasPrefix(const String *str, const String *prefix) { - int len_prefix = Len(prefix); - return (Len(str) > len_prefix) - && (Strncmp(str, prefix, len_prefix) == 0); - } - - /* ----------------------------------------------------------------------------- - * getQualifiedName() - * - * Return fully qualified identifier of n. - * ----------------------------------------------------------------------------- */ -#if 0 - // Swig_symbol_qualified returns NIL for enumeration nodes - String *getQualifiedName(Node *n) { - String *qual = Swig_symbol_qualified(n); - String *name = Getattr(n, "name"); - if (hasContent(qual)) { - return NewStringf("%s::%s", qual, name); - } else { - return name; - } - } -#else - String *getQualifiedName(Node *n) { - String *name = Copy(Getattr(n, "name")); - n = parentNode(n); - while (n != NIL) { - const String *type = nodeType(n); - if ((Strcmp(type, "class") == 0) || (Strcmp(type, "struct") == 0) || (Strcmp(type, "namespace") == 0)) { - String *newname = NewStringf("%s::%s", Getattr(n, "name"), name); - Delete(name); - //name = newname; - // Hmpf, the class name is already qualified. - return newname; - } - n = parentNode(n); - } - //printf("qualified name: %s\n", Char(name)); - return name; - } -#endif - - /* ----------------------------------------------------------------------------- - * nameToModula3() - * - * Turn usual C identifiers like "this_is_an_identifier" - * into usual Modula 3 identifier like "thisIsAnIdentifier" - * ----------------------------------------------------------------------------- */ - String *nameToModula3(const String *sym, bool leadingCap) { - int len_sym = Len(sym); - char *csym = Char(sym); - char *m3sym = new char[len_sym + 1]; - int i, j; - bool cap = leadingCap; - for (i = 0, j = 0; j < len_sym; j++) { - char c = csym[j]; - if ((c == '_') || (c == ':')) { - cap = true; - } else { - if (isdigit(c)) { - m3sym[i] = c; - cap = true; - } else { - if (cap) { - m3sym[i] = (char)toupper(c); - } else { - m3sym[i] = (char)tolower(c); - } - cap = false; - } - i++; - } - } - m3sym[i] = 0; - String *result = NewString(m3sym); - delete[]m3sym; - return result; - } - - /* ----------------------------------------------------------------------------- - * capitalizeFirst() - * - * Make the first character upper case. - * ----------------------------------------------------------------------------- */ - String *capitalizeFirst(const String *str) { - return NewStringf("%c%s", toupper(*Char(str)), Char(str) + 1); - } - - /* ----------------------------------------------------------------------------- - * prefixedNameToModula3() - * - * If feature modula3:oldprefix and modula3:newprefix is present - * and the C identifier has leading 'oldprefix' - * then it is replaced by the 'newprefix'. - * The rest is converted to Modula style. - * ----------------------------------------------------------------------------- */ - String *prefixedNameToModula3(Node *n, const String *sym, bool leadingCap) { - String *oldPrefix = Getattr(n, "feature:modula3:oldprefix"); - String *newPrefix = Getattr(n, "feature:modula3:newprefix"); - String *result = NewString(""); - char *short_sym = Char(sym); - // if at least one prefix feature is present - // the replacement takes place - if ((oldPrefix != NIL) || (newPrefix != NIL)) { - if ((oldPrefix == NIL) || hasPrefix(sym, oldPrefix)) { - short_sym += Len(oldPrefix); - if (newPrefix != NIL) { - Append(result, newPrefix); - } - } - } - String *suffix = nameToModula3(short_sym, leadingCap || hasContent(newPrefix)); - Append(result, suffix); - Delete(suffix); - return result; - } - - /* ----------------------------------------------------------------------------- - * hasContent() - * - * Check if the string exists and contains something. - * ----------------------------------------------------------------------------- */ - bool hasContent(const String *str) { - return (str != NIL) && (Strcmp(str, "") != 0); - } - - /* ----------------------------------------------------------------------------- - * openWriteFile() - * - * Caution: The file must be freshly allocated and will be destroyed - * by this routine. - * ----------------------------------------------------------------------------- */ - - File *openWriteFile(String *name) { - File *file = NewFile(name, "w", SWIG_output_files()); - if (!file) { - FileErrorDisplay(name); - SWIG_exit(EXIT_FAILURE); - } - Delete(name); - return file; - } - - /* ----------------------------------------------------------------------------- - * aToL() - * - * like atol but with additional user warning - * ----------------------------------------------------------------------------- */ - - long aToL(const String *value) { - char *endptr; - long numvalue = strtol(Char(value), &endptr, 0); - if (*endptr != 0) { - Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "The string <%s> does not denote a numeric value.\n", value); - } - return numvalue; - } - - /* ----------------------------------------------------------------------------- - * strToL() - * - * like strtol but returns if the conversion was successful - * ----------------------------------------------------------------------------- */ - - bool strToL(const String *value, long &numvalue) { - char *endptr; - numvalue = strtol(Char(value), &endptr, 0); - return (*endptr == 0); - } - - /* ----------------------------------------------------------------------------- - * evalExpr() - * - * Evaluate simple expression as they may occur in "enumvalue" attributes. - * ----------------------------------------------------------------------------- */ - - bool evalExpr(String *value, long &numvalue) { - // Split changes file status of String and thus cannot receive 'const' strings -//printf("evaluate <%s>\n", Char(value)); - List *summands = Split(value, '+', INT_MAX); - Iterator sm = First(summands); - numvalue = 0; - for (; sm.item != NIL; sm = Next(sm)) { - String *smvalue = Getattr(constant_values, sm.item); - long smnumvalue; - if (smvalue != NIL) { - if (!strToL(smvalue, smnumvalue)) { -//printf("evaluation: abort 0 <%s>\n", Char(smvalue)); - return false; - } - } else { - if (!strToL(sm.item, smnumvalue)) { -//printf("evaluation: abort 1 <%s>\n", Char(sm)); - return false; - } - } - numvalue += smnumvalue; - } -//printf("evaluation: return %ld\n", numvalue); - return true; - } - - /* ----------------------------------------------------------------------------- - * log2() - * - * Determine the position of the single bit of a power of two. - * Returns true if the given number is a power of two. - * ----------------------------------------------------------------------------- */ - - bool log2(long n, long &exp) { - exp = 0; - while (n > 0) { - if ((n & 1) != 0) { - return n == 1; - } - exp++; - n >>= 1; - } - return false; - } - - /* ----------------------------------------------------------------------------- - * writeArg - * - * Write a function argument or RECORD entry definition. - * Bundles arguments of same type and default value. - * 'name.next==NIL' denotes the end of the entry or argument list. - * ----------------------------------------------------------------------------- */ - - bool equalNilStr(const String *str0, const String *str1) { - if (str0 == NIL) { - return (str1 == NIL); - //return (str0==NIL) == (str1==NIL); - } else { - return (str1 != NIL) && (Cmp(str0, str1) == 0); - //return Cmp(str0,str1)==0; - } - } - - struct writeArgState { - String *mode, *name, *type, *value; - bool hold; - writeArgState():mode(NIL), name(NIL), type(NIL), value(NIL), hold(false) { - } - }; - - void writeArg(File *f, writeArgState & state, String *mode, String *name, String *type, String *value) { - /* skip the first argument, - only store the information for the next call in this case */ - if (state.name != NIL) { - if ((!state.hold) && (state.mode != NIL)) { - Printf(f, "%s ", state.mode); - } - if ((name != NIL) && equalNilStr(state.mode, mode) && equalNilStr(state.type, type) && (state.value == NIL) && (value == NIL) - /* the same expression may have different values - due to side effects of the called function */ - /*equalNilStr(state.value,value) */ - ) { - Printf(f, "%s, ", state.name); - state.hold = true; - } else { - Append(f, state.name); - if (state.type != NIL) { - Printf(f, ": %s", state.type); - } - if (state.value != NIL) { - Printf(f, ":= %s", state.value); - } - Append(f, ";\n"); - state.hold = false; - } - } - /* at the next call the current argument will be the previous one */ - state.mode = mode; - state.name = name; - state.type = type; - state.value = value; - } - - /* ----------------------------------------------------------------------------- - * getProxyName() - * - * Test to see if a type corresponds to something wrapped with a proxy class - * Return NULL if not otherwise the proxy class name - * ----------------------------------------------------------------------------- */ - - String *getProxyName(SwigType *t) { - if (proxy_flag) { - Node *n = classLookup(t); - if (n) { - return Getattr(n, "sym:name"); - } - } - return NULL; - } - - /*************** language processing ********************/ - - /* ------------------------------------------------------------ - * main() - * ------------------------------------------------------------ */ - - virtual void main(int argc, char *argv[]) { - - SWIG_library_directory("modula3"); - - // Look for certain command line options - for (int i = 1; i < argc; i++) { - if (argv[i]) { - if (strcmp(argv[i], "-generateconst") == 0) { - if (argv[i + 1]) { - constantfilename = NewString(argv[i + 1]); - Swig_mark_arg(i); - Swig_mark_arg(i + 1); - i++; - } else { - Swig_arg_error(); - } - } else if (strcmp(argv[i], "-generaterename") == 0) { - if (argv[i + 1]) { - renamefilename = NewString(argv[i + 1]); - Swig_mark_arg(i); - Swig_mark_arg(i + 1); - i++; - } else { - Swig_arg_error(); - } - } else if (strcmp(argv[i], "-generatetypemap") == 0) { - if (argv[i + 1]) { - typemapfilename = NewString(argv[i + 1]); - Swig_mark_arg(i); - Swig_mark_arg(i + 1); - i++; - } else { - Swig_arg_error(); - } - } else if (strcmp(argv[i], "-noproxy") == 0) { - Swig_mark_arg(i); - proxy_flag = false; - } else if (strcmp(argv[i], "-oldvarnames") == 0) { - Swig_mark_arg(i); - old_variable_names = true; - } else if (strcmp(argv[i], "-help") == 0) { - Printf(stdout, "%s\n", usage); - } - } - } - - // Add a symbol to the parser for conditional compilation - Preprocessor_define("SWIGMODULA3 1", 0); - - // Add typemap definitions - SWIG_typemap_lang("modula3"); - SWIG_config_file("modula3.swg"); - - allow_overloading(); - } - - /* --------------------------------------------------------------------- - * top() - * --------------------------------------------------------------------- */ - - virtual int top(Node *n) { - if (hasContent(constantfilename) || hasContent(renamefilename) || hasContent(typemapfilename)) { - int result = SWIG_OK; - if (hasContent(constantfilename)) { - result = generateConstantTop(n) && result; - } - if (hasContent(renamefilename)) { - result = generateRenameTop(n) && result; - } - if (hasContent(typemapfilename)) { - result = generateTypemapTop(n) && result; - } - return result; - } else { - return generateM3Top(n); - } - } - - void scanConstant(File *file, Node *n) { - Node *child = firstChild(n); - while (child != NIL) { - String *constname = NIL; - String *type = nodeType(child); - if ((Strcmp(type, "enumitem") == 0) - || (Strcmp(type, "constant") == 0)) { -#if 1 - constname = getQualifiedName(child); -#else - constname = Getattr(child, "value"); - if ((!hasContent(constname)) - || (('0' <= *Char(constname)) && (*Char(constname) <= '9'))) { - constname = Getattr(child, "name"); - } -#endif - } - if (constname != NIL) { - Printf(file, " printf(\"%%%%constnumeric(%%Lg) %s;\\n\", (long double)%s);\n", constname, constname); - } - scanConstant(file, child); - child = nextSibling(child); - } - } - - int generateConstantTop(Node *n) { - File *file = openWriteFile(NewStringf("%s.c", constantfilename)); - if (CPlusPlus) { - Printf(file, "#include \n"); - } else { - Printf(file, "#include \n"); - } - Printf(file, "#include \"%s\"\n", input_file); - Printf(file, "\n"); - Printf(file, "int main (int argc, char *argv[]) {\n"); - Printf(file, "\ -/*This program must work for floating point numbers and integers.\n\ - Thus all numbers are converted to double precision floating point format.*/\n"); - scanConstant(file, n); - Printf(file, " return 0;\n"); - Printf(file, "}\n"); - Delete(file); - return SWIG_OK; - } - - void scanRename(File *file, Node *n) { - Node *child = firstChild(n); - while (child != NIL) { - String *type = nodeType(child); - if (Strcmp(type, "cdecl") == 0) { - ParmList *p = Getattr(child, "parms"); - if (p != NIL) { - String *name = getQualifiedName(child); - String *m3name = nameToModula3(name, true); - /*don't know how to get the original C type identifiers */ - //String *arguments = createCSignature (child); - Printf(file, "%%rename(\"%s\") %s;\n", m3name, name); - /*Printf(file, "%%rename(\"%s\") %s %s(%s);\n", - m3name, Getattr(n,"type"), name, arguments); */ - Delete(name); - Delete(m3name); - //Delete (arguments); - } - } - scanRename(file, child); - child = nextSibling(child); - } - } - - int generateRenameTop(Node *n) { - File *file = openWriteFile(NewStringf("%s.i", renamefilename)); - Printf(file, "\ -/* This file was generated from %s\n\ - by SWIG with option -generaterename. */\n\ -\n", input_file); - scanRename(file, n); - Delete(file); - return SWIG_OK; - } - - void scanTypemap(File *file, Node *n) { - Node *child = firstChild(n); - while (child != NIL) { - String *type = nodeType(child); - //printf("nodetype %s\n", Char(type)); - String *storage = Getattr(child, "storage"); - if ((Strcmp(type, "class") == 0) || ((Strcmp(type, "cdecl") == 0) && (storage != NIL) - && (Strcmp(storage, "typedef") == 0))) { - String *name = getQualifiedName(child); - String *m3name = nameToModula3(name, true); - Printf(file, "%%typemap(\"m3wrapintype\") %s %%{%s%%}\n", name, m3name); - Printf(file, "%%typemap(\"m3rawintype\") %s %%{%s%%}\n", name, m3name); - Printf(file, "\n"); - } - scanTypemap(file, child); - child = nextSibling(child); - } - } - - int generateTypemapTop(Node *n) { - File *file = openWriteFile(NewStringf("%s.i", typemapfilename)); - Printf(file, "\ -/* This file was generated from %s\n\ - by SWIG with option -generatetypemap. */\n\ -\n", input_file); - scanTypemap(file, n); - Delete(file); - return SWIG_OK; - } - - int generateM3Top(Node *n) { - /* Initialize all of the output files */ - outfile = Getattr(n, "outfile"); - - f_begin = NewFile(outfile, "w", SWIG_output_files()); - if (!f_begin) { - FileErrorDisplay(outfile); - SWIG_exit(EXIT_FAILURE); - } - f_runtime = NewString(""); - f_init = NewString(""); - f_header = NewString(""); - f_wrappers = NewString(""); - - m3makefile = NewString(""); - - /* Register file targets with the SWIG file handler */ - Swig_register_filebyname("header", f_header); - Swig_register_filebyname("wrapper", f_wrappers); - Swig_register_filebyname("begin", f_begin); - Swig_register_filebyname("runtime", f_runtime); - Swig_register_filebyname("init", f_init); - - Swig_register_filebyname("m3rawintf", m3raw_intf.f); - Swig_register_filebyname("m3rawimpl", m3raw_impl.f); - Swig_register_filebyname("m3wrapintf", m3wrap_intf.f); - Swig_register_filebyname("m3wrapimpl", m3wrap_impl.f); - Swig_register_filebyname("m3makefile", m3makefile); - - swig_types_hash = NewHash(); - - String *name = Getattr(n, "name"); - // Make the intermediary class and module class names. The intermediary class name can be set in the module directive. - Node *optionsnode = Getattr(Getattr(n, "module"), "options"); - if (optionsnode != NIL) { - String *m3raw_name_tmp = Getattr(optionsnode, "m3rawname"); - if (m3raw_name_tmp != NIL) { - m3raw_name = Copy(m3raw_name_tmp); - } - } - if (m3raw_name == NIL) { - m3raw_name = NewStringf("%sRaw", name); - } - Setattr(m3wrap_impl.import, m3raw_name, ""); - - m3wrap_name = Copy(name); - - proxy_class_def = NewString(""); - proxy_class_code = NewString(""); - m3raw_baseclass = NewString(""); - m3raw_interfaces = NewString(""); - m3raw_class_modifiers = NewString(""); // package access only to the intermediary class by default - m3raw_imports = NewString(""); - m3raw_cppcasts_code = NewString(""); - m3wrap_modifiers = NewString("public"); - module_baseclass = NewString(""); - module_interfaces = NewString(""); - module_imports = NewString(""); - upcasts_code = NewString(""); - - Swig_banner(f_begin); - - Printf(f_runtime, "\n\n#ifndef SWIGMODULA3\n#define SWIGMODULA3\n#endif\n\n"); - - Swig_name_register("wrapper", "Modula3_%f"); - if (old_variable_names) { - Swig_name_register("set", "set_%n%v"); - Swig_name_register("get", "get_%n%v"); - } - - Printf(f_wrappers, "\n#ifdef __cplusplus\n"); - Printf(f_wrappers, "extern \"C\" {\n"); - Printf(f_wrappers, "#endif\n\n"); - - constant_values = NewHash(); - scanForConstPragmas(n); - enumeration_coll = NewHash(); - collectEnumerations(enumeration_coll, n); - - /* Emit code */ - Language::top(n); - - // Generate m3makefile - // This will be unnecessary if SWIG is invoked from Quake. - { - File *file = openWriteFile(NewStringf("%sm3makefile", SWIG_output_directory())); - - Printf(file, "%% automatically generated quake file for %s\n\n", name); - - /* Write the fragments written by '%insert' - collected while 'top' processed the parse tree */ - Printv(file, m3makefile, NIL); - - Printf(file, "import(\"libm3\")\n"); - //Printf(file, "import_lib(\"%s\",\"/usr/lib\")\n", name); - Printf(file, "module(\"%s\")\n", m3raw_name); - Printf(file, "module(\"%s\")\n\n", m3wrap_name); - - if (targetlibrary != NIL) { - Printf(file, "library(\"%s\")\n", targetlibrary); - } else { - Printf(file, "library(\"m3%s\")\n", name); - } - Delete(file); - } - - // Generate the raw interface - { - File *file = openWriteFile(NewStringf("%s%s.i3", SWIG_output_directory(), m3raw_name)); - - emitBanner(file); - - Printf(file, "INTERFACE %s;\n\n", m3raw_name); - - emitImportStatements(m3raw_intf.import, file); - Printf(file, "\n"); - - // Write the interface generated within 'top' - Printv(file, m3raw_intf.f, NIL); - - Printf(file, "\nEND %s.\n", m3raw_name); - Delete(file); - } - - // Generate the raw module - { - File *file = openWriteFile(NewStringf("%s%s.m3", SWIG_output_directory(), m3raw_name)); - - emitBanner(file); - - Printf(file, "MODULE %s;\n\n", m3raw_name); - - emitImportStatements(m3raw_impl.import, file); - Printf(file, "\n"); - - // will be empty usually - Printv(file, m3raw_impl.f, NIL); - - Printf(file, "BEGIN\nEND %s.\n", m3raw_name); - Delete(file); - } - - // Generate the interface for the comfort wrappers - { - File *file = openWriteFile(NewStringf("%s%s.i3", SWIG_output_directory(), m3wrap_name)); - - emitBanner(file); - - Printf(file, "INTERFACE %s;\n", m3wrap_name); - - emitImportStatements(m3wrap_intf.import, file); - Printf(file, "\n"); - - { - Iterator it = First(enumeration_coll); - if (it.key != NIL) { - Printf(file, "TYPE\n"); - } - for (; it.key != NIL; it = Next(it)) { - Printf(file, "\n"); - emitEnumeration(file, it.key, it.item); - } - } - - // Add the wrapper methods - Printv(file, m3wrap_intf.f, NIL); - - // Finish off the class - Printf(file, "\nEND %s.\n", m3wrap_name); - Delete(file); - } - - // Generate the wrapper routines implemented in Modula 3 - { - File *file = openWriteFile(NewStringf("%s%s.m3", SWIG_output_directory(), m3wrap_name)); - - emitBanner(file); - - if (unsafe_module) { - Printf(file, "UNSAFE "); - } - Printf(file, "MODULE %s;\n\n", m3wrap_name); - - emitImportStatements(m3wrap_impl.import, file); - Printf(file, "\n"); - - // Add the wrapper methods - Printv(file, m3wrap_impl.f, NIL); - - Printf(file, "\nBEGIN\nEND %s.\n", m3wrap_name); - Delete(file); - } - - if (upcasts_code) - Printv(f_wrappers, upcasts_code, NIL); - - Printf(f_wrappers, "#ifdef __cplusplus\n"); - Printf(f_wrappers, "}\n"); - Printf(f_wrappers, "#endif\n"); - - // Output a Modula 3 type wrapper class for each SWIG type - for (Iterator swig_type = First(swig_types_hash); swig_type.item != NIL; swig_type = Next(swig_type)) { - emitTypeWrapperClass(swig_type.key, swig_type.item); - } - - Delete(swig_types_hash); - swig_types_hash = NULL; - Delete(constant_values); - constant_values = NULL; - Delete(enumeration_coll); - enumeration_coll = NULL; - Delete(m3raw_name); - m3raw_name = NULL; - Delete(m3raw_baseclass); - m3raw_baseclass = NULL; - Delete(m3raw_interfaces); - m3raw_interfaces = NULL; - Delete(m3raw_class_modifiers); - m3raw_class_modifiers = NULL; - Delete(m3raw_imports); - m3raw_imports = NULL; - Delete(m3raw_cppcasts_code); - m3raw_cppcasts_code = NULL; - Delete(proxy_class_def); - proxy_class_def = NULL; - Delete(proxy_class_code); - proxy_class_code = NULL; - Delete(m3wrap_name); - m3wrap_name = NULL; - Delete(m3wrap_modifiers); - m3wrap_modifiers = NULL; - Delete(targetlibrary); - targetlibrary = NULL; - Delete(module_baseclass); - module_baseclass = NULL; - Delete(module_interfaces); - module_interfaces = NULL; - Delete(module_imports); - module_imports = NULL; - Delete(upcasts_code); - upcasts_code = NULL; - Delete(constantfilename); - constantfilename = NULL; - Delete(renamefilename); - renamefilename = NULL; - Delete(typemapfilename); - typemapfilename = NULL; - - /* Close all of the files */ - Dump(f_runtime, f_begin); - Dump(f_header, f_begin); - Dump(f_wrappers, f_begin); - Wrapper_pretty_print(f_init, f_begin); - Delete(f_header); - Delete(f_wrappers); - Delete(f_init); - Delete(f_runtime); - Delete(f_begin); - return SWIG_OK; - } - - /* ----------------------------------------------------------------------------- - * emitBanner() - * ----------------------------------------------------------------------------- */ - - void emitBanner(File *f) { - Printf(f, "(*******************************************************************************\n"); - Swig_banner_target_lang(f, " *"); - Printf(f, "*******************************************************************************)\n\n"); - } - - /* ---------------------------------------------------------------------- - * nativeWrapper() - * ---------------------------------------------------------------------- */ - - virtual int nativeWrapper(Node *n) { - String *wrapname = Getattr(n, "wrap:name"); - - if (!addSymbol(wrapname, n)) - return SWIG_ERROR; - - if (Getattr(n, "type")) { - Swig_save("nativeWrapper", n, "name", NIL); - Setattr(n, "name", wrapname); - native_function_flag = true; - functionWrapper(n); - Swig_restore(n); - native_function_flag = false; - } else { - Swig_error(input_file, line_number, "No return type for %%native method %s.\n", Getattr(n, "wrap:name")); - } - - return SWIG_OK; - } - - /* ---------------------------------------------------------------------- - * functionWrapper() - * ---------------------------------------------------------------------- */ - - virtual int functionWrapper(Node *n) { - String *type = nodeType(n); - String *funcType = Getattr(n, "modula3:functype"); - String *rawname = Getattr(n, "name"); - String *symname = Getattr(n, "sym:name"); - String *capname = capitalizeFirst(symname); - //String *wname = Swig_name_wrapper(symname); - - //printf("function: %s\n", Char(symname)); - //printf(" purpose: %s\n", Char(funcType)); - - if (Strcmp(type, "cdecl") == 0) { - if (funcType == NIL) { - // no wrapper needed for plain functions - emitM3RawPrototype(n, rawname, symname); - emitM3Wrapper(n, symname); - } else if (Strcmp(funcType, "method") == 0) { - Setattr(n, "modula3:funcname", capname); - emitCWrapper(n, capname); - emitM3RawPrototype(n, capname, capname); - emitM3Wrapper(n, capname); - } else if (Strcmp(funcType, "accessor") == 0) { - /* - * Generate the proxy class properties for public member variables. - * Not for enums and constants. - */ - if (proxy_flag && wrapping_member_flag && !enum_constant_flag) { - // Capitalize the first letter in the function name - Setattr(n, "proxyfuncname", capname); - Setattr(n, "imfuncname", symname); - if (hasPrefix(capname, "Set")) { - Setattr(n, "modula3:setname", capname); - } else { - Setattr(n, "modula3:getname", capname); - } - - emitCWrapper(n, capname); - emitM3RawPrototype(n, capname, capname); - emitM3Wrapper(n, capname); - //proxyClassFunctionHandler(n); - } -#ifdef DEBUG - } else { - Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Function type <%s> unknown.\n", Char(funcType)); -#endif - } - } else if ((Strcmp(type, "constructor") == 0) || (Strcmp(type, "destructor") == 0)) { - emitCWrapper(n, capname); - emitM3RawPrototype(n, capname, capname); - emitM3Wrapper(n, capname); - } -// a Java relict -#if 0 - if (!(proxy_flag && is_wrapping_class()) && !enum_constant_flag) { - emitM3Wrapper(n, capname); - } -#endif - - Delete(capname); - - return SWIG_OK; - } - - /* ---------------------------------------------------------------------- - * emitCWrapper() - * - * Generate the wrapper in C which calls C++ methods. - * ---------------------------------------------------------------------- */ - - virtual int emitCWrapper(Node *n, const String *wname) { - String *rawname = Getattr(n, "name"); - String *c_return_type = NewString(""); - String *cleanup = NewString(""); - String *outarg = NewString(""); - String *body = NewString(""); - Hash *throws_hash = NewHash(); - ParmList *l = Getattr(n, "parms"); - SwigType *t = Getattr(n, "type"); - String *symname = Getattr(n, "sym:name"); - - if (!Getattr(n, "sym:overloaded")) { - if (!addSymbol(wname, n)) { - return SWIG_ERROR; - } - } - // A new wrapper function object - Wrapper *f = NewWrapper(); - - /* Attach the non-standard typemaps to the parameter list. */ - Swig_typemap_attach_parms("ctype", l, f); - - /* Get return types */ - { - String *tm = getMappedTypeNew(n, "ctype", ""); - if (tm != NIL) { - Printf(c_return_type, "%s", tm); - } - } - - bool is_void_return = (Cmp(c_return_type, "void") == 0); - if (!is_void_return) { - Wrapper_add_localv(f, "cresult", c_return_type, "cresult = 0", NIL); - } - - Printv(f->def, " SWIGEXPORT ", c_return_type, " ", wname, "(", NIL); - - // Emit all of the local variables for holding arguments. - emit_parameter_variables(l, f); - - /* Attach the standard typemaps */ - emit_attach_parmmaps(l, f); - Setattr(n, "wrap:parms", l); - - // Generate signature and argument conversion for C wrapper - { - Parm *p; - attachParameterNames(n, "tmap:name", "c:wrapname", "m3arg%d"); - bool gencomma = false; - for (p = skipIgnored(l, "in"); p; p = skipIgnored(p, "in")) { - - String *arg = Getattr(p, "c:wrapname"); - { - /* Get the ctype types of the parameter */ - String *c_param_type = getMappedType(p, "ctype"); - // Add parameter to C function - Printv(f->def, gencomma ? ", " : "", c_param_type, " ", arg, NIL); - Delete(c_param_type); - gencomma = true; - } - - // Get typemap for this argument - String *tm = getMappedType(p, "in"); - if (tm != NIL) { - addThrows(throws_hash, "in", p); - Replaceall(tm, "$input", arg); - Setattr(p, "emit:input", arg); /*??? */ - Printf(f->code, "%s\n", tm); - p = Getattr(p, "tmap:in:next"); - } else { - p = nextSibling(p); - } - } - } - - /* Insert constraint checking code */ - { - Parm *p; - for (p = l; p;) { - String *tm = Getattr(p, "tmap:check"); - if (tm != NIL) { - addThrows(throws_hash, "check", p); - Replaceall(tm, "$target", Getattr(p, "lname")); /* deprecated */ - Replaceall(tm, "$arg", Getattr(p, "emit:input")); /* deprecated? */ - Replaceall(tm, "$input", Getattr(p, "emit:input")); - Printv(f->code, tm, "\n", NIL); - p = Getattr(p, "tmap:check:next"); - } else { - p = nextSibling(p); - } - } - } - - /* Insert cleanup code */ - { - Parm *p; - for (p = l; p;) { - String *tm = Getattr(p, "tmap:freearg"); - if (tm != NIL) { - addThrows(throws_hash, "freearg", p); - Replaceall(tm, "$source", Getattr(p, "emit:input")); /* deprecated */ - Replaceall(tm, "$arg", Getattr(p, "emit:input")); /* deprecated? */ - Replaceall(tm, "$input", Getattr(p, "emit:input")); - Printv(cleanup, tm, "\n", NIL); - p = Getattr(p, "tmap:freearg:next"); - } else { - p = nextSibling(p); - } - } - } - - /* Insert argument output code */ - { - Parm *p; - for (p = l; p;) { - String *tm = Getattr(p, "tmap:argout"); - if (tm != NIL) { - addThrows(throws_hash, "argout", p); - Replaceall(tm, "$source", Getattr(p, "emit:input")); /* deprecated */ - Replaceall(tm, "$target", Getattr(p, "lname")); /* deprecated */ - Replaceall(tm, "$arg", Getattr(p, "emit:input")); /* deprecated? */ - Replaceall(tm, "$result", "cresult"); - Replaceall(tm, "$input", Getattr(p, "emit:input")); - Printv(outarg, tm, "\n", NIL); - p = Getattr(p, "tmap:argout:next"); - } else { - p = nextSibling(p); - } - } - } - - // Get any Modula 3 exception classes in the throws typemap - ParmList *throw_parm_list = NULL; - if ((throw_parm_list = Getattr(n, "catchlist"))) { - Swig_typemap_attach_parms("throws", throw_parm_list, f); - Parm *p; - for (p = throw_parm_list; p; p = nextSibling(p)) { - addThrows(throws_hash, "throws", p); - } - } - - Setattr(n, "wrap:name", wname); - - // Now write code to make the function call - if (!native_function_flag) { - String *actioncode = emit_action(n); - - /* Return value if necessary */ - String *tm; - if ((tm = Swig_typemap_lookup_out("out", n, Swig_cresult_name(), f, actioncode))) { - addThrows(throws_hash, "out", n); - Replaceall(tm, "$source", Swig_cresult_name()); /* deprecated */ - Replaceall(tm, "$target", "cresult"); /* deprecated */ - Replaceall(tm, "$result", "cresult"); - Printf(f->code, "%s", tm); - if (hasContent(tm)) - Printf(f->code, "\n"); - } else { - Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(t, 0), rawname); - } - emit_return_variable(n, t, f); - } - - /* Output argument output code */ - Printv(f->code, outarg, NIL); - - /* Output cleanup code */ - Printv(f->code, cleanup, NIL); - - /* Look to see if there is any newfree cleanup code */ - if (GetFlag(n, "feature:new")) { - String *tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0); - if (tm != NIL) { - addThrows(throws_hash, "newfree", n); - Replaceall(tm, "$source", Swig_cresult_name()); /* deprecated */ - Printf(f->code, "%s\n", tm); - } - } - - /* See if there is any return cleanup code */ - if (!native_function_flag) { - String *tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0); - if (tm != NIL) { - Replaceall(tm, "$source", Swig_cresult_name()); /* deprecated */ - Printf(f->code, "%s\n", tm); - } - } - - /* Finish C wrapper */ - Printf(f->def, ") {"); - - if (!is_void_return) - Printv(f->code, " return cresult;\n", NIL); - Printf(f->code, "}\n"); - - /* Substitute the cleanup code */ - Replaceall(f->code, "$cleanup", cleanup); - - /* Substitute the function name */ - Replaceall(f->code, "$symname", symname); - - if (!is_void_return) { - Replaceall(f->code, "$null", "0"); - } else { - Replaceall(f->code, "$null", ""); - } - - /* Dump the function out */ - if (!native_function_flag) { - Wrapper_print(f, f_wrappers); - } - - Delete(c_return_type); - Delete(cleanup); - Delete(outarg); - Delete(body); - Delete(throws_hash); - DelWrapper(f); - return SWIG_OK; - } - - /* ---------------------------------------------------------------------- - * emitM3RawPrototype() - * - * Generate an EXTERNAL procedure declaration in Modula 3 - * which is the interface to an existing C routine or a C wrapper. - * ---------------------------------------------------------------------- */ - - virtual int emitM3RawPrototype(Node *n, const String *cname, const String *m3name) { - String *im_return_type = NewString(""); - //String *symname = Getattr(n,"sym:name"); - ParmList *l = Getattr(n, "parms"); - - /* Attach the non-standard typemaps to the parameter list. */ - Swig_typemap_attach_parms("m3rawinmode", l, NULL); - Swig_typemap_attach_parms("m3rawintype", l, NULL); - - /* Get return types */ - bool has_return; - { - String *tm = getMappedTypeNew(n, "m3rawrettype", ""); - if (tm != NIL) { - Printf(im_return_type, "%s", tm); - } - has_return = hasContent(tm); - } - - /* cname is the original name if 'n' denotes a C function - and it is the relabeled name (sym:name) if 'n' denotes a C++ method or similar */ - m3raw_intf.enterBlock(no_block); - Printf(m3raw_intf.f, "\n<* EXTERNAL %s *>\nPROCEDURE %s (", cname, m3name); - - // Generate signature for raw interface - { - Parm *p; - writeArgState state; - attachParameterNames(n, "tmap:rawinname", "modula3:rawname", "arg%d"); - for (p = skipIgnored(l, "m3rawintype"); p; p = skipIgnored(p, "m3rawintype")) { - - /* Get argument passing mode, should be one of VALUE, VAR, READONLY */ - String *mode = Getattr(p, "tmap:m3rawinmode"); - String *argname = Getattr(p, "modula3:rawname"); - String *im_param_type = getMappedType(p, "m3rawintype"); - addImports(m3raw_intf.import, "m3rawintype", p); - - writeArg(m3raw_intf.f, state, mode, argname, im_param_type, NIL); - if (im_param_type != NIL) { - p = Getattr(p, "tmap:m3rawintype:next"); - } else { - p = nextSibling(p); - } - } - writeArg(m3raw_intf.f, state, NIL, NIL, NIL, NIL); - } - - /* Finish M3 raw prototype */ - Printf(m3raw_intf.f, ")"); - // neither a C wrapper nor a plain C function may throw an exception - //generateThrowsClause(throws_hash, m3raw_intf.f); - if (has_return) { - Printf(m3raw_intf.f, ": %s", im_return_type); - } - Printf(m3raw_intf.f, ";\n"); - - Delete(im_return_type); - return SWIG_OK; - } - - /* ----------------------------------------------------------------------- - * variableWrapper() - * ----------------------------------------------------------------------- */ - - virtual int variableWrapper(Node *n) { - Language::variableWrapper(n); - return SWIG_OK; - } - - /* ----------------------------------------------------------------------- - * globalvariableHandler() - * ----------------------------------------------------------------------- */ - - virtual int globalvariableHandler(Node *n) { - SwigType *t = Getattr(n, "type"); - String *tm; - - // Get the variable type - if ((tm = getMappedTypeNew(n, "m3wraptype", ""))) { - substituteClassname(t, tm); - } - - variable_name = Getattr(n, "sym:name"); - variable_type = Copy(tm); - - // Get the variable type expressed in terms of Modula 3 equivalents of C types - if ((tm = getMappedTypeNew(n, "m3rawtype", ""))) { - m3raw_intf.enterBlock(no_block); - Printf(m3raw_intf.f, "\n<* EXTERNAL *> VAR %s: %s;\n", variable_name, tm); - } - // Output the property's accessor methods - /* - global_variable_flag = true; - int ret = Language::globalvariableHandler(n); - global_variable_flag = false; - */ - - Printf(m3wrap_impl.f, "\n\n"); - - //return ret; - return 1; - } - - long getConstNumeric(Node *n) { - String *constnumeric = Getfeature(n, "constnumeric"); - String *name = Getattr(n, "name"); - long numvalue; - if (constnumeric == NIL) { - Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Feature 'constnumeric' is necessary to obtain value of %s.\n", name); - return 0; - } else if (!strToL(constnumeric, numvalue)) { - Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, - "The feature 'constnumeric' of %s specifies value <%s> which is not an integer constant.\n", name, constnumeric); - return 0; - } else { - return numvalue; - } - } - - /* ------------------------------------------------------------------------ - * generateIntConstant() - * - * Considers node as an integer constant definition - * and generate a Modula 3 constant definition. - * ------------------------------------------------------------------------ */ - void generateIntConstant(Node *n, String *name) { - String *value = Getattr(n, "value"); - String *type = Getfeature(n, "modula3:constint:type"); - String *conv = Getfeature(n, "modula3:constint:conv"); - - if (name == NIL) { - name = Getattr(n, "sym:name"); - } - - long numvalue; - bool isSimpleNum = strToL(value, numvalue); - if (!isSimpleNum) { - numvalue = getConstNumeric(n); - } - - String *m3value; - if ((conv == NIL) || ((Strcmp(conv, "set:int") != 0) && (Strcmp(conv, "int:set") != 0))) { - /* The original value of the constant has precedence over - 'constnumeric' feature since we like to keep - the style (that is the base) of simple numeric constants */ - if (isSimpleNum) { - if (hasPrefix(value, "0x")) { - m3value = NewStringf("16_%s", Char(value) + 2); - } else if ((Len(value) > 1) && (*Char(value) == '0')) { - m3value = NewStringf("8_%s", Char(value) + 1); - } else { - m3value = Copy(value); - } - /* If we cannot easily obtain the value of a numeric constant, - we use the results given by a C compiler. */ - } else { - m3value = Copy(Getfeature(n, "constnumeric")); - } - } else { - // if the value can't be converted, it is ignored - if (convertInt(numvalue, numvalue, conv)) { - m3value = NewStringf("%d", numvalue); - } else { - m3value = NIL; - } - } - - if (m3value != NIL) { - m3wrap_intf.enterBlock(constant); - Printf(m3wrap_intf.f, "%s", name); - if (hasContent(type)) { - Printf(m3wrap_intf.f, ": %s", type); - } - Printf(m3wrap_intf.f, " = %s;\n", m3value); - Delete(m3value); - } - } - - /* ----------------------------------------------------------------------- - * generateSetConstant() - * - * Considers node as a set constant definition - * and generate a Modula 3 constant definition. - * ------------------------------------------------------------------------ */ - void generateSetConstant(Node *n, String *name) { - String *value = Getattr(n, "value"); - String *type = Getfeature(n, "modula3:constset:type"); - String *setname = Getfeature(n, "modula3:constset:set"); - String *basename = Getfeature(n, "modula3:constset:base"); - String *conv = Getfeature(n, "modula3:constset:conv"); - - m3wrap_intf.enterBlock(constant); - - Printf(m3wrap_intf.f, "%s", name); - if (type != NIL) { - Printf(m3wrap_intf.f, ":%s ", type); - } - Printf(m3wrap_intf.f, " = %s{", setname); - - long numvalue = 0; - if (!strToL(value, numvalue)) { - numvalue = getConstNumeric(n); - } - convertInt(numvalue, numvalue, conv); - - bool isIntType = Strcmp(basename, "CARDINAL") == 0; - Hash *items = NIL; - if (!isIntType) { - Hash *enumeration = Getattr(enumeration_coll, basename); - if (enumeration == NIL) { - Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "There is no enumeration <%s> as needed for the set.\n", setname); - isIntType = true; - } else { - items = Getattr(enumeration, "items"); - } - } - - bool gencomma = false; - int bitpos = 0; - while (numvalue > 0) { - if ((numvalue & 1) != 0) { - if (isIntType) { - if (gencomma) { - Printv(m3wrap_intf.f, ",", NIL); - } - gencomma = true; - Printf(m3wrap_intf.f, "%d", bitpos); - } else { - char bitval[15]; - sprintf(bitval, "%d", bitpos); - String *bitname = Getattr(items, bitval); - if (bitname == NIL) { - Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Enumeration <%s> has no value <%s>.\n", setname, bitval); - } else { - if (gencomma) { - Printv(m3wrap_intf.f, ",", NIL); - } - gencomma = true; - Printf(m3wrap_intf.f, "%s.%s", basename, bitname); - } - } - } - numvalue >>= 1; - bitpos++; - } - Printf(m3wrap_intf.f, "};\n"); - } - - void generateConstant(Node *n) { - // any of the special interpretation disables the default behaviour - String *enumitem = Getfeature(n, "modula3:enumitem:name"); - String *constset = Getfeature(n, "modula3:constset:name"); - String *constint = Getfeature(n, "modula3:constint:name"); - if (hasContent(enumitem) || hasContent(constset) || hasContent(constint)) { - if (hasContent(constset)) { - generateSetConstant(n, constset); - } - if (hasContent(constint)) { - generateIntConstant(n, constint); - } - } else { - String *value = Getattr(n, "value"); - String *name = Getattr(n, "sym:name"); - if (name == NIL) { - name = Getattr(n, "name"); - } - m3wrap_intf.enterBlock(constant); - Printf(m3wrap_intf.f, "%s = %s;\n", name, value); - } - } - - void emitEnumeration(File *file, String *name, Node *n) { - Printf(file, "%s = {", name); - int i; - bool gencomma = false; - int max = aToL(Getattr(n, "max")); - Hash *items = Getattr(n, "items"); - for (i = 0; i <= max; i++) { - if (gencomma) { - Printf(file, ","); - } - Printf(file, "\n"); - gencomma = true; - char numstr[15]; - sprintf(numstr, "%d", i); - String *name = Getattr(items, numstr); - if (name != NIL) { - Printv(file, name, NIL); - } else { - Printf(file, "Dummy%d", i); - } - } - Printf(file, "\n};\n"); - } - - /* ----------------------------------------------------------------------- - * constantWrapper() - * - * Handles constants and enumeration items. - * ------------------------------------------------------------------------ */ - - virtual int constantWrapper(Node *n) { - generateConstant(n); - return SWIG_OK; - } - -#if 0 -// enumerations are handled like constant definitions - /* ----------------------------------------------------------------------------- - * enumDeclaration() - * ----------------------------------------------------------------------------- */ - - virtual int enumDeclaration(Node *n) { - String *symname = nameToModula3(Getattr(n, "sym:name"), true); - enumerationStart(symname); - int result = Language::enumDeclaration(n); - enumerationStop(); - Delete(symname); - return result; - } -#endif - - /* ----------------------------------------------------------------------------- - * enumvalueDeclaration() - * ----------------------------------------------------------------------------- */ - - virtual int enumvalueDeclaration(Node *n) { - generateConstant(n); - /* - This call would continue processing in the constantWrapper - which cannot handle values like "RED+1". - return Language::enumvalueDeclaration(n); - */ - return SWIG_OK; - } - - /* ----------------------------------------------------------------------------- - * pragmaDirective() - * - * Valid Pragmas: - * imclassbase - base (extends) for the intermediary class - * imclassclassmodifiers - class modifiers for the intermediary class - * imclasscode - text (Modula 3 code) is copied verbatim to the intermediary class - * imclassimports - import statements for the intermediary class - * imclassinterfaces - interface (implements) for the intermediary class - * - * modulebase - base (extends) for the module class - * moduleclassmodifiers - class modifiers for the module class - * modulecode - text (Modula 3 code) is copied verbatim to the module class - * moduleimports - import statements for the module class - * moduleinterfaces - interface (implements) for the module class - * - * ----------------------------------------------------------------------------- */ - - virtual int pragmaDirective(Node *n) { - if (!ImportMode) { - String *lang = Getattr(n, "lang"); - String *code = Getattr(n, "name"); - String *value = Getattr(n, "value"); - - if (Strcmp(lang, "modula3") == 0) { - - String *strvalue = NewString(value); - Replaceall(strvalue, "\\\"", "\""); -/* - bool isEnumItem = Strcmp(code, "enumitem") == 0; - bool isSetItem = Strcmp(code, "setitem") == 0; -*/ - if (Strcmp(code, "imclassbase") == 0) { - Delete(m3raw_baseclass); - m3raw_baseclass = Copy(strvalue); - } else if (Strcmp(code, "imclassclassmodifiers") == 0) { - Delete(m3raw_class_modifiers); - m3raw_class_modifiers = Copy(strvalue); - } else if (Strcmp(code, "imclasscode") == 0) { - Printf(m3raw_intf.f, "%s\n", strvalue); - } else if (Strcmp(code, "imclassimports") == 0) { - Delete(m3raw_imports); - m3raw_imports = Copy(strvalue); - } else if (Strcmp(code, "imclassinterfaces") == 0) { - Delete(m3raw_interfaces); - m3raw_interfaces = Copy(strvalue); - } else if (Strcmp(code, "modulebase") == 0) { - Delete(module_baseclass); - module_baseclass = Copy(strvalue); - } else if (Strcmp(code, "moduleclassmodifiers") == 0) { - Delete(m3wrap_modifiers); - m3wrap_modifiers = Copy(strvalue); - } else if (Strcmp(code, "modulecode") == 0) { - Printf(m3wrap_impl.f, "%s\n", strvalue); - } else if (Strcmp(code, "moduleimports") == 0) { - Delete(module_imports); - module_imports = Copy(strvalue); - } else if (Strcmp(code, "moduleinterfaces") == 0) { - Delete(module_interfaces); - module_interfaces = Copy(strvalue); - } else if (Strcmp(code, "unsafe") == 0) { - unsafe_module = true; - } else if (Strcmp(code, "library") == 0) { - if (targetlibrary) { - Delete(targetlibrary); - } - targetlibrary = Copy(strvalue); - } else if (Strcmp(code, "enumitem") == 0) { - } else if (Strcmp(code, "constset") == 0) { - } else if (Strcmp(code, "constint") == 0) { - } else if (Strcmp(code, "makesetofenum") == 0) { - m3wrap_intf.enterBlock(blocktype); - Printf(m3wrap_intf.f, "%sSet = SET OF %s;\n", value, value); - } else { - Swig_warning(WARN_MODULA3_UNKNOWN_PRAGMA, input_file, line_number, "Unrecognized pragma <%s>.\n", code); - } - Delete(strvalue); - } - } - return Language::pragmaDirective(n); - } - - void Setfeature(Node *n, const char *feature, const String *value, bool warn = false) { - //printf("tag feature <%s> with value <%s>\n", feature, Char(value)); - String *attr = NewStringf("feature:%s", feature); - if ((Setattr(n, attr, value) != 0) && warn) { - Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Feature <%s> of %s did already exist.\n", feature, Getattr(n, "name")); - } - Delete(attr); - } - - String *Getfeature(Node *n, const char *feature) { - //printf("retrieve feature <%s> with value <%s>\n", feature, Char(value)); - String *attr = NewStringf("feature:%s", feature); - String *result = Getattr(n, attr); - Delete(attr); - return result; - } - - bool convertInt(long in, long &out, const String *mode) { - if ((mode == NIL) || (Strcmp(mode, "int:int") == 0) || (Strcmp(mode, "set:set") == 0)) { - out = in; - return true; - } else if (Strcmp(mode, "set:int") == 0) { - return log2(in, out); - } else if (Strcmp(mode, "int:set") == 0) { - out = 1L << in; - return unsigned (in) < (sizeof(out) * 8); - } else { - Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Unknown integer conversion method <%s>.\n", mode); - return false; - } - } - - void collectEnumerations(Hash *enums, Node *n) { - Node *child = firstChild(n); - while (child != NIL) { - String *name = Getattr(child, "name"); - const bool isConstant = Strcmp(nodeType(child), "constant") == 0; - const bool isEnumItem = Strcmp(nodeType(child), "enumitem") == 0; - if (isConstant || isEnumItem) { -//printf("%s%s name %s\n", isConstant?"constant":"", isEnumItem?"enumitem":"", Char(name)); - { - String *m3name = Getfeature(child, "modula3:enumitem:name"); - String *m3enum = Getfeature(child, "modula3:enumitem:enum"); - String *conv = Getfeature(child, "modula3:enumitem:conv"); - - if (m3enum != NIL) { -//printf("m3enum %s\n", Char(m3enum)); - if (m3name == NIL) { - m3name = name; - } - - long max = -1; - Hash *items; - Hash *enumnode = Getattr(enums, m3enum); - if (enumnode == NIL) { - enumnode = NewHash(); - items = NewHash(); - Setattr(enumnode, "items", items); - Setattr(enums, m3enum, enumnode); - } else { - String *maxstr = Getattr(enumnode, "max"); - if (maxstr != NIL) { - max = aToL(maxstr); - } - items = Getattr(enumnode, "items"); - } - long numvalue; - String *value = Getattr(child, "value"); -//printf("value: %s\n", Char(value)); - if ((value == NIL) || (!strToL(value, numvalue))) { - value = Getattr(child, "enumvalue"); - if ((value == NIL) || (!evalExpr(value, numvalue))) { - numvalue = getConstNumeric(child); - } -//printf("constnumeric: %s\n", Char(value)); - } - Setattr(constant_values, name, NewStringf("%d", numvalue)); - if (convertInt(numvalue, numvalue, conv)) { - String *newvalue = NewStringf("%d", numvalue); - String *oldname = Getattr(items, newvalue); - if (oldname != NIL) { - Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "The value <%s> is already assigned to <%s>.\n", value, oldname); - } -//printf("items %p, set %s = %s\n", items, Char(newvalue), Char(m3name)); - Setattr(items, newvalue, m3name); - if (max < numvalue) { - max = numvalue; - } - Setattr(enumnode, "max", NewStringf("%d", max)); - } - } - } - } - - collectEnumerations(enums, child); - child = nextSibling(child); - } - } - - enum const_pragma_type { cpt_none, cpt_constint, cpt_constset, cpt_enumitem }; - - struct const_id_pattern { - String *prefix, *parentEnum; - }; - - void tagConstants(Node *first, String *parentEnum, const const_id_pattern & pat, const String *pragma, List *convdesc) { - Node *n = first; - while (n != NIL) { - String *name = getQualifiedName(n); - bool isConstant = Strcmp(nodeType(n), "constant") == 0; - bool isEnumItem = Strcmp(nodeType(n), "enumitem") == 0; - if ((isConstant || isEnumItem) && ((pat.prefix == NIL) || (hasPrefix(name, pat.prefix))) && ((pat.parentEnum == NIL) || ((parentEnum != NIL) - && - (Strcmp - (pat.parentEnum, parentEnum) - == 0)))) { - //printf("tag %s\n", Char(name)); - String *srctype = Getitem(convdesc, 1); - String *relationstr = Getitem(convdesc, 3); - List *relationdesc = Split(relationstr, ',', 2); - - // transform name from C to Modula3 style - String *srcstyle = NIL; - String *newprefix = NIL; - { - //printf("name conversion <%s>\n", Char(Getitem(convdesc,2))); - List *namedesc = Split(Getitem(convdesc, 2), ',', INT_MAX); - Iterator nameit = First(namedesc); - for (; nameit.item != NIL; nameit = Next(nameit)) { - List *nameassign = Split(nameit.item, '=', 2); - String *tag = Getitem(nameassign, 0); - String *data = Getitem(nameassign, 1); - //printf("name conv <%s> = <%s>\n", Char(tag), Char(data)); - if (Strcmp(tag, "srcstyle") == 0) { - srcstyle = Copy(data); - } else if (Strcmp(tag, "prefix") == 0) { - newprefix = Copy(data); - } else { - Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Unknown name conversion tag <%s> with value <%s>.\n", tag, data); - } - Delete(nameassign); - } - Delete(namedesc); - } - const char *stem = Char(name); - if (pat.prefix != NIL) { - //printf("pat.prefix %s for %s\n", Char(pat.prefix), Char(name)); - stem += Len(pat.prefix); - } - String *newname; - if (srcstyle && Strcmp(srcstyle, "underscore") == 0) { - if (newprefix != NIL) { - String *newstem = nameToModula3(stem, true); - newname = NewStringf("%s%s", newprefix, newstem); - Delete(newstem); - } else { - newname = nameToModula3(stem, true); - } - } else { - if (srcstyle != NIL) { - Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Unknown C identifier style <%s>.\n", srcstyle); - } - newname = Copy(name); - } - - if (Strcmp(pragma, "enumitem") == 0) { - if (Len(relationdesc) != 1) { - Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Expected , got <%s>.\n", relationstr); - } - Setfeature(n, "modula3:enumitem:name", newname, true); - Setfeature(n, "modula3:enumitem:enum", relationstr, true); - Setfeature(n, "modula3:enumitem:conv", NewStringf("%s:int", srctype), true); - } else if (Strcmp(pragma, "constint") == 0) { - if (Len(relationdesc) != 1) { - Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Expected , got <%s>.\n", relationstr); - } - Setfeature(n, "modula3:constint:name", newname, true); - Setfeature(n, "modula3:constint:type", Getitem(relationdesc, 0), true); - Setfeature(n, "modula3:constint:conv", NewStringf("%s:int", srctype), true); - } else if (Strcmp(pragma, "constset") == 0) { - if (Len(relationdesc) != 2) { - Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Expected , got <%s>.\n", relationstr); - } - String *settype = Getitem(relationdesc, 0); - Setfeature(n, "modula3:constset:name", newname, true); - //Setfeature(n,"modula3:constset:type",settype,true); - Setfeature(n, "modula3:constset:set", settype, true); - Setfeature(n, "modula3:constset:base", Getitem(relationdesc, 1), true); - Setfeature(n, "modula3:constset:conv", NewStringf("%s:set", srctype), true); - } - - Delete(newname); - Delete(relationdesc); - } - - if (Strcmp(nodeType(n), "enum") == 0) { - //printf("explore enum %s, qualification %s\n", Char(name), Char(Swig_symbol_qualified(n))); - tagConstants(firstChild(n), name, pat, pragma, convdesc); - } else { - tagConstants(firstChild(n), NIL, pat, pragma, convdesc); - } - n = nextSibling(n); - } - } - - void scanForConstPragmas(Node *n) { - Node *child = firstChild(n); - while (child != NIL) { - const String *type = nodeType(child); - if (Strcmp(type, "pragma") == 0) { - const String *lang = Getattr(child, "lang"); - const String *code = Getattr(child, "name"); - String *value = Getattr(child, "value"); - - if (Strcmp(lang, "modula3") == 0) { - const_pragma_type cpt = cpt_none; - if (Strcmp(code, "constint") == 0) { - cpt = cpt_constint; - } else if (Strcmp(code, "constset") == 0) { - cpt = cpt_constset; - } else if (Strcmp(code, "enumitem") == 0) { - cpt = cpt_enumitem; - } - if (cpt != cpt_none) { - const_id_pattern pat = { NIL, NIL }; - - List *convdesc = Split(value, ';', 4); - List *patterndesc = Split(Getitem(convdesc, 0), ',', INT_MAX); - Iterator patternit; - for (patternit = First(patterndesc); patternit.item != NIL; patternit = Next(patternit)) { - List *patternassign = Split(patternit.item, '=', 2); - String *tag = Getitem(patternassign, 0); - String *data = Getitem(patternassign, 1); - if (Strcmp(tag, "prefix") == 0) { - pat.prefix = Copy(data); - } else if (Strcmp(tag, "enum") == 0) { - pat.parentEnum = Copy(data); - } else { - Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Unknown identification tag <%s> with value <%s>.\n", tag, data); - } - Delete(patternassign); - } - tagConstants(child, NIL, pat, code, convdesc); - - Delete(patterndesc); - } - } - } - scanForConstPragmas(child); - child = nextSibling(child); - } - } - - /* ----------------------------------------------------------------------------- - * emitProxyClassDefAndCPPCasts() - * ----------------------------------------------------------------------------- */ - - void emitProxyClassDefAndCPPCasts(Node *n) { - String *c_classname = SwigType_namestr(Getattr(n, "name")); - String *c_baseclass = NULL; - String *baseclass = NULL; - String *c_baseclassname = NULL; - String *name = Getattr(n, "name"); - - /* Deal with inheritance */ - List *baselist = Getattr(n, "bases"); - if (baselist) { - Iterator base = First(baselist); - while (base.item) { - if (!GetFlag(base.item, "feature:ignore")) { - String *baseclassname = Getattr(base.item, "name"); - if (!c_baseclassname) { - c_baseclassname = baseclassname; - baseclass = Copy(getProxyName(baseclassname)); - if (baseclass) - c_baseclass = SwigType_namestr(baseclassname); - } else { - /* Warn about multiple inheritance for additional base class(es) */ - String *proxyclassname = Getattr(n, "classtypeobj"); - Swig_warning(WARN_MODULA3_MULTIPLE_INHERITANCE, Getfile(n), Getline(n), - "Warning for %s, base %s ignored. Multiple inheritance is not supported in Modula 3.\n", SwigType_namestr(proxyclassname), SwigType_namestr(baseclassname)); - } - } - base = Next(base); - } - } - - bool derived = baseclass && getProxyName(c_baseclassname); - if (!baseclass) - baseclass = NewString(""); - - // Inheritance from pure Modula 3 classes - const String *pure_baseclass = typemapLookup(n, "m3base", name, WARN_NONE); - if (hasContent(pure_baseclass) && hasContent(baseclass)) { - Swig_warning(WARN_MODULA3_MULTIPLE_INHERITANCE, Getfile(n), Getline(n), - "Warning for %s, base %s ignored. Multiple inheritance is not supported in Modula 3.\n", name, pure_baseclass); - } - // Pure Modula 3 interfaces - const String *pure_interfaces = typemapLookup(n, derived ? "m3interfaces_derived" : "m3interfaces", - name, WARN_NONE); - - // Start writing the proxy class - Printv(proxy_class_def, typemapLookup(n, "m3imports", name, WARN_NONE), // Import statements - "\n", typemapLookup(n, "m3classmodifiers", name, WARN_MODULA3_TYPEMAP_CLASSMOD_UNDEF), // Class modifiers - " class $m3classname", // Class name and bases - (derived || *Char(pure_baseclass) || *Char(pure_interfaces)) ? " : " : "", baseclass, pure_baseclass, ((derived || *Char(pure_baseclass)) && *Char(pure_interfaces)) ? // Interfaces - ", " : "", pure_interfaces, " {\n", " private IntPtr swigCPtr;\n", // Member variables for memory handling - derived ? "" : " protected bool swigCMemOwn;\n", "\n", " ", typemapLookup(n, "m3ptrconstructormodifiers", name, WARN_MODULA3_TYPEMAP_PTRCONSTMOD_UNDEF), // pointer constructor modifiers - " $m3classname(IntPtr cPtr, bool cMemoryOwn) ", // Constructor used for wrapping pointers - derived ? - ": base($imclassname.$m3classnameTo$baseclass(cPtr), cMemoryOwn) {\n" - : "{\n swigCMemOwn = cMemoryOwn;\n", " swigCPtr = cPtr;\n", " }\n", NIL); - - if (!have_default_constructor_flag) { // All proxy classes need a constructor - Printv(proxy_class_def, "\n", " protected $m3classname() : this(IntPtr.Zero, false) {\n", " }\n", NIL); - } - // C++ destructor is wrapped by the Dispose method - // Note that the method name is specified in a typemap attribute called methodname - String *destruct = NewString(""); - const String *tm = NULL; - Node *attributes = NewHash(); - String *destruct_methodname = NULL; - if (derived) { - tm = typemapLookup(n, "m3destruct_derived", name, WARN_NONE, attributes); - destruct_methodname = Getattr(attributes, "tmap:m3destruct_derived:methodname"); - } else { - tm = typemapLookup(n, "m3destruct", name, WARN_NONE, attributes); - destruct_methodname = Getattr(attributes, "tmap:m3destruct:methodname"); - } - if (!destruct_methodname) { - Swig_error(Getfile(n), Getline(n), "No methodname attribute defined in m3destruct%s typemap for %s\n", (derived ? "_derived" : ""), proxy_class_name); - } - // Emit the Finalize and Dispose methods - if (tm) { - // Finalize method - if (*Char(destructor_call)) { - Printv(proxy_class_def, typemapLookup(n, "m3finalize", name, WARN_NONE), NIL); - } - // Dispose method - Printv(destruct, tm, NIL); - if (*Char(destructor_call)) - Replaceall(destruct, "$imcall", destructor_call); - else - Replaceall(destruct, "$imcall", "throw new MethodAccessException(\"C++ destructor does not have public access\")"); - if (*Char(destruct)) - Printv(proxy_class_def, "\n public ", derived ? "override" : "virtual", " void ", destruct_methodname, "() ", destruct, "\n", NIL); - } - Delete(attributes); - Delete(destruct); - - // Emit various other methods - Printv(proxy_class_def, typemapLookup(n, "m3getcptr", name, WARN_MODULA3_TYPEMAP_GETCPTR_UNDEF), // getCPtr method - typemapLookup(n, "m3code", name, WARN_NONE), // extra Modula 3 code - "\n", NIL); - - // Substitute various strings into the above template - Replaceall(proxy_class_def, "$m3classname", proxy_class_name); - Replaceall(proxy_class_code, "$m3classname", proxy_class_name); - - Replaceall(proxy_class_def, "$baseclass", baseclass); - Replaceall(proxy_class_code, "$baseclass", baseclass); - - Replaceall(proxy_class_def, "$imclassname", m3raw_name); - Replaceall(proxy_class_code, "$imclassname", m3raw_name); - - // Add code to do C++ casting to base class (only for classes in an inheritance hierarchy) - if (derived) { - Printv(m3raw_cppcasts_code, "\n [DllImport(\"", m3wrap_name, "\", EntryPoint=\"Modula3_", proxy_class_name, "To", baseclass, "\")]\n", NIL); - Printv(m3raw_cppcasts_code, " public static extern IntPtr ", "$m3classnameTo$baseclass(IntPtr objectRef);\n", NIL); - - Replaceall(m3raw_cppcasts_code, "$m3classname", proxy_class_name); - Replaceall(m3raw_cppcasts_code, "$baseclass", baseclass); - - Printv(upcasts_code, - "SWIGEXPORT long Modula3_$imclazznameTo$imbaseclass", - "(long objectRef) {\n", - " long baseptr = 0;\n" " *($cbaseclass **)&baseptr = *($cclass **)&objectRef;\n" " return baseptr;\n" "}\n", "\n", NIL); - - Replaceall(upcasts_code, "$imbaseclass", baseclass); - Replaceall(upcasts_code, "$cbaseclass", c_baseclass); - Replaceall(upcasts_code, "$imclazzname", proxy_class_name); - Replaceall(upcasts_code, "$cclass", c_classname); - } - Delete(baseclass); - } - - /* ---------------------------------------------------------------------- - * getAttrString() - * - * If necessary create and return the string - * associated with a certain attribute of 'n'. - * ---------------------------------------------------------------------- */ - - String *getAttrString(Node *n, const char *attr) { - String *str = Getattr(n, attr); - if (str == NIL) { - str = NewString(""); - Setattr(n, attr, str); - } - return str; - } - - /* ---------------------------------------------------------------------- - * getMethodDeclarations() - * - * If necessary create and return the handle - * where the methods of the current access can be written to. - * 'n' must be a member of a struct or a class. - * ---------------------------------------------------------------------- */ - - String *getMethodDeclarations(Node *n) { - String *acc_str = Getattr(n, "access"); - String *methodattr; - if (acc_str == NIL) { - methodattr = NewString("modula3:method:public"); - } else { - methodattr = NewStringf("modula3:method:%s", acc_str); - } - String *methods = getAttrString(parentNode(n), Char(methodattr)); - Delete(methodattr); - return methods; - } - - /* ---------------------------------------------------------------------- - * classHandler() - * ---------------------------------------------------------------------- */ - - virtual int classHandler(Node *n) { - - File *f_proxy = NULL; - proxy_class_name = Copy(Getattr(n, "sym:name")); - //String *rawname = Getattr(n,"name"); - - if (proxy_flag) { - if (!addSymbol(proxy_class_name, n)) - return SWIG_ERROR; - - if (Cmp(proxy_class_name, m3raw_name) == 0) { - Printf(stderr, "Class name cannot be equal to intermediary class name: %s\n", proxy_class_name); - SWIG_exit(EXIT_FAILURE); - } - - if (Cmp(proxy_class_name, m3wrap_name) == 0) { - Printf(stderr, "Class name cannot be equal to module class name: %s\n", proxy_class_name); - SWIG_exit(EXIT_FAILURE); - } - - String *filen = NewStringf("%s%s.m3", SWIG_output_directory(), proxy_class_name); - f_proxy = NewFile(filen, "w", SWIG_output_files()); - if (!f_proxy) { - FileErrorDisplay(filen); - SWIG_exit(EXIT_FAILURE); - } - Delete(filen); - filen = NULL; - - emitBanner(f_proxy); - - Clear(proxy_class_def); - Clear(proxy_class_code); - - have_default_constructor_flag = false; - destructor_call = NewString(""); - } - - /* This will invoke memberfunctionHandler, membervariableHandler ... - and finally it may invoke functionWrapper - for wrappers and member variable accessors. - It will invoke Language:constructorDeclaration - which decides whether to call MODULA3::constructorHandler */ - Language::classHandler(n); - - { - String *kind = Getattr(n, "kind"); - if (Cmp(kind, "struct") == 0) { - String *entries = NewString(""); - Node *child; - writeArgState state; - for (child = firstChild(n); child != NIL; child = nextSibling(child)) { - String *childType = nodeType(child); - if (Strcmp(childType, "cdecl") == 0) { - String *member = Getattr(child, "sym:name"); - ParmList *pl = Getattr(child, "parms"); - if (pl == NIL) { - // Get the variable type in Modula 3 type equivalents - String *m3ct = getMappedTypeNew(child, "m3rawtype", ""); - - writeArg(entries, state, NIL, member, m3ct, NIL); - } - } - } - writeArg(entries, state, NIL, NIL, NIL, NIL); - - m3raw_intf.enterBlock(blocktype); - Printf(m3raw_intf.f, "%s =\nRECORD\n%sEND;\n", proxy_class_name, entries); - - Delete(entries); - - } else if (Cmp(kind, "class") == 0) { - enum access_privilege { acc_public, acc_protected, acc_private }; - int max_acc = acc_public; - - const char *acc_name[3] = { "public", "protected", "private" }; - String *methods[3]; - int acc; - for (acc = acc_public; acc <= acc_private; acc++) { - String *methodattr = NewStringf("modula3:method:%s", acc_name[acc]); - methods[acc] = Getattr(n, methodattr); - Delete(methodattr); - max_acc = max_acc > acc ? max_acc : acc; - } - - /* Determine the name of the base class */ - String *baseclassname = NewString(""); - { - List *baselist = Getattr(n, "bases"); - if (baselist) { - /* Look for the first (principal?) base class - - Modula 3 does not support multiple inheritance */ - Iterator base = First(baselist); - if (base.item) { - Append(baseclassname, Getattr(base.item, "sym:name")); - base = Next(base); - if (base.item) { - Swig_warning(WARN_MODULA3_MULTIPLE_INHERITANCE, Getfile(n), Getline(n), - "Warning for %s, base %s ignored. Multiple inheritance is not supported in Modula 3.\n", - proxy_class_name, Getattr(base.item, "name")); - } - } - } - } - - /* the private class of the base class and only this - need a pointer to the C++ object */ - bool need_private = !hasContent(baseclassname); - max_acc = need_private ? acc_private : max_acc; - - /* Declare C++ object as abstract pointer in Modula 3 */ - /* The revelation system does not allow us - to imitate the whole class hierarchy of the C++ library, - but at least we can distinguish between classes of different roots. */ - if (hasContent(baseclassname)) { - m3raw_intf.enterBlock(blocktype); - Printf(m3raw_intf.f, "%s = %s;\n", proxy_class_name, baseclassname); - } else { - m3raw_intf.enterBlock(blocktype); - Printf(m3raw_intf.f, "%s <: ADDRESS;\n", proxy_class_name); - m3raw_impl.enterBlock(revelation); - Printf(m3raw_impl.f, "%s = UNTRACED BRANDED REF RECORD (*Dummy*) END;\n", proxy_class_name); - } - - String *superclass; - m3wrap_intf.enterBlock(blocktype); - if (hasContent(methods[acc_public])) { - superclass = NewStringf("%sPublic", proxy_class_name); - } else if (hasContent(baseclassname)) { - superclass = Copy(baseclassname); - } else { - superclass = NewString("ROOT"); - } - Printf(m3wrap_intf.f, "%s <: %s;\n", proxy_class_name, superclass); - Delete(superclass); - - { - static const char *acc_m3suffix[] = { "Public", "Protected", "Private" }; - int acc; - for (acc = acc_public; acc <= acc_private; acc++) { - bool process_private = (acc == acc_private) && need_private; - if (hasContent(methods[acc]) || process_private) { - String *subclass = NewStringf("%s%s", proxy_class_name, acc_m3suffix[acc]); - /* - m3wrap_intf.enterBlock(revelation); - Printf(m3wrap_intf.f, "%s <: %s;\n", proxy_class_name, subclass); - */ - if (acc == max_acc) { - m3wrap_intf.enterBlock(revelation); - Printf(m3wrap_intf.f, "%s =\n", proxy_class_name); - } else { - m3wrap_intf.enterBlock(blocktype); - Printf(m3wrap_intf.f, "%s =\n", subclass); - } - Printf(m3wrap_intf.f, "%s BRANDED OBJECT\n", baseclassname); - if (process_private) { - Setattr(m3wrap_intf.import, m3raw_name, ""); - Printf(m3wrap_intf.f, "cxxObj:%s.%s;\n", m3raw_name, proxy_class_name); - } - if (hasContent(methods[acc])) { - Printf(m3wrap_intf.f, "METHODS\n%s", methods[acc]); - } - if (acc == max_acc) { - String *overrides = Getattr(n, "modula3:override"); - Printf(m3wrap_intf.f, "OVERRIDES\n%s", overrides); - } - Printf(m3wrap_intf.f, "END;\n"); - Delete(baseclassname); - baseclassname = subclass; - } - } - } - - Delete(methods[acc_public]); - Delete(methods[acc_protected]); - Delete(methods[acc_private]); - - } else { - Swig_warning(WARN_MODULA3_TYPECONSTRUCTOR_UNKNOWN, input_file, line_number, "Unknown type constructor %s\n", kind); - } - } - - if (proxy_flag) { - - emitProxyClassDefAndCPPCasts(n); - - Printv(f_proxy, proxy_class_def, proxy_class_code, NIL); - - Printf(f_proxy, "}\n"); - Delete(f_proxy); - f_proxy = NULL; - - Delete(proxy_class_name); - proxy_class_name = NULL; - Delete(destructor_call); - destructor_call = NULL; - } - return SWIG_OK; - } - - /* ---------------------------------------------------------------------- - * memberfunctionHandler() - * ---------------------------------------------------------------------- */ - - virtual int memberfunctionHandler(Node *n) { - //printf("begin memberfunctionHandler(%s)\n", Char(Getattr(n,"name"))); - Setattr(n, "modula3:functype", "method"); - Language::memberfunctionHandler(n); - - { - /* Language::memberfunctionHandler will remove the mapped types - that emitM3Wrapper may attach */ - ParmList *pl = Getattr(n, "parms"); - Swig_typemap_attach_parms("m3wrapinmode", pl, NULL); - Swig_typemap_attach_parms("m3wrapinname", pl, NULL); - Swig_typemap_attach_parms("m3wrapintype", pl, NULL); - Swig_typemap_attach_parms("m3wrapindefault", pl, NULL); - attachParameterNames(n, "tmap:m3wrapinname", "autoname", "arg%d"); - String *rettype = getMappedTypeNew(n, "m3wrapouttype", ""); - - String *methodname = Getattr(n, "sym:name"); -/* - if (methodname==NIL) { - methodname = Getattr(n,"name"); - } -*/ - String *arguments = createM3Signature(n); - String *storage = Getattr(n, "storage"); - String *overridden = Getattr(n, "override"); - bool isVirtual = (storage != NIL) && (Strcmp(storage, "virtual") == 0); - bool isOverridden = (overridden != NIL) - && (Strcmp(overridden, "1") == 0); - if ((!isVirtual) || (!isOverridden)) { - { - String *methods = getMethodDeclarations(n); - Printf(methods, "%s(%s)%s%s;%s\n", - methodname, arguments, - hasContent(rettype) ? ": " : "", hasContent(rettype) ? (const String *) rettype : "", isVirtual ? " (* base method *)" : ""); - } - { - /* this was attached by functionWrapper - invoked by Language::memberfunctionHandler */ - String *fname = Getattr(n, "modula3:funcname"); - String *overrides = getAttrString(parentNode(n), "modula3:override"); - Printf(overrides, "%s := %s;\n", methodname, fname); - } - } - } - - if (proxy_flag) { - String *overloaded_name = getOverloadedName(n); - String *intermediary_function_name = Swig_name_member(NSPACE_TODO, proxy_class_name, overloaded_name); - Setattr(n, "proxyfuncname", Getattr(n, "sym:name")); - Setattr(n, "imfuncname", intermediary_function_name); - proxyClassFunctionHandler(n); - Delete(overloaded_name); - } - //printf("end memberfunctionHandler(%s)\n", Char(Getattr(n,"name"))); - return SWIG_OK; - } - - /* ---------------------------------------------------------------------- - * staticmemberfunctionHandler() - * ---------------------------------------------------------------------- */ - - virtual int staticmemberfunctionHandler(Node *n) { - - static_flag = true; - Language::staticmemberfunctionHandler(n); - - if (proxy_flag) { - String *overloaded_name = getOverloadedName(n); - String *intermediary_function_name = Swig_name_member(NSPACE_TODO, proxy_class_name, overloaded_name); - Setattr(n, "proxyfuncname", Getattr(n, "sym:name")); - Setattr(n, "imfuncname", intermediary_function_name); - proxyClassFunctionHandler(n); - Delete(overloaded_name); - } - static_flag = false; - - return SWIG_OK; - } - - /* ----------------------------------------------------------------------------- - * proxyClassFunctionHandler() - * - * Function called for creating a Modula 3 wrapper function around a c++ function in the - * proxy class. Used for both static and non-static C++ class functions. - * C++ class static functions map to Modula 3 static functions. - * Two extra attributes in the Node must be available. These are "proxyfuncname" - - * the name of the Modula 3 class proxy function, which in turn will call "imfuncname" - - * the intermediary (PInvoke) function name in the intermediary class. - * ----------------------------------------------------------------------------- */ - - void proxyClassFunctionHandler(Node *n) { - SwigType *t = Getattr(n, "type"); - ParmList *l = Getattr(n, "parms"); - Hash *throws_hash = NewHash(); - String *intermediary_function_name = Getattr(n, "imfuncname"); - String *proxy_function_name = Getattr(n, "proxyfuncname"); - String *tm; - Parm *p; - int i; - String *imcall = NewString(""); - String *return_type = NewString(""); - String *function_code = NewString(""); - bool setter_flag = false; - - if (!proxy_flag) - return; - - if (l) { - if (SwigType_type(Getattr(l, "type")) == T_VOID) { - l = nextSibling(l); - } - } - - /* Attach the non-standard typemaps to the parameter list */ - Swig_typemap_attach_parms("in", l, NULL); - Swig_typemap_attach_parms("m3wraptype", l, NULL); - Swig_typemap_attach_parms("m3in", l, NULL); - - /* Get return types */ - if ((tm = getMappedTypeNew(n, "m3wraptype", ""))) { - substituteClassname(t, tm); - Printf(return_type, "%s", tm); - } - - if (proxy_flag && wrapping_member_flag && !enum_constant_flag) { - // Properties - setter_flag = (Cmp(Getattr(n, "sym:name"), Swig_name_set(NSPACE_TODO, Swig_name_member(NSPACE_TODO, proxy_class_name, variable_name))) - == 0); - } - - /* Start generating the proxy function */ - Printf(function_code, " %s ", Getattr(n, "feature:modula3:methodmodifiers")); - if (static_flag) - Printf(function_code, "static "); - if (Getattr(n, "override")) - Printf(function_code, "override "); - else if (checkAttribute(n, "storage", "virtual")) - Printf(function_code, "virtual "); - - Printf(function_code, "%s %s(", return_type, proxy_function_name); - - Printv(imcall, m3raw_name, ".", intermediary_function_name, "(", NIL); - if (!static_flag) - Printv(imcall, "swigCPtr", NIL); - - emit_mark_varargs(l); - - int gencomma = !static_flag; - - /* Output each parameter */ - for (i = 0, p = l; p; i++) { - - /* Ignored varargs */ - if (checkAttribute(p, "varargs:ignore", "1")) { - p = nextSibling(p); - continue; - } - - /* Ignored parameters */ - if (checkAttribute(p, "tmap:in:numinputs", "0")) { - p = Getattr(p, "tmap:in:next"); - continue; - } - - /* Ignore the 'this' argument for variable wrappers */ - if (!(variable_wrapper_flag && i == 0)) { - SwigType *pt = Getattr(p, "type"); - String *param_type = NewString(""); - - /* Get the Modula 3 parameter type */ - if ((tm = getMappedType(p, "m3wraptype"))) { - substituteClassname(pt, tm); - Printf(param_type, "%s", tm); - } - - if (gencomma) - Printf(imcall, ", "); - - String *arg = variable_wrapper_flag ? NewString("value") : makeParameterName(n, - p, - i); - - // Use typemaps to transform type used in Modula 3 wrapper function (in proxy class) to type used in PInvoke function (in intermediary class) - if ((tm = getMappedType(p, "in"))) { - addThrows(throws_hash, "in", p); - substituteClassname(pt, tm); - Replaceall(tm, "$input", arg); - Printv(imcall, tm, NIL); - } - - /* Add parameter to proxy function */ - if (gencomma >= 2) - Printf(function_code, ", "); - gencomma = 2; - Printf(function_code, "%s %s", param_type, arg); - - Delete(arg); - Delete(param_type); - } - p = Getattr(p, "tmap:in:next"); - } - - Printf(imcall, ")"); - Printf(function_code, ")"); - - // Transform return type used in PInvoke function (in intermediary class) to type used in Modula 3 wrapper function (in proxy class) - if ((tm = getMappedTypeNew(n, "m3out", ""))) { - addThrows(throws_hash, "m3out", n); - if (GetFlag(n, "feature:new")) - Replaceall(tm, "$owner", "true"); - else - Replaceall(tm, "$owner", "false"); - substituteClassname(t, tm); - Replaceall(tm, "$imcall", imcall); - } - - generateThrowsClause(throws_hash, function_code); - Printf(function_code, " %s\n\n", tm ? (const String *) tm : empty_string); - - if (proxy_flag && wrapping_member_flag && !enum_constant_flag) { - // Properties - if (setter_flag) { - // Setter method - if ((tm = getMappedTypeNew(n, "m3varin", ""))) { - if (GetFlag(n, "feature:new")) - Replaceall(tm, "$owner", "true"); - else - Replaceall(tm, "$owner", "false"); - substituteClassname(t, tm); - Replaceall(tm, "$imcall", imcall); - Printf(proxy_class_code, "%s", tm); - } - } else { - // Getter method - if ((tm = getMappedTypeNew(n, "m3varout", ""))) { - if (GetFlag(n, "feature:new")) - Replaceall(tm, "$owner", "true"); - else - Replaceall(tm, "$owner", "false"); - substituteClassname(t, tm); - Replaceall(tm, "$imcall", imcall); - Printf(proxy_class_code, "%s", tm); - } - } - } else { - // Normal function call - Printv(proxy_class_code, function_code, NIL); - } - - Delete(function_code); - Delete(return_type); - Delete(imcall); - Delete(throws_hash); - } - - /* ---------------------------------------------------------------------- - * constructorHandler() - * ---------------------------------------------------------------------- */ - - virtual int constructorHandler(Node *n) { - // this invokes functionWrapper - Language::constructorHandler(n); - - if (proxy_flag) { - ParmList *l = Getattr(n, "parms"); - - Hash *throws_hash = NewHash(); - String *overloaded_name = getOverloadedName(n); - String *imcall = NewString(""); - - Printf(proxy_class_code, " %s %s(", Getattr(n, "feature:modula3:methodmodifiers"), proxy_class_name); - Printv(imcall, " : this(", m3raw_name, ".", Swig_name_construct(NSPACE_TODO, overloaded_name), "(", NIL); - - /* Attach the non-standard typemaps to the parameter list */ - Swig_typemap_attach_parms("in", l, NULL); - Swig_typemap_attach_parms("m3wraptype", l, NULL); - Swig_typemap_attach_parms("m3in", l, NULL); - - emit_mark_varargs(l); - - int gencomma = 0; - - String *tm; - Parm *p = l; - int i; - - /* Output each parameter */ - for (i = 0; p; i++) { - - /* Ignored varargs */ - if (checkAttribute(p, "varargs:ignore", "1")) { - p = nextSibling(p); - continue; - } - - /* Ignored parameters */ - if (checkAttribute(p, "tmap:in:numinputs", "0")) { - p = Getattr(p, "tmap:in:next"); - continue; - } - - SwigType *pt = Getattr(p, "type"); - String *param_type = NewString(""); - - /* Get the Modula 3 parameter type */ - if ((tm = getMappedType(p, "m3wraptype"))) { - substituteClassname(pt, tm); - Printf(param_type, "%s", tm); - } - - if (gencomma) - Printf(imcall, ", "); - - String *arg = makeParameterName(n, p, i); - - // Use typemaps to transform type used in Modula 3 wrapper function (in proxy class) to type used in PInvoke function (in intermediary class) - if ((tm = getMappedType(p, "in"))) { - addThrows(throws_hash, "in", p); - substituteClassname(pt, tm); - Replaceall(tm, "$input", arg); - Printv(imcall, tm, NIL); - } - - /* Add parameter to proxy function */ - if (gencomma) - Printf(proxy_class_code, ", "); - Printf(proxy_class_code, "%s %s", param_type, arg); - gencomma = 1; - - Delete(arg); - Delete(param_type); - p = Getattr(p, "tmap:in:next"); - } - - Printf(imcall, "), true)"); - - Printf(proxy_class_code, ")"); - Printf(proxy_class_code, "%s", imcall); - generateThrowsClause(throws_hash, proxy_class_code); - Printf(proxy_class_code, " {\n"); - Printf(proxy_class_code, " }\n\n"); - - if (!gencomma) // We must have a default constructor - have_default_constructor_flag = true; - - Delete(overloaded_name); - Delete(imcall); - Delete(throws_hash); - } - - return SWIG_OK; - } - - /* ---------------------------------------------------------------------- - * destructorHandler() - * ---------------------------------------------------------------------- */ - - virtual int destructorHandler(Node *n) { - Language::destructorHandler(n); - String *symname = Getattr(n, "sym:name"); - - if (proxy_flag) { - Printv(destructor_call, m3raw_name, ".", Swig_name_destroy(NSPACE_TODO, symname), "(swigCPtr)", NIL); - } - return SWIG_OK; - } - - /* ---------------------------------------------------------------------- - * membervariableHandler() - * ---------------------------------------------------------------------- */ - - virtual int membervariableHandler(Node *n) { - //printf("begin membervariableHandler(%s)\n", Char(Getattr(n,"name"))); - SwigType *t = Getattr(n, "type"); - String *tm; - - // Get the variable type - if ((tm = getMappedTypeNew(n, "m3wraptype", ""))) { - substituteClassname(t, tm); - } - - variable_name = Getattr(n, "sym:name"); - //printf("member variable: %s\n", Char(variable_name)); - - // Output the property's field declaration and accessor methods - Printf(proxy_class_code, " public %s %s {", tm, variable_name); - - Setattr(n, "modula3:functype", "accessor"); - wrapping_member_flag = true; - variable_wrapper_flag = true; - Language::membervariableHandler(n); - wrapping_member_flag = false; - variable_wrapper_flag = false; - - Printf(proxy_class_code, "\n }\n\n"); - - { - String *methods = getMethodDeclarations(n); - String *overrides = getAttrString(parentNode(n), "modula3:override"); - SwigType *type = Getattr(n, "type"); - String *m3name = capitalizeFirst(variable_name); - //String *m3name = nameToModula3(variable_name,true); - if (!SwigType_isconst(type)) { - { - String *inmode = getMappedTypeNew(n, "m3wrapinmode", "", false); - String *intype = getMappedTypeNew(n, "m3wrapintype", ""); - Printf(methods, "set%s(%s val:%s);\n", m3name, (inmode != NIL) ? (const String *) inmode : "", intype); - } - { - /* this was attached by functionWrapper - invoked by Language::memberfunctionHandler */ - String *fname = Getattr(n, "modula3:setname"); - Printf(overrides, "set%s := %s;\n", m3name, fname); - } - } - { - { - String *outtype = getMappedTypeNew(n, "m3wrapouttype", ""); - Printf(methods, "get%s():%s;\n", m3name, outtype); - } - { - /* this was attached by functionWrapper - invoked by Language::memberfunctionHandler */ - String *fname = Getattr(n, "modula3:getname"); - Printf(overrides, "get%s := %s;\n", m3name, fname); - } - } - Delete(m3name); - } - //printf("end membervariableHandler(%s)\n", Char(Getattr(n,"name"))); - - return SWIG_OK; - } - - /* ---------------------------------------------------------------------- - * staticmembervariableHandler() - * ---------------------------------------------------------------------- */ - - virtual int staticmembervariableHandler(Node *n) { - - bool static_const_member_flag = (Getattr(n, "value") == 0); - if (static_const_member_flag) { - SwigType *t = Getattr(n, "type"); - String *tm; - - // Get the variable type - if ((tm = getMappedTypeNew(n, "m3wraptype", ""))) { - substituteClassname(t, tm); - } - // Output the property's field declaration and accessor methods - Printf(proxy_class_code, " public static %s %s {", tm, Getattr(n, "sym:name")); - } - - variable_name = Getattr(n, "sym:name"); - wrapping_member_flag = true; - static_flag = true; - Language::staticmembervariableHandler(n); - wrapping_member_flag = false; - static_flag = false; - - if (static_const_member_flag) - Printf(proxy_class_code, "\n }\n\n"); - - return SWIG_OK; - } - - /* ---------------------------------------------------------------------- - * memberconstantHandler() - * ---------------------------------------------------------------------- */ - - virtual int memberconstantHandler(Node *n) { - variable_name = Getattr(n, "sym:name"); - wrapping_member_flag = true; - Language::memberconstantHandler(n); - wrapping_member_flag = false; - return SWIG_OK; - } - - /* ----------------------------------------------------------------------------- - * getOverloadedName() - * ----------------------------------------------------------------------------- */ - - String *getOverloadedName(Node *n) { - String *overloaded_name = Copy(Getattr(n, "sym:name")); - - if (Getattr(n, "sym:overloaded")) { - Printv(overloaded_name, Getattr(n, "sym:overname"), NIL); - } - - return overloaded_name; - } - - /* ----------------------------------------------------------------------------- - * emitM3Wrapper() - * It is also used for set and get methods of global variables. - * ----------------------------------------------------------------------------- */ - - void emitM3Wrapper(Node *n, const String *func_name) { - SwigType *t = Getattr(n, "type"); - ParmList *l = Getattr(n, "parms"); - Hash *throws_hash = NewHash(); - int num_exceptions = 0; - int num_returns = 0; - String *rawcall = NewString(""); - String *reccall = NewString(""); - String *local_variables = NewString(""); - String *local_constants = NewString(""); - String *incheck = NewString(""); - String *outcheck = NewString(""); - String *setup = NewString(""); - String *cleanup = NewString(""); - String *outarg = NewString(""); /* don't mix up with 'autark' :-] */ - String *storeout = NewString(""); - String *result_name = NewString(""); - String *return_variables = NewString(""); - const char *result_return = "ret"; - String *function_code = NewString(""); - /*several names for the same function */ - String *raw_name = Getattr(n, "name"); /*original C function name */ - //String *func_name = Getattr(n,"sym:name"); /*final Modula3 name chosen by the user*/ - bool setter_flag = false; - int multiretval = GetFlag(n, "feature:modula3:multiretval"); - - if (l) { - if (SwigType_type(Getattr(l, "type")) == T_VOID) { - l = nextSibling(l); - } - } - - /* Attach the non-standard typemaps to the parameter list */ - Swig_typemap_attach_parms("m3wrapargvar", l, NULL); - Swig_typemap_attach_parms("m3wrapargconst", l, NULL); - Swig_typemap_attach_parms("m3wrapargraw", l, NULL); - Swig_typemap_attach_parms("m3wrapargdir", l, NULL); - Swig_typemap_attach_parms("m3wrapinmode", l, NULL); - Swig_typemap_attach_parms("m3wrapinname", l, NULL); - Swig_typemap_attach_parms("m3wrapintype", l, NULL); - Swig_typemap_attach_parms("m3wrapindefault", l, NULL); - Swig_typemap_attach_parms("m3wrapinconv", l, NULL); - Swig_typemap_attach_parms("m3wrapincheck", l, NULL); - Swig_typemap_attach_parms("m3wrapoutname", l, NULL); - Swig_typemap_attach_parms("m3wrapouttype", l, NULL); - Swig_typemap_attach_parms("m3wrapoutconv", l, NULL); - Swig_typemap_attach_parms("m3wrapoutcheck", l, NULL); - - attachMappedType(n, "m3wrapretraw"); - attachMappedType(n, "m3wrapretname"); - attachMappedType(n, "m3wraprettype"); - attachMappedType(n, "m3wrapretvar"); - attachMappedType(n, "m3wrapretconv"); - attachMappedType(n, "m3wrapretcheck"); - - Swig_typemap_attach_parms("m3wrapfreearg", l, NULL); - -/* - Swig_typemap_attach_parms("m3wrapargvar:throws", l, NULL); - Swig_typemap_attach_parms("m3wrapargraw:throws", l, NULL); - Swig_typemap_attach_parms("m3wrapinconv:throws", l, NULL); - Swig_typemap_attach_parms("m3wrapincheck:throws", l, NULL); - Swig_typemap_attach_parms("m3wrapoutconv:throws", l, NULL); - Swig_typemap_attach_parms("m3wrapoutcheck:throws", l, NULL); - - attachMappedType(n, "m3wrapretvar:throws"); - attachMappedType(n, "m3wrapretconv:throws"); - attachMappedType(n, "m3wrapretcheck:throws"); - - Swig_typemap_attach_parms("m3wrapfreearg:throws", l, NULL); -*/ - - /* Attach argument names to the parameter list */ - /* should be a separate procedure making use of hashes */ - attachParameterNames(n, "tmap:m3wrapinname", "autoname", "arg%d"); - - /* Get return types */ - String *result_m3rawtype = Copy(getMappedTypeNew(n, "m3rawrettype", "")); - String *result_m3wraptype = Copy(getMappedTypeNew(n, "m3wraprettype", "")); - bool has_return_raw = hasContent(result_m3rawtype); - bool has_return_m3 = hasContent(result_m3wraptype); - if (has_return_m3) { - num_returns++; - //printf("%s: %s\n", Char(func_name),Char(result_m3wraptype)); - } - - String *arguments = createM3Signature(n); - - /* Create local variables or RECORD fields for return values - and determine return type that might result from a converted VAR argument. */ - { - writeArgState state; - if (multiretval && has_return_m3) { - writeArg(return_variables, state, NIL, NewString(result_return), result_m3wraptype, NIL); - } - - Parm *p = skipIgnored(l, "m3wrapouttype"); - while (p != NIL) { - - String *arg = Getattr(p, "tmap:m3wrapoutname"); - if (arg == NIL) { - arg = Getattr(p, "name"); - } - - String *tm = Getattr(p, "tmap:m3wrapouttype"); - if (tm != NIL) { - if (isOutParam(p)) { - if (!multiretval) { - if (num_returns == 0) { - Printv(result_name, arg, NIL); - Clear(result_m3wraptype); - Printv(result_m3wraptype, tm, NIL); - } else { - Swig_warning(WARN_MODULA3_TYPEMAP_MULTIPLE_RETURN, input_file, line_number, - "Typemap m3wrapargdir set to 'out' for %s implies a RETURN value, but the routine %s has already one.\nUse %%multiretval feature.\n", - SwigType_str(Getattr(p, "type"), 0), raw_name); - } - } - num_returns++; - addImports(m3wrap_intf.import, "m3wrapouttype", p); - writeArg(return_variables, state, NIL, arg, tm, NIL); - } - p = skipIgnored(Getattr(p, "tmap:m3wrapouttype:next"), "m3wrapouttype"); - } else { - p = nextSibling(p); - } - } - writeArg(return_variables, state, NIL, NIL, NIL, NIL); - - if (multiretval) { - Printv(result_name, Swig_cresult_name(), NIL); - Printf(result_m3wraptype, "%sResult", func_name); - m3wrap_intf.enterBlock(blocktype); - Printf(m3wrap_intf.f, "%s =\nRECORD\n%sEND;\n", result_m3wraptype, return_variables); - Printf(local_variables, "%s: %s;\n", result_name, result_m3wraptype); - } else { - Append(local_variables, return_variables); - } - } - - /* Declare local constants e.g. for storing argument names. */ - { - Parm *p = l; - while (p != NIL) { - - String *arg = Getattr(p, "autoname"); - - String *tm = Getattr(p, "tmap:m3wrapargconst"); - if (tm != NIL) { - addImports(m3wrap_impl.import, "m3wrapargconst", p); - Replaceall(tm, "$input", arg); - Printv(local_constants, tm, "\n", NIL); - p = Getattr(p, "tmap:m3wrapargconst:next"); - } else { - p = nextSibling(p); - } - - } - } - - /* Declare local variables e.g. for converted input values. */ - { - String *tm = getMappedTypeNew(n, "m3wrapretvar", "", false); - if (tm != NIL) { - addImports(m3wrap_impl.import, "m3wrapretvar", n); - addThrows(throws_hash, "m3wrapretvar", n); - Printv(local_variables, tm, "\n", NIL); - } - - Parm *p = l; - while (p != NIL) { - - String *arg = Getattr(p, "autoname"); - - tm = Getattr(p, "tmap:m3wrapargvar"); - if (tm != NIL) { - /* exceptions that may be raised but can't be caught, - thus we won't count them in num_exceptions */ - addImports(m3wrap_impl.import, "m3wrapargvar", p); - addThrows(throws_hash, "m3wrapargvar", p); - Replaceall(tm, "$input", arg); - Printv(local_variables, tm, "\n", NIL); - p = Getattr(p, "tmap:m3wrapargvar:next"); - } else { - p = nextSibling(p); - } - - } - } - - /* Convert input values from Modula 3 to C. */ - { - Parm *p = l; - while (p != NIL) { - - String *arg = Getattr(p, "autoname"); - - String *tm = Getattr(p, "tmap:m3wrapinconv"); - if (tm != NIL) { - addImports(m3wrap_impl.import, "m3wrapinconv", p); - num_exceptions += addThrows(throws_hash, "m3wrapinconv", p); - Replaceall(tm, "$input", arg); - Printv(setup, tm, "\n", NIL); - p = Getattr(p, "tmap:m3wrapinconv:next"); - } else { - p = nextSibling(p); - } - - } - } - - /* Generate checks for input value integrity. */ - { - Parm *p = l; - while (p != NIL) { - - String *arg = Getattr(p, "autoname"); - - String *tm = Getattr(p, "tmap:m3wrapincheck"); - if (tm != NIL) { - addImports(m3wrap_impl.import, "m3wrapincheck", p); - num_exceptions += addThrows(throws_hash, "m3wrapincheck", p); - Replaceall(tm, "$input", arg); - Printv(incheck, tm, "\n", NIL); - p = Getattr(p, "tmap:m3wrapincheck:next"); - } else { - p = nextSibling(p); - } - - } - } - - Printv(rawcall, m3raw_name, ".", func_name, "(", NIL); - /* Arguments to the raw C function */ - { - bool gencomma = false; - Parm *p = l; - while (p != NIL) { - if (gencomma) { - Printf(rawcall, ", "); - } - gencomma = true; - addImports(m3wrap_impl.import, "m3wrapargraw", p); - num_exceptions += addThrows(throws_hash, "m3wrapargraw", p); - - String *arg = Getattr(p, "autoname"); - String *qualarg = NewString(""); - if (!isInParam(p)) { - String *tmparg = Getattr(p, "tmap:m3wrapoutname"); - if (tmparg != NIL) { - arg = tmparg; - } - if (multiretval /*&& isOutParam(p) - automatically fulfilled */ ) { - Printf(qualarg, "%s.", result_name); - } - } - Append(qualarg, arg); - Setattr(p, "m3outarg", qualarg); - - String *tm = Getattr(p, "tmap:m3wrapargraw"); - if (tm != NIL) { - Replaceall(tm, "$input", arg); - Replaceall(tm, "$output", qualarg); - Printv(rawcall, tm, NIL); - p = Getattr(p, "tmap:m3wrapargraw:next"); - } else { - //Printv(rawcall, Getattr(p,"lname"), NIL); - Printv(rawcall, qualarg, NIL); - p = nextSibling(p); - } - Delete(qualarg); - } - } - Printf(rawcall, ")"); - - /* Check for error codes and integrity of results */ - { - String *tm = getMappedTypeNew(n, "m3wrapretcheck", "", false); - if (tm != NIL) { - addImports(m3wrap_impl.import, "m3wrapretcheck", n); - num_exceptions += addThrows(throws_hash, "m3wrapretcheck", n); - Printv(outcheck, tm, "\n", NIL); - } - - Parm *p = l; - while (p != NIL) { - tm = Getattr(p, "tmap:m3wrapoutcheck"); - if (tm != NIL) { - String *arg = Getattr(p, "autoname"); - String *outarg = Getattr(p, "m3outarg"); - addImports(m3wrap_impl.import, "m3wrapoutcheck", p); - num_exceptions += addThrows(throws_hash, "m3wrapoutcheck", p); - //substituteClassname(Getattr(p,"type"), tm); - Replaceall(tm, "$input", arg); - Replaceall(tm, "$output", outarg); - Printv(outcheck, tm, "\n", NIL); - p = Getattr(p, "tmap:m3wrapoutcheck:next"); - } else { - p = nextSibling(p); - } - } - } - - /* Convert the results to Modula 3 data structures and - put them in the record prepared for returning */ - { - /* m3wrapretconv is processed - when it is clear if there is some output conversion and checking code */ - Parm *p = l; - while (p != NIL) { - String *tm = Getattr(p, "tmap:m3wrapoutconv"); - if (tm != NIL) { - String *arg = Getattr(p, "autoname"); - String *outarg = Getattr(p, "m3outarg"); - addImports(m3wrap_impl.import, "m3wrapoutconv", n); - num_exceptions += addThrows(throws_hash, "m3wrapoutconv", p); - //substituteClassname(Getattr(p,"type"), tm); - Replaceall(tm, "$input", arg); - Replaceall(tm, "$output", outarg); - Printf(storeout, "%s := %s;\n", outarg, tm); - p = Getattr(p, "tmap:m3wrapoutconv:next"); - } else { - p = nextSibling(p); - } - } - } - - /* Generate cleanup code */ - { - Parm *p = l; - while (p != NIL) { - String *tm = Getattr(p, "tmap:m3wrapfreearg"); - if (tm != NIL) { - String *arg = Getattr(p, "autoname"); - String *outarg = Getattr(p, "m3outarg"); - addImports(m3wrap_impl.import, "m3wrapfreearg", p); - num_exceptions += addThrows(throws_hash, "m3wrapfreearg", p); - //substituteClassname(Getattr(p,"type"), tm); - Replaceall(tm, "$input", arg); - Replaceall(tm, "$output", outarg); - Printv(cleanup, tm, "\n", NIL); - p = Getattr(p, "tmap:m3wrapfreearg:next"); - } else { - p = nextSibling(p); - } - } - } - - { - /* Currently I don't know how a typemap similar to the original 'out' typemap - could help returning the return value. */ - /* Receive result from call to raw library function */ - if (!has_return_raw) { - /* - rawcall(arg1); - result.val := arg1; - RETURN result; - */ - /* - rawcall(arg1); - RETURN arg1; - */ - Printf(reccall, "%s;\n", rawcall); - - if (hasContent(result_name)) { - Printf(outarg, "RETURN %s;\n", result_name); - } - } else { - /* - arg0 := rawcall(arg1); - result.ret := Convert(arg0); - result.val := arg1; - RETURN result; - */ - /* - arg0 := rawcall(); - RETURN Convert(arg0); - */ - /* - RETURN rawcall(); - */ - String *return_raw = getMappedTypeNew(n, "m3wrapretraw", "", false); - String *return_conv = getMappedTypeNew(n, "m3wrapretconv", "", false); - - /* immediate RETURN would skip result checking */ - if ((hasContent(outcheck) || hasContent(storeout) - || hasContent(cleanup)) && (!hasContent(result_name)) - && (return_raw == NIL)) { - Printv(result_name, Swig_cresult_name(), NIL); - Printf(local_variables, "%s: %s;\n", result_name, result_m3wraptype); - } - - String *result_lvalue = Copy(result_name); - if (multiretval) { - Printf(result_lvalue, ".%s", result_return); - } - if (return_raw != NIL) { - Printf(reccall, "%s := %s;\n", return_raw, rawcall); - } else if (hasContent(result_name)) { - Printf(reccall, "%s := %s;\n", result_lvalue, rawcall); - } else { - Printf(outarg, "RETURN %s;\n", rawcall); - } - if (return_conv != NIL) { - addImports(m3wrap_impl.import, "m3wrapretconv", n); - num_exceptions += addThrows(throws_hash, "m3wrapretconv", n); - if (hasContent(result_name)) { - Printf(reccall, "%s := %s;\n", result_lvalue, return_conv); - Printf(outarg, "RETURN %s;\n", result_name); - } else { - Printf(outarg, "RETURN %s;\n", return_conv); - } - } else { - if (hasContent(result_name)) { - Printf(outarg, "RETURN %s;\n", result_name); - } - } - } - } - - /* Create procedure header */ - { - String *header = NewStringf("PROCEDURE %s (%s)", - func_name, arguments); - - if ((num_returns > 0) || multiretval) { - Printf(header, ": %s", result_m3wraptype); - } - generateThrowsClause(throws_hash, header); - - Append(function_code, header); - - m3wrap_intf.enterBlock(no_block); - Printf(m3wrap_intf.f, "%s;\n\n", header); - } - - { - String *body = NewStringf("%s%s%s%s%s", - incheck, - setup, - reccall, - outcheck, - storeout); - - String *exc_handler; - if (hasContent(cleanup) && (num_exceptions > 0)) { - exc_handler = NewStringf("TRY\n%sFINALLY\n%sEND;\n", body, cleanup); - } else { - exc_handler = NewStringf("%s%s", body, cleanup); - } - - Printf(function_code, " =\n%s%s%s%sBEGIN\n%s%sEND %s;\n\n", - hasContent(local_constants) ? "CONST\n" : "", local_constants, - hasContent(local_variables) ? "VAR\n" : "", local_variables, exc_handler, outarg, func_name); - - Delete(exc_handler); - Delete(body); - } - - m3wrap_impl.enterBlock(no_block); - if (proxy_flag && global_variable_flag) { - setter_flag = (Cmp(Getattr(n, "sym:name"), Swig_name_set(NSPACE_TODO, variable_name)) == 0); - // Properties - if (setter_flag) { - // Setter method - String *tm = getMappedTypeNew(n, "m3varin", ""); - if (tm != NIL) { - if (GetFlag(n, "feature:new")) { - Replaceall(tm, "$owner", "true"); - } else { - Replaceall(tm, "$owner", "false"); - } - substituteClassname(t, tm); - Replaceall(tm, "$rawcall", rawcall); - Replaceall(tm, "$vartype", variable_type); /* $type is already replaced by some super class */ - Replaceall(tm, "$var", variable_name); - Printf(m3wrap_impl.f, "%s", tm); - } - } else { - // Getter method - String *tm = getMappedTypeNew(n, "m3varout", ""); - if (tm != NIL) { - if (GetFlag(n, "feature:new")) - Replaceall(tm, "$owner", "true"); - else - Replaceall(tm, "$owner", "false"); - substituteClassname(t, tm); - Replaceall(tm, "$rawcall", rawcall); - Replaceall(tm, "$vartype", variable_type); - Replaceall(tm, "$var", variable_name); - Printf(m3wrap_impl.f, "%s", tm); - } - } - } else { - // Normal function call - Printv(m3wrap_impl.f, function_code, NIL); - } - - Delete(arguments); - Delete(return_variables); - Delete(local_variables); - Delete(local_constants); - Delete(outarg); - Delete(incheck); - Delete(outcheck); - Delete(setup); - Delete(cleanup); - Delete(storeout); - Delete(function_code); - Delete(result_name); - Delete(result_m3wraptype); - Delete(reccall); - Delete(rawcall); - Delete(throws_hash); - } - - /*---------------------------------------------------------------------- - * replaceSpecialVariables() - *--------------------------------------------------------------------*/ - - virtual void replaceSpecialVariables(String *method, String *tm, Parm *parm) { - (void)method; - SwigType *type = Getattr(parm, "type"); - substituteClassname(type, tm); - } - - /* ----------------------------------------------------------------------------- - * substituteClassname() - * - * Substitute the special variable $m3classname with the proxy class name for classes/structs/unions - * that SWIG knows about. - * Otherwise use the $descriptor name for the Modula 3 class name. Note that the $&m3classname substitution - * is the same as a $&descriptor substitution, ie one pointer added to descriptor name. - * Inputs: - * pt - parameter type - * tm - typemap contents that might contain the special variable to be replaced - * Outputs: - * tm - typemap contents complete with the special variable substitution - * Return: - * substitution_performed - flag indicating if a substitution was performed - * ----------------------------------------------------------------------------- */ - - bool substituteClassname(SwigType *pt, String *tm) { - bool substitution_performed = false; - if (Strstr(tm, "$m3classname") || Strstr(tm, "$&m3classname")) { - String *classname = getProxyName(pt); - if (classname) { - Replaceall(tm, "$&m3classname", classname); // getProxyName() works for pointers to classes too - Replaceall(tm, "$m3classname", classname); - } else { // use $descriptor if SWIG does not know anything about this type. Note that any typedefs are resolved. - String *descriptor = NULL; - SwigType *type = Copy(SwigType_typedef_resolve_all(pt)); - - if (Strstr(tm, "$&m3classname")) { - SwigType_add_pointer(type); - descriptor = NewStringf("SWIGTYPE%s", SwigType_manglestr(type)); - Replaceall(tm, "$&m3classname", descriptor); - } else { // $m3classname - descriptor = NewStringf("SWIGTYPE%s", SwigType_manglestr(type)); - Replaceall(tm, "$m3classname", descriptor); - } - - // Add to hash table so that the type wrapper classes can be created later - Setattr(swig_types_hash, descriptor, type); - Delete(descriptor); - Delete(type); - } - substitution_performed = true; - } - return substitution_performed; - } - - /* ----------------------------------------------------------------------------- - * attachParameterNames() - * - * Inputs: - * n - Node of a function declaration - * tmid - attribute name for overriding C argument names, - * e.g. "tmap:m3wrapinname", - * don't forget to attach the mapped types before - * nameid - attribute for attaching the names, - * e.g. "modula3:inname" - * fmt - format for the argument name containing %d - * e.g. "arg%d" - * ----------------------------------------------------------------------------- */ - - void attachParameterNames(Node *n, const char *tmid, const char *nameid, const char *fmt) { - /* Use C parameter name if present and unique, - otherwise create an 'arg%d' name */ - Hash *hash = NewHash(); - Parm *p = Getattr(n, "parms"); - int count = 0; - while (p != NIL) { - String *name = Getattr(p, tmid); - if (name == NIL) { - name = Getattr(p, "name"); - } - String *newname; - if ((!hasContent(name)) || (Getattr(hash, name) != NIL)) { - newname = NewStringf(fmt, count); - } else { - newname = Copy(name); - } - if (1 == Setattr(hash, newname, "1")) { - Swig_warning(WARN_MODULA3_DOUBLE_ID, input_file, line_number, "Argument '%s' twice.\n", newname); - } - Setattr(p, nameid, newname); -// Delete(newname); - p = nextSibling(p); - count++; - } - Delete(hash); - } - - /* ----------------------------------------------------------------------------- - * createM3Signature() - * - * Create signature of M3 wrapper procedure - * Call attachParameterNames and attach mapped types before! - * m3wrapintype, m3wrapinmode, m3wrapindefault - * ----------------------------------------------------------------------------- */ - - String *createM3Signature(Node *n) { - String *arguments = NewString(""); - Parm *p = skipIgnored(Getattr(n, "parms"), "m3wrapintype"); - writeArgState state; - while (p != NIL) { - - /* Get the M3 parameter type */ - String *tm = getMappedType(p, "m3wrapintype"); - if (tm != NIL) { - if (isInParam(p)) { - addImports(m3wrap_intf.import, "m3wrapintype", p); - addImports(m3wrap_impl.import, "m3wrapintype", p); - String *mode = Getattr(p, "tmap:m3wrapinmode"); - String *deflt = Getattr(p, "tmap:m3wrapindefault"); - String *arg = Getattr(p, "autoname"); - SwigType *pt = Getattr(p, "type"); - substituteClassname(pt, tm); /* do we need this ? */ - - writeArg(arguments, state, mode, arg, tm, deflt); - } - p = skipIgnored(Getattr(p, "tmap:m3wrapintype:next"), "m3wrapintype"); - } else { - p = nextSibling(p); - } - } - writeArg(arguments, state, NIL, NIL, NIL, NIL); - return (arguments); - } - -/* not used any longer - - try SwigType_str if required again */ -#if 0 - /* ----------------------------------------------------------------------------- - * createCSignature() - * - * Create signature of C function - * ----------------------------------------------------------------------------- */ - - String *createCSignature(Node *n) { - String *arguments = NewString(""); - bool gencomma = false; - Node *p; - for (p = Getattr(n, "parms"); p != NIL; p = nextSibling(p)) { - if (gencomma) { - Append(arguments, ","); - } - gencomma = true; - String *type = Getattr(p, "type"); - String *ctype = getMappedTypeNew(type, "ctype"); - Append(arguments, ctype); - } - return arguments; - } -#endif - - /* ----------------------------------------------------------------------------- - * emitTypeWrapperClass() - * ----------------------------------------------------------------------------- */ - - void emitTypeWrapperClass(String *classname, SwigType *type) { - Node *n = NewHash(); - Setfile(n, input_file); - Setline(n, line_number); - - String *filen = NewStringf("%s%s.m3", SWIG_output_directory(), classname); - File *f_swigtype = NewFile(filen, "w", SWIG_output_files()); - if (!f_swigtype) { - FileErrorDisplay(filen); - SWIG_exit(EXIT_FAILURE); - } - String *swigtype = NewString(""); - - // Emit banner name - emitBanner(f_swigtype); - - // Pure Modula 3 baseclass and interfaces - const String *pure_baseclass = typemapLookup(n, "m3base", type, WARN_NONE); - const String *pure_interfaces = typemapLookup(n, "m3interfaces", type, WARN_NONE); - - // Emit the class - Printv(swigtype, typemapLookup(n, "m3imports", type, WARN_NONE), // Import statements - "\n", typemapLookup(n, "m3classmodifiers", type, WARN_MODULA3_TYPEMAP_CLASSMOD_UNDEF), // Class modifiers - " class $m3classname", // Class name and bases - *Char(pure_baseclass) ? " : " : "", pure_baseclass, *Char(pure_interfaces) ? // Interfaces - " : " : "", pure_interfaces, " {\n", " private IntPtr swigCPtr;\n", "\n", " ", typemapLookup(n, "m3ptrconstructormodifiers", type, WARN_MODULA3_TYPEMAP_PTRCONSTMOD_UNDEF), // pointer constructor modifiers - " $m3classname(IntPtr cPtr, bool bFutureUse) {\n", // Constructor used for wrapping pointers - " swigCPtr = cPtr;\n", " }\n", "\n", " protected $m3classname() {\n", // Default constructor - " swigCPtr = IntPtr.Zero;\n", " }\n", typemapLookup(n, "m3getcptr", type, WARN_MODULA3_TYPEMAP_GETCPTR_UNDEF), // getCPtr method - typemapLookup(n, "m3code", type, WARN_NONE), // extra Modula 3 code - "}\n", "\n", NIL); - - Replaceall(swigtype, "$m3classname", classname); - Printv(f_swigtype, swigtype, NIL); - - Delete(f_swigtype); - Delete(filen); - Delete(swigtype); - } - - /* ----------------------------------------------------------------------------- - * typemapLookup() - * n - for input only and must contain info for Getfile(n) and Getline(n) to work - * tmap_method - typemap method name - * type - typemap type to lookup - * warning - warning number to issue if no typemaps found - * typemap_attributes - the typemap attributes are attached to this node and will - * also be used for temporary storage if non null - * return is never NULL, unlike Swig_typemap_lookup() - * ----------------------------------------------------------------------------- */ - - const String *typemapLookup(Node *n, const_String_or_char_ptr tmap_method, SwigType *type, int warning, Node *typemap_attributes = 0) { - Node *node = !typemap_attributes ? NewHash() : typemap_attributes; - Setattr(node, "type", type); - Setfile(node, Getfile(n)); - Setline(node, Getline(n)); - const String *tm = Swig_typemap_lookup(tmap_method, node, "", 0); - if (!tm) { - tm = empty_string; - if (warning != WARN_NONE) - Swig_warning(warning, Getfile(n), Getline(n), "No %s typemap defined for %s\n", tmap_method, SwigType_str(type, 0)); - } - if (!typemap_attributes) - Delete(node); - return tm; - } - - /* ----------------------------------------------------------------------------- - * addThrows() - * - * Add all exceptions to a hash that are associated with the 'typemap'. - * Return number the number of these exceptions. - * ----------------------------------------------------------------------------- */ - - int addThrows(Hash *throws_hash, const String *typemap, Node *parameter) { - // Get the comma separated throws clause - held in "throws" attribute in the typemap passed in - int len = 0; - String *throws_attribute = NewStringf("%s:throws", typemap); - - addImports(m3wrap_intf.import, throws_attribute, parameter); - addImports(m3wrap_impl.import, throws_attribute, parameter); - - String *throws = getMappedTypeNew(parameter, Char(throws_attribute), "", false); - //printf("got exceptions %s for %s\n", Char(throws), Char(throws_attribute)); - - if (throws) { - // Put the exception classes in the throws clause into a temporary List - List *temp_classes_list = Split(throws, ',', INT_MAX); - len = Len(temp_classes_list); - - // Add the exception classes to the node throws list, but don't duplicate if already in list - if (temp_classes_list /*&& hasContent(temp_classes_list) */ ) { - for (Iterator cls = First(temp_classes_list); cls.item != NIL; cls = Next(cls)) { - String *exception_class = NewString(cls.item); - Replaceall(exception_class, " ", ""); // remove spaces - Replaceall(exception_class, "\t", ""); // remove tabs - if (hasContent(exception_class)) { - // $m3classname substitution - SwigType *pt = Getattr(parameter, "type"); - substituteClassname(pt, exception_class); - // Don't duplicate the exception class in the throws clause - //printf("add exception %s\n", Char(exception_class)); - Setattr(throws_hash, exception_class, "1"); - } - Delete(exception_class); - } - } - Delete(temp_classes_list); - } - Delete(throws_attribute); - return len; - } - - /* ----------------------------------------------------------------------------- - * generateThrowsClause() - * ----------------------------------------------------------------------------- */ - - void generateThrowsClause(Hash *throws_hash, String *code) { - // Add the throws clause into code - if (Len(throws_hash) > 0) { - Iterator cls = First(throws_hash); - Printf(code, " RAISES {%s", cls.key); - for (cls = Next(cls); cls.key != NIL; cls = Next(cls)) { - Printf(code, ", %s", cls.key); - } - Printf(code, "}"); - } - } - - /* ----------------------------------------------------------------------------- - * addImports() - * - * Add all imports that are needed for contents of 'typemap'. - * ----------------------------------------------------------------------------- */ - - void addImports(Hash *imports_hash, const String *typemap, Node *node) { - // Get the comma separated throws clause - held in "throws" attribute in the typemap passed in - String *imports_attribute = NewStringf("%s:import", typemap); - String *imports = getMappedTypeNew(node, Char(imports_attribute), "", false); - //printf("got imports %s for %s\n", Char(imports), Char(imports_attribute)); - - if (imports != NIL) { - List *import_list = Split(imports, ',', INT_MAX); - - // Add the exception classes to the node imports list, but don't duplicate if already in list - if (import_list != NIL) { - for (Iterator imp = First(import_list); imp.item != NIL; imp = Next(imp)) { - List *import_pair = Split(imp.item, ' ', 3); - if (Len(import_pair) == 1) { - Setattr(imports_hash, Getitem(import_pair, 0), ""); - } else if ((Len(import_pair) == 3) - && Strcmp(Getitem(import_pair, 1), "AS") == 0) { - Setattr(imports_hash, Getitem(import_pair, 0), Getitem(import_pair, 2)); - } else { - Swig_warning(WARN_MODULA3_BAD_IMPORT, input_file, line_number, - "Malformed import '%s' for typemap '%s' defined for type '%s'\n", imp, typemap, SwigType_str(Getattr(node, "type"), 0)); - } - Delete(import_pair); - } - } - Delete(import_list); - } - Delete(imports_attribute); - } - - /* ----------------------------------------------------------------------------- - * emitImportStatements() - * ----------------------------------------------------------------------------- */ - - void emitImportStatements(Hash *imports_hash, String *code) { - // Add the imports statements into code - Iterator imp = First(imports_hash); - while (imp.key != NIL) { - Printf(code, "IMPORT %s", imp.key); - String *imp_as = imp.item; - if (hasContent(imp_as)) { - Printf(code, " AS %s", imp_as); - } - Printf(code, ";\n"); - imp = Next(imp); - } - } - -}; /* class MODULA3 */ - -/* ----------------------------------------------------------------------------- - * swig_modula3() - Instantiate module - * ----------------------------------------------------------------------------- */ - -extern "C" Language *swig_modula3(void) { - return new MODULA3(); -} - -/* ----------------------------------------------------------------------------- - * Static member variables - * ----------------------------------------------------------------------------- */ - -const char *MODULA3::usage = "\ -Modula 3 Options (available with -modula3)\n\ - -generateconst - Generate code for computing numeric values of constants\n\ - -generaterename - Generate suggestions for %rename\n\ - -generatetypemap - Generate templates for some basic typemaps\n\ - -oldvarnames - Old intermediary method names for variable wrappers\n\ -\n"; - -/* - -generateconst - stem of the .c source file for computing the numeric values of constants\n\ - -generaterename - stem of the .i source file containing %rename suggestions\n\ - -generatetypemap - stem of the .i source file containing typemap patterns\n\ -*/ diff --git a/Source/Modules/mzscheme.cxx b/Source/Modules/mzscheme.cxx index 788681330..3ff691662 100644 --- a/Source/Modules/mzscheme.cxx +++ b/Source/Modules/mzscheme.cxx @@ -322,8 +322,6 @@ public: } // Handle parameter types. if ((tm = Getattr(p, "tmap:in"))) { - Replaceall(tm, "$source", source); - Replaceall(tm, "$target", target); Replaceall(tm, "$input", source); Setattr(p, "emit:input", source); Printv(f->code, tm, "\n", NIL); @@ -343,7 +341,6 @@ public: /* Insert constraint checking code */ for (p = l; p;) { if ((tm = Getattr(p, "tmap:check"))) { - Replaceall(tm, "$target", Getattr(p, "lname")); Printv(f->code, tm, "\n", NIL); p = Getattr(p, "tmap:check:next"); } else { @@ -355,8 +352,6 @@ public: for (p = l; p;) { if ((tm = Getattr(p, "tmap:argout"))) { - Replaceall(tm, "$source", Getattr(p, "emit:input")); /* Deprecated */ - Replaceall(tm, "$target", Getattr(p, "lname")); /* Deprecated */ Replaceall(tm, "$arg", Getattr(p, "emit:input")); Replaceall(tm, "$input", Getattr(p, "emit:input")); Printv(outarg, tm, "\n", NIL); @@ -371,7 +366,6 @@ public: /* Insert cleanup code */ for (p = l; p;) { if ((tm = Getattr(p, "tmap:freearg"))) { - Replaceall(tm, "$target", Getattr(p, "lname")); Printv(cleanup, tm, "\n", NIL); p = Getattr(p, "tmap:freearg:next"); } else { @@ -385,8 +379,6 @@ public: // Now have return value, figure out what to do with it. if ((tm = Swig_typemap_lookup_out("out", n, Swig_cresult_name(), f, actioncode))) { - Replaceall(tm, "$source", Swig_cresult_name()); - Replaceall(tm, "$target", "values[0]"); Replaceall(tm, "$result", "values[0]"); if (GetFlag(n, "feature:new")) Replaceall(tm, "$owner", "1"); @@ -408,14 +400,12 @@ public: if (GetFlag(n, "feature:new")) { if ((tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); Printv(f->code, tm, "\n", NIL); } } // Free any memory allocated by the function being wrapped.. if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); Printv(f->code, tm, "\n", NIL); } // Wrap things up (in a manner of speaking) @@ -453,7 +443,7 @@ public: Printv(df->def, "static Scheme_Object *\n", dname, "(int argc, Scheme_Object **argv) {", NIL); Printv(df->code, dispatch, "\n", NIL); Printf(df->code, "scheme_signal_error(\"No matching function for overloaded '%s'\");\n", iname); - Printf(df->code, "return NULL;\n", iname); + Printf(df->code, "return NULL;\n"); Printv(df->code, "}\n", NIL); Wrapper_print(df, f_wrappers); Printf(init_func_def, "scheme_add_global(\"%s\", scheme_make_prim_w_arity(%s,\"%s\",%d,%d),menv);\n", proc_name, dname, proc_name, 0, maxargs); @@ -521,8 +511,6 @@ public: /* Check for a setting of the variable value */ Printf(f->code, "if (argc) {\n"); if ((tm = Swig_typemap_lookup("varin", n, name, 0))) { - Replaceall(tm, "$source", "argv[0]"); - Replaceall(tm, "$target", name); Replaceall(tm, "$input", "argv[0]"); Replaceall(tm, "$argnum", "1"); emit_action_code(n, f->code, tm); @@ -535,8 +523,6 @@ public: // of evaluating or setting) if ((tm = Swig_typemap_lookup("varout", n, name, 0))) { - Replaceall(tm, "$source", name); - Replaceall(tm, "$target", "swig_result"); Replaceall(tm, "$result", "swig_result"); /* Printf (f->code, "%s\n", tm); */ emit_action_code(n, f->code, tm); @@ -609,9 +595,7 @@ public: Printv(rvalue, "'", temp, "'", NIL); } if ((tm = Swig_typemap_lookup("constant", n, name, 0))) { - Replaceall(tm, "$source", rvalue); Replaceall(tm, "$value", rvalue); - Replaceall(tm, "$target", name); Printf(f_init, "%s\n", tm); } else { // Create variable and assign it a value diff --git a/Source/Modules/nested.cxx b/Source/Modules/nested.cxx index 0fcd5ad18..808ee5d05 100644 --- a/Source/Modules/nested.cxx +++ b/Source/Modules/nested.cxx @@ -396,7 +396,7 @@ void Swig_nested_name_unnamed_c_structs(Node *n) { Delete(ins); Delattr(c, "nested:outer"); } else { - // global unnamed struct - ignore it and it's instances + // global unnamed struct - ignore it and its instances SetFlag(c, "feature:ignore"); while (next && Getattr(next, "nested:unnamedtype") == c) { SetFlag(next, "feature:ignore"); diff --git a/Source/Modules/ocaml.cxx b/Source/Modules/ocaml.cxx index 9f7504b87..a36912ab7 100644 --- a/Source/Modules/ocaml.cxx +++ b/Source/Modules/ocaml.cxx @@ -407,7 +407,7 @@ public: printf("Fatal error. SwigType_del_pointer applied to non-pointer.\n"); abort(); } - Replace(t, "r.", "", DOH_REPLACE_ANY | DOH_REPLACE_FIRST); + Replace(t, "r.", "", DOH_REPLACE_FIRST); } void oc_SwigType_del_array(SwigType *t) { @@ -590,8 +590,6 @@ public: } // Handle parameter types. if ((tm = Getattr(p, "tmap:in"))) { - Replaceall(tm, "$source", source); - Replaceall(tm, "$target", target); Replaceall(tm, "$input", source); Setattr(p, "emit:input", source); Printv(f->code, tm, "\n", NIL); @@ -611,7 +609,6 @@ public: /* Insert constraint checking code */ for (p = l; p;) { if ((tm = Getattr(p, "tmap:check"))) { - Replaceall(tm, "$target", Getattr(p, "lname")); Printv(f->code, tm, "\n", NIL); p = Getattr(p, "tmap:check:next"); } else { @@ -623,8 +620,6 @@ public: for (p = l; p;) { if ((tm = Getattr(p, "tmap:argout"))) { - Replaceall(tm, "$source", Getattr(p, "emit:input")); /* Deprecated */ - Replaceall(tm, "$target", Getattr(p, "lname")); /* Deprecated */ Replaceall(tm, "$arg", Getattr(p, "emit:input")); Replaceall(tm, "$input", Getattr(p, "emit:input")); Replaceall(tm, "$ntype", normalizeTemplatedClassName(Getattr(p, "type"))); @@ -640,7 +635,6 @@ public: /* Insert cleanup code */ for (p = l; p;) { if ((tm = Getattr(p, "tmap:freearg"))) { - Replaceall(tm, "$target", Getattr(p, "lname")); Printv(cleanup, tm, "\n", NIL); p = Getattr(p, "tmap:freearg:next"); } else { @@ -681,8 +675,6 @@ public: String *actioncode = emit_action(n); if ((tm = Swig_typemap_lookup_out("out", n, Swig_cresult_name(), f, actioncode))) { - Replaceall(tm, "$source", "swig_result"); - Replaceall(tm, "$target", "rv"); Replaceall(tm, "$result", "rv"); Replaceall(tm, "$ntype", return_type_normalized); Printv(f->code, tm, "\n", NIL); @@ -701,14 +693,12 @@ public: if (GetFlag(n, "feature:new")) { if ((tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", "swig_result"); Printv(f->code, tm, "\n", NIL); } } /* See if there is any return cleanup code */ if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); Printf(f->code, "%s\n", tm); Delete(tm); } @@ -716,7 +706,6 @@ public: // Free any memory allocated by the function being wrapped.. if ((tm = Swig_typemap_lookup("swig_result", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); Printv(f->code, tm, "\n", NIL); } // Wrap things up (in a manner of speaking) @@ -853,13 +842,9 @@ public: /* Check for a setting of the variable value */ Printf(f->code, "if (args != Val_int(0)) {\n"); if ((tm = Swig_typemap_lookup("varin", n, name, 0))) { - Replaceall(tm, "$source", "args"); - Replaceall(tm, "$target", name); Replaceall(tm, "$input", "args"); emit_action_code(n, f->code, tm); } else if ((tm = Swig_typemap_lookup("in", n, name, 0))) { - Replaceall(tm, "$source", "args"); - Replaceall(tm, "$target", name); Replaceall(tm, "$input", "args"); emit_action_code(n, f->code, tm); } else { @@ -871,13 +856,9 @@ public: // of evaluating or setting) if ((tm = Swig_typemap_lookup("varout", n, name, 0))) { - Replaceall(tm, "$source", name); - Replaceall(tm, "$target", "swig_result"); Replaceall(tm, "$result", "swig_result"); emit_action_code(n, f->code, tm); } else if ((tm = Swig_typemap_lookup("out", n, name, 0))) { - Replaceall(tm, "$source", name); - Replaceall(tm, "$target", "swig_result"); Replaceall(tm, "$result", "swig_result"); emit_action_code(n, f->code, tm); } else { diff --git a/Source/Modules/octave.cxx b/Source/Modules/octave.cxx index b1769e42a..04b315eaf 100644 --- a/Source/Modules/octave.cxx +++ b/Source/Modules/octave.cxx @@ -611,9 +611,7 @@ public: sprintf(source, "args(%d)", j); Setattr(p, "emit:input", source); - Replaceall(tm, "$source", Getattr(p, "emit:input")); Replaceall(tm, "$input", Getattr(p, "emit:input")); - Replaceall(tm, "$target", Getattr(p, "lname")); if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) { Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); @@ -658,7 +656,6 @@ public: // Insert constraint checking code for (p = l; p;) { if ((tm = Getattr(p, "tmap:check"))) { - Replaceall(tm, "$target", Getattr(p, "lname")); Printv(f->code, tm, "\n", NIL); p = Getattr(p, "tmap:check:next"); } else { @@ -681,7 +678,6 @@ public: } } if (tm && (Len(tm) != 0)) { - Replaceall(tm, "$source", Getattr(p, "lname")); Printv(cleanup, tm, "\n", NIL); } p = Getattr(p, "tmap:freearg:next"); @@ -694,8 +690,6 @@ public: String *outarg = NewString(""); for (p = l; p;) { if ((tm = Getattr(p, "tmap:argout"))) { - Replaceall(tm, "$source", Getattr(p, "lname")); - Replaceall(tm, "$target", "_outp"); Replaceall(tm, "$result", "_outp"); Replaceall(tm, "$arg", Getattr(p, "emit:input")); Replaceall(tm, "$input", Getattr(p, "emit:input")); @@ -723,8 +717,6 @@ public: // Return the function value if ((tm = Swig_typemap_lookup_out("out", n, Swig_cresult_name(), f, actioncode))) { - Replaceall(tm, "$source", Swig_cresult_name()); - Replaceall(tm, "$target", "_outv"); Replaceall(tm, "$result", "_outv"); if (GetFlag(n, "feature:new")) @@ -745,13 +737,11 @@ public: if (GetFlag(n, "feature:new")) { if ((tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); Printf(f->code, "%s\n", tm); } } if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); Replaceall(tm, "$result", "_outv"); Printf(f->code, "%s\n", tm); Delete(tm); @@ -815,7 +805,7 @@ public: Printf(tmp, "}"); Wrapper_add_local(f, "argv", tmp); Printv(f->code, dispatch, "\n", NIL); - Printf(f->code, "error(\"No matching function for overload\");\n", iname); + Printf(f->code, "error(\"No matching function for overload\");\n"); Printf(f->code, "return octave_value_list();\n"); Printv(f->code, "}\n", NIL); @@ -849,8 +839,6 @@ public: if (is_assignable(n)) { Setattr(n, "wrap:name", setname); if ((tm = Swig_typemap_lookup("varin", n, name, 0))) { - Replaceall(tm, "$source", "args(0)"); - Replaceall(tm, "$target", name); Replaceall(tm, "$input", "args(0)"); if (Getattr(n, "tmap:varin:implicitconv")) { Replaceall(tm, "$implicitconv", get_implicitconv_flag(n)); @@ -874,8 +862,6 @@ public: Octave_begin_function(n, getf->def, getname, getwname, true); Wrapper_add_local(getf, "obj", "octave_value obj"); if ((tm = Swig_typemap_lookup("varout", n, name, 0))) { - Replaceall(tm, "$source", name); - Replaceall(tm, "$target", "obj"); Replaceall(tm, "$result", "obj"); addfail = emit_action_code(n, getf->code, tm); Delete(tm); @@ -920,8 +906,6 @@ public: value = wname; } if ((tm = Swig_typemap_lookup("constcode", n, name, 0))) { - Replaceall(tm, "$source", value); - Replaceall(tm, "$target", name); Replaceall(tm, "$value", cppvalue ? cppvalue : value); Replaceall(tm, "$nsname", iname); Printf(f_init, "%s\n", tm); diff --git a/Source/Modules/overload.cxx b/Source/Modules/overload.cxx index 5d278107c..8a4ce48f7 100644 --- a/Source/Modules/overload.cxx +++ b/Source/Modules/overload.cxx @@ -21,6 +21,7 @@ String *argv_template_string; String *argc_template_string; +namespace { struct Overloaded { Node *n; /* Node */ int argc; /* Argument count */ @@ -28,6 +29,7 @@ struct Overloaded { int error; /* Ambiguity error */ bool implicitconv_function; /* For ordering implicitconv functions*/ }; +} static int fast_dispatch_mode = 0; static int cast_dispatch_mode = 0; @@ -809,7 +811,7 @@ String *Swig_overload_dispatch(Node *n, const_String_or_char_ptr fmt, int *maxar } if (num_arguments) { - Printf(f, "int _v;\n"); + Printf(f, "int _v = 0;\n"); } int num_braces = 0; diff --git a/Source/Modules/perl5.cxx b/Source/Modules/perl5.cxx index dfa85f3c8..459d403bf 100644 --- a/Source/Modules/perl5.cxx +++ b/Source/Modules/perl5.cxx @@ -445,13 +445,7 @@ public: Printv(magic, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n", - "#ifdef PERL_OBJECT\n", - "#define MAGIC_CLASS _wrap_", underscore_module, "_var::\n", - "class _wrap_", underscore_module, "_var : public CPerlObj {\n", - "public:\n", - "#else\n", "#define MAGIC_CLASS\n", - "#endif\n", "SWIGCLASS_STATIC int swig_magic_readonly(pTHX_ SV *SWIGUNUSEDPARM(sv), MAGIC *SWIGUNUSEDPARM(mg)) {\n", tab4, "MAGIC_PPERL\n", tab4, "croak(\"Value is read-only.\");\n", tab4, "return 0;\n", "}\n", NIL); @@ -470,7 +464,6 @@ public: /* Dump out variable wrappers */ - Printv(magic, "\n\n#ifdef PERL_OBJECT\n", "};\n", "#endif\n", NIL); Printv(magic, "\n#ifdef __cplusplus\n}\n#endif\n", NIL); Printf(f_header, "%s\n", magic); @@ -725,14 +718,11 @@ public: /* Produce string representation of source and target arguments */ sprintf(source, "ST(%d)", i); - String *target = Getattr(p, "lname"); if (i >= num_required) { Printf(f->code, " if (items > %d) {\n", i); } if ((tm = Getattr(p, "tmap:in"))) { - Replaceall(tm, "$target", target); - Replaceall(tm, "$source", source); Replaceall(tm, "$input", source); Setattr(p, "emit:input", source); /* Save input location */ @@ -767,7 +757,6 @@ public: /* Insert constraint checking code */ for (p = l; p;) { if ((tm = Getattr(p, "tmap:check"))) { - Replaceall(tm, "$target", Getattr(p, "lname")); Printv(f->code, tm, "\n", NIL); p = Getattr(p, "tmap:check:next"); } else { @@ -778,7 +767,6 @@ public: /* Insert cleanup code */ for (i = 0, p = l; p; i++) { if ((tm = Getattr(p, "tmap:freearg"))) { - Replaceall(tm, "$source", Getattr(p, "lname")); Replaceall(tm, "$arg", Getattr(p, "emit:input")); Replaceall(tm, "$input", Getattr(p, "emit:input")); Printv(cleanup, tm, "\n", NIL); @@ -793,8 +781,6 @@ public: for (i = 0, p = l; p; i++) { if ((tm = Getattr(p, "tmap:argout"))) { SwigType *t = Getattr(p, "type"); - Replaceall(tm, "$source", Getattr(p, "lname")); - Replaceall(tm, "$target", "ST(argvi)"); Replaceall(tm, "$result", "ST(argvi)"); if (is_shadow(t)) { Replaceall(tm, "$shadow", "SWIG_SHADOW"); @@ -855,8 +841,6 @@ public: if ((tm = Swig_typemap_lookup_out("out", n, Swig_cresult_name(), f, actioncode))) { SwigType *t = Getattr(n, "type"); - Replaceall(tm, "$source", Swig_cresult_name()); - Replaceall(tm, "$target", "ST(argvi)"); Replaceall(tm, "$result", "ST(argvi)"); if (is_shadow(t)) { Replaceall(tm, "$shadow", "SWIG_SHADOW"); @@ -884,13 +868,11 @@ public: if (GetFlag(n, "feature:new")) { if ((tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); Printf(f->code, "%s\n", tm); } } if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); Printf(f->code, "%s\n", tm); } @@ -995,8 +977,6 @@ public: /* Check for a few typemaps */ tm = Swig_typemap_lookup("varin", n, name, 0); if (tm) { - Replaceall(tm, "$source", "sv"); - Replaceall(tm, "$target", name); Replaceall(tm, "$input", "sv"); /* Printf(setf->code,"%s\n", tm); */ emit_action_code(n, setf->code, tm); @@ -1019,9 +999,7 @@ public: Printv(getf->code, tab4, "MAGIC_PPERL\n", NIL); if ((tm = Swig_typemap_lookup("varout", n, name, 0))) { - Replaceall(tm, "$target", "sv"); Replaceall(tm, "$result", "sv"); - Replaceall(tm, "$source", name); if (is_shadow(t)) { Replaceall(tm, "$shadow", "SWIG_SHADOW"); } else { @@ -1111,8 +1089,6 @@ public: } if ((tm = Swig_typemap_lookup("consttab", n, name, 0))) { - Replaceall(tm, "$source", value); - Replaceall(tm, "$target", name); Replaceall(tm, "$value", value); if (is_shadow(type)) { Replaceall(tm, "$shadow", "SWIG_SHADOW"); @@ -1121,8 +1097,6 @@ public: } Printf(constant_tab, "%s,\n", tm); } else if ((tm = Swig_typemap_lookup("constcode", n, name, 0))) { - Replaceall(tm, "$source", value); - Replaceall(tm, "$target", name); Replaceall(tm, "$value", value); if (is_shadow(type)) { Replaceall(tm, "$shadow", "SWIG_SHADOW"); @@ -2341,7 +2315,7 @@ public: Replaceall(tm, "$error", "ERRSV"); Printv(w->code, Str(tm), "\n", NIL); } else { - Printf(w->code, " Swig::DirectorMethodException::raise(ERRSV);\n", classname, pyname); + Printf(w->code, " Swig::DirectorMethodException::raise(ERRSV);\n"); } Append(w->code, "}\n"); Delete(tm); diff --git a/Source/Modules/php.cxx b/Source/Modules/php.cxx index 1edbd874c..6862c214b 100644 --- a/Source/Modules/php.cxx +++ b/Source/Modules/php.cxx @@ -1,5 +1,5 @@ /* ----------------------------------------------------------------------------- - * This file is part of SWIG, which is licensed as a whole under version 3 + * This file is part of SWIG, which is licensed as a whole under version 3 * (or any later version) of the GNU General Public License. Some additional * terms also apply to certain portions of SWIG. The full details of the SWIG * license and copyrights can be found in the LICENSE and COPYRIGHT files @@ -12,72 +12,36 @@ * ----------------------------------------------------------------------------- */ -/* FIXME: PHP OO wrapping TODO list: - * - * Medium term: - * - * Handle default parameters on overloaded methods in PHP where possible. - * (Mostly done - just need to handle cases of overloaded methods with - * default parameters...) - * This is an optimisation - we could handle this case using a PHP - * default value, but currently we treat it as we would for a default - * value which is a compound C++ expression (i.e. as if we had a - * method with two overloaded forms instead of a single method with - * a default parameter value). - * - * Long term: - * - * Sort out locale-dependent behaviour of strtod() - it's harmless unless - * SWIG ever sets the locale and DOH/base.c calls atof, so we're probably - * OK currently at least. - */ - -/* - * TODO: Replace remaining stderr messages with Swig_error or Swig_warning - * (may need to add more WARN_PHP_xxx codes...) - */ - #include "swigmod.h" #include #include static const char *usage = "\ -PHP 7 Options (available with -php7)\n\ - -noproxy - Don't generate proxy classes.\n\ +PHP Options (available with -php7)\n\ -prefix - Prepend to all class names in PHP wrappers\n\ \n"; -/* The original class wrappers for PHP stored the pointer to the C++ class in - * the object property _cPtr. If we use the same name for the member variable - * which we put the pointer to the C++ class in, then the flat function - * wrappers will automatically pull it out without any changes being required. - * FIXME: Isn't using a leading underscore a bit suspect here? - */ -#define SWIG_PTR "_cPtr" +// How to wrap non-class functions, variables and constants: +// FIXME: Make this specifiable and also allow a real namespace. -/* This is the name of the hash where the variables existing only in PHP - * classes are stored. - */ -#define SWIG_DATA "_pData" +// Wrap as global PHP names. +static bool wrap_nonclass_global = true; + +// Wrap in a class to fake a namespace (for compatibility with SWIG's behaviour +// before PHP added namespaces. +static bool wrap_nonclass_fake_class = true; -static int constructors = 0; -static String *NOTCLASS = NewString("Not a class"); -static Node *classnode = 0; static String *module = 0; static String *cap_module = 0; static String *prefix = 0; -static String *shadow_classname = 0; - static File *f_begin = 0; static File *f_runtime = 0; static File *f_runtime_h = 0; static File *f_h = 0; -static File *f_phpcode = 0; static File *f_directors = 0; static File *f_directors_h = 0; -static String *phpfilename = 0; static String *s_header; static String *s_wrappers; @@ -85,7 +49,6 @@ static String *s_init; static String *r_init; // RINIT user code static String *s_shutdown; // MSHUTDOWN user code static String *r_shutdown; // RSHUTDOWN user code -static String *s_vinit; // varinit initialization code. static String *s_vdecl; static String *s_cinit; // consttab initialization code. static String *s_oinit; @@ -93,31 +56,56 @@ static String *s_arginfo; static String *s_entry; static String *cs_entry; static String *all_cs_entry; +static String *fake_cs_entry; +static String *s_creation; static String *pragma_incl; static String *pragma_code; static String *pragma_phpinfo; static String *pragma_version; -static String *s_oowrappers; -static String *s_fakeoowrappers; -static String *s_phpclasses; + +static String *class_name = NULL; +static String *destructor_action = NULL; +static String *magic_set = NULL; +static String *magic_get = NULL; +static String *magic_isset = NULL; + +// Class used as pseudo-namespace for compatibility. +static String *fake_class_name() { + static String *result = NULL; + if (!result) { + result = Len(prefix) ? prefix : module; + if (!fake_cs_entry) { + fake_cs_entry = NewStringf("static const zend_function_entry class_%s_functions[] = {\n", result); + } + + Printf(s_creation, "static zend_class_entry *SWIG_Php_ce_%s;\n\n",result); + + Printf(s_oinit, " INIT_CLASS_ENTRY(internal_ce, \"%s\", class_%s_functions);\n", result, result); + Printf(s_oinit, " SWIG_Php_ce_%s = zend_register_internal_class(&internal_ce);\n", result); + Printf(s_oinit, "\n"); + } + return result; +} + +static String *swig_wrapped_interface_ce() { + static String *result = NULL; + if (!result) { + result = NewStringf("SWIG_Php_swig_wrapped_interface_ce"); + Printf(s_oinit, " INIT_CLASS_ENTRY(%s, \"SWIG\\\\wrapped\", NULL);\n", result); + } + return result; +} /* To reduce code size (generated and compiled) we only want to emit each * different arginfo once, so we need to track which have been used. */ static Hash *arginfo_used; -/* Variables for using PHP classes */ -static Node *current_class = 0; - -static Hash *shadow_get_vars; -static Hash *shadow_set_vars; +/* Track non-class pointer types we need to to wrap */ static Hash *zend_types = 0; static int shadow = 1; -static bool class_has_ctor = false; -static String *wrapping_member_constant = NULL; - // These static variables are used to pass some state from Handlers into functionWrapper static enum { standard = 0, @@ -126,73 +114,169 @@ static enum { membervar, staticmembervar, constructor, - directorconstructor + destructor, + directorconstructor, + directordisown } wrapperType = standard; extern "C" { static void (*r_prevtracefunc) (const SwigType *t, String *mangled, String *clientdata) = 0; } -static void SwigPHP_emit_resource_registrations() { - Iterator ki; - bool emitted_default_dtor = false; - +static void SwigPHP_emit_pointer_type_registrations() { if (!zend_types) return; - ki = First(zend_types); - if (ki.key) - Printf(s_oinit, "\n /* Register resource destructors for pointer types */\n"); + Iterator ki = First(zend_types); + if (!ki.key) + return; + + Printf(s_wrappers, "/* class object handlers for pointer wrappers */\n"); + Printf(s_wrappers, "static zend_object_handlers swig_ptr_object_handlers;\n\n"); + + Printf(s_wrappers, "/* Object Creation Method for pointer wrapping class */\n"); + Printf(s_wrappers, "static zend_object *swig_ptr_object_new(zend_class_entry *ce) {\n"); + Printf(s_wrappers, " swig_object_wrapper *obj = (swig_object_wrapper*)zend_object_alloc(sizeof(swig_object_wrapper), ce);\n"); + Printf(s_wrappers, " zend_object_std_init(&obj->std, ce);\n"); + Printf(s_wrappers, " object_properties_init(&obj->std, ce);\n"); + Printf(s_wrappers, " obj->std.handlers = &swig_ptr_object_handlers;\n"); + Printf(s_wrappers, " obj->newobject = 0;\n"); + Printf(s_wrappers, " return &obj->std;\n"); + Printf(s_wrappers, "}\n\n"); + + Printf(s_wrappers, "/* Implement __toString equivalent, since that worked for the old-style resource wrapped pointers. */\n"); + Append(s_wrappers, "#if PHP_MAJOR_VERSION < 8\n"); + Printf(s_wrappers, "static int swig_ptr_cast_object(zval *z, zval *retval, int type) {\n"); + Append(s_wrappers, "#else\n"); + Printf(s_wrappers, "static int swig_ptr_cast_object(zend_object *zobj, zval *retval, int type) {\n"); + Append(s_wrappers, "#endif\n"); + Printf(s_wrappers, " if (type == IS_STRING) {\n"); + Printf(s_wrappers, " char buf[80];\n"); + Append(s_wrappers, "#if PHP_MAJOR_VERSION < 8\n"); + Printf(s_wrappers, " swig_object_wrapper *obj = SWIG_Z_FETCH_OBJ_P(z);\n"); + Append(s_wrappers, "#else\n"); + Printf(s_wrappers, " swig_object_wrapper *obj = swig_php_fetch_object(zobj);\n"); + Append(s_wrappers, "#endif\n"); + Printv(s_wrappers, " sprintf(buf, \"SWIGPointer(%p,owned=%d)\", obj->ptr, obj->newobject);\n", NIL); + Printf(s_wrappers, " ZVAL_STRING(retval, buf);\n"); + Printf(s_wrappers, " return SUCCESS;\n"); + Printf(s_wrappers, " }\n"); + Printf(s_wrappers, " return FAILURE;\n"); + Printf(s_wrappers, "}\n\n"); + + Printf(s_oinit, "\n /* Register classes to represent non-class pointer types */\n"); + Printf(s_oinit, " swig_ptr_object_handlers = *zend_get_std_object_handlers();\n"); + Printf(s_oinit, " swig_ptr_object_handlers.offset = XtOffsetOf(swig_object_wrapper, std);\n"); + Printf(s_oinit, " swig_ptr_object_handlers.cast_object = swig_ptr_cast_object;\n"); + while (ki.key) { - DOH *key = ki.key; - Node *class_node = ki.item; - String *human_name = key; - String *rsrc_dtor_name = NULL; + String *type = ki.key; - // write out body - if (class_node != NOTCLASS) { - String *destructor = Getattr(class_node, "destructor"); - human_name = Getattr(class_node, "sym:name"); - if (!human_name) - human_name = Getattr(class_node, "name"); - // Do we have a known destructor for this type? - if (destructor) { - rsrc_dtor_name = NewStringf("_wrap_destroy%s", key); - // Write out custom destructor function - Printf(s_wrappers, "static ZEND_RSRC_DTOR_FUNC(%s) {\n", rsrc_dtor_name); - Printf(s_wrappers, " %s(res, SWIGTYPE%s->name);\n", destructor, key); - Printf(s_wrappers, "}\n"); - } - } + String *swig_wrapped = swig_wrapped_interface_ce(); + Printf(s_creation, "/* class entry for pointer to %s */\n", type); + Printf(s_creation, "static zend_class_entry *SWIG_Php_ce_%s;\n\n", type); - if (!rsrc_dtor_name) { - rsrc_dtor_name = NewString("_swig_default_rsrc_destroy"); - if (!emitted_default_dtor) { - // Write out custom destructor function - Printf(s_wrappers, "static ZEND_RSRC_DTOR_FUNC(%s) {\n", rsrc_dtor_name); - Printf(s_wrappers, " efree(res->ptr);\n"); - Printf(s_wrappers, "}\n"); - emitted_default_dtor = true; - } - } - - // declare le_swig_ to store php registration - Printf(s_vdecl, "static int le_swig_%s=0; /* handle for %s */\n", key, human_name); - - // register with php - Printf(s_oinit, " le_swig_%s=zend_register_list_destructors_ex" - "(%s, NULL, SWIGTYPE%s->name, module_number);\n", key, rsrc_dtor_name, key); - - // store php type in class struct - Printf(s_oinit, " SWIG_TypeClientData(SWIGTYPE%s,&le_swig_%s);\n", key, key); - - Delete(rsrc_dtor_name); + Printf(s_oinit, " INIT_CLASS_ENTRY(internal_ce, \"%s\\\\%s\", NULL);\n", "SWIG", type); + Printf(s_oinit, " SWIG_Php_ce_%s = zend_register_internal_class(&internal_ce);\n", type); + Printf(s_oinit, " SWIG_Php_ce_%s->create_object = swig_ptr_object_new;\n", type); + Printv(s_oinit, " zend_do_implement_interface(SWIG_Php_ce_", type, ", &", swig_wrapped, ");\n", NIL); + Printf(s_oinit, " SWIG_TypeClientData(SWIGTYPE%s,SWIG_Php_ce_%s);\n", type, type); + Printf(s_oinit, "\n"); ki = Next(ki); } } +// Class encapsulating the machinery to add PHP type declarations. +class PHPTypes { + Hash *phptypes; + + // List with an entry for each parameter and one for the return type. + // + // We assemble the types in here before emitting them so for an overloaded + // function we combine the type declarations from each overloaded form. + List *merged_types; + + // List with an entry for each parameter which is passed "byref" in any + // overloaded form. We use this to pass such parameters by reference in + // the dispatch function. If NULL, no parameters are passed by reference. + List *byref; + +public: + PHPTypes() : phptypes(NewHash()), merged_types(NULL), byref(NULL) { + Setattr(phptypes, "array", "MAY_BE_ARRAY"); + Setattr(phptypes, "bool", "MAY_BE_BOOL"); + Setattr(phptypes, "callable", "MAY_BE_CALLABLE"); + Setattr(phptypes, "float", "MAY_BE_DOUBLE"); + Setattr(phptypes, "int", "MAY_BE_LONG"); + Setattr(phptypes, "iterable", "MAY_BE_ITERABLE"); + Setattr(phptypes, "mixed", "MAY_BE_MIXED"); + Setattr(phptypes, "null", "MAY_BE_NULL"); + Setattr(phptypes, "object", "MAY_BE_OBJECT"); + Setattr(phptypes, "resource", "MAY_BE_RESOURCE"); + Setattr(phptypes, "string", "MAY_BE_STRING"); + Setattr(phptypes, "void", "MAY_BE_VOID"); + } + + void reset() { + Delete(merged_types); + merged_types = NewList(); + Delete(byref); + byref = NULL; + } + + // key is 0 for return type, or >= 1 for parameters numbered from 1 + void process_phptype(Node *n, int key, const String_or_char *attribute_name); + + String *get_phptype(int key, String *classtypes) { + Clear(classtypes); + DOH *types = Getitem(merged_types, key); + String *result = NewStringEmpty(); + if (types != None) { + SortList(types, NULL); + String *prev = NULL; + for (Iterator i = First(types); i.item; i = Next(i)) { + if (prev && Equal(prev, i.item)) { + // Skip duplicates when merging. + continue; + } + String *c = Getattr(phptypes, i.item); + if (c) { + if (Len(result) > 0) Append(result, "|"); + Append(result, c); + } else { + if (Len(classtypes) > 0) Append(classtypes, "|"); + Append(classtypes, prefix); + Append(classtypes, i.item); + } + prev = i.item; + } + } + // Make the mask 0 if there are only class names specified. + if (Len(result) == 0) { + Append(result, "0"); + } + return result; + } + + void set_byref(int key) { + if (!byref) { + byref = NewList(); + } + while (Len(byref) <= key) { + Append(byref, None); + } + Setitem(byref, key, ""); // Just needs to be something != None. + } + + int get_byref(int key) const { + return byref && key < Len(byref) && Getitem(byref, key) != None; + } +}; + class PHP : public Language { + PHPTypes phptypes; + public: PHP() { director_language = 1; @@ -215,7 +299,7 @@ public: } else { Swig_arg_error(); } - } else if ((strcmp(argv[i], "-noshadow") == 0) || (strcmp(argv[i], "-noproxy") == 0)) { + } else if ((strcmp(argv[i], "-noshadow") == 0)) { shadow = 0; Swig_mark_arg(i); } else if (strcmp(argv[i], "-help") == 0) { @@ -269,13 +353,12 @@ public: r_shutdown = NewStringEmpty(); s_header = NewString("/* header section */\n"); s_wrappers = NewString("/* wrapper section */\n"); + s_creation = NewStringEmpty(); /* subsections of the init section */ - s_vinit = NewStringEmpty(); s_vdecl = NewString("/* vdecl subsection */\n"); s_cinit = NewString(" /* cinit subsection */\n"); s_oinit = NewString(" /* oinit subsection */\n"); pragma_phpinfo = NewStringEmpty(); - s_phpclasses = NewString("/* PHP Proxy Classes */\n"); f_directors_h = NewStringEmpty(); f_directors = NewStringEmpty(); @@ -313,9 +396,6 @@ public: if (!prefix) prefix = NewStringEmpty(); - Printf(f_runtime, "#define SWIG_PREFIX \"%s\"\n", prefix); - Printf(f_runtime, "#define SWIG_PREFIX_LEN %lu\n", (unsigned long)Len(prefix)); - if (directorsEnabled()) { Swig_banner(f_directors_h); Printf(f_directors_h, "\n"); @@ -327,36 +407,6 @@ public: Delete(filename); } - /* PHP module file */ - filen = NewStringEmpty(); - Printv(filen, SWIG_output_directory(), module, ".php", NIL); - phpfilename = NewString(filen); - - f_phpcode = NewFile(filen, "w", SWIG_output_files()); - if (!f_phpcode) { - FileErrorDisplay(filen); - SWIG_exit(EXIT_FAILURE); - } - - Printf(f_phpcode, "error_msg = default_error_msg;\n"); - Printf(s_header, " globals->error_code = default_error_code;\n"); - Printf(s_header, "}\n"); - - Printf(s_header, "static void SWIG_ResetError(void) {\n"); - Printf(s_header, " SWIG_ErrorMsg() = default_error_msg;\n"); - Printf(s_header, " SWIG_ErrorCode() = default_error_code;\n"); - Printf(s_header, "}\n"); - - Append(s_header, "\n"); - Printf(s_header, "ZEND_NAMED_FUNCTION(_wrap_swig_%s_alter_newobject) {\n", module); - Append(s_header, " zval args[2];\n"); - Append(s_header, " swig_object_wrapper *value;\n"); - Append(s_header, "\n"); - Append(s_header, " SWIG_ResetError();\n"); - Append(s_header, " if(ZEND_NUM_ARGS() != 2 || zend_get_parameters_array_ex(2, args) != SUCCESS) {\n"); - Append(s_header, " WRONG_PARAM_COUNT;\n"); - Append(s_header, " }\n"); - Append(s_header, "\n"); - Append(s_header, " value = (swig_object_wrapper *) Z_RES_VAL(args[0]);\n"); - Append(s_header, " value->newobject = zval_is_true(&args[1]);\n"); - Append(s_header, "\n"); - Append(s_header, " return;\n"); - Append(s_header, "}\n"); - Printf(s_header, "ZEND_NAMED_FUNCTION(_wrap_swig_%s_get_newobject) {\n", module); - Append(s_header, " zval args[1];\n"); - Append(s_header, " swig_object_wrapper *value;\n"); - Append(s_header, "\n"); - Append(s_header, " SWIG_ResetError();\n"); - Append(s_header, " if(ZEND_NUM_ARGS() != 1 || zend_get_parameters_array_ex(1, args) != SUCCESS) {\n"); - Append(s_header, " WRONG_PARAM_COUNT;\n"); - Append(s_header, " }\n"); - Append(s_header, "\n"); - Append(s_header, " value = (swig_object_wrapper *) Z_RES_VAL(args[0]);\n"); - Append(s_header, " RETVAL_LONG(value->newobject);\n"); - Append(s_header, "\n"); - Append(s_header, " return;\n"); - Append(s_header, "}\n"); - Printf(s_header, "#define SWIG_name \"%s\"\n", module); Printf(s_header, "#ifdef __cplusplus\n"); Printf(s_header, "extern \"C\" {\n"); Printf(s_header, "#endif\n"); - Printf(s_header, "#include \"php.h\"\n"); Printf(s_header, "#include \"php_ini.h\"\n"); Printf(s_header, "#include \"ext/standard/info.h\"\n"); Printf(s_header, "#include \"php_%s.h\"\n", module); @@ -479,30 +464,34 @@ public: /* holds all the per-class function entry sections */ all_cs_entry = NewString("/* class entry subsection */\n"); cs_entry = NULL; + fake_cs_entry = NULL; Printf(s_entry, "/* Every non-class user visible function must have an entry here */\n"); - Printf(s_entry, "static zend_function_entry %s_functions[] = {\n", module); + Printf(s_entry, "static const zend_function_entry module_%s_functions[] = {\n", module); /* Emit all of the code */ Language::top(n); - SwigPHP_emit_resource_registrations(); + SwigPHP_emit_pointer_type_registrations(); + Dump(s_creation, s_header); + Delete(s_creation); + s_creation = NULL; /* start the init section */ { - String * s_init_old = s_init; + String *s_init_old = s_init; s_init = NewString("/* init section */\n"); Printv(s_init, "zend_module_entry ", module, "_module_entry = {\n", NIL); Printf(s_init, " STANDARD_MODULE_HEADER,\n"); Printf(s_init, " \"%s\",\n", module); - Printf(s_init, " %s_functions,\n", module); + Printf(s_init, " module_%s_functions,\n", module); Printf(s_init, " PHP_MINIT(%s),\n", module); if (Len(s_shutdown) > 0) { Printf(s_init, " PHP_MSHUTDOWN(%s),\n", module); } else { Printf(s_init, " NULL, /* No MSHUTDOWN code */\n"); } - if (Len(r_init) > 0 || Len(s_vinit) > 0) { + if (Len(r_init) > 0) { Printf(s_init, " PHP_RINIT(%s),\n", module); } else { Printf(s_init, " NULL, /* No RINIT code */\n"); @@ -523,8 +512,7 @@ public: Printf(s_init, " NO_VERSION_YET,\n"); } Printf(s_init, " STANDARD_MODULE_PROPERTIES\n"); - Printf(s_init, "};\n"); - Printf(s_init, "zend_module_entry* SWIG_module_entry = &%s_module_entry;\n\n", module); + Printf(s_init, "};\n\n"); Printf(s_init, "#ifdef __cplusplus\n"); Printf(s_init, "extern \"C\" {\n"); @@ -547,9 +535,6 @@ public: * things are being called in the wrong order */ - // Printv(s_init,s_resourcetypes,NIL); - /* We need this after all classes written out by ::top */ - Printf(s_oinit, " CG(active_class_entry) = NULL;\n"); Printf(s_oinit, " /* end oinit subsection */\n"); Printf(s_init, "%s\n", s_oinit); @@ -563,27 +548,14 @@ public: Printf(s_init, "}\n\n"); // Now do REQUEST init which holds any user specified %rinit, and also vinit - if (Len(r_init) > 0 || Len(s_vinit) > 0) { + if (Len(r_init) > 0) { Printf(f_h, "PHP_RINIT_FUNCTION(%s);\n", module); Printf(s_init, "PHP_RINIT_FUNCTION(%s)\n{\n", module); - if (Len(r_init) > 0) { - Printv(s_init, - "/* rinit section */\n", - r_init, "\n", - NIL); - } - - if (Len(s_vinit) > 0) { - /* finish our init section which will have been used by class wrappers */ - Printv(s_init, - " /* vinit subsection */\n", - s_vinit, "\n" - " /* end vinit subsection */\n", - NIL); - Clear(s_vinit); - } - Delete(s_vinit); + Printv(s_init, + "/* rinit section */\n", + r_init, "\n", + NIL); Printf(s_init, " return SUCCESS;\n"); Printf(s_init, "}\n\n"); @@ -652,10 +624,13 @@ public: Dump(f_directors, f_begin); } Printv(f_begin, s_vdecl, s_wrappers, NIL); - Printv(f_begin, all_cs_entry, "\n\n", s_arginfo, "\n\n", s_entry, - " SWIG_ZEND_NAMED_FE(swig_", module, "_alter_newobject,_wrap_swig_", module, "_alter_newobject,NULL)\n" - " SWIG_ZEND_NAMED_FE(swig_", module, "_get_newobject,_wrap_swig_", module, "_get_newobject,NULL)\n" + Printv(f_begin, s_arginfo, "\n\n", all_cs_entry, "\n\n", s_entry, " ZEND_FE_END\n};\n\n", NIL); + if (fake_cs_entry) { + Printv(f_begin, fake_cs_entry, " ZEND_FE_END\n};\n\n", NIL); + Delete(fake_cs_entry); + fake_cs_entry = NULL; + } Printv(f_begin, s_init, NIL); Delete(s_header); Delete(s_wrappers); @@ -668,78 +643,250 @@ public: Delete(f_begin); Delete(arginfo_used); - Printf(f_phpcode, "%s\n%s\n", pragma_incl, pragma_code); - if (s_fakeoowrappers) { - Printf(f_phpcode, "abstract class %s {", Len(prefix) ? prefix : module); - Printf(f_phpcode, "%s", s_fakeoowrappers); - Printf(f_phpcode, "}\n\n"); - Delete(s_fakeoowrappers); - s_fakeoowrappers = NULL; + if (Len(pragma_incl) > 0 || Len(pragma_code) > 0) { + /* PHP module file */ + String *php_filename = NewStringEmpty(); + Printv(php_filename, SWIG_output_directory(), module, ".php", NIL); + + File *f_phpcode = NewFile(php_filename, "w", SWIG_output_files()); + if (!f_phpcode) { + FileErrorDisplay(php_filename); + SWIG_exit(EXIT_FAILURE); + } + + Printf(f_phpcode, " 0) { + Printv(f_phpcode, pragma_incl, "\n", NIL); + } + + if (Len(pragma_code) > 0) { + Printv(f_phpcode, pragma_code, "\n", NIL); + } + + Delete(f_phpcode); + Delete(php_filename); } - Printf(f_phpcode, "%s\n", s_phpclasses); - Delete(f_phpcode); return SWIG_OK; } /* Just need to append function names to function table to register with PHP. */ - void create_command(String *cname, String *iname, Node *n) { + void create_command(String *cname, String *fname, Node *n, bool dispatch, String *modes = NULL) { // This is for the single main zend_function_entry record - Printf(f_h, "ZEND_NAMED_FUNCTION(%s);\n", iname); + ParmList *l = Getattr(n, "parms"); + if (cname && Cmp(Getattr(n, "storage"), "friend") != 0) { + Printf(f_h, "static PHP_METHOD(%s%s,%s);\n", prefix, cname, fname); + if (wrapperType != staticmemberfn && + wrapperType != staticmembervar && + !Equal(fname, "__construct")) { + // Skip the first entry in the parameter list which is the this pointer. + l = Getattr(l, "tmap:in:next"); + // FIXME: does this throw the phptype key value off? + } + } else { + if (dispatch) { + Printf(f_h, "static ZEND_NAMED_FUNCTION(%s);\n", fname); + } else { + Printf(f_h, "static PHP_FUNCTION(%s);\n", fname); + } + } + + int num_required = emit_num_required(l); // We want to only emit each different arginfo once, as that reduces the // size of both the generated source code and the compiled extension - // module. To do this, we name the arginfo to encode the number of - // parameters and which (if any) are passed by reference by using a - // sequence of 0s (for non-reference) and 1s (for by references). - ParmList *l = Getattr(n, "parms"); - String * arginfo_code = NewStringEmpty(); + // module. The parameters at this level are just named arg1, arg2, etc + // so the arginfo will be the same for any function with the same number + // of parameters and (if present) PHP type declarations for parameters and + // return type. + // + // We generate the arginfo we want (taking care to normalise, e.g. the + // lists of types are unique and in sorted order), then use the + // arginfo_used Hash to see if we've already generated it. + + // Don't add a return type declaration for a constructor (because there + // is no return type as far as PHP is concerned). + String *out_phptype = NULL; + String *out_phpclasses = NewStringEmpty(); + if (!Equal(fname, "__construct")) { + String *php_type_flag = GetFlagAttr(n, "feature:php:type"); + if (Equal(php_type_flag, "1") || + (php_type_flag && !Getattr(n, "directorNode"))) { + // We provide a simple way to generate PHP return type declarations + // except for directed methods. The point of directors is to allow + // subclassing in the target language, and if the wrapped method has + // a return type declaration then an overriding method in user code + // needs to have a compatible declaration. + // + // The upshot of this is that enabling return type declarations for + // existing bindings would break compatibility with user code written + // for an older version. For parameters however the situation is + // different because if the parent class declares types for parameters + // a subclass overriding the function will be compatible whether it + // declares them or not. + // + // directorNode being present seems to indicate if this method or one + // it inherits from is directed, which is what we care about here. + // Using (!is_member_director(n)) would get it wrong for testcase + // director_frob. + out_phptype = phptypes.get_phptype(0, out_phpclasses); + } + } + + // ### in arginfo_code will be replaced with the id once that is known. + String *arginfo_code = NewStringEmpty(); + if (out_phptype) { + if (Len(out_phpclasses)) { + Replace(out_phpclasses, "\\", "\\\\", DOH_REPLACE_ANY); + Printf(arginfo_code, "ZEND_BEGIN_ARG_WITH_RETURN_OBJ_TYPE_MASK_EX(swig_arginfo_###, 0, %d, %s, %s)\n", num_required, out_phpclasses, out_phptype); + } else { + Printf(arginfo_code, "ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(swig_arginfo_###, 0, %d, %s)\n", num_required, out_phptype); + } + } else { + Printf(arginfo_code, "ZEND_BEGIN_ARG_INFO_EX(swig_arginfo_###, 0, 0, %d)\n", num_required); + } + + if (Getattr(n, "defaultargs")) { + // Include parameters with default values in the arginfo. + l = Getattr(Getattr(n, "defaultargs"), "parms"); + } + int param_count = 0; for (Parm *p = l; p; p = Getattr(p, "tmap:in:next")) { - /* Ignored parameters */ - if (checkAttribute(p, "tmap:in:numinputs", "0")) { + String *tmap_in_numinputs = Getattr(p, "tmap:in:numinputs"); + // tmap:in:numinputs is unset for varargs, which we don't count here. + if (!tmap_in_numinputs || Equal(tmap_in_numinputs, "0")) { + /* Ignored parameter */ continue; } - Append(arginfo_code, GetFlag(p, "tmap:in:byref") ? "1" : "0"); - } - if (!GetFlag(arginfo_used, arginfo_code)) { - // Not had this one before, so emit it. - SetFlag(arginfo_used, arginfo_code); - Printf(s_arginfo, "ZEND_BEGIN_ARG_INFO_EX(swig_arginfo_%s, 0, 0, 0)\n", arginfo_code); - for (const char * p = Char(arginfo_code); *p; ++p) { - Printf(s_arginfo, " ZEND_ARG_PASS_INFO(%c)\n", *p); + ++param_count; + + String *phpclasses = NewStringEmpty(); + String *phptype = NULL; + if (GetFlag(n, "feature:php:type")) { + phptype = phptypes.get_phptype(param_count, phpclasses); } - Printf(s_arginfo, "ZEND_END_ARG_INFO()\n"); - } - String * s = cs_entry; - if (!s) s = s_entry; - Printf(s, " SWIG_ZEND_NAMED_FE(%(lower)s,%s,swig_arginfo_%s)\n", cname, iname, arginfo_code); + int byref; + if (!dispatch) { + byref = GetFlag(p, "tmap:in:byref"); + if (byref) phptypes.set_byref(param_count); + } else { + // If any overload takes a particular parameter by reference then the + // dispatch function also needs to take that parameter by reference. + byref = phptypes.get_byref(param_count); + } + + // FIXME: Should we be doing byref for return value as well? + + if (phptype) { + if (Len(phpclasses)) { + // We need to double any backslashes (which are PHP namespace + // separators) in the PHP class names as they get turned into + // C strings by the ZEND_ARG_OBJ_TYPE_MASK macro. + Replace(phpclasses, "\\", "\\\\", DOH_REPLACE_ANY); + Printf(arginfo_code, " ZEND_ARG_OBJ_TYPE_MASK(%d,arg%d,%s,%s,NULL)\n", byref, param_count, phpclasses, phptype); + } else { + Printf(arginfo_code, " ZEND_ARG_TYPE_MASK(%d,arg%d,%s,NULL)\n", byref, param_count, phptype); + } + } else { + Printf(arginfo_code, " ZEND_ARG_INFO(%d,arg%d)\n", byref, param_count); + } + } + Printf(arginfo_code, "ZEND_END_ARG_INFO()\n"); + + String *arginfo_id_new = Getattr(n, "sym:name"); + String *arginfo_id = Getattr(arginfo_used, arginfo_code); + if (arginfo_id) { + Printf(s_arginfo, "#define swig_arginfo_%s swig_arginfo_%s\n", arginfo_id_new, arginfo_id); + } else { + // Not had this arginfo before. + Setattr(arginfo_used, arginfo_code, arginfo_id_new); + arginfo_code = Copy(arginfo_code); + Replace(arginfo_code, "###", arginfo_id_new, DOH_REPLACE_FIRST); + Append(s_arginfo, arginfo_code); + } Delete(arginfo_code); + arginfo_code = NULL; + + String *s = cs_entry; + if (!s) s = s_entry; + if (cname && Cmp(Getattr(n, "storage"), "friend") != 0) { + Printf(all_cs_entry, " PHP_ME(%s%s,%s,swig_arginfo_%s,%s)\n", prefix, cname, fname, arginfo_id_new, modes); + } else { + if (dispatch) { + if (wrap_nonclass_global) { + Printf(s, " ZEND_NAMED_FE(%(lower)s,%s,swig_arginfo_%s)\n", Getattr(n, "sym:name"), fname, arginfo_id_new); + } + + if (wrap_nonclass_fake_class) { + (void)fake_class_name(); + Printf(fake_cs_entry, " ZEND_NAMED_ME(%(lower)s,%s,swig_arginfo_%s,ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)\n", Getattr(n, "sym:name"), fname, arginfo_id_new); + } + } else { + if (wrap_nonclass_global) { + Printf(s, " PHP_FE(%s,swig_arginfo_%s)\n", fname, arginfo_id_new); + } + + if (wrap_nonclass_fake_class) { + String *fake_class = fake_class_name(); + Printf(fake_cs_entry, " PHP_ME(%s,%s,swig_arginfo_%s,ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)\n", fake_class, fname, arginfo_id_new); + } + } + } } /* ------------------------------------------------------------ * dispatchFunction() * ------------------------------------------------------------ */ - void dispatchFunction(Node *n) { + void dispatchFunction(Node *n, int constructor) { /* Last node in overloaded chain */ int maxargs; String *tmp = NewStringEmpty(); - if (Swig_directorclass(n) && wrapperType == directorconstructor) { - /* We have an extra 'this' parameter. */ - SetFlag(n, "wrap:this"); - } String *dispatch = Swig_overload_dispatch(n, "%s(INTERNAL_FUNCTION_PARAM_PASSTHRU); return;", &maxargs); /* Generate a dispatch wrapper for all overloaded functions */ Wrapper *f = NewWrapper(); String *symname = Getattr(n, "sym:name"); - String *wname = Swig_name_wrapper(symname); + String *wname = NULL; + String *modes = NULL; + bool constructorRenameOverload = false; - create_command(symname, wname, n); - Printv(f->def, "ZEND_NAMED_FUNCTION(", wname, ") {\n", NIL); + if (constructor) { + // Renamed constructor - turn into static factory method + if (Cmp(class_name, Getattr(n, "constructorHandler:sym:name")) != 0) { + constructorRenameOverload = true; + wname = Copy(Getattr(n, "constructorHandler:sym:name")); + } else { + wname = NewString("__construct"); + } + } else if (class_name) { + wname = Getattr(n, "wrapper:method:name"); + } else { + wname = Swig_name_wrapper(symname); + } + + if (constructor) { + modes = NewString("ZEND_ACC_PUBLIC | ZEND_ACC_CTOR"); + if (constructorRenameOverload) { + Append(modes, " | ZEND_ACC_STATIC"); + } + } else if (wrapperType == staticmemberfn || Cmp(Getattr(n, "storage"), "static") == 0) { + modes = NewString("ZEND_ACC_PUBLIC | ZEND_ACC_STATIC"); + } else { + modes = NewString("ZEND_ACC_PUBLIC"); + } + + create_command(class_name, wname, n, true, modes); + + if (class_name && Cmp(Getattr(n, "storage"), "friend") != 0) { + Printv(f->def, "static PHP_METHOD(", prefix, class_name, ",", wname, ") {\n", NIL); + } else { + Printv(f->def, "static ZEND_NAMED_FUNCTION(", wname, ") {\n", NIL); + } Wrapper_add_local(f, "argc", "int argc"); @@ -754,37 +901,206 @@ public: Printv(f->code, dispatch, "\n", NIL); - Printf(f->code, "SWIG_ErrorCode() = E_ERROR;\n"); - Printf(f->code, "SWIG_ErrorMsg() = \"No matching function for overloaded '%s'\";\n", symname); - Printv(f->code, "SWIG_FAIL();\n", NIL); - + Printf(f->code, "zend_throw_exception(zend_ce_type_error, \"No matching function for overloaded '%s'\", 0);\n", symname); + Printv(f->code, "fail:\n", NIL); + Printv(f->code, "return;\n", NIL); Printv(f->code, "}\n", NIL); Wrapper_print(f, s_wrappers); DelWrapper(f); Delete(dispatch); Delete(tmp); - Delete(wname); } /* ------------------------------------------------------------ * functionWrapper() * ------------------------------------------------------------ */ - /* Helper method for PHP::functionWrapper */ - bool is_class(SwigType *t) { - Node *n = classLookup(t); - if (n) { - String *r = Getattr(n, "php:proxy"); // Set by classDeclaration() - if (!r) - r = Getattr(n, "sym:name"); // Not seen by classDeclaration yet, but this is the name - if (r) + /* Helper function to check if class is wrapped */ + bool is_class_wrapped(String *className) { + if (!className) + return false; + Node *n = symbolLookup(className); + return n && Getattr(n, "classtype") != NULL; + } + + void generate_magic_property_methods(Node *class_node, String *base_class) { + if (Equal(base_class, "Exception") || !is_class_wrapped(base_class)) { + base_class = NULL; + } + + static bool generated_magic_arginfo = false; + if (!generated_magic_arginfo) { + // Create arginfo entries for __get, __set and __isset. + Append(s_arginfo, + "ZEND_BEGIN_ARG_INFO_EX(swig_magic_arginfo_get, 0, 0, 1)\n" + " ZEND_ARG_TYPE_MASK(0,arg1,MAY_BE_STRING,NULL)\n" + "ZEND_END_ARG_INFO()\n"); + Append(s_arginfo, + "ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(swig_magic_arginfo_set, 0, 1, MAY_BE_VOID)\n" + " ZEND_ARG_TYPE_MASK(0,arg1,MAY_BE_STRING,NULL)\n" + " ZEND_ARG_INFO(0,arg2)\n" + "ZEND_END_ARG_INFO()\n"); + Append(s_arginfo, + "ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(swig_magic_arginfo_isset, 0, 1, MAY_BE_BOOL)\n" + " ZEND_ARG_TYPE_MASK(0,arg1,MAY_BE_STRING,NULL)\n" + "ZEND_END_ARG_INFO()\n"); + generated_magic_arginfo = true; + } + + Wrapper *f = NewWrapper(); + + Printf(f_h, "PHP_METHOD(%s%s,__set);\n", prefix, class_name); + Printf(all_cs_entry, " PHP_ME(%s%s,__set,swig_magic_arginfo_set,ZEND_ACC_PUBLIC)\n", prefix, class_name); + Printf(f->code, "PHP_METHOD(%s%s,__set) {\n", prefix, class_name); + + Printf(f->code, " swig_object_wrapper *arg = SWIG_Z_FETCH_OBJ_P(ZEND_THIS);\n"); + Printf(f->code, " zval args[2];\n zval tempZval;\n zend_string *arg2 = 0;\n\n"); + Printf(f->code, " if(ZEND_NUM_ARGS() != 2 || zend_get_parameters_array_ex(2, args) != SUCCESS) {\n"); + Printf(f->code, "\tWRONG_PARAM_COUNT;\n}\n\n"); + Printf(f->code, " if (!arg) {\n"); + Printf(f->code, " zend_throw_exception(zend_ce_type_error, \"this pointer is NULL\", 0);\n"); + Printf(f->code, " return;\n"); + Printf(f->code, " }\n"); + Printf(f->code, " arg2 = Z_STR(args[0]);\n\n"); + + Printf(f->code, "if (!arg2) {\n RETVAL_NULL();\n}\n"); + if (magic_set) { + Append(f->code, magic_set); + } + Printf(f->code, "\nelse if (strcmp(ZSTR_VAL(arg2),\"thisown\") == 0) {\n"); + Printf(f->code, "arg->newobject = zval_get_long(&args[1]);\n"); + if (Swig_directorclass(class_node)) { + Printv(f->code, "if (arg->newobject == 0) {\n", + " Swig::Director *director = SWIG_DIRECTOR_CAST((", Getattr(class_node, "classtype"), "*)(arg->ptr));\n", + " if (director) director->swig_disown();\n", + "}\n", NIL); + } + Printf(f->code, "} else {\n"); + if (base_class) { + Printf(f->code, "PHP_MN(%s%s___set)(INTERNAL_FUNCTION_PARAM_PASSTHRU);\n}\n", prefix, base_class); + } else { + Printf(f->code, "add_property_zval_ex(ZEND_THIS, ZSTR_VAL(arg2), ZSTR_LEN(arg2), &args[1]);\n}\n"); + } + + Printf(f->code, "fail:\n"); + Printf(f->code, "return;\n"); + Printf(f->code, "}\n\n\n"); + + + Printf(f_h, "PHP_METHOD(%s%s,__get);\n", prefix, class_name); + Printf(all_cs_entry, " PHP_ME(%s%s,__get,swig_magic_arginfo_get,ZEND_ACC_PUBLIC)\n", prefix, class_name); + Printf(f->code, "PHP_METHOD(%s%s,__get) {\n",prefix, class_name); + + Printf(f->code, " swig_object_wrapper *arg = SWIG_Z_FETCH_OBJ_P(ZEND_THIS);\n"); + Printf(f->code, " zval args[1];\n zval tempZval;\n zend_string *arg2 = 0;\n\n"); + Printf(f->code, " if(ZEND_NUM_ARGS() != 1 || zend_get_parameters_array_ex(1, args) != SUCCESS) {\n"); + Printf(f->code, "\tWRONG_PARAM_COUNT;\n}\n\n"); + Printf(f->code, " if (!arg) {\n"); + Printf(f->code, " zend_throw_exception(zend_ce_type_error, \"this pointer is NULL\", 0);\n"); + Printf(f->code, " return;\n"); + Printf(f->code, " }\n"); + Printf(f->code, " arg2 = Z_STR(args[0]);\n\n"); + + Printf(f->code, "if (!arg2) {\n RETVAL_NULL();\n}\n"); + if (magic_get) { + Append(f->code, magic_get); + } + Printf(f->code, "\nelse if (strcmp(ZSTR_VAL(arg2),\"thisown\") == 0) {\n"); + Printf(f->code, "if(arg->newobject) {\nRETVAL_LONG(1);\n}\nelse {\nRETVAL_LONG(0);\n}\n}\n\n"); + Printf(f->code, "else {\n"); + if (base_class) { + Printf(f->code, "PHP_MN(%s%s___get)(INTERNAL_FUNCTION_PARAM_PASSTHRU);\n}\n", prefix, base_class); + } else { + // __get is only called if the property isn't set on the zend_object. + Printf(f->code, "RETVAL_NULL();\n}\n"); + } + + Printf(f->code, "fail:\n"); + Printf(f->code, "return;\n"); + Printf(f->code, "}\n\n\n"); + + + Printf(f_h, "PHP_METHOD(%s%s,__isset);\n", prefix, class_name); + Printf(all_cs_entry, " PHP_ME(%s%s,__isset,swig_magic_arginfo_isset,ZEND_ACC_PUBLIC)\n", prefix, class_name); + Printf(f->code, "PHP_METHOD(%s%s,__isset) {\n",prefix, class_name); + + Printf(f->code, " swig_object_wrapper *arg = SWIG_Z_FETCH_OBJ_P(ZEND_THIS);\n"); + Printf(f->code, " zval args[1];\n zend_string *arg2 = 0;\n\n"); + Printf(f->code, " if(ZEND_NUM_ARGS() != 1 || zend_get_parameters_array_ex(1, args) != SUCCESS) {\n"); + Printf(f->code, "\tWRONG_PARAM_COUNT;\n}\n\n"); + Printf(f->code, " if(!arg) {\n"); + Printf(f->code, " zend_throw_exception(zend_ce_type_error, \"this pointer is NULL\", 0);\n"); + Printf(f->code, " return;\n"); + Printf(f->code, " }\n"); + Printf(f->code, " arg2 = Z_STR(args[0]);\n\n"); + + Printf(f->code, "if (!arg2) {\n RETVAL_FALSE;\n}\n"); + Printf(f->code, "\nelse if (strcmp(ZSTR_VAL(arg2),\"thisown\") == 0) {\n"); + Printf(f->code, "RETVAL_TRUE;\n}\n\n"); + if (magic_isset) { + Append(f->code, magic_isset); + } + Printf(f->code, "else {\n"); + if (base_class) { + Printf(f->code, "PHP_MN(%s%s___isset)(INTERNAL_FUNCTION_PARAM_PASSTHRU);\n}\n", prefix, base_class); + } else { + // __isset is only called if the property isn't set on the zend_object. + Printf(f->code, "RETVAL_FALSE;\n}\n"); + } + + Printf(f->code, "fail:\n"); + Printf(f->code, "return;\n"); + Printf(f->code, "}\n\n\n"); + + Wrapper_print(f, s_wrappers); + DelWrapper(f); + f = NULL; + + Delete(magic_set); + Delete(magic_get); + Delete(magic_isset); + magic_set = NULL; + magic_get = NULL; + magic_isset = NULL; + } + + String *getAccessMode(String *access) { + if (Cmp(access, "protected") == 0) { + return NewString("ZEND_ACC_PROTECTED"); + } else if (Cmp(access, "private") == 0) { + return NewString("ZEND_ACC_PRIVATE"); + } + return NewString("ZEND_ACC_PUBLIC"); + } + + bool is_setter_method(Node *n) { + const char *p = GetChar(n, "sym:name"); + if (strlen(p) > 4) { + p += strlen(p) - 4; + if (strcmp(p, "_set") == 0) { return true; + } + } + return false; + } + + bool is_getter_method(Node *n) { + const char *p = GetChar(n, "sym:name"); + if (strlen(p) > 4) { + p += strlen(p) - 4; + if (strcmp(p, "_get") == 0) { + return true; + } } return false; } virtual int functionWrapper(Node *n) { + if (wrapperType == directordisown) { + // Handled via __set magic method - no explicit wrapper method wanted. + return SWIG_OK; + } String *name = GetChar(n, "name"); String *iname = GetChar(n, "sym:name"); SwigType *d = Getattr(n, "type"); @@ -799,44 +1115,127 @@ public: String *tm; Wrapper *f; - String *wname; + String *wname = NewStringEmpty(); + String *overloadwname = NULL; int overloaded = 0; - String *overname = 0; + String *modes = NULL; + bool static_setter = false; + bool static_getter = false; - if (Cmp(nodeType, "destructor") == 0) { - // We just generate the Zend List Destructor and let Zend manage the - // reference counting. There's no explicit destructor, but the user can - // just do `$obj = null;' to remove a reference to an object. - return CreateZendListDestructor(n); + modes = getAccessMode(Getattr(n, "access")); + + if (constructor) { + Append(modes, " | ZEND_ACC_CTOR"); } - // Test for overloading; + if (wrapperType == staticmemberfn || Cmp(Getattr(n, "storage"), "static") == 0) { + Append(modes, " | ZEND_ACC_STATIC"); + } + if (GetFlag(n, "abstract") && Swig_directorclass(Swig_methodclass(n)) && !is_member_director(n)) + Append(modes, " | ZEND_ACC_ABSTRACT"); + if (Getattr(n, "sym:overloaded")) { overloaded = 1; - overname = Getattr(n, "sym:overname"); + overloadwname = NewString(Swig_name_wrapper(iname)); + Printf(overloadwname, "%s", Getattr(n, "sym:overname")); } else { if (!addSymbol(iname, n)) return SWIG_ERROR; } - wname = Swig_name_wrapper(iname); - if (overname) { - Printf(wname, "%s", overname); + if (!Getattr(n, "sym:previousSibling")) { + // First function of an overloaded group or a function which isn't part + // of a group so reset the phptype information. + phptypes.reset(); + } + + if (constructor) { + wname = NewString("__construct"); + } else if (wrapperType == membervar) { + wname = Copy(Getattr(n, "membervariableHandler:sym:name")); + if (is_setter_method(n)) { + Append(wname, "_set"); + } else if (is_getter_method(n)) { + Append(wname, "_get"); + } + } else if (wrapperType == memberfn) { + wname = Getattr(n, "memberfunctionHandler:sym:name"); + } else if (wrapperType == staticmembervar) { + // Shape::nshapes -> nshapes + wname = Getattr(n, "staticmembervariableHandler:sym:name"); + + /* We get called twice for getter and setter methods. But to maintain + compatibility, Shape::nshapes() is being used for both setter and + getter methods. So using static_setter and static_getter variables + to generate half of the code each time. + */ + static_setter = is_setter_method(n); + + if (is_getter_method(n)) { + // This is to overcome types that can't be set and hence no setter. + if (Cmp(Getattr(n, "feature:immutable"), "1") != 0) + static_getter = true; + } + } else if (wrapperType == staticmemberfn) { + wname = Getattr(n, "staticmemberfunctionHandler:sym:name"); + } else { + if (class_name) { + if (Cmp(Getattr(n, "storage"), "friend") == 0 && Cmp(Getattr(n, "view"), "globalfunctionHandler") == 0) { + wname = iname; + } else { + wname = Getattr(n, "destructorHandler:sym:name"); + } + } else { + wname = iname; + } + } + + if (wrapperType == destructor) { + // We don't explicitly wrap the destructor for PHP - Zend manages the + // reference counting, and the user can just do `$obj = null;' or similar + // to remove a reference to an object. + Setattr(n, "wrap:name", wname); + (void)emit_action(n); + return SWIG_OK; } f = NewWrapper(); + if (static_getter) { + Printf(f->def, "{\n"); + } + String *outarg = NewStringEmpty(); String *cleanup = NewStringEmpty(); - Printv(f->def, "ZEND_NAMED_FUNCTION(", wname, ") {\n", NIL); + if (!overloaded) { + if (!static_getter) { + if (class_name && Cmp(Getattr(n, "storage"), "friend") != 0) { + Printv(f->def, "static PHP_METHOD(", prefix, class_name, ",", wname, ") {\n", NIL); + } else { + if (wrap_nonclass_global) { + Printv(f->def, "static PHP_METHOD(", fake_class_name(), ",", wname, ") {\n", + " PHP_FN(", wname, ")(INTERNAL_FUNCTION_PARAM_PASSTHRU);\n", + "}\n\n", NIL); + } + + if (wrap_nonclass_fake_class) { + Printv(f->def, "static PHP_FUNCTION(", wname, ") {\n", NIL); + } + } + } + } else { + Printv(f->def, "static ZEND_NAMED_FUNCTION(", overloadwname, ") {\n", NIL); + } emit_parameter_variables(l, f); /* Attach standard typemaps */ emit_attach_parmmaps(l, f); - // Not issued for overloaded functions. - if (!overloaded) { - create_command(iname, wname, n); + + if (wrapperType == memberfn || wrapperType == membervar) { + // Assign "this" to arg1 and remove first entry from ParmList l. + Printf(f->code, "arg1 = (%s)SWIG_Z_FETCH_OBJ_P(ZEND_THIS)->ptr;\n", SwigType_lstr(Getattr(l, "type"), "")); + l = nextSibling(l); } // wrap:parms is used by overload resolution. @@ -846,18 +1245,16 @@ public: int num_required = emit_num_required(l); numopt = num_arguments - num_required; - if (wrapperType == directorconstructor) - num_arguments++; - if (num_arguments > 0) { String *args = NewStringEmpty(); - if (wrapperType == directorconstructor) - Wrapper_add_local(f, "arg0", "zval * arg0"); Printf(args, "zval args[%d]", num_arguments); Wrapper_add_local(f, "args", args); Delete(args); args = NULL; } + if (wrapperType == directorconstructor) { + Wrapper_add_local(f, "arg0", "zval *arg0 = ZEND_THIS"); + } // This generated code may be called: // 1) as an object method, or @@ -867,14 +1264,18 @@ public: // NOTE: possible we ignore this_ptr as a param for native constructor - Printf(f->code, "SWIG_ResetError();\n"); - if (numopt > 0) { // membervariable wrappers do not have optional args Wrapper_add_local(f, "arg_count", "int arg_count"); Printf(f->code, "arg_count = ZEND_NUM_ARGS();\n"); Printf(f->code, "if(arg_count<%d || arg_count>%d ||\n", num_required, num_arguments); Printf(f->code, " zend_get_parameters_array_ex(arg_count,args)!=SUCCESS)\n"); Printf(f->code, "\tWRONG_PARAM_COUNT;\n\n"); + } else if (static_setter || static_getter) { + if (num_arguments == 0) { + Printf(f->code, "if(ZEND_NUM_ARGS() == 0) {\n"); + } else { + Printf(f->code, "if(ZEND_NUM_ARGS() == %d && zend_get_parameters_array_ex(%d, args) == SUCCESS) {\n", num_arguments, num_arguments); + } } else { if (num_arguments == 0) { Printf(f->code, "if(ZEND_NUM_ARGS() != 0) {\n"); @@ -883,8 +1284,6 @@ public: } Printf(f->code, "WRONG_PARAM_COUNT;\n}\n\n"); } - if (wrapperType == directorconstructor) - Printf(f->code, "arg0 = &args[0];\n \n"); /* Now convert from PHP to C variables */ // At this point, argcount if used is the number of deliberately passed args @@ -896,60 +1295,52 @@ public: // _this and not the first argument. // This may mean looking at Language::memberfunctionHandler - int limit = num_arguments; - if (wrapperType == directorconstructor) - limit--; - for (i = 0, p = l; i < limit; i++) { - String *source; - + for (i = 0, p = l; i < num_arguments; i++) { /* Skip ignored arguments */ - //while (Getattr(p,"tmap:ignore")) { p = Getattr(p,"tmap:ignore:next");} while (checkAttribute(p, "tmap:in:numinputs", "0")) { p = Getattr(p, "tmap:in:next"); } - SwigType *pt = Getattr(p, "type"); - - if (wrapperType == directorconstructor) { - source = NewStringf("args[%d]", i+1); - } else { - source = NewStringf("args[%d]", i); - } - - String *ln = Getattr(p, "lname"); - /* Check if optional */ if (i >= num_required) { Printf(f->code, "\tif(arg_count > %d) {\n", i); } - if ((tm = Getattr(p, "tmap:in"))) { - Replaceall(tm, "$source", &source); - Replaceall(tm, "$target", ln); - Replaceall(tm, "$input", source); - Setattr(p, "emit:input", source); - Printf(f->code, "%s\n", tm); - if (i == 0 && Getattr(p, "self")) { - Printf(f->code, "\tif(!arg1) SWIG_PHP_Error(E_ERROR, \"this pointer is NULL\");\n"); - } - p = Getattr(p, "tmap:in:next"); - if (i >= num_required) { - Printf(f->code, "}\n"); - } - continue; - } else { + tm = Getattr(p, "tmap:in"); + if (!tm) { + SwigType *pt = Getattr(p, "type"); Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0)); + p = nextSibling(p); + continue; } - if (i >= num_required) { + + phptypes.process_phptype(p, i + 1, "tmap:in:phptype"); + + String *source = NewStringf("args[%d]", i); + Replaceall(tm, "$input", source); + Setattr(p, "emit:input", source); + Printf(f->code, "%s\n", tm); + if (i == 0 && Getattr(p, "self")) { + Printf(f->code, "\tif(!arg1) {\n"); + Printf(f->code, "\t zend_throw_exception(zend_ce_type_error, \"this pointer is NULL\", 0);\n"); + Printf(f->code, "\t return;\n"); Printf(f->code, "\t}\n"); } + + if (i >= num_required) { + Printf(f->code, "}\n"); + } + + p = Getattr(p, "tmap:in:next"); + Delete(source); } if (is_member_director(n)) { + Wrapper_add_local(f, "director", "Swig::Director *director = 0"); + Append(f->code, "director = SWIG_DIRECTOR_CAST(arg1);\n"); Wrapper_add_local(f, "upcall", "bool upcall = false"); - Printf(f->code, "upcall = !Swig::Director::swig_is_overridden_method(\"%s%s\", \"%s\");\n", - prefix, Swig_class_name(Swig_methodclass(n)), name); + Printf(f->code, "upcall = (director && (director->swig_get_self()==Z_OBJ_P(ZEND_THIS)));\n"); } Swig_director_emit_dynamic_cast(n, f); @@ -957,7 +1348,6 @@ public: /* Insert constraint checking code */ for (p = l; p;) { if ((tm = Getattr(p, "tmap:check"))) { - Replaceall(tm, "$target", Getattr(p, "lname")); Printv(f->code, tm, "\n", NIL); p = Getattr(p, "tmap:check:next"); } else { @@ -968,7 +1358,6 @@ public: /* Insert cleanup code */ for (i = 0, p = l; p; i++) { if ((tm = Getattr(p, "tmap:freearg"))) { - Replaceall(tm, "$source", Getattr(p, "lname")); Printv(cleanup, tm, "\n", NIL); p = Getattr(p, "tmap:freearg:next"); } else { @@ -977,13 +1366,8 @@ public: } /* Insert argument output code */ - bool hasargout = false; for (i = 0, p = l; p; i++) { if ((tm = Getattr(p, "tmap:argout")) && Len(tm)) { - hasargout = true; - Replaceall(tm, "$source", Getattr(p, "lname")); - // Replaceall(tm,"$input",Getattr(p,"lname")); - Replaceall(tm, "$target", "return_value"); Replaceall(tm, "$result", "return_value"); Replaceall(tm, "$arg", Getattr(p, "emit:input")); Replaceall(tm, "$input", Getattr(p, "emit:input")); @@ -994,16 +1378,21 @@ public: } } - Setattr(n, "wrap:name", wname); + if (!overloaded) { + Setattr(n, "wrap:name", wname); + } else { + Setattr(n, "wrap:name", overloadwname); + } + Setattr(n, "wrapper:method:name", wname); + + bool php_constructor = (constructor && Cmp(class_name, Getattr(n, "constructorHandler:sym:name")) == 0); /* emit function call */ String *actioncode = emit_action(n); if ((tm = Swig_typemap_lookup_out("out", n, Swig_cresult_name(), f, actioncode))) { Replaceall(tm, "$input", Swig_cresult_name()); - Replaceall(tm, "$source", Swig_cresult_name()); - Replaceall(tm, "$target", "return_value"); - Replaceall(tm, "$result", "return_value"); + Replaceall(tm, "$result", php_constructor ? "ZEND_THIS" : "return_value"); Replaceall(tm, "$owner", newobject ? "1" : "0"); Printf(f->code, "%s\n", tm); } else { @@ -1011,11 +1400,13 @@ public: } emit_return_variable(n, d, f); + phptypes.process_phptype(n, 0, "tmap:out:phptype"); + if (outarg) { Printv(f->code, outarg, NIL); } - if (cleanup) { + if (static_setter && cleanup) { Printv(f->code, cleanup, NIL); } @@ -1033,15 +1424,20 @@ public: Delete(tm); } - Printf(f->code, "thrown:\n"); - Printf(f->code, "return;\n"); + if (static_getter) { + Printf(f->code, "}\n"); + } - /* Error handling code */ - Printf(f->code, "fail:\n"); - Printv(f->code, cleanup, NIL); - Append(f->code, "SWIG_FAIL();\n"); + if (static_setter || static_getter) { + Printf(f->code, "}\n"); + } - Printf(f->code, "}\n"); + if (!static_setter) { + Printf(f->code, "fail:\n"); + Printv(f->code, cleanup, NIL); + Printf(f->code, "return;\n"); + Printf(f->code, "}\n"); + } Replaceall(f->code, "$cleanup", cleanup); Replaceall(f->code, "$symname", iname); @@ -1050,827 +1446,14 @@ public: DelWrapper(f); f = NULL; - if (overloaded && !Getattr(n, "sym:nextSibling")) { - dispatchFunction(n); - } - - Delete(wname); - wname = NULL; - - if (!shadow) { - return SWIG_OK; - } - - // Handle getters and setters. - if (wrapperType == membervar) { - const char *p = Char(iname); - if (strlen(p) > 4) { - p += strlen(p) - 4; - String *varname = Getattr(n, "membervariableHandler:sym:name"); - if (strcmp(p, "_get") == 0) { - Setattr(shadow_get_vars, varname, Getattr(n, "type")); - } else if (strcmp(p, "_set") == 0) { - Setattr(shadow_set_vars, varname, iname); - } + if (overloaded) { + if (!Getattr(n, "sym:nextSibling")) { + dispatchFunction(n, constructor); } - return SWIG_OK; - } - - // Only look at non-overloaded methods and the last entry in each overload - // chain (we check the last so that wrap:parms and wrap:name have been set - // for them all). - if (overloaded && Getattr(n, "sym:nextSibling") != 0) - return SWIG_OK; - - if (!s_oowrappers) - s_oowrappers = NewStringEmpty(); - - if (newobject || wrapperType == memberfn || wrapperType == staticmemberfn || wrapperType == standard || wrapperType == staticmembervar) { - bool handle_as_overload = false; - String **arg_names; - String **arg_values; - unsigned char * byref; - // Method or static method or plain function. - const char *methodname = 0; - String *output = s_oowrappers; - if (constructor) { - class_has_ctor = true; - // Skip the Foo:: prefix. - char *ptr = strrchr(GetChar(current_class, "sym:name"), ':'); - if (ptr) { - ptr++; - } else { - ptr = GetChar(current_class, "sym:name"); - } - if (strcmp(ptr, GetChar(n, "constructorHandler:sym:name")) == 0) { - methodname = "__construct"; - } else { - // The class has multiple constructors and this one is - // renamed, so this will be a static factory function - methodname = GetChar(n, "constructorHandler:sym:name"); - } - } else if (wrapperType == memberfn) { - methodname = Char(Getattr(n, "memberfunctionHandler:sym:name")); - } else if (wrapperType == staticmemberfn) { - methodname = Char(Getattr(n, "staticmemberfunctionHandler:sym:name")); - } else if (wrapperType == staticmembervar) { - // Static member variable, wrapped as a function due to PHP limitations. - methodname = Char(Getattr(n, "staticmembervariableHandler:sym:name")); - } else { // wrapperType == standard - methodname = Char(iname); - if (!s_fakeoowrappers) - s_fakeoowrappers = NewStringEmpty(); - output = s_fakeoowrappers; + } else { + if (!static_getter) { + create_command(class_name, wname, n, false, modes); } - - bool really_overloaded = overloaded ? true : false; - int min_num_of_arguments = emit_num_required(l); - int max_num_of_arguments = emit_num_arguments(l); - - Hash *ret_types = NewHash(); - Setattr(ret_types, d, d); - - bool non_void_return = (Cmp(d, "void") != 0); - - if (overloaded) { - // Look at all the overloaded versions of this method in turn to - // decide if it's really an overloaded method, or just one where some - // parameters have default values. - Node *o = Getattr(n, "sym:overloaded"); - while (o) { - if (o == n) { - o = Getattr(o, "sym:nextSibling"); - continue; - } - - SwigType *d2 = Getattr(o, "type"); - if (!d2) { - assert(constructor); - } else if (!Getattr(ret_types, d2)) { - Setattr(ret_types, d2, d2); - non_void_return = non_void_return || (Cmp(d2, "void") != 0); - } - - ParmList *l2 = Getattr(o, "wrap:parms"); - int num_arguments = emit_num_arguments(l2); - int num_required = emit_num_required(l2); - if (num_required < min_num_of_arguments) - min_num_of_arguments = num_required; - - if (num_arguments > max_num_of_arguments) { - max_num_of_arguments = num_arguments; - } - o = Getattr(o, "sym:nextSibling"); - } - - o = Getattr(n, "sym:overloaded"); - while (o) { - if (o == n) { - o = Getattr(o, "sym:nextSibling"); - continue; - } - - ParmList *l2 = Getattr(o, "wrap:parms"); - Parm *p = l, *p2 = l2; - if (wrapperType == memberfn) { - p = nextSibling(p); - p2 = nextSibling(p2); - } - while (p && p2) { - if (Cmp(Getattr(p, "type"), Getattr(p2, "type")) != 0) - break; - if (Cmp(Getattr(p, "name"), Getattr(p2, "name")) != 0) - break; - String *value = Getattr(p, "value"); - String *value2 = Getattr(p2, "value"); - if (value && !value2) - break; - if (!value && value2) - break; - if (value) { - if (Cmp(value, value2) != 0) - break; - } - p = nextSibling(p); - p2 = nextSibling(p2); - } - if (p && p2) - break; - // One parameter list is a prefix of the other, so check that all - // remaining parameters of the longer list are optional. - if (p2) - p = p2; - while (p && Getattr(p, "value")) - p = nextSibling(p); - if (p) - break; - o = Getattr(o, "sym:nextSibling"); - } - if (!o) { - // This "overloaded method" is really just one with default args. - really_overloaded = false; - } - } - - if (wrapperType == memberfn) { - // Allow for the "this" pointer. - --min_num_of_arguments; - --max_num_of_arguments; - } - - arg_names = (String **) malloc(max_num_of_arguments * sizeof(String *)); - if (!arg_names) { - /* FIXME: How should this be handled? The rest of SWIG just seems - * to not bother checking for malloc failing! */ - fprintf(stderr, "Malloc failed!\n"); - SWIG_exit(EXIT_FAILURE); - } - for (i = 0; i < max_num_of_arguments; ++i) { - arg_names[i] = NULL; - } - - arg_values = (String **) malloc(max_num_of_arguments * sizeof(String *)); - byref = (unsigned char *) malloc(max_num_of_arguments); - if (!arg_values || !byref) { - /* FIXME: How should this be handled? The rest of SWIG just seems - * to not bother checking for malloc failing! */ - fprintf(stderr, "Malloc failed!\n"); - SWIG_exit(EXIT_FAILURE); - } - for (i = 0; i < max_num_of_arguments; ++i) { - arg_values[i] = NULL; - byref[i] = false; - } - - Node *o; - if (overloaded) { - o = Getattr(n, "sym:overloaded"); - } else { - o = n; - } - while (o) { - int argno = 0; - Parm *p = Getattr(o, "wrap:parms"); - if (wrapperType == memberfn) - p = nextSibling(p); - while (p) { - if (GetInt(p, "tmap:in:numinputs") == 0) { - p = nextSibling(p); - continue; - } - assert(0 <= argno && argno < max_num_of_arguments); - byref[argno] = GetFlag(p, "tmap:in:byref"); - String *&pname = arg_names[argno]; - const char *pname_cstr = GetChar(p, "name"); - // Just get rid of the C++ namespace part for now. - const char *ptr = NULL; - if (pname_cstr && (ptr = strrchr(pname_cstr, ':'))) { - pname_cstr = ptr + 1; - } - if (!pname_cstr) { - // Unnamed parameter, e.g. int foo(int); - } else if (!pname) { - pname = NewString(pname_cstr); - } else { - size_t len = strlen(pname_cstr); - size_t spc = 0; - size_t len_pname = strlen(Char(pname)); - while (spc + len <= len_pname) { - if (strncmp(pname_cstr, Char(pname) + spc, len) == 0) { - char ch = ((char *) Char(pname))[spc + len]; - if (ch == '\0' || ch == ' ') { - // Already have this pname_cstr. - pname_cstr = NULL; - break; - } - } - char *p = strchr(Char(pname) + spc, ' '); - if (!p) - break; - spc = (p + 4) - Char(pname); - } - if (pname_cstr) { - Printf(pname, " or_%s", pname_cstr); - } - } - String *value = NewString(Getattr(p, "value")); - if (Len(value)) { - /* Check that value is a valid constant in PHP (and adjust it if - * necessary, or replace it with "?" if it's just not valid). */ - SwigType *type = Getattr(p, "type"); - switch (SwigType_type(type)) { - case T_BOOL: { - if (Strcmp(value, "true") == 0 || Strcmp(value, "false") == 0) - break; - char *p; - errno = 0; - long n = strtol(Char(value), &p, 0); - Clear(value); - if (errno || *p) { - Append(value, "?"); - } else if (n) { - Append(value, "true"); - } else { - Append(value, "false"); - } - break; - } - case T_CHAR: - case T_SCHAR: - case T_SHORT: - case T_INT: - case T_LONG: - case T_LONGLONG: { - char *p; - errno = 0; - long n = strtol(Char(value), &p, 0); - (void) n; - if (errno || *p) { - Clear(value); - Append(value, "?"); - } - break; - } - case T_UCHAR: - case T_USHORT: - case T_UINT: - case T_ULONG: - case T_ULONGLONG: { - char *p; - errno = 0; - unsigned int n = strtoul(Char(value), &p, 0); - (void) n; - if (errno || *p) { - Clear(value); - Append(value, "?"); - } - break; - } - case T_FLOAT: - case T_DOUBLE: - case T_LONGDOUBLE: { - char *p; - errno = 0; - /* FIXME: strtod is locale dependent... */ - double val = strtod(Char(value), &p); - if (errno || *p) { - Clear(value); - Append(value, "?"); - } else if (strchr(Char(value), '.') == 0) { - // Ensure value is a double constant, not an integer one. - Append(value, ".0"); - double val2 = strtod(Char(value), &p); - if (errno || *p || val != val2) { - Clear(value); - Append(value, "?"); - } - } - break; - } - case T_STRING: - if (Len(value) < 2) { - // How can a string (including "" be less than 2 characters?) - Clear(value); - Append(value, "?"); - } else { - const char *v = Char(value); - if (v[0] != '"' || v[Len(value) - 1] != '"') { - Clear(value); - Append(value, "?"); - } - // Strings containing "$" require special handling, but we do - // that later. - } - break; - case T_VOID: - assert(false); - break; - case T_POINTER: { - const char *v = Char(value); - if (v[0] == '(') { - // Handle "(void*)0", "(TYPE*)0", "(char*)NULL", etc. - v += strcspn(v + 1, "*()") + 1; - if (*v == '*') { - do { - v++; - v += strspn(v, " \t"); - } while (*v == '*'); - if (*v++ == ')') { - v += strspn(v, " \t"); - String * old = value; - value = NewString(v); - Delete(old); - } - } - } - if (Strcmp(value, "NULL") == 0 || - Strcmp(value, "nullptr") == 0 || - Strcmp(value, "0") == 0 || - Strcmp(value, "0L") == 0) { - Clear(value); - Append(value, "null"); - } else { - Clear(value); - Append(value, "?"); - } - break; - } - default: - /* Safe default */ - Clear(value); - Append(value, "?"); - break; - } - - if (!arg_values[argno]) { - arg_values[argno] = value; - value = NULL; - } else if (Cmp(arg_values[argno], value) != 0) { - // If a parameter has two different default values in - // different overloaded forms of the function, we can't - // set its default in PHP. Flag this by setting its - // default to `?'. - Delete(arg_values[argno]); - arg_values[argno] = NewString("?"); - } - } else if (arg_values[argno]) { - // This argument already has a default value in another overloaded - // form, but doesn't in this form. So don't try to do anything - // clever, just let the C wrappers resolve the overload and set the - // default values. - // - // This handling is safe, but I'm wondering if it may be overly - // conservative (FIXME) in some cases. It seems it's only bad when - // there's an overloaded form with the appropriate number of - // parameters which doesn't want the default value, but I need to - // think about this more. - Delete(arg_values[argno]); - arg_values[argno] = NewString("?"); - } - Delete(value); - p = nextSibling(p); - ++argno; - } - if (!really_overloaded) - break; - o = Getattr(o, "sym:nextSibling"); - } - - /* Clean up any parameters which haven't yet got names, or whose - * names clash. */ - Hash *seen = NewHash(); - /* We need $this to refer to the current class, so can't allow it - * to be used as a parameter. */ - Setattr(seen, "this", seen); - - for (int argno = 0; argno < max_num_of_arguments; ++argno) { - String *&pname = arg_names[argno]; - if (pname) { - Replaceall(pname, " ", "_"); - } else { - /* We get here if the SWIG .i file has "int foo(int);" */ - pname = NewStringEmpty(); - Printf(pname, "arg%d", argno + 1); - } - // Check if we've already used this parameter name. - while (Getattr(seen, pname)) { - // Append "_" to clashing names until they stop clashing... - Printf(pname, "_"); - } - Setattr(seen, Char(pname), seen); - - if (arg_values[argno] && Cmp(arg_values[argno], "?") == 0) { - handle_as_overload = true; - } - } - Delete(seen); - seen = NULL; - - String *invoke = NewStringEmpty(); - String *prepare = NewStringEmpty(); - String *args = NewStringEmpty(); - - if (!handle_as_overload && !(really_overloaded && max_num_of_arguments > min_num_of_arguments)) { - Printf(invoke, "%s(", iname); - if (wrapperType == memberfn) { - Printf(invoke, "$this->%s", SWIG_PTR); - } - for (int i = 0; i < max_num_of_arguments; ++i) { - if (i) - Printf(args, ","); - if (i || wrapperType == memberfn) - Printf(invoke, ","); - if (byref[i]) Printf(args, "&"); - String *value = arg_values[i]; - if (value) { - const char *v = Char(value); - if (v[0] == '"') { - /* In a PHP double quoted string, $ needs to be escaped as \$. */ - Replaceall(value, "$", "\\$"); - } - Printf(args, "$%s=%s", arg_names[i], value); - } else if (constructor && strcmp(methodname, "__construct") == 0 && i >= 1 && i < min_num_of_arguments) { - // We need to be able to call __construct($resource). - Printf(args, "$%s=null", arg_names[i]); - } else { - Printf(args, "$%s", arg_names[i]); - } - Printf(invoke, "$%s", arg_names[i]); - } - Printf(invoke, ")"); - } else { - int i; - for (i = 0; i < min_num_of_arguments; ++i) { - if (i) - Printf(args, ","); - Printf(args, "$%s", arg_names[i]); - } - String *invoke_args = NewStringEmpty(); - if (wrapperType == memberfn) { - Printf(invoke_args, "$this->%s", SWIG_PTR); - if (min_num_of_arguments > 0) - Printf(invoke_args, ","); - } - Printf(invoke_args, "%s", args); - if (constructor && min_num_of_arguments > 1) { - // We need to be able to call __construct($resource). - Clear(args); - Printf(args, "$%s", arg_names[0]); - for (i = 1; i < min_num_of_arguments; ++i) { - Printf(args, ","); - Printf(args, "$%s=null", arg_names[i]); - } - } - bool had_a_case = false; - int last_handled_i = i - 1; - for (; i < max_num_of_arguments; ++i) { - if (i) - Printf(args, ","); - const char *value = Char(arg_values[i]); - // FIXME: (really_overloaded && handle_as_overload) is perhaps a - // little conservative, but it doesn't hit any cases that it - // shouldn't for Xapian at least (and we need it to handle - // "Enquire::get_mset()" correctly). - bool non_php_default = ((really_overloaded && handle_as_overload) || - !value || strcmp(value, "?") == 0); - if (non_php_default) - value = "null"; - Printf(args, "$%s=%s", arg_names[i], value); - if (non_php_default) { - if (!had_a_case) { - Printf(prepare, "\t\tswitch (func_num_args()) {\n"); - had_a_case = true; - } - Printf(prepare, "\t\t"); - while (last_handled_i < i) { - Printf(prepare, "case %d: ", ++last_handled_i); - } - if (non_void_return) { - if ((!directorsEnabled() || !Swig_directorclass(n)) && !constructor) { - Append(prepare, "$r="); - } else if (wrapperType == staticmemberfn || wrapperType == staticmembervar) { - Append(prepare, "$r="); - } else { - Printf(prepare, "$this->%s=", SWIG_PTR); - } - } - if (!directorsEnabled() || !Swig_directorclass(n) || !constructor) { - Printf(prepare, "%s(%s); break;\n", iname, invoke_args); - } else if (!i) { - Printf(prepare, "%s($_this%s); break;\n", iname, invoke_args); - } else { - Printf(prepare, "%s($_this, %s); break;\n", iname, invoke_args); - } - } - if (i || wrapperType == memberfn) - Printf(invoke_args, ","); - Printf(invoke_args, "$%s", arg_names[i]); - } - Printf(prepare, "\t\t"); - if (had_a_case) - Printf(prepare, "default: "); - if (non_void_return) { - if ((!directorsEnabled() || !Swig_directorclass(n)) && !constructor) { - Append(prepare, "$r="); - } else if (wrapperType == staticmemberfn || wrapperType == staticmembervar) { - Append(prepare, "$r="); - } else { - Printf(prepare, "$this->%s=", SWIG_PTR); - } - } - - if (!directorsEnabled() || !Swig_directorclass(n) || !constructor) { - Printf(prepare, "%s(%s);\n", iname, invoke_args); - } else { - Printf(prepare, "%s($_this, %s);\n", iname, invoke_args); - } - if (had_a_case) - Printf(prepare, "\t\t}\n"); - Delete(invoke_args); - Printf(invoke, "$r"); - } - - Printf(output, "\n"); - // If it's a member function or a class constructor... - if (wrapperType == memberfn || (constructor && current_class)) { - String *acc = NewString(Getattr(n, "access")); - // If a base has the same method with public access, then PHP - // requires to have it here as public as well - Node *bases = Getattr(Swig_methodclass(n), "bases"); - if (bases && Strcmp(acc, "public") != 0) { - String *warnmsg = 0; - int haspublicbase = 0; - Iterator i = First(bases); - while (i.item) { - Node *j = firstChild(i.item); - while (j) { - String *jname = Getattr(j, "name"); - if (!jname || Strcmp(jname, Getattr(n, "name")) != 0) { - j = nextSibling(j); - continue; - } - if (Strcmp(nodeType(j), "cdecl") == 0) { - if (!Getattr(j, "access") || checkAttribute(j, "access", "public")) { - haspublicbase = 1; - } - } else if (Strcmp(nodeType(j), "using") == 0 && firstChild(j) && Strcmp(nodeType(firstChild(j)), "cdecl") == 0) { - if (!Getattr(firstChild(j), "access") || checkAttribute(firstChild(j), "access", "public")) { - haspublicbase = 1; - } - } - if (haspublicbase) { - warnmsg = NewStringf("Modifying the access of '%s::%s' to public, as the base '%s' has it as public as well.\n", Getattr(current_class, "classtype"), Getattr(n, "name"), Getattr(i.item, "classtype")); - break; - } - j = nextSibling(j); - } - i = Next(i); - if (haspublicbase) { - break; - } - } - if (Getattr(n, "access") && haspublicbase) { - Delete(acc); - acc = NewStringEmpty(); // implicitly public - Swig_warning(WARN_PHP_PUBLIC_BASE, input_file, line_number, Char(warnmsg)); - Delete(warnmsg); - } - } - - if (Cmp(acc, "public") == 0) { - // The default visibility for methods is public, so don't specify - // that explicitly to keep the wrapper size down. - Delete(acc); - acc = NewStringEmpty(); - } else if (Cmp(acc, "") != 0) { - Append(acc, " "); - } - - if (constructor) { - // Discriminate between the PHP constructor and a C++ constructor - // renamed to become a factory function in PHP. - bool php_constructor = (strcmp(methodname, "__construct") == 0); - const char * arg0 = NULL; - if (max_num_of_arguments > 0) { - arg0 = Char(arg_names[0]); - } else if (php_constructor) { - // The PHP constructor needs to be able to wrap a resource, but a - // renamed constructor doesn't. - arg0 = "res"; - Delete(args); - args = NewString("$res=null"); - } - String *mangled_type = SwigType_manglestr(Getattr(n, "type")); - if (!php_constructor) { - // A renamed constructor should be a static method. - Append(acc, "static "); - } - Printf(output, "\t%sfunction %s(%s) {\n", acc, methodname, args); - if (php_constructor) { - // The PHP constructor needs to be able to wrap a resource, but a - // renamed constructor doesn't. - Printf(output, "\t\tif (is_resource($%s) && get_resource_type($%s) === '%s') {\n", arg0, arg0, mangled_type); - Printf(output, "\t\t\t$this->%s=$%s;\n", SWIG_PTR, arg0); - Printf(output, "\t\t\treturn;\n"); - Printf(output, "\t\t}\n"); - } - } else { - Printf(output, "\t%sfunction %s(%s) {\n", acc, methodname, args); - } - Delete(acc); - } else if (wrapperType == staticmembervar) { - // We're called twice for a writable static member variable - first - // with "foo_set" and then with "foo_get" - so generate half the - // wrapper function each time. - // - // For a const static member, we only get called once. - static bool started = false; - if (!started) { - Printf(output, "\tstatic function %s() {\n", methodname); - if (max_num_of_arguments) { - // Setter. - Printf(output, "\t\tif (func_num_args()) {\n"); - Printf(output, "\t\t\t%s(func_get_arg(0));\n", iname); - Printf(output, "\t\t\treturn;\n"); - Printf(output, "\t\t}\n"); - started = true; - goto done; - } - } - started = false; - } else { - Printf(output, "\tstatic function %s(%s) {\n", methodname, args); - } - - if (!constructor) - Printf(output, "%s", prepare); - if (constructor) { - if (!directorsEnabled() || !Swig_directorclass(n)) { - if (!Len(prepare)) { - if (strcmp(methodname, "__construct") == 0) { - Printf(output, "\t\t$this->%s=%s;\n", SWIG_PTR, invoke); - } else { - String *classname = Swig_class_name(current_class); - Printf(output, "\t\treturn new %s%s(%s);\n", prefix, classname, invoke); - } - } - } else { - Node *parent = Swig_methodclass(n); - String *classname = Swig_class_name(parent); - Printf(output, "\t\tif (get_class($this) === '%s%s') {\n", prefix, classname); - Printf(output, "\t\t\t$_this = null;\n"); - Printf(output, "\t\t} else {\n"); - Printf(output, "\t\t\t$_this = $this;\n"); - Printf(output, "\t\t}\n"); - if (!Len(prepare)) { - if (num_arguments > 1) { - Printf(output, "\t\t$this->%s=%s($_this, %s);\n", SWIG_PTR, iname, args); - } else { - Printf(output, "\t\t$this->%s=%s($_this);\n", SWIG_PTR, iname); - } - } - } - Printf(output, "%s", prepare); - } else if (!non_void_return && !hasargout) { - if (Cmp(invoke, "$r") != 0) - Printf(output, "\t\t%s;\n", invoke); - } else if (is_class(d)) { - if (Cmp(invoke, "$r") != 0) - Printf(output, "\t\t$r=%s;\n", invoke); - if (Len(ret_types) == 1) { - /* If d is abstract we can't create a new wrapper type d. */ - Node *d_class = classLookup(d); - int is_abstract = 0; - if (Getattr(d_class, "abstracts")) { - is_abstract = 1; - } - if (newobject || !is_abstract) { - Printf(output, "\t\tif (is_resource($r)) {\n"); - if (Getattr(classLookup(Getattr(n, "type")), "module")) { - /* - * _p_Foo -> Foo, _p_ns__Bar -> Bar - * TODO: do this in a more elegant way - */ - if (Len(prefix) == 0) { - Printf(output, "\t\t\t$c=substr(get_resource_type($r), (strpos(get_resource_type($r), '__') ? strpos(get_resource_type($r), '__') + 2 : 3));\n"); - } else { - Printf(output, "\t\t\t$c='%s'.substr(get_resource_type($r), (strpos(get_resource_type($r), '__') ? strpos(get_resource_type($r), '__') + 2 : 3));\n", prefix); - } - Printf(output, "\t\t\tif (class_exists($c)) return new $c($r);\n"); - 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\treturn $c;\n"); - } - Printf(output, "\t\t}\n\t\treturn $r;\n"); - } else { - Printf(output, "\t\t$this->%s = $r;\n", SWIG_PTR); - Printf(output, "\t\treturn $this;\n"); - } - } else { - Printf(output, "\t\tif (!is_resource($r)) return $r;\n"); - String *wrapobj = NULL; - String *common = NULL; - Iterator i = First(ret_types); - while (i.item) { - SwigType *ret_type = i.item; - i = Next(i); - String *mangled = NewString("_p"); - Printf(mangled, "%s", SwigType_manglestr(ret_type)); - Node *class_node = Getattr(zend_types, mangled); - if (!class_node) { - /* This is needed when we're returning a pointer to a type - * rather than returning the type by value or reference. */ - Delete(mangled); - mangled = NewString(SwigType_manglestr(ret_type)); - class_node = Getattr(zend_types, mangled); - if (!class_node) { - // Return type isn't an object, so will be handled by the - // !is_resource() check before the switch. - continue; - } - } - const char *classname = GetChar(class_node, "sym:name"); - if (!classname) - classname = GetChar(class_node, "name"); - String * action = NewStringEmpty(); - if (classname) - Printf(action, "return new %s%s($r);\n", prefix, classname); - else - Printf(action, "return $r;\n"); - if (!wrapobj) { - wrapobj = NewString("\t\tswitch (get_resource_type($r)) {\n"); - common = action; - } else { - if (common && Cmp(common, action) != 0) { - Delete(common); - common = NULL; - } - } - Printf(wrapobj, "\t\t"); - if (i.item) { - Printf(wrapobj, "case '%s': ", mangled); - } else { - Printf(wrapobj, "default: "); - } - Printv(wrapobj, action, NIL); - if (action != common) Delete(action); - Delete(mangled); - } - Printf(wrapobj, "\t\t}\n"); - if (common) { - // All cases have the same action, so eliminate the switch - // wrapper. - Printf(output, "\t\t%s", common); - Delete(common); - } else { - Printv(output, wrapobj, NIL); - } - Delete(wrapobj); - } - } else { - if (non_void_return || hasargout) { - Printf(output, "\t\treturn %s;\n", invoke); - } else if (Cmp(invoke, "$r") != 0) { - Printf(output, "\t\t%s;\n", invoke); - } - } - Printf(output, "\t}\n"); - -done: - Delete(prepare); - Delete(invoke); - free(arg_values); - - Delete(args); - args = NULL; - - for (int i = 0; i < max_num_of_arguments; ++i) { - Delete(arg_names[i]); - } - free(arg_names); - arg_names = NULL; } return SWIG_OK; @@ -1880,57 +1463,13 @@ done: * globalvariableHandler() * ------------------------------------------------------------ */ - virtual int globalvariableHandler(Node *n) { - char *name = GetChar(n, "name"); - char *iname = GetChar(n, "sym:name"); - SwigType *t = Getattr(n, "type"); - String *tm; - - /* First do the wrappers such as name_set(), name_get() - * as provided by the baseclass's implementation of variableWrapper - */ - if (Language::globalvariableHandler(n) == SWIG_NOWRAP) { - return SWIG_NOWRAP; - } - - if (!addSymbol(iname, n)) - return SWIG_ERROR; - - /* First link C variables to PHP */ - - tm = Swig_typemap_lookup("varinit", n, name, 0); - if (tm) { - Replaceall(tm, "$target", name); - Printf(s_vinit, "%s\n", tm); - } else { - Swig_error(input_file, line_number, "Unable to link with type %s\n", SwigType_str(t, 0)); - } - - /* Now generate PHP -> C sync blocks */ - /* - tm = Swig_typemap_lookup("varin", n, name, 0); - if(tm) { - Replaceall(tm, "$symname", iname); - Printf(f_c->code, "%s\n", tm); - } else { - Swig_error(input_file, line_number, "Unable to link with type %s\n", SwigType_str(t, 0)); - } - */ - /* Now generate C -> PHP sync blocks */ - /* - if(!GetFlag(n,"feature:immutable")) { - - tm = Swig_typemap_lookup("varout", n, name, 0); - if(tm) { - Replaceall(tm, "$symname", iname); - Printf(f_php->code, "%s\n", tm); - } else { - Swig_error(input_file, line_number, "Unable to link with type %s\n", SwigType_str(t, 0)); - } - } - */ - return SWIG_OK; - } + /* PHP doesn't support intercepting reads and writes to global variables + * (nor static property reads and writes so we can't wrap them as static + * properties on a dummy class) so just let SWIG do its default thing and + * wrap them as name_get() and name_set(). + */ + //virtual int globalvariableHandler(Node *n) { + //} /* ------------------------------------------------------------ * constantWrapper() @@ -1949,48 +1488,43 @@ done: SwigType_remember(type); - if ((tm = Swig_typemap_lookup("consttab", n, name, 0))) { - Replaceall(tm, "$source", value); - Replaceall(tm, "$target", name); - Replaceall(tm, "$value", value); - Printf(s_cinit, "%s\n", tm); - } - - if (shadow) { - String *enumvalue = GetChar(n, "enumvalue"); - String *set_to = iname; - - if (!enumvalue) { - enumvalue = GetChar(n, "enumvalueex"); - } - - if (enumvalue && *Char(enumvalue)) { - // Check for a simple constant expression which is valid in PHP. - // If we find one, initialise the const member with it; otherwise - // we initialise it using the C/C++ wrapped constant. - const char *p; - for (p = Char(enumvalue); *p; ++p) { - if (!isdigit((unsigned char)*p) && !strchr(" +-", *p)) { - // FIXME: enhance to handle ` + 1' which is what - // we get for enums that don't have an explicit value set. - break; - } + String *wrapping_member_constant = Getattr(n, "memberconstantHandler:sym:name"); + if (!wrapping_member_constant) { + { + tm = Swig_typemap_lookup("consttab", n, name, 0); + Replaceall(tm, "$value", value); + if (Getattr(n, "tmap:consttab:rinit")) { + Printf(r_init, "%s\n", tm); + } else { + Printf(s_cinit, "%s\n", tm); } - if (!*p) - set_to = enumvalue; } - if (wrapping_member_constant) { - if (!s_oowrappers) - s_oowrappers = NewStringEmpty(); - Printf(s_oowrappers, "\n\tconst %s = %s;\n", wrapping_member_constant, set_to); + { + tm = Swig_typemap_lookup("classconsttab", n, name, 0); + + Replaceall(tm, "$class", fake_class_name()); + Replaceall(tm, "$const_name", iname); + Replaceall(tm, "$value", value); + if (Getattr(n, "tmap:classconsttab:rinit")) { + Printf(r_init, "%s\n", tm); + } else { + Printf(s_cinit, "%s\n", tm); + } + } + } else { + tm = Swig_typemap_lookup("classconsttab", n, name, 0); + Replaceall(tm, "$class", class_name); + Replaceall(tm, "$const_name", wrapping_member_constant); + Replaceall(tm, "$value", value); + if (Getattr(n, "tmap:classconsttab:rinit")) { + Printf(r_init, "%s\n", tm); } else { - if (!s_fakeoowrappers) - s_fakeoowrappers = NewStringEmpty(); - Printf(s_fakeoowrappers, "\n\tconst %s = %s;\n", iname, set_to); + Printf(s_cinit, "%s\n", tm); } } + wrapperType = standard; return SWIG_OK; } @@ -2052,219 +1586,224 @@ done: * ------------------------------------------------------------ */ virtual int classHandler(Node *n) { - constructors = 0; - current_class = n; + String *symname = Getattr(n, "sym:name"); + String *base_class = NULL; + + class_name = symname; + destructor_action = NULL; + + Printf(all_cs_entry, "static const zend_function_entry class_%s_functions[] = {\n", class_name); + + // namespace code to introduce namespaces into wrapper classes. + //if (nameSpace != NULL) + //Printf(s_oinit, "INIT_CLASS_ENTRY(internal_ce, \"%s\\\\%s\", class_%s_functions);\n", nameSpace, class_name, class_name); + //else + Printf(s_oinit, " INIT_CLASS_ENTRY(internal_ce, \"%s%s\", class_%s_functions);\n", prefix, class_name, class_name); if (shadow) { char *rename = GetChar(n, "sym:name"); if (!addSymbol(rename, n)) return SWIG_ERROR; - shadow_classname = NewString(rename); - - shadow_get_vars = NewHash(); - shadow_set_vars = NewHash(); /* Deal with inheritance */ List *baselist = Getattr(n, "bases"); if (baselist) { Iterator base = First(baselist); - while (base.item && GetFlag(base.item, "feature:ignore")) { - base = Next(base); - } - base = Next(base); - if (base.item) { - /* Warn about multiple inheritance for additional base class(es) */ - while (base.item) { - if (GetFlag(base.item, "feature:ignore")) { - base = Next(base); - continue; + while (base.item) { + if (!GetFlag(base.item, "feature:ignore")) { + if (!base_class) { + base_class = Getattr(base.item, "sym:name"); + } else { + /* Warn about multiple inheritance for additional base class(es) */ + String *proxyclassname = SwigType_str(Getattr(n, "classtypeobj"), 0); + String *baseclassname = SwigType_str(Getattr(base.item, "name"), 0); + Swig_warning(WARN_PHP_MULTIPLE_INHERITANCE, input_file, line_number, + "Warning for %s, base %s ignored. Multiple inheritance is not supported in PHP.\n", proxyclassname, baseclassname); } - String *proxyclassname = SwigType_str(Getattr(n, "classtypeobj"), 0); - String *baseclassname = SwigType_str(Getattr(base.item, "name"), 0); - Swig_warning(WARN_PHP_MULTIPLE_INHERITANCE, input_file, line_number, - "Warning for %s, base %s ignored. Multiple inheritance is not supported in PHP.\n", proxyclassname, baseclassname); - base = Next(base); } - } - } - } - - classnode = n; - Language::classHandler(n); - classnode = 0; - - if (shadow) { - List *baselist = Getattr(n, "bases"); - Iterator ki, base; - - if (baselist) { - base = First(baselist); - while (base.item && GetFlag(base.item, "feature:ignore")) { base = Next(base); } - } else { - base.item = NULL; } - - if (Getattr(n, "abstracts") && !GetFlag(n, "feature:notabstract")) { - Printf(s_phpclasses, "abstract "); - } - - Printf(s_phpclasses, "class %s%s ", prefix, shadow_classname); - String *baseclass = NULL; - if (base.item && Getattr(base.item, "module")) { - baseclass = Getattr(base.item, "sym:name"); - if (!baseclass) - baseclass = Getattr(base.item, "name"); - Printf(s_phpclasses, "extends %s%s ", prefix, baseclass); - } else if (GetFlag(n, "feature:exceptionclass")) { - Append(s_phpclasses, "extends Exception "); - } - { - Node *node = NewHash(); - Setattr(node, "type", Getattr(n, "name")); - Setfile(node, Getfile(n)); - Setline(node, Getline(n)); - String * interfaces = Swig_typemap_lookup("phpinterfaces", node, "", 0); - if (interfaces) { - Printf(s_phpclasses, "implements %s ", interfaces); - } - Delete(node); - } - Printf(s_phpclasses, "{\n\tpublic $%s=null;\n", SWIG_PTR); - if (!baseclass) { - // Only store this in the base class (NB !baseclass means we *are* - // a base class...) - Printf(s_phpclasses, "\tprotected $%s=array();\n", SWIG_DATA); - } - - // Write property SET handlers - ki = First(shadow_set_vars); - if (ki.key) { - // This class has setters. - Printf(s_phpclasses, "\n\tfunction __set($var,$value) {\n"); - // FIXME: tune this threshold... - if (Len(shadow_set_vars) <= 2) { - // Not many setters, so avoid call_user_func. - for (; ki.key; ki = Next(ki)) { - DOH *key = ki.key; - String *iname = ki.item; - Printf(s_phpclasses, "\t\tif ($var === '%s') return %s($this->%s,$value);\n", key, iname, SWIG_PTR); - } - } else { - Printf(s_phpclasses, "\t\t$func = '%s_'.$var.'_set';\n", shadow_classname); - Printf(s_phpclasses, "\t\tif (function_exists($func)) return call_user_func($func,$this->%s,$value);\n", SWIG_PTR); - } - Printf(s_phpclasses, "\t\tif ($var === 'thisown') return swig_%s_alter_newobject($this->%s,$value);\n", module, SWIG_PTR); - if (baseclass) { - Printf(s_phpclasses, "\t\t%s%s::__set($var,$value);\n", prefix, baseclass); - } else { - Printf(s_phpclasses, "\t\t$this->%s[$var] = $value;\n", SWIG_DATA); - } - Printf(s_phpclasses, "\t}\n"); - } else { - Printf(s_phpclasses, "\n\tfunction __set($var,$value) {\n"); - Printf(s_phpclasses, "\t\tif ($var === 'thisown') return swig_%s_alter_newobject($this->%s,$value);\n", module, SWIG_PTR); - if (baseclass) { - Printf(s_phpclasses, "\t\t%s%s::__set($var,$value);\n", prefix, baseclass); - } else { - Printf(s_phpclasses, "\t\t$this->%s[$var] = $value;\n", SWIG_DATA); - } - Printf(s_phpclasses, "\t}\n"); - } - - // Write property GET handlers - ki = First(shadow_get_vars); - if (ki.key) { - // This class has getters. - Printf(s_phpclasses, "\n\tfunction __get($var) {\n"); - int non_class_getters = 0; - for (; ki.key; ki = Next(ki)) { - DOH *key = ki.key; - SwigType *d = ki.item; - if (!is_class(d)) { - ++non_class_getters; - continue; - } - Printv(s_phpclasses, "\t\tif ($var === '", key, "') return new ", prefix, Getattr(classLookup(d), "sym:name"), "(", shadow_classname, "_", key, "_get($this->", SWIG_PTR, "));\n", NIL); - } - // FIXME: tune this threshold... - if (non_class_getters <= 2) { - // Not many non-class getters, so avoid call_user_func. - for (ki = First(shadow_get_vars); non_class_getters && ki.key; ki = Next(ki)) { - DOH *key = ki.key; - SwigType *d = ki.item; - if (is_class(d)) continue; - Printv(s_phpclasses, "\t\tif ($var === '", key, "') return ", shadow_classname, "_", key, "_get($this->", SWIG_PTR, ");\n", NIL); - --non_class_getters; - } - } else { - Printf(s_phpclasses, "\t\t$func = '%s_'.$var.'_get';\n", shadow_classname); - Printf(s_phpclasses, "\t\tif (function_exists($func)) return call_user_func($func,$this->%s);\n", SWIG_PTR); - } - Printf(s_phpclasses, "\t\tif ($var === 'thisown') return swig_%s_get_newobject($this->%s);\n", module, SWIG_PTR); - if (baseclass) { - Printf(s_phpclasses, "\t\treturn %s%s::__get($var);\n", prefix, baseclass); - } else { - // Reading an unknown property name gives null in PHP. - Printf(s_phpclasses, "\t\treturn $this->%s[$var];\n", SWIG_DATA); - } - Printf(s_phpclasses, "\t}\n"); - - /* __isset() should return true for read-only properties, so check for - * *_get() not *_set(). */ - Printf(s_phpclasses, "\n\tfunction __isset($var) {\n"); - Printf(s_phpclasses, "\t\tif (function_exists('%s_'.$var.'_get')) return true;\n", shadow_classname); - Printf(s_phpclasses, "\t\tif ($var === 'thisown') return true;\n"); - if (baseclass) { - Printf(s_phpclasses, "\t\treturn %s%s::__isset($var);\n", prefix, baseclass); - } else { - Printf(s_phpclasses, "\t\treturn array_key_exists($var, $this->%s);\n", SWIG_DATA); - } - Printf(s_phpclasses, "\t}\n"); - } else { - Printf(s_phpclasses, "\n\tfunction __get($var) {\n"); - Printf(s_phpclasses, "\t\tif ($var === 'thisown') return swig_%s_get_newobject($this->%s);\n", module, SWIG_PTR); - if (baseclass) { - Printf(s_phpclasses, "\t\treturn %s%s::__get($var);\n", prefix, baseclass); - } else { - Printf(s_phpclasses, "\t\treturn $this->%s[$var];\n", SWIG_DATA); - } - Printf(s_phpclasses, "\t}\n"); - Printf(s_phpclasses, "\n\tfunction __isset($var) {\n"); - Printf(s_phpclasses, "\t\tif ($var === 'thisown') return true;\n"); - if (baseclass) { - Printf(s_phpclasses, "\t\treturn %s%s::__isset($var);\n", prefix, baseclass); - } else { - Printf(s_phpclasses, "\t\treturn array_key_exists($var, $this->%s);\n", SWIG_DATA); - } - Printf(s_phpclasses, "\t}\n"); - } - - if (!class_has_ctor) { - Printf(s_phpclasses, "\tfunction __construct($h) {\n"); - Printf(s_phpclasses, "\t\t$this->%s=$h;\n", SWIG_PTR); - Printf(s_phpclasses, "\t}\n"); - } - - if (s_oowrappers) { - Printf(s_phpclasses, "%s", s_oowrappers); - Delete(s_oowrappers); - s_oowrappers = NULL; - } - class_has_ctor = false; - - Printf(s_phpclasses, "}\n\n"); - - Delete(shadow_classname); - shadow_classname = NULL; - - Delete(shadow_set_vars); - shadow_set_vars = NULL; - Delete(shadow_get_vars); - shadow_get_vars = NULL; } + + if (GetFlag(n, "feature:exceptionclass") && Getattr(n, "feature:except")) { + /* PHP requires thrown objects to be instances of or derived from + * Exception, so that really needs to take priority over any + * explicit base class. + */ + if (base_class) { + String *proxyclassname = SwigType_str(Getattr(n, "classtypeobj"), 0); + Swig_warning(WARN_PHP_MULTIPLE_INHERITANCE, input_file, line_number, + "Warning for %s, base %s ignored. Multiple inheritance is not supported in PHP.\n", proxyclassname, base_class); + } + base_class = NewString("Exception"); + } + + if (Equal(base_class, "Exception")) { + Printf(s_oinit, " SWIG_Php_ce_%s = zend_register_internal_class_ex(&internal_ce, zend_ce_exception);\n", class_name); + } else if (is_class_wrapped(base_class)) { + Printf(s_oinit, " SWIG_Php_ce_%s = zend_register_internal_class_ex(&internal_ce, SWIG_Php_ce_%s);\n", class_name, base_class); + } else { + Printf(s_oinit, " SWIG_Php_ce_%s = zend_register_internal_class(&internal_ce);\n", class_name); + } + + if (Getattr(n, "abstracts") && !GetFlag(n, "feature:notabstract")) { + Printf(s_oinit, " SWIG_Php_ce_%s->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS;\n", class_name); + } + String *swig_wrapped = swig_wrapped_interface_ce(); + Printv(s_oinit, " zend_do_implement_interface(SWIG_Php_ce_", class_name, ", &", swig_wrapped, ");\n", NIL); + + { + Node *node = NewHash(); + Setattr(node, "type", Getattr(n, "name")); + Setfile(node, Getfile(n)); + Setline(node, Getline(n)); + String *interfaces = Swig_typemap_lookup("phpinterfaces", node, "", 0); + Replaceall(interfaces, " ", ""); + if (interfaces && Len(interfaces) > 0) { + // It seems we need to wait until RINIT time to look up class entries + // for interfaces by name. The downside is that this then happens for + // every request. + // + // Most pre-defined interfaces are accessible via zend_class_entry* + // variables declared in the PHP C API - these we can use at MINIT + // time, so we special case them. This will also be a little faster + // than looking up by name. + Printv(s_header, + "#ifdef __cplusplus\n", + "extern \"C\" {\n", + "#endif\n", + NIL); + + String *r_init_prefix = NewStringEmpty(); + + List *interface_list = Split(interfaces, ',', -1); + int num_interfaces = Len(interface_list); + for (int i = 0; i < num_interfaces; ++i) { + String *interface = Getitem(interface_list, i); + // We generate conditional code in both minit and rinit - then we or the user + // just need to define SWIG_PHP_INTERFACE_xxx_CE (and optionally + // SWIG_PHP_INTERFACE_xxx_HEADER) to handle interface `xxx` at minit-time. + Printv(s_header, + "#ifdef SWIG_PHP_INTERFACE_", interface, "_HEADER\n", + "# include SWIG_PHP_INTERFACE_", interface, "_HEADER\n", + "#endif\n", + NIL); + Printv(s_oinit, + "#ifdef SWIG_PHP_INTERFACE_", interface, "_CE\n", + " zend_do_implement_interface(SWIG_Php_ce_", class_name, ", SWIG_PHP_INTERFACE_", interface, "_CE);\n", + "#endif\n", + NIL); + Printv(r_init_prefix, + "#ifndef SWIG_PHP_INTERFACE_", interface, "_CE\n", + " {\n", + " zend_class_entry *swig_interface_ce = zend_lookup_class(zend_string_init(\"", interface, "\", sizeof(\"", interface, "\") - 1, 0));\n", + " if (swig_interface_ce)\n", + " zend_do_implement_interface(SWIG_Php_ce_", class_name, ", swig_interface_ce);\n", + " else\n", + " zend_throw_exception(zend_ce_error, \"Interface \\\"", interface, "\\\" not found\", 0);\n", + " }\n", + "#endif\n", + NIL); + } + + // Handle interfaces at the start of rinit so that they're added + // before any potential constant objects, etc which might be created + // later in rinit. + Insert(r_init, 0, r_init_prefix); + Delete(r_init_prefix); + + Printv(s_header, + "#ifdef __cplusplus\n", + "}\n", + "#endif\n", + NIL); + } + Delete(interfaces); + } + + Language::classHandler(n); + + static bool emitted_base_object_handlers = false; + if (!emitted_base_object_handlers) { + Printf(s_creation, "static zend_object_handlers Swig_Php_base_object_handlers;\n\n"); + + // Set up a base zend_object_handlers structure which we can use as-is + // for classes without a destructor, and copy as the basis for other + // classes. + Printf(s_oinit, " Swig_Php_base_object_handlers = *zend_get_std_object_handlers();\n"); + Printf(s_oinit, " Swig_Php_base_object_handlers.offset = XtOffsetOf(swig_object_wrapper, std);\n"); + Printf(s_oinit, " Swig_Php_base_object_handlers.clone_obj = NULL;\n"); + emitted_base_object_handlers = true; + } + + Printf(s_creation, "static zend_class_entry *SWIG_Php_ce_%s;\n\n", class_name); + + if (Getattr(n, "has_destructor")) { + if (destructor_action ? Equal(destructor_action, "free((char *) arg1);") : !CPlusPlus) { + // We can use a single function if the destructor action calls free() + // (either explicitly or as the default in C-mode) since free() doesn't + // care about the object's type. We currently only check for the exact + // code that Swig_cdestructor_call() emits. + static bool emitted_common_cdestructor = false; + if (!emitted_common_cdestructor) { + Printf(s_creation, "static zend_object_handlers Swig_Php_common_c_object_handlers;\n\n"); + Printf(s_creation, "static void SWIG_Php_common_c_free_obj(zend_object *object) {free(SWIG_Php_free_obj(object));}\n\n"); + Printf(s_creation, "static zend_object *SWIG_Php_common_c_create_object(zend_class_entry *ce) {return SWIG_Php_do_create_object(ce, &Swig_Php_common_c_object_handlers);}\n"); + + Printf(s_oinit, " Swig_Php_common_c_object_handlers = Swig_Php_base_object_handlers;\n"); + Printf(s_oinit, " Swig_Php_common_c_object_handlers.free_obj = SWIG_Php_common_c_free_obj;\n"); + + emitted_common_cdestructor = true; + } + + Printf(s_oinit, " SWIG_Php_ce_%s->create_object = SWIG_Php_common_c_create_object;\n", class_name); + } else { + Printf(s_creation, "static zend_object_handlers %s_object_handlers;\n", class_name); + Printf(s_creation, "static zend_object *SWIG_Php_create_object_%s(zend_class_entry *ce) {return SWIG_Php_do_create_object(ce, &%s_object_handlers);}\n", class_name, class_name); + + Printf(s_creation, "static void SWIG_Php_free_obj_%s(zend_object *object) {",class_name); + String *type = Getattr(n, "classtype"); + // Special case handling the delete call generated by + // Swig_cppdestructor_call() and generate simpler code. + if (destructor_action && !Equal(destructor_action, "delete arg1;")) { + Printv(s_creation, "\n" + " ", type, " *arg1 = (" , type, " *)SWIG_Php_free_obj(object);\n" + " if (arg1) {\n" + " ", destructor_action, "\n" + " }\n", NIL); + } else { + Printf(s_creation, "delete (%s *)SWIG_Php_free_obj(object);", type); + } + Printf(s_creation, "}\n\n"); + + Printf(s_oinit, " SWIG_Php_ce_%s->create_object = SWIG_Php_create_object_%s;\n", class_name, class_name); + Printf(s_oinit, " %s_object_handlers = Swig_Php_base_object_handlers;\n", class_name); + Printf(s_oinit, " %s_object_handlers.free_obj = SWIG_Php_free_obj_%s;\n", class_name, class_name); + } + } else { + static bool emitted_destructorless_create_object = false; + if (!emitted_destructorless_create_object) { + emitted_destructorless_create_object = true; + Printf(s_creation, "static zend_object *SWIG_Php_create_object(zend_class_entry *ce) {return SWIG_Php_do_create_object(ce, &Swig_Php_base_object_handlers);}\n", class_name); + } + + Printf(s_oinit, " SWIG_Php_ce_%s->create_object = SWIG_Php_create_object;\n", class_name); + } + + // If not defined we aren't wrapping any functions which use this type as a + // parameter or return value, in which case we don't need the clientdata + // set. + Printf(s_oinit, "#ifdef SWIGTYPE_p%s\n", SwigType_manglestr(Getattr(n, "classtypeobj"))); + Printf(s_oinit, " SWIG_TypeClientData(SWIGTYPE_p%s,SWIG_Php_ce_%s);\n", SwigType_manglestr(Getattr(n, "classtypeobj")), class_name); + Printf(s_oinit, "#endif\n"); + Printf(s_oinit, "\n"); + + generate_magic_property_methods(n, base_class); + Printf(all_cs_entry, " ZEND_FE_END\n};\n\n"); + + class_name = NULL; return SWIG_OK; } @@ -2285,6 +1824,25 @@ done: * ------------------------------------------------------------ */ virtual int membervariableHandler(Node *n) { + if (magic_set == NULL) { + magic_set = NewStringEmpty(); + magic_get = NewStringEmpty(); + magic_isset = NewStringEmpty(); + } + + String *v_name = GetChar(n, "name"); + + Printf(magic_set, "\nelse if (strcmp(ZSTR_VAL(arg2),\"%s\") == 0) {\n", v_name); + Printf(magic_set, "ZVAL_STRING(&tempZval, \"%s_set\");\n", v_name); + Printf(magic_set, "call_user_function(EG(function_table),ZEND_THIS,&tempZval,return_value,1,&args[1]);\n}\n"); + + Printf(magic_get, "\nelse if (strcmp(ZSTR_VAL(arg2),\"%s\") == 0) {\n", v_name); + Printf(magic_get, "ZVAL_STRING(&tempZval, \"%s_get\");\n", v_name); + Printf(magic_get, "call_user_function(EG(function_table),ZEND_THIS,&tempZval,return_value,0,NULL);\n}\n"); + + Printf(magic_isset, "\nelse if (strcmp(ZSTR_VAL(arg2),\"%s\") == 0) {\n", v_name); + Printf(magic_isset, "RETVAL_TRUE;\n}\n"); + wrapperType = membervar; Language::membervariableHandler(n); wrapperType = standard; @@ -2325,9 +1883,7 @@ done: * ------------------------------------------------------------ */ virtual int constructorHandler(Node *n) { - constructors++; if (Swig_directorclass(n)) { - String *name = GetChar(Swig_methodclass(n), "name"); String *ctype = GetChar(Swig_methodclass(n), "classtype"); String *sname = GetChar(Swig_methodclass(n), "sym:name"); String *args = NewStringEmpty(); @@ -2352,10 +1908,12 @@ done: Delete(director_ctor_code); director_ctor_code = NewStringEmpty(); director_prot_ctor_code = NewStringEmpty(); - Printf(director_ctor_code, "if (Z_TYPE_P(arg0) == IS_NULL) { /* not subclassed */\n"); - Printf(director_prot_ctor_code, "if (Z_TYPE_P(arg0) == IS_NULL) { /* not subclassed */\n"); - Printf(director_ctor_code, " %s = (%s *)new %s(%s);\n", Swig_cresult_name(), ctype, ctype, args); - Printf(director_prot_ctor_code, " SWIG_PHP_Error(E_ERROR, \"accessing abstract class or protected constructor\");\n", name, name, args); + Printf(director_ctor_code, "if (Z_OBJCE_P(arg0) == SWIG_Php_ce_%s) { /* not subclassed */\n", class_name); + Printf(director_prot_ctor_code, "if (Z_OBJCE_P(arg0) == SWIG_Php_ce_%s) { /* not subclassed */\n", class_name); + Printf(director_ctor_code, " %s = new %s(%s);\n", Swig_cresult_name(), ctype, args); + Printf(director_prot_ctor_code, + " zend_throw_exception(zend_ce_type_error, \"accessing abstract class or protected constructor\", 0);\n" + " return;\n"); if (i) { Insert(args, 0, ", "); } @@ -2374,71 +1932,13 @@ done: } /* ------------------------------------------------------------ - * CreateZendListDestructor() + * destructorHandler() * ------------------------------------------------------------ */ - //virtual int destructorHandler(Node *n) { - //} - int CreateZendListDestructor(Node *n) { - String *name = GetChar(Swig_methodclass(n), "name"); - String *iname = GetChar(n, "sym:name"); - ParmList *l = Getattr(n, "parms"); - - String *destructorname = NewStringEmpty(); - Printf(destructorname, "_%s", Swig_name_wrapper(iname)); - Setattr(classnode, "destructor", destructorname); - - Wrapper *f = NewWrapper(); - Printf(f->def, "/* This function is designed to be called by the zend list destructors */\n"); - Printf(f->def, "/* to typecast and do the actual destruction */\n"); - Printf(f->def, "static void %s(zend_resource *res, const char *type_name) {\n", destructorname); - - Wrapper_add_localv(f, "value", "swig_object_wrapper *value=(swig_object_wrapper *) res->ptr", NIL); - Wrapper_add_localv(f, "ptr", "void *ptr=value->ptr", NIL); - Wrapper_add_localv(f, "newobject", "int newobject=value->newobject", NIL); - - emit_parameter_variables(l, f); - emit_attach_parmmaps(l, f); - - // Get type of first arg, thing to be destructed - // Skip ignored arguments - Parm *p = l; - //while (Getattr(p,"tmap:ignore")) {p = Getattr(p,"tmap:ignore:next");} - while (checkAttribute(p, "tmap:in:numinputs", "0")) { - p = Getattr(p, "tmap:in:next"); - } - SwigType *pt = Getattr(p, "type"); - - Printf(f->code, " efree(value);\n"); - Printf(f->code, " if (! newobject) return; /* can't delete it! */\n"); - Printf(f->code, " arg1 = (%s)SWIG_ConvertResourceData(ptr, type_name, SWIGTYPE%s);\n", SwigType_lstr(pt, 0), SwigType_manglestr(pt)); - Printf(f->code, " if (! arg1) zend_error(E_ERROR, \"%s resource already free'd\");\n", Char(name)); - - Setattr(n, "wrap:name", destructorname); - - String *actioncode = emit_action(n); - Append(f->code, actioncode); - Delete(actioncode); - - Printf(f->code, "thrown:\n"); - Append(f->code, "return;\n"); - Append(f->code, "fail:\n"); - Append(f->code, "SWIG_FAIL();\n"); - Printf(f->code, "}\n"); - - Wrapper_print(f, s_wrappers); - DelWrapper(f); - - return SWIG_OK; - } - - /* ------------------------------------------------------------ - * memberconstantHandler() - * ------------------------------------------------------------ */ - - virtual int memberconstantHandler(Node *n) { - wrapping_member_constant = Getattr(n, "sym:name"); - Language::memberconstantHandler(n); - wrapping_member_constant = NULL; + virtual int destructorHandler(Node *n) { + wrapperType = destructor; + Language::destructorHandler(n); + destructor_action = Getattr(n, "wrap:action"); + wrapperType = standard; return SWIG_OK; } @@ -2583,7 +2083,7 @@ done: Append(w->def, " {"); Append(declaration, ";\n"); - /* declare method return value + /* declare method return value * if the return value is a reference or const reference, a specialized typemap must * handle it, including declaration of c_result ($result). */ @@ -2612,12 +2112,10 @@ done: Delete(super_call); } else { Printf(w->code, "Swig::DirectorPureVirtualException::raise(\"Attempted to invoke pure virtual method %s::%s\");\n", SwigType_namestr(c_classname), - SwigType_namestr(name)); + SwigType_namestr(name)); } } else { /* attach typemaps to arguments (C/C++ -> PHP) */ - String *parse_args = NewStringEmpty(); - Swig_director_parms_fixup(l); /* remove the wrapper 'w' since it was producing spurious temps */ @@ -2655,9 +2153,7 @@ done: Delete(input); Replaceall(tm, "$owner", "0"); Printv(wrap_args, tm, "\n", NIL); - Putc('O', parse_args); } else { - Append(parse_args, parse); Setattr(p, "emit:directorinput", pname); Replaceall(tm, "$input", pname); Replaceall(tm, "$owner", "0"); @@ -2676,25 +2172,6 @@ done: p = nextSibling(p); } - /* exception handling */ - bool error_used_in_typemap = false; - tm = Swig_typemap_lookup("director:except", n, Swig_cresult_name(), 0); - if (!tm) { - tm = Getattr(n, "feature:director:except"); - if (tm) - tm = Copy(tm); - } - if ((tm) && Len(tm) && (Strcmp(tm, "1") != 0)) { - if (Replaceall(tm, "$error", "error")) { - /* Only declare error if it is used by the typemap. */ - error_used_in_typemap = true; - Append(w->code, "int error;\n"); - } - } else { - Delete(tm); - tm = NULL; - } - if (!idx) { Printf(w->code, "zval *args = NULL;\n"); } else { @@ -2703,24 +2180,38 @@ done: // typemap_directorout testcase requires that 0 can be assigned to the // variable named after the result of Swig_cresult_name(), so that can't // be a zval - make it a pointer to one instead. - Printf(w->code, "zval swig_zval_result, swig_funcname;\n", Swig_cresult_name()); + Printf(w->code, "zval swig_zval_result;\n"); Printf(w->code, "zval * SWIGUNUSED %s = &swig_zval_result;\n", Swig_cresult_name()); - const char * funcname = GetChar(n, "sym:name"); - Printf(w->code, "ZVAL_STRINGL(&swig_funcname, \"%s\", %d);\n", funcname, strlen(funcname)); /* wrap complex arguments to zvals */ - Printv(w->code, wrap_args, NIL); + Append(w->code, wrap_args); - if (error_used_in_typemap) { - Append(w->code, "error = "); + const char *funcname = GetChar(n, "sym:name"); + Append(w->code, "{\n"); + Append(w->code, "#if PHP_MAJOR_VERSION < 8\n"); + Printf(w->code, "zval swig_funcname;\n"); + Printf(w->code, "ZVAL_STRINGL(&swig_funcname, \"%s\", %d);\n", funcname, strlen(funcname)); + Printf(w->code, "call_user_function(EG(function_table), &swig_self, &swig_funcname, &swig_zval_result, %d, args);\n", idx); + Append(w->code, "#else\n"); + Printf(w->code, "zend_string *swig_funcname = zend_string_init(\"%s\", %d, 0);\n", funcname, strlen(funcname)); + Append(w->code, "zend_function *swig_zend_func = zend_std_get_method(&Z_OBJ(swig_self), swig_funcname, NULL);\n"); + Append(w->code, "zend_string_release(swig_funcname);\n"); + Printf(w->code, "if (swig_zend_func) zend_call_known_instance_method(swig_zend_func, Z_OBJ(swig_self), &swig_zval_result, %d, args);\n", idx); + Append(w->code, "#endif\n"); + + /* exception handling */ + tm = Swig_typemap_lookup("director:except", n, Swig_cresult_name(), 0); + if (!tm) { + tm = Getattr(n, "feature:director:except"); + if (tm) + tm = Copy(tm); } - Append(w->code, "call_user_function(EG(function_table), &swig_self, &swig_funcname,"); - Printf(w->code, " &swig_zval_result, %d, args);\n", idx); - - if (tm) { + if ((tm) && Len(tm) && (Strcmp(tm, "1") != 0)) { + Replaceall(tm, "$error", "EG(exception)"); Printv(w->code, Str(tm), "\n", NIL); - Delete(tm); } + Append(w->code, "}\n"); + Delete(tm); /* marshal return value from PHP to C/C++ type */ @@ -2749,8 +2240,8 @@ done: Delete(tm); } else { Swig_warning(WARN_TYPEMAP_DIRECTOROUT_UNDEF, input_file, line_number, - "Unable to use return type %s in director method %s::%s (skipping method).\n", SwigType_str(returntype, 0), SwigType_namestr(c_classname), - SwigType_namestr(name)); + "Unable to use return type %s in director method %s::%s (skipping method).\n", SwigType_str(returntype, 0), + SwigType_namestr(c_classname), SwigType_namestr(name)); status = SWIG_ERROR; } } @@ -2767,12 +2258,11 @@ done: } } - Delete(parse_args); Delete(cleanup); Delete(outarg); } - Append(w->code, "thrown:\n"); + Append(w->code, "fail: ;\n"); if (!is_void) { if (!(ignored_method && !pure_virtual)) { String *rettype = SwigType_str(returntype, 0); @@ -2783,12 +2273,7 @@ done: } Delete(rettype); } - } else { - Append(w->code, "return;\n"); } - - Append(w->code, "fail:\n"); - Append(w->code, "SWIG_FAIL();\n"); Append(w->code, "}\n"); // We expose protected methods via an extra public inline method which makes a straight call to the wrapped class' method @@ -2823,36 +2308,107 @@ done: return status; } - int classDirectorDisown(Node *) { - return SWIG_OK; + int classDirectorDisown(Node *n) { + wrapperType = directordisown; + int result = Language::classDirectorDisown(n); + wrapperType = standard; + return result; } }; /* class PHP */ static PHP *maininstance = 0; -// We use this function to be able to write out zend_register_list_destructor_ex -// lines for most things in the type table +void PHPTypes::process_phptype(Node *n, int key, const String_or_char *attribute_name) { + + while (Len(merged_types) <= key) { + Append(merged_types, NewList()); + } + + String *phptype = Getattr(n, attribute_name); + if (!phptype || Len(phptype) == 0) { + // There's no type declaration, so any merged version has no type declaration. + // + // Use a DOH None object as a marker to indicate there's no type + // declaration for this parameter/return value (you can't store NULL as a + // value in a DOH List). + Setitem(merged_types, key, None); + return; + } + + DOH *merge_list = Getitem(merged_types, key); + if (merge_list == None) return; + + List *types = Split(phptype, '|', -1); + String *first_type = Getitem(types, 0); + if (Char(first_type)[0] == '?') { + if (Len(types) > 1) { + Printf(stderr, "warning: Invalid phptype: '%s' (can't use ? and | together)\n", phptype); + } + // Treat `?foo` just like `foo|null`. + Append(types, "null"); + Setitem(types, 0, NewString(Char(first_type) + 1)); + } + + SortList(types, NULL); + String *prev = NULL; + for (Iterator i = First(types); i.item; i = Next(i)) { + if (prev && Equal(prev, i.item)) { + Printf(stderr, "warning: Invalid phptype: '%s' (duplicate entry for '%s')\n", phptype, i.item); + continue; + } + + if (key > 0 && Equal(i.item, "void")) { + // Reject void for parameter type. + Printf(stderr, "warning: Invalid phptype: '%s' ('%s' can't be used as a parameter phptype)\n", phptype, i.item); + continue; + } + + if (Equal(i.item, "SWIGTYPE")) { + String *type = Getattr(n, "type"); + Node *class_node = maininstance->classLookup(type); + if (class_node) { + // FIXME: Prefix classname with a backslash to prevent collisions + // with built-in types? Or are non of those valid anyway and so will + // have been renamed at this point? + Append(merge_list, Getattr(class_node, "sym:name")); + } else { + // SWIG wraps a pointer to a non-object type as an object in a PHP + // class named based on the SWIG-mangled C/C++ type. + // + // FIXME: We should check this is actually a known pointer to + // non-object type so we complain about `phptype="SWIGTYPE"` being + // used for PHP types like `int` or `string` (currently this only + // fails at runtime and the error isn't very helpful). We could + // check the condition + // + // zend_types && Getattr(zend_types, SwigType_manglestr(type)) + // + // except that zend_types may not have been fully filled in when + // we are called. + Append(merge_list, NewStringf("SWIG\\%s", SwigType_manglestr(type))); + } + } else { + Append(merge_list, i.item); + } + prev = i.item; + } +} + +// Collect non-class pointer types from the type table so we can set up PHP +// classes for them later. +// // NOTE: it's a function NOT A PHP::METHOD extern "C" { static void typetrace(const SwigType *ty, String *mangled, String *clientdata) { - Node *class_node; - if (!zend_types) { - zend_types = NewHash(); - } - // we want to know if the type which reduced to this has a constructor - if ((class_node = maininstance->classLookup(ty))) { - if (!Getattr(zend_types, mangled)) { - // OK it may have been set before by a different SwigType but it would - // have had the same underlying class node I think - // - it is certainly required not to have different originating class - // nodes for the same SwigType - Setattr(zend_types, mangled, class_node); + if (maininstance->classLookup(ty) == NULL) { + // a non-class pointer + if (!zend_types) { + zend_types = NewHash(); } - } else { // a non-class pointer - Setattr(zend_types, mangled, NOTCLASS); + Setattr(zend_types, mangled, mangled); } if (r_prevtracefunc) - (*r_prevtracefunc) (ty, mangled, (String *) clientdata); + (*r_prevtracefunc) (ty, mangled, clientdata); } } diff --git a/Source/Modules/pike.cxx b/Source/Modules/pike.cxx deleted file mode 100644 index b8ed4037a..000000000 --- a/Source/Modules/pike.cxx +++ /dev/null @@ -1,904 +0,0 @@ -/* ----------------------------------------------------------------------------- - * This file is part of SWIG, which is licensed as a whole under version 3 - * (or any later version) of the GNU General Public License. Some additional - * terms also apply to certain portions of SWIG. The full details of the SWIG - * license and copyrights can be found in the LICENSE and COPYRIGHT files - * included with the SWIG source code as distributed by the SWIG developers - * and at http://www.swig.org/legal.html. - * - * pike.cxx - * - * Pike language module for SWIG. - * ----------------------------------------------------------------------------- */ - -/* - * Notes: - * - * - The current approach used for "out" typemaps is inconsistent with - * how "out" typemaps are handled by other language modules. Instead - * of converting the C/C++ type ($1) to a Pike object type (e.g. a - * struct svalue), we're just calling the appropriate push_XXX - * (e.g. push_int) to push the return value onto the stack. - * - * - Pike classes can't have static member functions or data, so we need - * to find some other appropriate mapping for C++ static member functions - * and data. - * - * - Pike doesn't seem to provide any default way to print the memory - * address, etc. for extension objects. Should we do something here? - * - */ - -#include "swigmod.h" - -#include // for isalnum() - -static const char *usage = "\ -Pike Options (available with -pike)\n\ - [no additional options]\n\ -\n"; - -class PIKE:public Language { -private: - - File *f_begin; - File *f_runtime; - File *f_header; - File *f_wrappers; - File *f_init; - File *f_classInit; - - String *PrefixPlusUnderscore; - int current; - - // Wrap modes - enum { - NO_CPP, - MEMBER_FUNC, - CONSTRUCTOR, - DESTRUCTOR, - MEMBER_VAR, - CLASS_CONST, - STATIC_FUNC, - STATIC_VAR - }; - -public: - - /* --------------------------------------------------------------------- - * PIKE() - * - * Initialize member data - * --------------------------------------------------------------------- */ - - PIKE() { - f_begin = 0; - f_runtime = 0; - f_header = 0; - f_wrappers = 0; - f_init = 0; - f_classInit = 0; - PrefixPlusUnderscore = 0; - current = NO_CPP; - } - - /* --------------------------------------------------------------------- - * main() - * - * Parse command line options and initializes variables. - * --------------------------------------------------------------------- */ - - virtual void main(int argc, char *argv[]) { - - /* Set location of SWIG library */ - SWIG_library_directory("pike"); - - /* Look for certain command line options */ - for (int i = 1; i < argc; i++) { - if (argv[i]) { - if (strcmp(argv[i], "-help") == 0) { - fputs(usage, stdout); - } - } - } - - /* Add a symbol to the parser for conditional compilation */ - Preprocessor_define("SWIGPIKE 1", 0); - - /* Set language-specific configuration file */ - SWIG_config_file("pike.swg"); - - /* Set typemap language */ - SWIG_typemap_lang("pike"); - - /* Enable overloaded methods support */ - allow_overloading(); - } - - /* --------------------------------------------------------------------- - * top() - * --------------------------------------------------------------------- */ - - virtual int top(Node *n) { - /* Get the module name */ - String *module = Getattr(n, "name"); - - /* Get the output file name */ - String *outfile = Getattr(n, "outfile"); - - /* Open the output file */ - f_begin = NewFile(outfile, "w", SWIG_output_files()); - if (!f_begin) { - FileErrorDisplay(outfile); - SWIG_exit(EXIT_FAILURE); - } - f_runtime = NewString(""); - f_init = NewString(""); - f_classInit = NewString(""); - f_header = NewString(""); - f_wrappers = NewString(""); - - /* Register file targets with the SWIG file handler */ - Swig_register_filebyname("header", f_header); - Swig_register_filebyname("wrapper", f_wrappers); - Swig_register_filebyname("begin", f_begin); - Swig_register_filebyname("runtime", f_runtime); - Swig_register_filebyname("init", f_init); - Swig_register_filebyname("classInit", f_classInit); - - /* Standard stuff for the SWIG runtime section */ - Swig_banner(f_begin); - - Printf(f_runtime, "\n\n#ifndef SWIGPIKE\n#define SWIGPIKE\n#endif\n\n"); - - Printf(f_header, "#define SWIG_init pike_module_init\n"); - Printf(f_header, "#define SWIG_name \"%s\"\n\n", module); - - /* Change naming scheme for constructors and destructors */ - Swig_name_register("construct", "%n%c_create"); - Swig_name_register("destroy", "%n%c_destroy"); - - /* Current wrap type */ - current = NO_CPP; - - /* Emit code for children */ - Language::top(n); - - /* Close the initialization function */ - Printf(f_init, "}\n"); - SwigType_emit_type_table(f_runtime, f_wrappers); - - /* Close all of the files */ - Dump(f_runtime, f_begin); - Dump(f_header, f_begin); - Dump(f_wrappers, f_begin); - Wrapper_pretty_print(f_init, f_begin); - - Delete(f_header); - Delete(f_wrappers); - Delete(f_init); - Delete(f_classInit); - Delete(f_runtime); - Delete(f_begin); - - /* Done */ - return SWIG_OK; - } - - /* ------------------------------------------------------------ - * validIdentifier() - * ------------------------------------------------------------ */ - - virtual int validIdentifier(String *s) { - char *c = Char(s); - const char *c0 = c; - const char *c1 = c0 + 1; - while (*c) { - if (*c == '`' && c == c0) { - c++; - continue; - } - if ((*c == '+' || *c == '-' || *c == '*' || *c == '/') && c == c1) { - c++; - continue; - } - if (!(isalnum(*c) || (*c == '_'))) - return 0; - c++; - } - return 1; - } - - /* ------------------------------------------------------------ - * importDirective() - * ------------------------------------------------------------ */ - - virtual int importDirective(Node *n) { - String *modname = Getattr(n, "module"); - if (modname) { - Printf(f_init, "pike_require(\"%s\");\n", modname); - } - return Language::importDirective(n); - } - - /* ------------------------------------------------------------ - * strip() - * - * For names that begin with the current class prefix plus an - * underscore (e.g. "Foo_enum_test"), return the base function - * name (i.e. "enum_test"). - * ------------------------------------------------------------ */ - - String *strip(const DOHconst_String_or_char_ptr name) { - String *s = Copy(name); - if (Strncmp(name, PrefixPlusUnderscore, Len(PrefixPlusUnderscore)) != 0) { - return s; - } - Replaceall(s, PrefixPlusUnderscore, ""); - return s; - } - - /* ------------------------------------------------------------ - * add_method() - * ------------------------------------------------------------ */ - - void add_method(const DOHconst_String_or_char_ptr name, const DOHconst_String_or_char_ptr function, const DOHconst_String_or_char_ptr description) { - String *rename = NULL; - switch (current) { - case NO_CPP: - rename = NewString(name); - Printf(f_init, "ADD_FUNCTION(\"%s\", %s, tFunc(%s), 0);\n", rename, function, description); - break; - case STATIC_FUNC: - case STATIC_VAR: - rename = NewString(name); - Printf(f_init, "ADD_FUNCTION(\"%s\", %s, tFunc(%s), 0);\n", rename, function, description); - break; - case CONSTRUCTOR: - case DESTRUCTOR: - case MEMBER_FUNC: - case MEMBER_VAR: - rename = strip(name); - Printf(f_classInit, "ADD_FUNCTION(\"%s\", %s, tFunc(%s), 0);\n", rename, function, description); - break; - case CLASS_CONST: // shouldn't have gotten here for CLASS_CONST nodes - default: // what is this? - assert(false); - } - Delete(rename); - } - - /* --------------------------------------------------------------------- - * functionWrapper() - * - * Create a function declaration and register it with the interpreter. - * --------------------------------------------------------------------- */ - - virtual int functionWrapper(Node *n) { - - String *name = Getattr(n, "name"); - String *iname = Getattr(n, "sym:name"); - SwigType *d = Getattr(n, "type"); - ParmList *l = Getattr(n, "parms"); - - Parm *p; - String *tm; - int i; - - String *overname = 0; - if (Getattr(n, "sym:overloaded")) { - overname = Getattr(n, "sym:overname"); - } else { - if (!addSymbol(iname, n)) - return SWIG_ERROR; - } - - Wrapper *f = NewWrapper(); - - // Emit all of the local variables for holding arguments. - emit_parameter_variables(l, f); - - /* Attach the standard typemaps */ - emit_attach_parmmaps(l, f); - Setattr(n, "wrap:parms", l); - - /* Get number of required and total arguments */ - int num_arguments = emit_num_arguments(l); - int varargs = emit_isvarargs(l); - - /* Which input argument to start with? */ - int start = (current == MEMBER_FUNC || current == MEMBER_VAR || current == DESTRUCTOR) ? 1 : 0; - - /* Offset to skip over the attribute name */ - // int offset = (current == MEMBER_VAR) ? 1 : 0; - int offset = 0; - - String *wname = Swig_name_wrapper(iname); - if (overname) { - Append(wname, overname); - } - Setattr(n, "wrap:name", wname); - - Printv(f->def, "static void ", wname, "(INT32 args) {", NIL); - - /* Generate code for argument marshalling */ - String *description = NewString(""); - char source[64]; - for (i = 0, p = l; i < num_arguments; i++) { - - while (checkAttribute(p, "tmap:in:numinputs", "0")) { - p = Getattr(p, "tmap:in:next"); - } - - SwigType *pt = Getattr(p, "type"); - String *ln = Getattr(p, "lname"); - - if (i < start) { - String *lstr = SwigType_lstr(pt, 0); - Printf(f->code, "%s = (%s) THIS;\n", ln, lstr); - Delete(lstr); - } else { - /* Look for an input typemap */ - sprintf(source, "Pike_sp[%d-args]", i - start + offset); - if ((tm = Getattr(p, "tmap:in"))) { - Replaceall(tm, "$source", source); - Replaceall(tm, "$target", ln); - Replaceall(tm, "$input", source); - Setattr(p, "emit:input", source); - Printf(f->code, "%s\n", tm); - String *pikedesc = Getattr(p, "tmap:in:pikedesc"); - if (pikedesc) { - Printv(description, pikedesc, " ", NIL); - } - p = Getattr(p, "tmap:in:next"); - continue; - } else { - Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0)); - break; - } - } - p = nextSibling(p); - } - - /* Check for trailing varargs */ - if (varargs) { - if (p && (tm = Getattr(p, "tmap:in"))) { - Replaceall(tm, "$input", "varargs"); - Printv(f->code, tm, "\n", NIL); - } - } - - /* Insert constraint checking code */ - for (p = l; p;) { - if ((tm = Getattr(p, "tmap:check"))) { - Replaceall(tm, "$target", Getattr(p, "lname")); - Printv(f->code, tm, "\n", NIL); - p = Getattr(p, "tmap:check:next"); - } else { - p = nextSibling(p); - } - } - - /* Insert cleanup code */ - String *cleanup = NewString(""); - for (p = l; p;) { - if ((tm = Getattr(p, "tmap:freearg"))) { - Replaceall(tm, "$source", Getattr(p, "lname")); - Printv(cleanup, tm, "\n", NIL); - p = Getattr(p, "tmap:freearg:next"); - } else { - p = nextSibling(p); - } - } - - /* Insert argument output code */ - String *outarg = NewString(""); - for (p = l; p;) { - if ((tm = Getattr(p, "tmap:argout"))) { - Replaceall(tm, "$source", Getattr(p, "lname")); - Replaceall(tm, "$target", "resultobj"); - Replaceall(tm, "$arg", Getattr(p, "emit:input")); - Replaceall(tm, "$input", Getattr(p, "emit:input")); - Printv(outarg, tm, "\n", NIL); - p = Getattr(p, "tmap:argout:next"); - } else { - p = nextSibling(p); - } - } - - /* Emit the function call */ - String *actioncode = emit_action(n); - - /* Clear the return stack */ - Printf(actioncode, "pop_n_elems(args);\n"); - - /* Return the function value */ - if (current == CONSTRUCTOR) { - Printv(actioncode, "THIS = (void *) ", Swig_cresult_name(), ";\n", NIL); - Printv(description, ", tVoid", NIL); - } else if (current == DESTRUCTOR) { - Printv(description, ", tVoid", NIL); - } else { - Printv(description, ", ", NIL); - if ((tm = Swig_typemap_lookup_out("out", n, Swig_cresult_name(), f, actioncode))) { - actioncode = 0; - Replaceall(tm, "$source", Swig_cresult_name()); - Replaceall(tm, "$target", "resultobj"); - Replaceall(tm, "$result", "resultobj"); - if (GetFlag(n, "feature:new")) { - Replaceall(tm, "$owner", "1"); - } else { - Replaceall(tm, "$owner", "0"); - } - String *pikedesc = Getattr(n, "tmap:out:pikedesc"); - if (pikedesc) { - Printv(description, pikedesc, NIL); - } - Printf(f->code, "%s\n", tm); - } else { - Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(d, 0), name); - } - } - if (actioncode) { - Append(f->code, actioncode); - Delete(actioncode); - } - emit_return_variable(n, d, f); - - /* Output argument output code */ - Printv(f->code, outarg, NIL); - - /* Output cleanup code */ - Printv(f->code, cleanup, NIL); - - /* Look to see if there is any newfree cleanup code */ - if (GetFlag(n, "feature:new")) { - if ((tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); - Printf(f->code, "%s\n", tm); - } - } - - /* See if there is any return cleanup code */ - if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); - Printf(f->code, "%s\n", tm); - } - - /* Close the function */ - Printf(f->code, "}\n"); - - /* Substitute the cleanup code */ - Replaceall(f->code, "$cleanup", cleanup); - - /* Substitute the function name */ - Replaceall(f->code, "$symname", iname); - Replaceall(f->code, "$result", "resultobj"); - - /* Dump the function out */ - Wrapper_print(f, f_wrappers); - - /* Now register the function with the interpreter. */ - if (!Getattr(n, "sym:overloaded")) { - add_method(iname, wname, description); - } else { - if (!Getattr(n, "sym:nextSibling")) { - dispatchFunction(n); - } - } - - Delete(cleanup); - Delete(outarg); - Delete(description); - Delete(wname); - DelWrapper(f); - - return SWIG_OK; - } - - /* ------------------------------------------------------------ - * dispatchFunction() - * - * Emit overloading dispatch function - * ------------------------------------------------------------ */ - - void dispatchFunction(Node *n) { - /* Last node in overloaded chain */ - - int maxargs; - String *tmp = NewString(""); - String *dispatch = Swig_overload_dispatch(n, "%s(args); return;", &maxargs); - - /* Generate a dispatch wrapper for all overloaded functions */ - - Wrapper *f = NewWrapper(); - String *symname = Getattr(n, "sym:name"); - String *wname = Swig_name_wrapper(symname); - - Printf(f->def, "static void %s(INT32 args) {", wname); - - Wrapper_add_local(f, "argc", "INT32 argc"); - Printf(tmp, "struct svalue argv[%d]", maxargs); - Wrapper_add_local(f, "argv", tmp); - Wrapper_add_local(f, "ii", "INT32 ii"); - - Printf(f->code, "argc = args;\n"); - Printf(f->code, "for (ii = 0; (ii < argc) && (ii < %d); ii++) {\n", maxargs); - Printf(f->code, "argv[ii] = Pike_sp[ii-args];\n"); - Printf(f->code, "}\n"); - - Replaceall(dispatch, "$args", "self, args"); - Printv(f->code, dispatch, "\n", NIL); - Printf(f->code, "Pike_error(\"No matching function for overloaded '%s'.\");\n", symname); - Printv(f->code, "}\n", NIL); - - Wrapper_print(f, f_wrappers); - - String *description = NewString(""); - Printf(description, "tAny,"); - if (current == CONSTRUCTOR || current == DESTRUCTOR) { - Printf(description, " tVoid"); - } else { - String *pd = Getattr(n, "tmap:out:pikedesc"); - if (pd) - Printf(description, " %s", pd); - } - add_method(symname, wname, description); - Delete(description); - - DelWrapper(f); - Delete(dispatch); - Delete(tmp); - Delete(wname); - } - - /* ------------------------------------------------------------ - * variableWrapper() - * ------------------------------------------------------------ */ - - virtual int variableWrapper(Node *n) { - return Language::variableWrapper(n); - } - - /* ------------------------------------------------------------ - * constantWrapper() - * ------------------------------------------------------------ */ - - virtual int constantWrapper(Node *n) { - - Swig_require("constantWrapper", n, "*sym:name", "type", "value", NIL); - - String *symname = Getattr(n, "sym:name"); - SwigType *type = Getattr(n, "type"); - String *value = Getattr(n, "value"); - bool is_enum_item = (Cmp(nodeType(n), "enumitem") == 0); - - if (SwigType_type(type) == T_MPOINTER) { - /* Special hook for member pointer */ - String *wname = Swig_name_wrapper(symname); - Printf(f_header, "static %s = %s;\n", SwigType_str(type, wname), value); - value = wname; - } else if (SwigType_type(type) == T_CHAR && is_enum_item) { - type = NewSwigType(T_INT); - Setattr(n, "type", type); - } - - /* Perform constant typemap substitution */ - String *tm = Swig_typemap_lookup("constant", n, value, 0); - if (tm) { - Replaceall(tm, "$source", value); - Replaceall(tm, "$target", symname); - Replaceall(tm, "$symname", symname); - Replaceall(tm, "$value", value); - Printf(f_init, "%s\n", tm); - } else { - Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value %s = %s\n", SwigType_str(type, 0), value); - } - - Swig_restore(n); - - return SWIG_OK; - } - - /* ------------------------------------------------------------ - * nativeWrapper() - * ------------------------------------------------------------ */ - - virtual int nativeWrapper(Node *n) { - // return Language::nativeWrapper(n); - String *name = Getattr(n, "sym:name"); - String *wrapname = Getattr(n, "wrap:name"); - - if (!addSymbol(wrapname, n)) - return SWIG_ERROR; - - add_method(name, wrapname, 0); - return SWIG_OK; - } - - /* ------------------------------------------------------------ - * enumDeclaration() - * ------------------------------------------------------------ */ - - virtual int enumDeclaration(Node *n) { - return Language::enumDeclaration(n); - } - - /* ------------------------------------------------------------ - * enumvalueDeclaration() - * ------------------------------------------------------------ */ - - virtual int enumvalueDeclaration(Node *n) { - return Language::enumvalueDeclaration(n); - } - - /* ------------------------------------------------------------ - * classDeclaration() - * ------------------------------------------------------------ */ - - virtual int classDeclaration(Node *n) { - return Language::classDeclaration(n); - } - - /* ------------------------------------------------------------ - * classHandler() - * ------------------------------------------------------------ */ - - virtual int classHandler(Node *n) { - - String *symname = Getattr(n, "sym:name"); - if (!addSymbol(symname, n)) - return SWIG_ERROR; - - PrefixPlusUnderscore = NewStringf("%s_", getClassPrefix()); - - Printf(f_classInit, "start_new_program();\n"); - - /* Handle inheritance */ - List *baselist = Getattr(n, "bases"); - if (baselist && Len(baselist) > 0) { - Iterator base = First(baselist); - while (base.item) { - String *basename = Getattr(base.item, "name"); - SwigType *basetype = NewString(basename); - SwigType_add_pointer(basetype); - SwigType_remember(basetype); - String *basemangle = SwigType_manglestr(basetype); - Printf(f_classInit, "low_inherit((struct program *) SWIGTYPE%s->clientdata, 0, 0, 0, 0, 0);\n", basemangle); - Delete(basemangle); - Delete(basetype); - base = Next(base); - } - } else { - Printf(f_classInit, "ADD_STORAGE(swig_object_wrapper);\n"); - } - - Language::classHandler(n); - - /* Accessors for member variables */ - /* - List *membervariables = Getattr(n,"membervariables"); - if (membervariables && Len(membervariables) > 0) { - membervariableAccessors(membervariables); - } - */ - - /* Done, close the class and dump its definition to the init function */ - Printf(f_classInit, "add_program_constant(\"%s\", pr = end_program(), 0);\n", symname); - Dump(f_classInit, f_init); - Clear(f_classInit); - - SwigType *tt = NewString(symname); - SwigType_add_pointer(tt); - SwigType_remember(tt); - String *tm = SwigType_manglestr(tt); - Printf(f_init, "SWIG_TypeClientData(SWIGTYPE%s, (void *) pr);\n", tm); - Delete(tm); - Delete(tt); - - Delete(PrefixPlusUnderscore); - PrefixPlusUnderscore = 0; - - return SWIG_OK; - } - - /* ------------------------------------------------------------ - * memberfunctionHandler() - * - * Method for adding C++ member function - * ------------------------------------------------------------ */ - - virtual int memberfunctionHandler(Node *n) { - current = MEMBER_FUNC; - Language::memberfunctionHandler(n); - current = NO_CPP; - return SWIG_OK; - } - - /* ------------------------------------------------------------ - * constructorHandler() - * - * Method for adding C++ member constructor - * ------------------------------------------------------------ */ - - virtual int constructorHandler(Node *n) { - current = CONSTRUCTOR; - Language::constructorHandler(n); - current = NO_CPP; - return SWIG_OK; - } - - /* ------------------------------------------------------------ - * destructorHandler() - * ------------------------------------------------------------ */ - - virtual int destructorHandler(Node *n) { - current = DESTRUCTOR; - Language::destructorHandler(n); - current = NO_CPP; - return SWIG_OK; - } - - /* ------------------------------------------------------------ - * membervariableAccessors() - * ------------------------------------------------------------ */ - - void membervariableAccessors(List *membervariables) { - String *name; - Iterator i; - bool need_setter; - String *funcname; - - /* If at least one of them is mutable, we need a setter */ - need_setter = false; - i = First(membervariables); - while (i.item) { - if (!GetFlag(i.item, "feature:immutable")) { - need_setter = true; - break; - } - i = Next(i); - } - - /* Create a function to set the values of the (mutable) variables */ - if (need_setter) { - Wrapper *wrapper = NewWrapper(); - String *setter = Swig_name_member(NSPACE_TODO, getClassPrefix(), "`->="); - String *wname = Swig_name_wrapper(setter); - Printv(wrapper->def, "static void ", wname, "(INT32 args) {", NIL); - Printf(wrapper->locals, "char *name = (char *) STR0(Pike_sp[0-args].u.string);\n"); - - i = First(membervariables); - while (i.item) { - if (!GetFlag(i.item, "feature:immutable")) { - name = Getattr(i.item, "name"); - funcname = Swig_name_wrapper(Swig_name_set(NSPACE_TODO, Swig_name_member(NSPACE_TODO, getClassPrefix(), name))); - Printf(wrapper->code, "if (!strcmp(name, \"%s\")) {\n", name); - Printf(wrapper->code, "%s(args);\n", funcname); - Printf(wrapper->code, "return;\n"); - Printf(wrapper->code, "}\n"); - Delete(funcname); - } - i = Next(i); - } - - /* Close the function */ - Printf(wrapper->code, "pop_n_elems(args);\n"); - Printf(wrapper->code, "}\n"); - - /* Dump wrapper code to the output file */ - Wrapper_print(wrapper, f_wrappers); - - /* Register it with Pike */ - String *description = NewString("tStr tFloat, tVoid"); - add_method("`->=", wname, description); - Delete(description); - - /* Clean up */ - Delete(wname); - Delete(setter); - DelWrapper(wrapper); - } - - /* Create a function to get the values of the (mutable) variables */ - Wrapper *wrapper = NewWrapper(); - String *getter = Swig_name_member(NSPACE_TODO, getClassPrefix(), "`->"); - String *wname = Swig_name_wrapper(getter); - Printv(wrapper->def, "static void ", wname, "(INT32 args) {", NIL); - Printf(wrapper->locals, "char *name = (char *) STR0(Pike_sp[0-args].u.string);\n"); - - i = First(membervariables); - while (i.item) { - name = Getattr(i.item, "name"); - funcname = Swig_name_wrapper(Swig_name_get(NSPACE_TODO, Swig_name_member(NSPACE_TODO, getClassPrefix(), name))); - Printf(wrapper->code, "if (!strcmp(name, \"%s\")) {\n", name); - Printf(wrapper->code, "%s(args);\n", funcname); - Printf(wrapper->code, "return;\n"); - Printf(wrapper->code, "}\n"); - Delete(funcname); - i = Next(i); - } - - /* Close the function */ - Printf(wrapper->code, "pop_n_elems(args);\n"); - Printf(wrapper->code, "}\n"); - - /* Dump wrapper code to the output file */ - Wrapper_print(wrapper, f_wrappers); - - /* Register it with Pike */ - String *description = NewString("tStr, tMix"); - add_method("`->", wname, description); - Delete(description); - - /* Clean up */ - Delete(wname); - Delete(getter); - DelWrapper(wrapper); - } - - /* ------------------------------------------------------------ - * membervariableHandler() - * ------------------------------------------------------------ */ - - virtual int membervariableHandler(Node *n) { - List *membervariables = Getattr(getCurrentClass(), "membervariables"); - if (!membervariables) { - membervariables = NewList(); - Setattr(getCurrentClass(), "membervariables", membervariables); - } - Append(membervariables, n); - current = MEMBER_VAR; - Language::membervariableHandler(n); - current = NO_CPP; - return SWIG_OK; - } - - /* ----------------------------------------------------------------------- - * staticmemberfunctionHandler() - * - * Wrap a static C++ function - * ---------------------------------------------------------------------- */ - - virtual int staticmemberfunctionHandler(Node *n) { - current = STATIC_FUNC; - Language::staticmemberfunctionHandler(n); - current = NO_CPP; - return SWIG_OK; - } - - /* ------------------------------------------------------------ - * memberconstantHandler() - * - * Create a C++ constant - * ------------------------------------------------------------ */ - - virtual int memberconstantHandler(Node *n) { - current = CLASS_CONST; - constantWrapper(n); - current = NO_CPP; - return SWIG_OK; - } - - /* --------------------------------------------------------------------- - * staticmembervariableHandler() - * --------------------------------------------------------------------- */ - - virtual int staticmembervariableHandler(Node *n) { - current = STATIC_VAR; - Language::staticmembervariableHandler(n); - current = NO_CPP; - return SWIG_OK; - } -}; - -/* ----------------------------------------------------------------------------- - * swig_pike() - Instantiate module - * ----------------------------------------------------------------------------- */ - -static Language *new_swig_pike() { - return new PIKE(); -} -extern "C" Language *swig_pike(void) { - return new_swig_pike(); -} diff --git a/Source/Modules/python.cxx b/Source/Modules/python.cxx index 336f6c219..7bfe9fc0e 100644 --- a/Source/Modules/python.cxx +++ b/Source/Modules/python.cxx @@ -73,8 +73,10 @@ static int py3 = 0; /* C++ Support + Shadow Classes */ -static int have_constructor; -static int have_repr; +static int have_constructor = 0; +static int have_repr = 0; +static bool have_builtin_static_member_method_callback = false; +static bool have_fast_proxy_static_member_method_callback = false; static String *real_classname; /* Thread Support */ @@ -93,6 +95,7 @@ static int nortti = 0; static int relativeimport = 0; /* flags for the make_autodoc function */ +namespace { enum autodoc_t { AUTODOC_CLASS, AUTODOC_CTOR, @@ -103,7 +106,7 @@ enum autodoc_t { AUTODOC_CONST, AUTODOC_VAR }; - +} static const char *usage1 = "\ Python Options (available with -python)\n\ @@ -313,7 +316,6 @@ public: } else { Swig_arg_error(); } - /* end added */ } else if (strcmp(argv[i], "-globals") == 0) { if (argv[i + 1]) { global_name = NewString(argv[i + 1]); @@ -444,6 +446,15 @@ public: } } + if (builtin && !shadow) { + Printf(stderr, "Incompatible options -builtin and -noproxy specified.\n"); + SWIG_exit(EXIT_FAILURE); + } + + if (fastproxy) { + Preprocessor_define("SWIGPYTHON_FASTPROXY", 0); + } + if (doxygen) doxygenTranslator = new PyDocConverter(doxygen_translator_flags); @@ -611,6 +622,10 @@ public: Printf(f_runtime, "#define SWIGPYTHON_BUILTIN\n"); } + if (fastproxy) { + Printf(f_runtime, "#define SWIGPYTHON_FASTPROXY\n"); + } + Printf(f_runtime, "\n"); Printf(f_header, "#ifdef SWIG_TypeQuery\n"); @@ -814,6 +829,10 @@ public: Append(const_code, "{0, 0, 0, 0.0, 0, 0}};\n"); Printf(f_wrappers, "%s\n", const_code); + + if (have_fast_proxy_static_member_method_callback) + Printf(f_init, " SWIG_Python_FixMethods(SwigMethods_proxydocs, swig_const_table, swig_types, swig_type_initial);\n\n"); + initialize_threads(f_init); Printf(f_init, "#if PY_VERSION_HEX >= 0x03000000\n"); @@ -846,8 +865,13 @@ public: Printv(f_shadow_py, "\n", f_shadow_begin, "\n", NIL); Printv(f_shadow_py, "\nfrom sys import version_info as _swig_python_version_info\n", NULL); - Printv(f_shadow_py, "if _swig_python_version_info < (2, 7, 0):\n", NULL); - Printv(f_shadow_py, tab4, "raise RuntimeError(\"Python 2.7 or later required\")\n\n", NULL); + if (py3) { + Printv(f_shadow_py, "if _swig_python_version_info < (3, 0):\n", NULL); + Printv(f_shadow_py, tab4, "raise RuntimeError(\"Python 3.x or later required\")\n\n", NULL); + } else { + Printv(f_shadow_py, "if _swig_python_version_info < (2, 7, 0):\n", NULL); + Printv(f_shadow_py, tab4, "raise RuntimeError(\"Python 2.7 or later required\")\n\n", NULL); + } if (Len(f_shadow_after_begin) > 0) Printv(f_shadow_py, f_shadow_after_begin, "\n", NIL); @@ -905,15 +929,15 @@ public: * as a replacement of new.instancemethod in Python 3. * ------------------------------------------------------------ */ int add_pyinstancemethod_new() { - String *name = NewString("SWIG_PyInstanceMethod_New"); - String *line = NewString(""); - Printf(line, "\t { \"%s\", %s, METH_O, NULL},\n", name, name); - Append(methods, line); - if (fastproxy) { + if (!builtin && fastproxy) { + String *name = NewString("SWIG_PyInstanceMethod_New"); + String *line = NewString(""); + Printf(line, "\t { \"%s\", %s, METH_O, NULL},\n", name, name); + Append(methods, line); Append(methods_proxydocs, line); + Delete(line); + Delete(name); } - Delete(line); - Delete(name); return 0; } @@ -923,7 +947,7 @@ public: * generated for static methods when using -fastproxy * ------------------------------------------------------------ */ int add_pystaticmethod_new() { - if (fastproxy) { + if (!builtin && fastproxy) { String *name = NewString("SWIG_PyStaticMethod_New"); String *line = NewString(""); Printf(line, "\t { \"%s\", %s, METH_O, NULL},\n", name, name); @@ -2250,7 +2274,7 @@ public: return parms; } - bool funcanno = py3 ? true : false; + bool funcanno = Equal(Getattr(n, "feature:python:annotations"), "c") ? true : false; String *params = NewString(""); String *_params = make_autodocParmList(n, false, ((in_class || has_self_for_count)? 2 : 1), is_calling, funcanno); @@ -2366,8 +2390,8 @@ public: if (ret) ret = SwigType_str(ret, 0); } - return (ret && py3) ? NewStringf(" -> \"%s\"", ret) - : NewString(""); + bool funcanno = Equal(Getattr(n, "feature:python:annotations"), "c") ? true : false; + return (ret && funcanno) ? NewStringf(" -> \"%s\"", ret) : NewString(""); } /* ------------------------------------------------------------ @@ -2472,6 +2496,7 @@ public: Printf(methods, "\"swig_ptr: %s\"", Getattr(n, "feature:callback:name")); if (fastproxy) { Printf(methods_proxydocs, "\"swig_ptr: %s\"", Getattr(n, "feature:callback:name")); + have_fast_proxy_static_member_method_callback = true; } } else { Append(methods, "NULL"); @@ -2527,6 +2552,11 @@ public: const char *builtin_kwargs = builtin_ctor ? ", PyObject *kwargs" : ""; Printv(f->def, linkage, builtin_ctor ? "int " : "PyObject *", wname, "(PyObject *self, PyObject *args", builtin_kwargs, ") {", NIL); + if (builtin) { + /* Avoid warning if the self parameter is not used. */ + Append(f->code, "(void)self;\n"); + } + Wrapper_add_local(f, "argc", "Py_ssize_t argc"); Printf(tmp, "PyObject *argv[%d] = {0}", maxargs + 1); Wrapper_add_local(f, "argv", tmp); @@ -2696,7 +2726,6 @@ public: bool add_self = builtin_self && (!builtin_ctor || director_class); bool builtin_getter = (builtin && GetFlag(n, "memberget")); bool builtin_setter = (builtin && GetFlag(n, "memberset") && !builtin_getter); - char const *self_param = builtin ? "self" : "SWIGUNUSEDPARM(self)"; char const *wrap_return = builtin_ctor ? "int " : "PyObject *"; String *linkage = NewString("SWIGINTERN "); String *wrapper_name = Swig_name_wrapper(iname); @@ -2751,9 +2780,9 @@ public: const char *builtin_kwargs = builtin_ctor ? ", PyObject *kwargs" : ""; if (!allow_kwargs || overname) { if (!varargs) { - Printv(f->def, linkage, wrap_return, wname, "(PyObject *", self_param, ", PyObject *args", builtin_kwargs, ") {", NIL); + Printv(f->def, linkage, wrap_return, wname, "(PyObject *self, PyObject *args", builtin_kwargs, ") {", NIL); } else { - Printv(f->def, linkage, wrap_return, wname, "__varargs__", "(PyObject *", self_param, ", PyObject *args, PyObject *varargs) {", NIL); + Printv(f->def, linkage, wrap_return, wname, "__varargs__", "(PyObject *self, PyObject *args, PyObject *varargs", builtin_kwargs, ") {", NIL); } if (allow_kwargs) { Swig_warning(WARN_LANG_OVERLOAD_KEYWORD, input_file, line_number, "Can't use keyword arguments with overloaded functions (%s).\n", Swig_name_decl(n)); @@ -2764,8 +2793,14 @@ public: Swig_warning(WARN_LANG_VARARGS_KEYWORD, input_file, line_number, "Can't wrap varargs with keyword arguments enabled\n"); varargs = 0; } - Printv(f->def, linkage, wrap_return, wname, "(PyObject *", self_param, ", PyObject *args, PyObject *kwargs) {", NIL); + Printv(f->def, linkage, wrap_return, wname, "(PyObject *self, PyObject *args, PyObject *kwargs) {", NIL); } + + if (builtin) { + /* Avoid warning if the self parameter is not used. */ + Append(f->code, "(void)self;\n"); + } + if (!builtin || !in_class || tuple_arguments > 0 || builtin_ctor) { if (!allow_kwargs) { Append(parse_args, " if (!PyArg_ParseTuple(args, \""); @@ -2792,7 +2827,7 @@ public: /* Generate code for argument marshalling */ if (funpack) { - if (num_arguments > 0 && !overname) { + if (num_arguments > (builtin_self && !constructor ? 1 : 0) && !overname) { sprintf(source, "PyObject *swig_obj[%d]", num_arguments); Wrapper_add_localv(f, "swig_obj", source, NIL); } @@ -2862,8 +2897,6 @@ public: } else { Replaceall(tm, "$self", "obj0"); } - Replaceall(tm, "$source", source); - Replaceall(tm, "$target", ln); Replaceall(tm, "$input", source); Setattr(p, "emit:input", source); /* Save the location of the object */ @@ -2926,14 +2959,14 @@ public: Clear(f->def); if (overname) { if (noargs) { - Printv(f->def, linkage, wrap_return, wname, "(PyObject *", self_param, ", Py_ssize_t nobjs, PyObject **SWIGUNUSEDPARM(swig_obj)) {", NIL); + Printv(f->def, linkage, wrap_return, wname, "(PyObject *self, Py_ssize_t nobjs, PyObject **SWIGUNUSEDPARM(swig_obj)) {", NIL); } else { - Printv(f->def, linkage, wrap_return, wname, "(PyObject *", self_param, ", Py_ssize_t nobjs, PyObject **swig_obj) {", NIL); + Printv(f->def, linkage, wrap_return, wname, "(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {", NIL); } Printf(parse_args, "if ((nobjs < %d) || (nobjs > %d)) SWIG_fail;\n", num_required, num_arguments); } else { int is_tp_call = Equal(Getattr(n, "feature:python:slot"), "tp_call"); - Printv(f->def, linkage, wrap_return, wname, "(PyObject *", self_param, ", PyObject *args", builtin_kwargs, ") {", NIL); + Printv(f->def, linkage, wrap_return, wname, "(PyObject *self, PyObject *args", builtin_kwargs, ") {", NIL); if (builtin_ctor) Printf(parse_args, "if (!SWIG_Python_CheckNoKeywords(kwargs, \"%s\")) SWIG_fail;\n", iname); if (onearg && !builtin_ctor && !is_tp_call) { @@ -2971,7 +3004,6 @@ public: /* Insert constraint checking code */ for (p = l; p;) { if ((tm = Getattr(p, "tmap:check"))) { - Replaceall(tm, "$target", Getattr(p, "lname")); Printv(f->code, tm, "\n", NIL); p = Getattr(p, "tmap:check:next"); } else { @@ -2993,7 +3025,6 @@ public: } } if (tm && (Len(tm) != 0)) { - Replaceall(tm, "$source", Getattr(p, "lname")); Printv(cleanup, tm, "\n", NIL); } p = Getattr(p, "tmap:freearg:next"); @@ -3005,8 +3036,6 @@ public: /* Insert argument output code */ for (p = l; p;) { if ((tm = Getattr(p, "tmap:argout"))) { - Replaceall(tm, "$source", Getattr(p, "lname")); - Replaceall(tm, "$target", "resultobj"); Replaceall(tm, "$arg", Getattr(p, "emit:input")); Replaceall(tm, "$input", Getattr(p, "emit:input")); Printv(outarg, tm, "\n", NIL); @@ -3095,8 +3124,6 @@ public: } else { Replaceall(tm, "$self", "obj0"); } - Replaceall(tm, "$source", Swig_cresult_name()); - Replaceall(tm, "$target", "resultobj"); Replaceall(tm, "$result", "resultobj"); if (builtin_ctor) { Replaceall(tm, "$owner", "SWIG_BUILTIN_INIT"); @@ -3160,7 +3187,6 @@ public: /* Look to see if there is any newfree cleanup code */ if (GetFlag(n, "feature:new")) { if ((tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); Printf(f->code, "%s\n", tm); Delete(tm); } @@ -3168,7 +3194,6 @@ public: /* See if there is any return cleanup code */ if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); Printf(f->code, "%s\n", tm); Delete(tm); } @@ -3231,9 +3256,9 @@ public: f = NewWrapper(); if (funpack) { // Note: funpack is currently always false for varargs - Printv(f->def, linkage, wrap_return, wname, "(PyObject *", self_param, ", Py_ssize_t nobjs, PyObject **swig_obj) {", NIL); + Printv(f->def, linkage, wrap_return, wname, "(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {", NIL); } else { - Printv(f->def, linkage, wrap_return, wname, "(PyObject *", self_param, ", PyObject *args", builtin_kwargs, ") {", NIL); + Printv(f->def, linkage, wrap_return, wname, "(PyObject *self, PyObject *args", builtin_kwargs, ") {", NIL); } Wrapper_add_local(f, "resultobj", builtin_ctor ? "int resultobj" : "PyObject *resultobj"); Wrapper_add_local(f, "varargs", "PyObject *varargs"); @@ -3251,10 +3276,10 @@ public: Printf(f->code, " Py_XINCREF(swig_obj[i + %d]);\n", num_fixed_arguments); Printf(f->code, "}\n"); } else { - Printf(f->code, "newargs = PyTuple_GetSlice(args,0,%d);\n", num_fixed_arguments); - Printf(f->code, "varargs = PyTuple_GetSlice(args,%d,PyTuple_Size(args));\n", num_fixed_arguments); + Printf(f->code, "newargs = PyTuple_GetSlice(args, 0, %d);\n", num_fixed_arguments); + Printf(f->code, "varargs = PyTuple_GetSlice(args, %d, PyTuple_Size(args));\n", num_fixed_arguments); } - Printf(f->code, "resultobj = %s__varargs__(%s,newargs,varargs);\n", wname, builtin ? "self" : "NULL"); + Printf(f->code, "resultobj = %s__varargs__(%s, newargs, varargs%s);\n", wname, builtin ? "self" : "NULL", strlen(builtin_kwargs) == 0 ? "" : ", kwargs"); Append(f->code, "Py_XDECREF(newargs);\n"); Append(f->code, "Py_XDECREF(varargs);\n"); Append(f->code, "return resultobj;\n"); @@ -3426,7 +3451,6 @@ public: Printf(f_init, "#endif\n"); Printf(f_init, "\t }\n"); Printf(f_init, "\t PyDict_SetItemString(md, \"%s\", globals);\n", global_name); - Printf(f_init, "\t Py_DECREF(globals);\n"); if (builtin) Printf(f_init, "\t SwigPyBuiltin_AddPublicSymbol(public_interface, \"%s\");\n", global_name); have_globals = 1; @@ -3454,8 +3478,6 @@ public: } Printf(setf->def, "SWIGINTERN int %s(PyObject *_val) {", varsetname); if ((tm = Swig_typemap_lookup("varin", n, name, 0))) { - Replaceall(tm, "$source", "_val"); - Replaceall(tm, "$target", name); Replaceall(tm, "$input", "_val"); if (Getattr(n, "tmap:varin:implicitconv")) { Replaceall(tm, "$implicitconv", get_implicitconv_flag(n)); @@ -3496,8 +3518,6 @@ public: Append(getf->code, " (void)self;\n"); } if ((tm = Swig_typemap_lookup("varout", n, name, 0))) { - Replaceall(tm, "$source", name); - Replaceall(tm, "$target", "pyobj"); Replaceall(tm, "$result", "pyobj"); addfail = emit_action_code(n, getf->code, tm); Delete(tm); @@ -3577,8 +3597,6 @@ public: } if ((tm = Swig_typemap_lookup("consttab", n, name, 0))) { - Replaceall(tm, "$source", value); - Replaceall(tm, "$target", name); Replaceall(tm, "$value", value); Printf(const_code, "%s,\n", tm); Delete(tm); @@ -3593,8 +3611,6 @@ public: } if ((tm = Swig_typemap_lookup("constcode", n, name, 0))) { - Replaceall(tm, "$source", value); - Replaceall(tm, "$target", name); Replaceall(tm, "$value", value); if (needs_swigconstant(n) && !builtin && (shadow) && (!(shadow & PYSHADOW_MEMBER)) && (!in_class || !Getattr(n, "feature:python:callback"))) { // Generate `*_swigconstant()` method which registers the new constant. @@ -3606,7 +3622,7 @@ public: // class type (the SWIG_init() is called before shadow classes are // defined and registered). Printf(f_wrappers, "SWIGINTERN PyObject *%s_swigconstant(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {\n", iname); - Printf(f_wrappers, tab2 "PyObject *module;\n", tm); + Printf(f_wrappers, tab2 "PyObject *module;\n"); Printf(f_wrappers, tab2 "PyObject *d;\n"); Printf(f_wrappers, tab2 "if (!SWIG_Python_UnpackTuple(args, \"swigconstant\", 1, 1, &module)) return NULL;\n"); Printf(f_wrappers, tab2 "d = PyModule_GetDict(module);\n"); @@ -3946,6 +3962,10 @@ public: int funpack = fastunpack; static String *tp_new = NewString("PyType_GenericNew"); + if (have_builtin_static_member_method_callback) { + Printf(f_init, " SWIG_Python_FixMethods(SwigPyBuiltin_%s_methods, swig_const_table, swig_types, swig_type_initial);\n", mname); + } + Printv(f_init, " SwigPyBuiltin_SetMetaType(builtin_pytype, metatype);\n", NIL); // We can’t statically initialize a structure member with a function defined in another C module @@ -4016,7 +4036,7 @@ public: if (GetFlag(mgetset, "static")) { Printf(f, "static PyGetSetDef %s_def = %s;\n", gspair, entry); Printf(f_init, "static_getset = SwigPyStaticVar_new_getset(metatype, &%s_def);\n", gspair); - Printf(f_init, "PyDict_SetItemString(d, static_getset->d_getset->name, (PyObject *) static_getset);\n", memname); + Printf(f_init, "PyDict_SetItemString(d, static_getset->d_getset->name, (PyObject *) static_getset);\n"); Printf(f_init, "Py_DECREF(static_getset);\n"); } else { Printf(getset_def, " %s,\n", entry); @@ -4306,6 +4326,10 @@ public: // struct _dictkeysobject *ht_cached_keys; printSlot(f, getSlot(n, "feature:python:ht_cached_keys"), "ht_cached_keys"); Printv(f, "#endif\n", NIL); + + Printv(f, "#if PY_VERSION_HEX >= 0x03090000\n", NIL); + printSlot(f, getSlot(n, "feature:python:ht_module"), "ht_module", "PyObject *"); + Printv(f, "#endif\n", NIL); Printf(f, "};\n\n"); String *clientdata = NewString(""); @@ -4372,6 +4396,7 @@ public: /* Create new strings for building up a wrapper function */ have_constructor = 0; have_repr = 0; + have_builtin_static_member_method_callback = false; class_name = Getattr(n, "sym:name"); real_classname = Getattr(n, "name"); @@ -4461,7 +4486,9 @@ public: Printf(f_shadow, "(Exception)"); } else { Printf(f_shadow, "(object"); - Printf(f_shadow, py3 && GetFlag(n, "feature:python:nondynamic") ? ", metaclass=_SwigNonDynamicMeta" : "", ")"); + if (py3 && GetFlag(n, "feature:python:nondynamic")) { + Printf(f_shadow, ", metaclass=_SwigNonDynamicMeta"); + } Printf(f_shadow, ")"); } } @@ -4732,6 +4759,7 @@ public: Swig_restore(n); } + int kw = (check_kwargs(n) && !Getattr(n, "sym:overloaded")) ? 1 : 0; if (builtin && in_class) { if ((GetFlagAttr(n, "feature:extend") || checkAttribute(n, "access", "public")) && !Getattr(class_members, symname)) { @@ -4746,7 +4774,7 @@ public: else if (funpack && argcount == 1) Append(pyflags, "METH_O"); else - Append(pyflags, "METH_VARARGS"); + Append(pyflags, kw ? "METH_VARARGS|METH_KEYWORDS" : "METH_VARARGS"); // Cast via void(*)(void) to suppress GCC -Wcast-function-type warning. // Python should always call the function correctly, but the Python C // API requires us to store it in function pointer of a different type. @@ -4754,6 +4782,11 @@ public: String *ds = cdocstring(n, AUTODOC_STATICFUNC); Printf(builtin_methods, " { \"%s\", (PyCFunction)(void(*)(void))%s, %s, \"%s\" },\n", symname, wname, pyflags, ds); Delete(ds); + } else if (Getattr(n, "feature:callback")) { + String *ds = NewStringf("swig_ptr: %s", Getattr(n, "feature:callback:name")); + Printf(builtin_methods, " { \"%s\", (PyCFunction)(void(*)(void))%s, %s, \"%s\" },\n", symname, wname, pyflags, ds); + Delete(ds); + have_builtin_static_member_method_callback = true; } else { Printf(builtin_methods, " { \"%s\", (PyCFunction)(void(*)(void))%s, %s, \"\" },\n", symname, wname, pyflags); } @@ -4772,7 +4805,6 @@ public: String *staticfunc_name = NewString(fastproxy ? "_swig_new_static_method" : "staticmethod"); bool fast = (fastproxy && !have_addtofunc(n)) || Getattr(n, "feature:callback"); if (!fast || olddefs) { - int kw = (check_kwargs(n) && !Getattr(n, "sym:overloaded")) ? 1 : 0; String *parms = make_pyParmList(n, false, false, kw); String *callParms = make_pyParmList(n, false, true, kw); Printv(f_shadow, "\n", tab4, "@staticmethod", NIL); @@ -4869,6 +4901,7 @@ public: String *classname = Swig_class_name(parent); String *rclassname = Swig_class_name(getCurrentClass()); assert(rclassname); + (void)rclassname; String *parms = make_pyParmList(n, true, false, allow_kwargs); /* Pass 'self' only if using director */ diff --git a/Source/Modules/r.cxx b/Source/Modules/r.cxx index 3e3c23e44..ca9ce649c 100644 --- a/Source/Modules/r.cxx +++ b/Source/Modules/r.cxx @@ -634,7 +634,6 @@ String * R::createFunctionPointerHandler(SwigType *t, Node *n, int *numArgs) { if(returnTM) { String *tm = returnTM; Replaceall(tm,"$input", "r_swig_cb_data->retValue"); - Replaceall(tm,"$target", Swig_cresult_name()); replaceRClass(tm, rettype); Replaceall(tm,"$owner", "0"); Replaceall(tm,"$disown","0"); @@ -1302,13 +1301,14 @@ void R::addAccessor(String *memberName, Wrapper *wrapper, String *name, #define MAX_OVERLOAD 256 +namespace { struct Overloaded { Node *n; /* Node */ int argc; /* Argument count */ ParmList *parms; /* Parameters used for overload check */ int error; /* Ambiguity error */ }; - +} List * R::Swig_overload_rank(Node *n, bool script_lang_wrapping) { @@ -1745,7 +1745,7 @@ int R::functionWrapper(Node *n) { /* Add the name of this member to a list for this class_name. We will dump all these at the end. */ - bool isSet(GetFlag(n, "memberset")); + bool isSet = GetFlag(n, "memberset") ? true : false; String *tmp = NewString(isSet ? Swig_name_set(NSPACE_TODO, class_name) : Swig_name_get(NSPACE_TODO, class_name)); @@ -1912,8 +1912,6 @@ int R::functionWrapper(Node *n) { if ((tm = Getattr(p,"tmap:scheck"))) { - Replaceall(tm,"$target", lname); - Replaceall(tm,"$source", name); Replaceall(tm,"$input", name); replaceRClass(tm, Getattr(p, "type")); Printf(sfun->code,"%s\n",tm); @@ -1924,8 +1922,6 @@ int R::functionWrapper(Node *n) { curP = p; if ((tm = Getattr(p,"tmap:in"))) { - Replaceall(tm,"$target", lname); - Replaceall(tm,"$source", name); Replaceall(tm,"$input", name); if (Getattr(p,"wrap:disown") || (Getattr(p,"tmap:in:disown"))) { @@ -1984,7 +1980,6 @@ int R::functionWrapper(Node *n) { String *cleanup = NewString(""); for (p = l; p;) { if ((tm = Getattr(p, "tmap:freearg"))) { - Replaceall(tm, "$source", Getattr(p, "lname")); if (tm && (Len(tm) != 0)) { Printv(cleanup, tm, "\n", NIL); } @@ -2001,7 +1996,6 @@ int R::functionWrapper(Node *n) { // String *lname = Getattr(p, "lname"); numOutArgs++; String *pos = NewStringf("%d", numOutArgs); - Replaceall(tm,"$source", Getattr(p, "lname")); Replaceall(tm,"$result", "r_ans"); Replaceall(tm,"$n", pos); // The position into which to store the answer. Replaceall(tm,"$arg", Getattr(p, "emit:input")); @@ -2076,14 +2070,12 @@ int R::functionWrapper(Node *n) { /* Look to see if there is any newfree cleanup code */ if (GetFlag(n, "feature:new")) { if ((tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); /* deprecated */ Printf(f->code, "%s\n", tm); } } /* See if there is any return cleanup code */ if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); Printf(f->code, "%s\n", tm); Delete(tm); } @@ -2092,7 +2084,6 @@ int R::functionWrapper(Node *n) { /*If the user gave us something to convert the result in */ if ((tm = Swig_typemap_lookup("scoerceout", n, Swig_cresult_name(), sfun))) { - Replaceall(tm,"$source","ans"); Replaceall(tm,"$result","ans"); if (constructor) { Node * parent = Getattr(n, "parentNode"); @@ -2578,7 +2569,7 @@ int R::generateCopyRoutines(Node *n) { Printf(sfile, "# Start definition of copy methods for %s\n", rclassName); - Printf(sfile, "setMethod('copyToR', '_p_%s', CopyToR%s);\n", rclassName, + Printf(sfile, "setMethod('copyToR', '_p%s', CopyToR%s);\n", mangledName, mangledName); Printf(sfile, "setMethod('copyToC', '%s', CopyToC%s);\n\n", rclassName, mangledName); diff --git a/Source/Modules/ruby.cxx b/Source/Modules/ruby.cxx index 64bc4df89..d00ffa35c 100644 --- a/Source/Modules/ruby.cxx +++ b/Source/Modules/ruby.cxx @@ -106,9 +106,10 @@ public: char *strip(const_String_or_char_ptr s) { Clear(temp); - Append(temp, s); if (Strncmp(s, prefix, Len(prefix)) == 0) { - Replaceall(temp, prefix, ""); + Append(temp, Char(s) + Len(prefix)); + } else { + Append(temp, s); } return Char(temp); } @@ -116,6 +117,7 @@ public: /* flags for the make_autodoc function */ +namespace { enum autodoc_t { AUTODOC_CLASS, AUTODOC_CTOR, @@ -127,6 +129,7 @@ enum autodoc_t { AUTODOC_SETTER, AUTODOC_NONE }; +} static const char *usage = "\ Ruby Options (available with -ruby)\n\ @@ -1425,16 +1428,14 @@ public: * applyInputTypemap() * * Look up the appropriate "in" typemap for this parameter (p), - * substitute the correct strings for the $target and $input typemap - * parameters, and dump the resulting code to the wrapper file. + * substitute the correct strings for the typemap parameters, and dump the + * resulting code to the wrapper file. * --------------------------------------------------------------------- */ - Parm *applyInputTypemap(Parm *p, String *ln, String *source, Wrapper *f, String *symname) { + Parm *applyInputTypemap(Parm *p, String *source, Wrapper *f, String *symname) { String *tm; SwigType *pt = Getattr(p, "type"); if ((tm = Getattr(p, "tmap:in"))) { - Replaceall(tm, "$target", ln); - Replaceall(tm, "$source", source); Replaceall(tm, "$input", source); Replaceall(tm, "$symname", symname); @@ -1474,10 +1475,8 @@ public: Parm *p; String *tm; String *source; - String *target; source = NewString(""); - target = NewString(""); bool ctor_director = (current == CONSTRUCTOR_INITIALIZE && Swig_directorclass(n)); @@ -1498,7 +1497,6 @@ public: p = skipIgnoredArgs(p); String *pn = Getattr(p, "name"); - String *ln = Getattr(p, "lname"); /* Produce string representation of source argument */ Clear(source); @@ -1510,10 +1508,6 @@ public: Printf(source, "argv[%d]", i - start); } - /* Produce string representation of target argument */ - Clear(target); - Printf(target, "%s", Char(ln)); - if (i >= (numreq)) { /* Check if parsing an optional argument */ Printf(f->code, " if (argc > %d) {\n", i - start); } @@ -1526,7 +1520,7 @@ public: } /* Look for an input typemap */ - p = applyInputTypemap(p, ln, source, f, Getattr(n, "name")); + p = applyInputTypemap(p, source, f, Getattr(n, "name")); if (i >= numreq) { Printf(f->code, "}\n"); } @@ -1553,7 +1547,6 @@ public: } Delete(source); - Delete(target); } /* --------------------------------------------------------------------- @@ -1569,7 +1562,6 @@ public: String *tm; for (p = l; p;) { if ((tm = Getattr(p, "tmap:check"))) { - Replaceall(tm, "$target", Getattr(p, "lname")); Printv(f->code, tm, "\n", NIL); p = Getattr(p, "tmap:check:next"); } else { @@ -1591,7 +1583,6 @@ public: for (Parm *p = l; p;) { if ((tm = Getattr(p, "tmap:freearg"))) { if (Len(tm) != 0) { - Replaceall(tm, "$source", Getattr(p, "lname")); Printv(cleanup, tm, "\n", NIL); } p = Getattr(p, "tmap:freearg:next"); @@ -1613,8 +1604,6 @@ public: String *tm; for (Parm *p = l; p;) { if ((tm = Getattr(p, "tmap:argout"))) { - Replaceall(tm, "$source", Getattr(p, "lname")); - Replaceall(tm, "$target", "vresult"); Replaceall(tm, "$result", "vresult"); Replaceall(tm, "$arg", Getattr(p, "emit:input")); Replaceall(tm, "$input", Getattr(p, "emit:input")); @@ -1876,8 +1865,6 @@ public: actioncode = 0; if (tm) { Replaceall(tm, "$result", "vresult"); - Replaceall(tm, "$source", Swig_cresult_name()); - Replaceall(tm, "$target", "vresult"); if (GetFlag(n, "feature:new")) Replaceall(tm, "$owner", "SWIG_POINTER_OWN"); @@ -1973,7 +1960,6 @@ public: if (current != CONSTRUCTOR_ALLOCATE && GetFlag(n, "feature:new")) { tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0); if (tm) { - Replaceall(tm, "$source", Swig_cresult_name()); Printv(f->code, tm, "\n", NIL); Delete(tm); } @@ -1982,7 +1968,6 @@ public: /* Special processing on return value. */ tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0); if (tm) { - Replaceall(tm, "$source", Swig_cresult_name()); Printv(f->code, tm, NIL); Delete(tm); } @@ -2212,8 +2197,6 @@ public: tm = Swig_typemap_lookup("varout", n, name, 0); if (tm) { Replaceall(tm, "$result", "_val"); - Replaceall(tm, "$target", "_val"); - Replaceall(tm, "$source", name); /* Printv(getf->code,tm, NIL); */ addfail = emit_action_code(n, getf->code, tm); } else { @@ -2248,8 +2231,6 @@ public: tm = Swig_typemap_lookup("varin", n, name, 0); if (tm) { Replaceall(tm, "$input", "_val"); - Replaceall(tm, "$source", "_val"); - Replaceall(tm, "$target", name); /* Printv(setf->code,tm,"\n",NIL); */ emit_action_code(n, setf->code, tm); } else { @@ -2361,8 +2342,6 @@ public: if (!tm) tm = Swig_typemap_lookup("constcode", n, value, 0); if (tm) { - Replaceall(tm, "$source", value); - Replaceall(tm, "$target", iname); Replaceall(tm, "$symname", iname); Replaceall(tm, "$value", value); if (current == CLASS_CONST) { diff --git a/Source/Modules/s-exp.cxx b/Source/Modules/s-exp.cxx deleted file mode 100644 index fe3b1facc..000000000 --- a/Source/Modules/s-exp.cxx +++ /dev/null @@ -1,402 +0,0 @@ -/* ----------------------------------------------------------------------------- - * This file is part of SWIG, which is licensed as a whole under version 3 - * (or any later version) of the GNU General Public License. Some additional - * terms also apply to certain portions of SWIG. The full details of the SWIG - * license and copyrights can be found in the LICENSE and COPYRIGHT files - * included with the SWIG source code as distributed by the SWIG developers - * and at http://www.swig.org/legal.html. - * - * s-exp.cxx - * - * A parse tree represented as Lisp s-expressions. - * ----------------------------------------------------------------------------- */ - -#include "swigmod.h" -#include "dohint.h" - -static const char *usage = "\ -S-Exp Options (available with -sexp)\n\ - -typemaplang - Typemap language\n\n"; - -//static Node *view_top = 0; -static File *out = 0; - -class Sexp:public Language { - int indent_level; - DOHHash *print_circle_hash; - int print_circle_count; - int hanging_parens; - bool need_whitespace; - bool need_newline; - -public: - Sexp(): - indent_level(0), - print_circle_hash(0), - print_circle_count(0), - hanging_parens(0), - need_whitespace(0), - need_newline(0) { - } - - virtual ~ Sexp() { - } - - virtual void main(int argc, char *argv[]) { - // Add a symbol to the parser for conditional compilation - Preprocessor_define("SWIGSEXP 1", 0); - - SWIG_typemap_lang("sexp"); - for (int iX = 0; iX < argc; iX++) { - if (strcmp(argv[iX], "-typemaplang") == 0) { - Swig_mark_arg(iX); - iX++; - SWIG_typemap_lang(argv[iX]); - Swig_mark_arg(iX); - continue; - } - if (strcmp(argv[iX], "-help") == 0) { - fputs(usage, stdout); - } - } - } - - /* Top of the parse tree */ - virtual int top(Node *n) { - if (out == 0) { - String *outfile = Getattr(n, "outfile"); - Replaceall(outfile, "_wrap.cxx", ".lisp"); - Replaceall(outfile, "_wrap.c", ".lisp"); - out = NewFile(outfile, "w", SWIG_output_files()); - if (!out) { - FileErrorDisplay(outfile); - SWIG_exit(EXIT_FAILURE); - } - } - String *f_sink = NewString(""); - Swig_register_filebyname("header", f_sink); - Swig_register_filebyname("wrapper", f_sink); - Swig_register_filebyname("begin", f_sink); - Swig_register_filebyname("runtime", f_sink); - Swig_register_filebyname("init", f_sink); - - Swig_banner_target_lang(out, ";;;"); - - Language::top(n); - Printf(out, "\n"); - Printf(out, ";;; Lisp parse tree produced by SWIG\n"); - print_circle_hash = NewHash(); - print_circle_count = 0; - hanging_parens = 0; - need_whitespace = 0; - need_newline = 0; - Sexp_print_node(n); - flush_parens(); - return SWIG_OK; - } - - void print_indent() { - int i; - for (i = 0; i < indent_level; i++) { - Printf(out, " "); - } - } - - void open_paren(const String *oper) { - flush_parens(); - Printf(out, "("); - if (oper) - Printf(out, "%s ", oper); - indent_level += 2; - } - - void close_paren(bool neednewline = false) { - hanging_parens++; - if (neednewline) - print_lazy_whitespace(); - indent_level -= 2; - } - - void flush_parens() { - int i; - if (hanging_parens) { - for (i = 0; i < hanging_parens; i++) - Printf(out, ")"); - hanging_parens = 0; - need_newline = true; - need_whitespace = true; - } - if (need_newline) { - Printf(out, "\n"); - print_indent(); - need_newline = false; - need_whitespace = false; - } else if (need_whitespace) { - Printf(out, " "); - need_whitespace = false; - } - } - - void print_lazy_whitespace() { - need_whitespace = 1; - } - - void print_lazy_newline() { - need_newline = 1; - } - - bool internal_key_p(DOH *key) { - return ((Cmp(key, "nodeType") == 0) - || (Cmp(key, "firstChild") == 0) - || (Cmp(key, "lastChild") == 0) - || (Cmp(key, "parentNode") == 0) - || (Cmp(key, "nextSibling") == 0) - || (Cmp(key, "previousSibling") == 0) - || (Cmp(key, "csym:nextSibling") == 0) - || (Cmp(key, "csym:previousSibling") == 0) - || (Cmp(key, "typepass:visit") == 0) - || (Cmp(key, "allocate:visit") == 0) - || (*(Char(key)) == '$')); - } - - bool boolean_key_p(DOH *key) { - return ((Cmp(key, "allocate:default_constructor") == 0) - || (Cmp(key, "allocate:default_destructor") == 0) - || (Cmp(key, "allows_typedef") == 0) - || (Cmp(key, "feature:immutable") == 0)); - } - - bool list_key_p(DOH *key) { - return ((Cmp(key, "parms") == 0) - || (Cmp(key, "baselist") == 0)); - } - - bool plist_key_p(DOH *key) - // true if KEY is the name of data that is a mapping from keys to - // values, which should be printed as a plist. - { - return ((Cmp(key, "typescope") == 0)); - } - - bool maybe_plist_key_p(DOH *key) { - return (Strncmp(key, "tmap:", 5) == 0); - } - - bool print_circle(DOH *obj, bool list_p) - // We have a complex object, which might be referenced several - // times, or even recursively. Use Lisp's reader notation for - // circular structures (#n#, #n=). - // - // An object can be printed in list-mode or object-mode; LIST_P toggles. - // return TRUE if OBJ still needs to be printed - { - flush_parens(); - // Following is a silly hack. It works around the limitation of - // DOH's hash tables that only work with string keys! - char address[32]; - sprintf(address, "%p%c", obj, list_p ? 'L' : 'O'); - DOH *placeholder = Getattr(print_circle_hash, address); - if (placeholder) { - Printv(out, placeholder, NIL); - return false; - } else { - String *placeholder = NewStringf("#%d#", ++print_circle_count); - Setattr(print_circle_hash, address, placeholder); - Printf(out, "#%d=", print_circle_count); - return true; - } - } - - void Sexp_print_value_of_key(DOH *value, DOH *key) { - if ((Cmp(key, "parms") == 0) || (Cmp(key, "wrap:parms") == 0) - || (Cmp(key, "kwargs") == 0) || (Cmp(key, "pattern") == 0)) - Sexp_print_parms(value); - else if (plist_key_p(key)) - Sexp_print_plist(value); - else if (maybe_plist_key_p(key)) { - if (DohIsMapping(value)) - Sexp_print_plist(value); - else - Sexp_print_doh(value); - } else if (list_key_p(key)) - Sexp_print_list(value); - else if (boolean_key_p(key)) - Sexp_print_boolean(value); - else - Sexp_print_doh(value); - } - - void Sexp_print_boolean(DOH *obj) { - flush_parens(); - /* See DOH/Doh/base.c, DohGetInt() */ - if (DohIsString(obj)) { - if (atoi(Char(obj)) != 0) - Printf(out, "t"); - else - Printf(out, "nil"); - } else - Printf(out, "nil"); - } - - void Sexp_print_list(DOH *obj) { - if (print_circle(obj, true)) { - open_paren(NIL); - for (; obj; obj = nextSibling(obj)) { - Sexp_print_doh(obj); - print_lazy_whitespace(); - } - close_paren(true); - } - } - - void Sexp_print_parms(DOH *obj) { - // print it as a list of plists - if (print_circle(obj, true)) { - open_paren(NIL); - for (; obj; obj = nextSibling(obj)) { - if (DohIsMapping(obj)) { - Iterator k; - open_paren(NIL); - for (k = First(obj); k.key; k = Next(k)) { - if (!internal_key_p(k.key)) { - DOH *value = Getattr(obj, k.key); - Sexp_print_as_keyword(k.key); - Sexp_print_value_of_key(value, k.key); - print_lazy_whitespace(); - } - } - close_paren(true); - } else - Sexp_print_doh(obj); - print_lazy_whitespace(); - } - close_paren(true); - } - } - - void Sexp_print_doh(DOH *obj) { - flush_parens(); - if (DohIsString(obj)) { - String *o = Str(obj); - Replaceall(o, "\\", "\\\\"); - Replaceall(o, "\"", "\\\""); - Printf(out, "\"%s\"", o); - Delete(o); - } else { - if (print_circle(obj, false)) { - // Dispatch type - if (nodeType(obj)) { - Sexp_print_node(obj); - } - - else if (DohIsMapping(obj)) { - Iterator k; - open_paren(NIL); - for (k = First(obj); k.key; k = Next(k)) { - if (!internal_key_p(k.key)) { - DOH *value = Getattr(obj, k.key); - flush_parens(); - open_paren(NIL); - Sexp_print_doh(k.key); - Printf(out, " . "); - Sexp_print_value_of_key(value, k.key); - close_paren(); - } - } - close_paren(); - } else if (strcmp(ObjType(obj)->objname, "List") == 0) { - int i; - open_paren(NIL); - for (i = 0; i < Len(obj); i++) { - DOH *item = Getitem(obj, i); - Sexp_print_doh(item); - } - close_paren(); - } else { - // What is it? - Printf(out, "#", ObjType(obj)->objname, obj); - } - } - } - } - - void Sexp_print_as_keyword(const DOH *k) { - /* Print key, replacing ":" with "-" because : is CL's package prefix */ - flush_parens(); - String *key = NewString(k); - Replaceall(key, ":", "-"); - Replaceall(key, "_", "-"); - Printf(out, ":%s ", key); - Delete(key); - } - - void Sexp_print_plist_noparens(DOH *obj) { - /* attributes map names to objects */ - Iterator k; - bool first; - for (k = First(obj), first = true; k.key; k = Next(k), first = false) { - if (!internal_key_p(k.key)) { - DOH *value = Getattr(obj, k.key); - flush_parens(); - if (!first) { - Printf(out, " "); - } - Sexp_print_as_keyword(k.key); - /* Print value */ - Sexp_print_value_of_key(value, k.key); - } - } - } - - void Sexp_print_plist(DOH *obj) { - flush_parens(); - if (print_circle(obj, true)) { - open_paren(NIL); - Sexp_print_plist_noparens(obj); - close_paren(); - } - } - - void Sexp_print_attributes(Node *obj) { - Sexp_print_plist_noparens(obj); - } - - void Sexp_print_node(Node *obj) { - Node *cobj; - open_paren(nodeType(obj)); - /* A node has an attribute list... */ - Sexp_print_attributes(obj); - /* ... and child nodes. */ - cobj = firstChild(obj); - if (cobj) { - print_lazy_newline(); - flush_parens(); - Sexp_print_as_keyword("children"); - open_paren(NIL); - for (; cobj; cobj = nextSibling(cobj)) { - Sexp_print_node(cobj); - } - close_paren(); - } - close_paren(); - } - - - virtual int functionWrapper(Node *n) { - ParmList *l = Getattr(n, "parms"); - Wrapper *f = NewWrapper(); - emit_attach_parmmaps(l, f); - Setattr(n, "wrap:parms", l); - DelWrapper(f); - return SWIG_OK; - } - -}; - - -static Language *new_swig_sexp() { - return new Sexp(); -} -extern "C" Language *swig_sexp(void) { - return new_swig_sexp(); -} diff --git a/Source/Modules/scilab.cxx b/Source/Modules/scilab.cxx index 23e45f787..9c8e374a0 100644 --- a/Source/Modules/scilab.cxx +++ b/Source/Modules/scilab.cxx @@ -11,10 +11,11 @@ * Scilab language module for SWIG. * --------------------------------------------------------------------------*/ +#include +#include #include "swigmod.h" static const int SCILAB_IDENTIFIER_NAME_CHAR_MAX = 24; -static const int SCILAB_VARIABLE_NAME_CHAR_MAX = SCILAB_IDENTIFIER_NAME_CHAR_MAX - 4; static const char *usage = (char *) " \ Scilab options (available with -scilab)\n \ @@ -25,7 +26,6 @@ Scilab options (available with -scilab)\n \ -buildersources - Add the (comma separated) files to the builder sources\n \ -builderverbositylevel - Set the builder verbosity level to (default 0: off, 2: high)\n \ -gatewayxml - Generate gateway xml with the given \n \ - -targetversion - Generate for Scilab target (major) version (default: 5)\n \ \n"; @@ -40,11 +40,11 @@ protected: String *variablesCode; - int targetVersion; - bool generateBuilder; File *builderFile; String *builderCode; + String *builderCode5; + String *builderCode6; int builderFunctionCount; List *sourceFileList; @@ -67,6 +67,9 @@ protected: bool createLoader; File *loaderFile; String *loaderScript; + String *loaderScript5; + String *loaderScript6; + int loaderFunctionCount; public: /* ------------------------------------------------------------------------ @@ -74,8 +77,6 @@ public: * ----------------------------------------------------------------------*/ virtual void main(int argc, char *argv[]) { - targetVersion = 5; - generateBuilder = false; sourceFileList = NewList(); cflags = NewList(); @@ -99,23 +100,23 @@ public: /* Manage command line arguments */ for (int argIndex = 1; argIndex < argc; argIndex++) { if (argv[argIndex] != NULL) { - if (strcmp(argv[argIndex], "-help") == 0) { - Printf(stdout, "%s\n", usage); - } else if (strcmp(argv[argIndex], "-builder") == 0) { - Swig_mark_arg(argIndex); - generateBuilder = true; - createLoader = false; - } else if (strcmp(argv[argIndex], "-buildersources") == 0) { - if (argv[argIndex + 1] != NULL) { - Swig_mark_arg(argIndex); - char *sourceFile = strtok(argv[argIndex + 1], ","); - while (sourceFile != NULL) { - Insert(sourceFileList, Len(sourceFileList), sourceFile); - sourceFile = strtok(NULL, ","); - } - Swig_mark_arg(argIndex + 1); - } - } else if (strcmp(argv[argIndex], "-buildercflags") == 0) { + if (strcmp(argv[argIndex], "-help") == 0) { + Printf(stdout, "%s\n", usage); + } else if (strcmp(argv[argIndex], "-builder") == 0) { + Swig_mark_arg(argIndex); + generateBuilder = true; + createLoader = false; + } else if (strcmp(argv[argIndex], "-buildersources") == 0) { + if (argv[argIndex + 1] != NULL) { + Swig_mark_arg(argIndex); + char *sourceFile = strtok(argv[argIndex + 1], ","); + while (sourceFile != NULL) { + Insert(sourceFileList, Len(sourceFileList), sourceFile); + sourceFile = strtok(NULL, ","); + } + Swig_mark_arg(argIndex + 1); + } + } else if (strcmp(argv[argIndex], "-buildercflags") == 0) { Swig_mark_arg(argIndex); if (argv[argIndex + 1] != NULL) { Insert(cflags, Len(cflags), argv[argIndex + 1]); @@ -140,12 +141,6 @@ public: createGatewayXML = true; gatewayID = NewString(argv[argIndex + 1]); Swig_mark_arg(argIndex + 1); - } else if (strcmp(argv[argIndex], "-targetversion") == 0) { - if (argv[argIndex + 1] != NULL) { - Swig_mark_arg(argIndex); - targetVersion = atoi(argv[argIndex + 1]); - Swig_mark_arg(argIndex + 1); - } } } } @@ -227,10 +222,13 @@ public: } // Module initialization function + String *smallFunctionName = createSmallIdentifierName(gatewayName, SCILAB_IDENTIFIER_NAME_CHAR_MAX - 5); String *gatewayInitFunctionName = NewStringf("%s_Init", gatewayName); + String *gatewayInitSmallFunctionName = NewStringf("%s_Init", smallFunctionName); + String *wrapperFunctionName = NewStringf("SWIG_%s_Init", gatewayName); /* Add initialization function to builder table */ - addFunctionToScilab(gatewayInitFunctionName, gatewayInitFunctionName); + addFunctionToScilab(gatewayInitFunctionName, gatewayInitSmallFunctionName, wrapperFunctionName); // Add helper functions to builder table addHelperFunctions(); @@ -316,6 +314,8 @@ public: /* Get some useful attributes of this function */ String *functionName = Getattr(node, "sym:name"); + String *smallFunctionName = createSmallIdentifierName(functionName); + SwigType *functionReturnType = Getattr(node, "type"); ParmList *functionParamsList = Getattr(node, "parms"); @@ -360,7 +360,7 @@ public: int maxInputArguments = emit_num_arguments(functionParamsList); int minInputArguments = emit_num_required(functionParamsList); int minOutputArguments = 0; - int maxOutputArguments = 0; + int maxOutputArguments = 1; if (!emit_isvarargs(functionParamsList)) { Printf(wrapper->code, "SWIG_CheckInputArgument(pvApiCtx, $mininputarguments, $maxinputarguments);\n"); @@ -472,7 +472,6 @@ public: String *tm; if ((tm = Getattr(param, "tmap:freearg"))) { if (tm && (Len(tm) != 0)) { - Replaceall(tm, "$source", Getattr(param, "lname")); Printf(wrapper->code, "%s\n", tm); } param = Getattr(param, "tmap:freearg:next"); @@ -484,7 +483,6 @@ public: /* See if there is any return cleanup code */ String *tm; if ((tm = Swig_typemap_lookup("ret", node, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); Printf(wrapper->code, "%s\n", tm); Delete(tm); } @@ -500,10 +498,12 @@ public: Replaceall(wrapper->code, "$symname", functionName); /* Set CheckInputArgument and CheckOutputArgument input arguments */ - /* In Scilab there is always one output even if not defined */ - if (minOutputArguments == 0) { + if (maxOutputArguments < 1) { maxOutputArguments = 1; } + if (minOutputArguments == 1) { + minOutputArguments = 0; + } String *argnumber = NewString(""); Printf(argnumber, "%d", minInputArguments); Replaceall(wrapper->code, "$mininputarguments", argnumber); @@ -523,16 +523,14 @@ public: /* Dump the function out */ Wrapper_print(wrapper, wrappersSection); - String *scilabFunctionName = checkIdentifierName(functionName, SCILAB_IDENTIFIER_NAME_CHAR_MAX); - /* Update builder.sce contents */ if (isLastOverloaded) { - addFunctionToScilab(scilabFunctionName, wrapperName); + addFunctionToScilab(functionName, smallFunctionName, wrapperName); dispatchFunction(node); } if (!isOverloaded) { - addFunctionToScilab(scilabFunctionName, wrapperName); + addFunctionToScilab(functionName, smallFunctionName, wrapperName); } /* tidy up */ @@ -593,21 +591,20 @@ public: /* Get information about variable */ String *origVariableName = Getattr(node, "name"); // Ex: Shape::nshapes String *variableName = Getattr(node, "sym:name"); // Ex; Shape_nshapes (can be used for function names, ...) - - // Variable names can have SCILAB_VARIABLE_NAME_CHAR_MAX because of suffixes "_get" or "_set" added to function - String *scilabVariableName = checkIdentifierName(variableName, SCILAB_VARIABLE_NAME_CHAR_MAX); + String *smallVariableName = createSmallIdentifierName(variableName, SCILAB_IDENTIFIER_NAME_CHAR_MAX - 4); /* Manage GET function */ Wrapper *getFunctionWrapper = NewWrapper(); String *getFunctionName = Swig_name_get(NSPACE_TODO, variableName); - String *scilabGetFunctionName = Swig_name_get(NSPACE_TODO, scilabVariableName); + String *scilabGetFunctionName = Swig_name_get(NSPACE_TODO, variableName); + String *scilabGetSmallFunctionName = Swig_name_get(NSPACE_TODO, smallVariableName); Setattr(node, "wrap:name", getFunctionName); Printv(getFunctionWrapper->def, "int ", getFunctionName, "(SWIG_GatewayParameters) {\n", NIL); /* Check the number of input and output */ Printf(getFunctionWrapper->def, "SWIG_CheckInputArgument(pvApiCtx, 0, 0);\n"); - Printf(getFunctionWrapper->def, "SWIG_CheckOutputArgument(pvApiCtx, 1, 1);\n"); + Printf(getFunctionWrapper->def, "SWIG_CheckOutputArgument(pvApiCtx, 0, 1);\n"); Printf(getFunctionWrapper->def, "SWIG_Scilab_SetApiContext(pvApiCtx);\n"); String *varoutTypemap = Swig_typemap_lookup("varout", node, origVariableName, 0); @@ -623,20 +620,21 @@ public: Wrapper_print(getFunctionWrapper, wrappersSection); /* Add function to builder table */ - addFunctionToScilab(scilabGetFunctionName, getFunctionName); + addFunctionToScilab(scilabGetFunctionName, scilabGetSmallFunctionName, getFunctionName); /* Manage SET function */ if (is_assignable(node)) { Wrapper *setFunctionWrapper = NewWrapper(); String *setFunctionName = Swig_name_set(NSPACE_TODO, variableName); - String *scilabSetFunctionName = Swig_name_set(NSPACE_TODO, scilabVariableName); + String *scilabSetFunctionName = Swig_name_set(NSPACE_TODO, variableName); + String *scilabSetSmallFunctionName = Swig_name_set(NSPACE_TODO, smallVariableName); Setattr(node, "wrap:name", setFunctionName); Printv(setFunctionWrapper->def, "int ", setFunctionName, "(SWIG_GatewayParameters) {\n", NIL); /* Check the number of input and output */ Printf(setFunctionWrapper->def, "SWIG_CheckInputArgument(pvApiCtx, 1, 1);\n"); - Printf(setFunctionWrapper->def, "SWIG_CheckOutputArgument(pvApiCtx, 1, 1);\n"); + Printf(setFunctionWrapper->def, "SWIG_CheckOutputArgument(pvApiCtx, 0, 1);\n"); Printf(setFunctionWrapper->def, "SWIG_Scilab_SetApiContext(pvApiCtx);\n"); String *varinTypemap = Swig_typemap_lookup("varin", node, origVariableName, 0); @@ -650,7 +648,7 @@ public: Wrapper_print(setFunctionWrapper, wrappersSection); /* Add function to builder table */ - addFunctionToScilab(scilabSetFunctionName, setFunctionName); + addFunctionToScilab(scilabSetFunctionName, scilabSetSmallFunctionName, setFunctionName); DelWrapper(setFunctionWrapper); } @@ -686,10 +684,9 @@ public: constantTypemap = Swig_typemap_lookup("scilabconstcode", node, nodeName, 0); if (constantTypemap != NULL) { - String *scilabConstantName = checkIdentifierName(constantName, SCILAB_IDENTIFIER_NAME_CHAR_MAX); Setattr(node, "wrap:name", constantName); - Replaceall(constantTypemap, "$result", scilabConstantName); + Replaceall(constantTypemap, "$result", constantName); Replaceall(constantTypemap, "$value", constantValue); emit_action_code(node, variablesCode, constantTypemap); @@ -707,19 +704,21 @@ public: Delete(str); constantValue = wname; } + // Constant names can have SCILAB_VARIABLE_NAME_CHAR_MAX because of suffixes "_get" added to function - String *scilabConstantName = checkIdentifierName(constantName, SCILAB_VARIABLE_NAME_CHAR_MAX); + String *smallConstantName = createSmallIdentifierName(constantName, SCILAB_IDENTIFIER_NAME_CHAR_MAX - 4); /* Create GET function to get the constant value */ Wrapper *getFunctionWrapper = NewWrapper(); String *getFunctionName = Swig_name_get(NSPACE_TODO, constantName); - String *scilabGetFunctionName = Swig_name_get(NSPACE_TODO, scilabConstantName); + String *scilabGetSmallFunctionName = Swig_name_get(NSPACE_TODO, smallConstantName); + Setattr(node, "wrap:name", getFunctionName); Setattr(node, "wrap:name", getFunctionName); Printv(getFunctionWrapper->def, "int ", getFunctionName, "(SWIG_GatewayParameters) {\n", NIL); /* Check the number of input and output */ Printf(getFunctionWrapper->def, "SWIG_CheckInputArgument(pvApiCtx, 0, 0);\n"); - Printf(getFunctionWrapper->def, "SWIG_CheckOutputArgument(pvApiCtx, 1, 1);\n"); + Printf(getFunctionWrapper->def, "SWIG_CheckOutputArgument(pvApiCtx, 0, 1);\n"); Printf(getFunctionWrapper->def, "SWIG_Scilab_SetApiContext(pvApiCtx);\n"); constantTypemap = Swig_typemap_lookup("constcode", node, nodeName, 0); @@ -737,7 +736,7 @@ public: Wrapper_print(getFunctionWrapper, wrappersSection); /* Add the function to Scilab */ - addFunctionToScilab(scilabGetFunctionName, getFunctionName); + addFunctionToScilab(getFunctionName, scilabGetSmallFunctionName, getFunctionName); DelWrapper(getFunctionWrapper); @@ -784,78 +783,13 @@ public: return Language::enumvalueDeclaration(node); } - /* --------------------------------------------------------------------- - * membervariableHandler() - * --------------------------------------------------------------------- */ - virtual int membervariableHandler(Node *node) { - checkMemberIdentifierName(node, SCILAB_VARIABLE_NAME_CHAR_MAX); - return Language::membervariableHandler(node); - } - - /* ----------------------------------------------------------------------- - * checkIdentifierName() - * If Scilab target version is lower than 6: - * truncates (and displays a warning) too long member identifier names - * (applies on members of structs, classes...) - * (Scilab 5 identifier names are limited to 24 chars max) - * ----------------------------------------------------------------------- */ - - String *checkIdentifierName(String *name, int char_size_max) { - String *scilabIdentifierName; - if (targetVersion <= 5) { - if (Len(name) > char_size_max) { - scilabIdentifierName = DohNewStringWithSize(name, char_size_max); - Swig_warning(WARN_SCILAB_TRUNCATED_NAME, input_file, line_number, - "Identifier name '%s' exceeds 24 characters and has been truncated to '%s'.\n", name, scilabIdentifierName); - } else - scilabIdentifierName = name; - } else { - scilabIdentifierName = DohNewString(name); - } - return scilabIdentifierName; - } - - /* ----------------------------------------------------------------------- - * checkMemberIdentifierName() - * If Scilab target version is lower than 6: - * truncates (and displays a warning) too long member identifier names - * (applies on members of structs, classes...) - * (Scilab 5 identifier names are limited to 24 chars max) - * ----------------------------------------------------------------------- */ - - void checkMemberIdentifierName(Node *node, int char_size_max) { - if (targetVersion <= 5) { - String *memberName = Getattr(node, "sym:name"); - Node *containerNode = parentNode(node); - String *containerName = Getattr(containerNode, "sym:name"); - int lenContainerName = Len(containerName); - int lenMemberName = Len(memberName); - - if (lenContainerName + lenMemberName + 1 > char_size_max) { - int lenScilabMemberName = char_size_max - lenContainerName - 1; - - if (lenScilabMemberName > 0) { - String *scilabMemberName = DohNewStringWithSize(memberName, lenScilabMemberName); - Setattr(node, "sym:name", scilabMemberName); - Swig_warning(WARN_SCILAB_TRUNCATED_NAME, input_file, line_number, - "Wrapping functions names for member '%s.%s' will exceed 24 characters, " - "so member name has been truncated to '%s'.\n", containerName, memberName, scilabMemberName); - } else { - Swig_error(input_file, line_number, - "Wrapping functions names for member '%s.%s' will exceed 24 characters, " - "please rename the container of member '%s'.\n", containerName, memberName, containerName); - } - } - } - } - /* ----------------------------------------------------------------------- * addHelperFunctions() * ----------------------------------------------------------------------- */ void addHelperFunctions() { - addFunctionToScilab("SWIG_this", "SWIG_this"); - addFunctionToScilab("SWIG_ptr", "SWIG_ptr"); + addFunctionToScilab("SWIG_this", "SWIG_this", "SWIG_this"); + addFunctionToScilab("SWIG_ptr", "SWIG_ptr", "SWIG_ptr"); } /* ----------------------------------------------------------------------- @@ -863,20 +797,20 @@ public: * Declare a wrapped function in Scilab (builder, gateway, XML, ...) * ----------------------------------------------------------------------- */ - void addFunctionToScilab(const_String_or_char_ptr scilabFunctionName, const_String_or_char_ptr wrapperFunctionName) { + void addFunctionToScilab(const_String_or_char_ptr scilabFunctionName, const_String_or_char_ptr scilabSmallFunctionName, const_String_or_char_ptr wrapperFunctionName) { if (!generateBuilder) - addFunctionInGatewayHeader(scilabFunctionName, wrapperFunctionName); + addFunctionInGatewayHeader(scilabFunctionName, scilabSmallFunctionName, wrapperFunctionName); if (generateBuilder) { - addFunctionInScriptTable(scilabFunctionName, wrapperFunctionName, builderCode); + addFunctionInScriptTable(scilabFunctionName, scilabSmallFunctionName, wrapperFunctionName, builderCode5, builderCode6); } if (createLoader) { - addFunctionInLoader(scilabFunctionName); + addFunctionInLoader(scilabFunctionName, scilabSmallFunctionName); } if (gatewayXMLFile) { - Printf(gatewayXML, "\n", gatewayID, primitiveID++, scilabFunctionName); + Printf(gatewayXML, "\n", gatewayID, primitiveID++, scilabSmallFunctionName); } } @@ -945,7 +879,8 @@ public: } } - Printf(builderCode, "table = ["); + Printf(builderCode5, "table = [ ..\n"); + Printf(builderCode6, "table = [ ..\n"); } /* ----------------------------------------------------------------------- @@ -953,11 +888,13 @@ public: * Add a function wrapper in the function table of generated builder script * ----------------------------------------------------------------------- */ - void addFunctionInScriptTable(const_String_or_char_ptr scilabFunctionName, const_String_or_char_ptr wrapperFunctionName, String *scriptCode) { + void addFunctionInScriptTable(const_String_or_char_ptr scilabFunctionName, const_String_or_char_ptr scilabSmallFunctionName, const_String_or_char_ptr wrapperFunctionName, String *scriptCode5, String *scriptCode6) { if (++builderFunctionCount % 10 == 0) { - Printf(scriptCode, "];\ntable = [table;"); + Printf(scriptCode5, "];\ntable = [table; ..\n"); + Printf(scriptCode6, "];\ntable = [table; ..\n"); } - Printf(scriptCode, "\"%s\",\"%s\";", scilabFunctionName, wrapperFunctionName); + Printf(scriptCode5, "\"%s\",\"%s\"; ..\n", scilabSmallFunctionName, wrapperFunctionName); + Printf(scriptCode6, "\"%s\",\"%s\"; ..\n", scilabFunctionName, wrapperFunctionName); } /* ----------------------------------------------------------------------- @@ -965,7 +902,26 @@ public: * ----------------------------------------------------------------------- */ void saveBuilderFile(String *gatewayName) { - Printf(builderCode, "];\n"); + Printf(builderCode5, "];\n"); + Printf(builderCode6, "];\n"); + + if (Equal(builderCode5, builderCode6)) { + Append(builderCode, builderCode6); + } else { + Printf(builderCode, "ver = getversion('scilab');\n"); + Printf(builderCode, "if ver(1) < 6 then\n"); + Printf(builderCode, " // version is less or equal to 5.5.2\n"); + Printf(builderCode, " \n"); + Append(builderCode, builderCode5); + Printf(builderCode, " \n"); + Printf(builderCode, "else\n"); + Printf(builderCode, " // version is 6.0.0 or more\n"); + Printf(builderCode, " \n"); + Append(builderCode, builderCode6); + Printf(builderCode, " \n"); + Printf(builderCode, "end\n"); + } + Printf(builderCode, "ierr = 0;\n"); Printf(builderCode, "if ~isempty(table) then\n"); Printf(builderCode, " ierr = execstr(\"ilib_build(''%s'', table, files, libs, [], ldflags, cflags);\", 'errcatch');\n", gatewayName); @@ -977,7 +933,9 @@ public: Printf(builderCode, "if ierr <> 0 then\n"); Printf(builderCode, " error(ierr, err_msg);\n"); Printf(builderCode, "end\n"); - Printv(builderFile, builderCode, NIL); + Write(builderFile, builderCode, Len(builderCode)); + + Delete(builderCode); Delete(builderFile); } @@ -1049,13 +1007,13 @@ public: * Add a function in the gateway header * ----------------------------------------------------------------------- */ - void addFunctionInGatewayHeader(const_String_or_char_ptr scilabFunctionName, const_String_or_char_ptr wrapperFunctionName) { + void addFunctionInGatewayHeader(const_String_or_char_ptr scilabFunctionName, const_String_or_char_ptr scilabSmallFunctionName, const_String_or_char_ptr wrapperFunctionName) { if (gatewayHeaderV5 == NULL) { gatewayHeaderV5 = NewString(""); Printf(gatewayHeaderV5, "static GenericTable Tab[] = {\n"); } else Printf(gatewayHeaderV5, ",\n"); - Printf(gatewayHeaderV5, " {(Myinterfun)sci_gateway, (GT)%s, (char *)\"%s\"}", wrapperFunctionName, scilabFunctionName); + Printf(gatewayHeaderV5, " {(Myinterfun)sci_gateway, (GT)%s, (char *)\"%s\"}", wrapperFunctionName, scilabSmallFunctionName); Printf(gatewayHeaderV6, "if (wcscmp(pwstFuncName, L\"%s\") == 0) { addCStackFunction((wchar_t *)L\"%s\", &%s, (wchar_t *)MODULE_NAME); }\n", scilabFunctionName, scilabFunctionName, wrapperFunctionName); } @@ -1113,13 +1071,15 @@ public: emitBanner(loaderFile); - loaderScript = NewString(""); - Printf(loaderScript, "%s_path = get_absolute_file_path('loader.sce');\n", gatewayLibraryName); - Printf(loaderScript, "[bOK, ilib] = c_link('%s');\n", gatewayLibraryName); - Printf(loaderScript, "if bOK then\n"); - Printf(loaderScript, " ulink(ilib);\n"); - Printf(loaderScript, "end\n"); - Printf(loaderScript, "list_functions = [..\n"); + loaderFunctionCount = 0; + loaderScript = NewString("function loader_function()\n"); + Printf(loaderScript, " p = get_absolute_file_path('loader.sce');\n", gatewayLibraryName); + Printf(loaderScript, " [bOK, ilib] = c_link('%s');\n", gatewayLibraryName); + Printf(loaderScript, " if bOK then\n"); + Printf(loaderScript, " ulink(ilib);\n"); + Printf(loaderScript, " end\n"); + loaderScript5 = NewString(" list_functions = [ ..\n"); + loaderScript6 = NewString(" list_functions = [ ..\n"); } /* ----------------------------------------------------------------------- @@ -1127,8 +1087,13 @@ public: * Add a function in the loader script table * ----------------------------------------------------------------------- */ - void addFunctionInLoader(const_String_or_char_ptr scilabFunctionName) { - Printf(loaderScript, " '%s'; ..\n", scilabFunctionName); + void addFunctionInLoader(const_String_or_char_ptr scilabFunctionName, const_String_or_char_ptr scilabSmallFunctionName) { + if (++loaderFunctionCount % 10 == 0) { + Printf(loaderScript5, " ];\n list_functions = [list_functions; ..\n"); + Printf(loaderScript6, " ];\n list_functions = [list_functions; ..\n"); + } + Printf(loaderScript5, " '%s'; ..\n", scilabSmallFunctionName); + Printf(loaderScript6, " '%s'; ..\n", scilabFunctionName); } /* ----------------------------------------------------------------------- @@ -1137,18 +1102,66 @@ public: * ----------------------------------------------------------------------- */ void saveLoaderFile(String *gatewayLibraryName) { - Printf(loaderScript, "];\n"); - Printf(loaderScript, "addinter(fullfile(%s_path, '%s' + getdynlibext()), '%s', list_functions);\n", - gatewayLibraryName, gatewayLibraryName, gatewayLibraryName); - Printf(loaderScript, "clear %s_path;\n", gatewayLibraryName); - Printf(loaderScript, "clear bOK;\n"); - Printf(loaderScript, "clear ilib;\n"); - Printf(loaderScript, "clear list_functions;\n"); + Printf(loaderScript5, " ];\n"); + Printf(loaderScript6, " ];\n"); + + if (Equal(loaderScript5, loaderScript6)) { + Append(loaderScript, loaderScript6); + } else { + Printf(loaderScript, " ver = getversion('scilab');\n"); + Printf(loaderScript, " if ver(1) < 6 then\n"); + Printf(loaderScript, " // version is less or equal to 5.5.2\n"); + Printf(loaderScript, " \n"); + Append(loaderScript, loaderScript5); + Delete(loaderScript5); + Printf(loaderScript, " \n"); + Printf(loaderScript, " else\n"); + Printf(loaderScript, " // version is 6.0.0 or more\n"); + Printf(loaderScript, " \n"); + Append(loaderScript, loaderScript6); + Delete(loaderScript6); + Printf(loaderScript, " \n"); + Printf(loaderScript, " end\n"); + } + + Printf(loaderScript, " addinter(p + '%s' + getdynlibext(), '%s', list_functions);\n", gatewayLibraryName, gatewayLibraryName); + Printf(loaderScript, "endfunction\n"); + Printf(loaderScript, "loader_function();\n"); + Printf(loaderScript, "clear loader_function;\n"); Printv(loaderFile, loaderScript, NIL); + Delete(loaderScript); Delete(loaderFile); } + /* ----------------------------------------------------------------------- + * createSmallIdentifierName() + * Create a Scilab small identifier to be used by Scilab 5 + * ----------------------------------------------------------------------- */ + + String* createSmallIdentifierName(String* name, int outputLen = SCILAB_IDENTIFIER_NAME_CHAR_MAX) { + char* s = Char(name); + int nameLen = Len(s); + + // truncate and preserve common suffix + if (outputLen > 4 && nameLen > outputLen) { + String* smallName = NewStringWithSize(name, outputLen); + char* smallNameStr = (char*) Data(smallName); + + if (s[nameLen-4] == '_' && s[nameLen - 3] == 'g' && s[nameLen - 2] == 'e' && s[nameLen - 1] == 't') { + // get + memcpy(&smallNameStr[outputLen - 4], &s[nameLen - 4], 4); + } else if (s[nameLen-4] == '_' && s[nameLen - 3] == 's' && s[nameLen - 2] == 'e' && s[nameLen - 1] == 't') { + // set + memcpy(&smallNameStr[outputLen - 4], &s[nameLen - 4], 4); + } + + return smallName; + } + + return name; + } + }; extern "C" Language *swig_scilab(void) { diff --git a/Source/Modules/tcl8.cxx b/Source/Modules/tcl8.cxx index 7a78ede9b..d90d1d3b1 100644 --- a/Source/Modules/tcl8.cxx +++ b/Source/Modules/tcl8.cxx @@ -336,8 +336,6 @@ public: if ((tm = Getattr(p, "tmap:in"))) { String *parse = Getattr(p, "tmap:in:parse"); if (!parse) { - Replaceall(tm, "$target", ln); - Replaceall(tm, "$source", source); Replaceall(tm, "$input", source); Setattr(p, "emit:input", source); @@ -401,7 +399,6 @@ public: /* Insert constraint checking code */ for (p = parms; p;) { if ((tm = Getattr(p, "tmap:check"))) { - Replaceall(tm, "$target", Getattr(p, "lname")); Printv(f->code, tm, "\n", NIL); p = Getattr(p, "tmap:check:next"); } else { @@ -414,7 +411,6 @@ public: if (!checkAttribute(p, "tmap:in:numinputs", "0") && !Getattr(p, "tmap:in:parse") && (tm = Getattr(p, "tmap:freearg"))) { if (Len(tm) != 0) { - Replaceall(tm, "$source", Getattr(p, "lname")); Printv(cleanup, tm, "\n", NIL); } p = Getattr(p, "tmap:freearg:next"); @@ -426,12 +422,9 @@ public: /* Insert argument output code */ for (i = 0, p = parms; p; i++) { if ((tm = Getattr(p, "tmap:argout"))) { - Replaceall(tm, "$source", Getattr(p, "lname")); #ifdef SWIG_USE_RESULTOBJ - Replaceall(tm, "$target", "resultobj"); Replaceall(tm, "$result", "resultobj"); #else - Replaceall(tm, "$target", "(Tcl_GetObjResult(interp))"); Replaceall(tm, "$result", "(Tcl_GetObjResult(interp))"); #endif Replaceall(tm, "$arg", Getattr(p, "emit:input")); @@ -450,12 +443,9 @@ public: /* Return value if necessary */ if ((tm = Swig_typemap_lookup_out("out", n, Swig_cresult_name(), f, actioncode))) { - Replaceall(tm, "$source", Swig_cresult_name()); #ifdef SWIG_USE_RESULTOBJ - Replaceall(tm, "$target", "resultobj"); Replaceall(tm, "$result", "resultobj"); #else - Replaceall(tm, "$target", "(Tcl_GetObjResult(interp))"); Replaceall(tm, "$result", "(Tcl_GetObjResult(interp))"); #endif if (GetFlag(n, "feature:new")) { @@ -478,13 +468,11 @@ public: /* Look for any remaining cleanup */ if (GetFlag(n, "feature:new")) { if ((tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); Printf(f->code, "%s\n", tm); } } if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); Printf(f->code, "%s\n", tm); } #ifdef SWIG_USE_RESULTOBJ @@ -580,8 +568,6 @@ public: Printv(getf->def, "SWIGINTERN const char *", getfname, "(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, char *name1, char *name2, int flags) {", NIL); Wrapper_add_local(getf, "value", "Tcl_Obj *value = 0"); if ((tm = Swig_typemap_lookup("varout", n, name, 0))) { - Replaceall(tm, "$source", name); - Replaceall(tm, "$target", "value"); Replaceall(tm, "$result", "value"); /* Printf(getf->code, "%s\n",tm); */ addfail = emit_action_code(n, getf->code, tm); @@ -616,8 +602,6 @@ public: Wrapper_add_local(setf, "name1o", "Tcl_Obj *name1o = 0"); if ((tm = Swig_typemap_lookup("varin", n, name, 0))) { - Replaceall(tm, "$source", "value"); - Replaceall(tm, "$target", name); Replaceall(tm, "$input", "value"); Printf(setf->code, "name1o = Tcl_NewStringObj(name1,-1);\n"); Printf(setf->code, "value = Tcl_ObjGetVar2(interp, name1o, 0, flags);\n"); @@ -690,14 +674,10 @@ public: } if ((tm = Swig_typemap_lookup("consttab", n, name, 0))) { - Replaceall(tm, "$source", value); - Replaceall(tm, "$target", name); Replaceall(tm, "$value", value); Replaceall(tm, "$nsname", nsname); Printf(const_tab, "%s,\n", tm); } else if ((tm = Swig_typemap_lookup("constcode", n, name, 0))) { - Replaceall(tm, "$source", value); - Replaceall(tm, "$target", name); Replaceall(tm, "$value", value); Replaceall(tm, "$nsname", nsname); Printf(f_init, "%s\n", tm); @@ -909,7 +889,7 @@ public: // Add methods if (have_methods) { Printv(ptrclass, imethods, NIL); - }; + } // Close out the pointer class Printv(ptrclass, "}\n\n", NIL); @@ -967,7 +947,7 @@ public: if (!itcl) { Printv(cmd_tab, tab4, "{ SWIG_prefix \"", class_name, "\", (swig_wrapper_func) SWIG_ObjectConstructor, (ClientData)&_wrap_class_", mangled_classname, "},\n", NIL); - }; + } Delete(t); Delete(mangled_classname); @@ -1043,7 +1023,7 @@ public: Printv(imethods, "{ ", ns_name, "::", class_name, "_", realname, " $swigobj", NIL); } else { Printv(imethods, "{ ", class_name, "_", realname, " $swigobj", NIL); - }; + } pnum = 0; for (p = l; p; p = nextSibling(p)) { diff --git a/Source/Modules/typepass.cxx b/Source/Modules/typepass.cxx index dc84cf94a..d1a16b53a 100644 --- a/Source/Modules/typepass.cxx +++ b/Source/Modules/typepass.cxx @@ -1047,13 +1047,6 @@ class TypePass:private Dispatcher { || (Getattr(c, "feature:extend") && !Getattr(c, "code")) || GetFlag(c, "feature:ignore"))) { - /* Don't generate a method if the method is overridden in this class, - * for example don't generate another m(bool) should there be a Base::m(bool) : - * struct Derived : Base { - * void m(bool); - * using Base::m; - * }; - */ String *csymname = Getattr(c, "sym:name"); if (!csymname || (Strcmp(csymname, symname) == 0)) { { @@ -1069,11 +1062,20 @@ class TypePass:private Dispatcher { over = Getattr(over, "sym:nextSibling"); } if (match) { + /* Don't generate a method if the method is overridden in this class, + * for example don't generate another m(bool) should there be a Base::m(bool) : + * struct Derived : Base { + * void m(bool); + * using Base::m; + * }; + */ c = Getattr(c, "csym:nextSibling"); continue; } } Node *nn = copyNode(c); + Setfile(nn, Getfile(n)); + Setline(nn, Getline(n)); Delattr(nn, "access"); // access might be different from the method in the base class Setattr(nn, "access", Getattr(n, "access")); if (!Getattr(nn, "sym:name")) @@ -1117,6 +1119,9 @@ class TypePass:private Dispatcher { } else { Delete(nn); } + } else { + Swig_warning(WARN_LANG_USING_NAME_DIFFERENT, Getfile(n), Getline(n), "Using declaration %s, with name '%s', is not actually using\n", SwigType_namestr(Getattr(n, "uname")), symname); + Swig_warning(WARN_LANG_USING_NAME_DIFFERENT, Getfile(c), Getline(c), "the method from %s, with name '%s', as the names are different.\n", Swig_name_decl(c), csymname); } } } diff --git a/Source/Modules/uffi.cxx b/Source/Modules/uffi.cxx deleted file mode 100644 index 10a53a561..000000000 --- a/Source/Modules/uffi.cxx +++ /dev/null @@ -1,405 +0,0 @@ -/* ----------------------------------------------------------------------------- - * This file is part of SWIG, which is licensed as a whole under version 3 - * (or any later version) of the GNU General Public License. Some additional - * terms also apply to certain portions of SWIG. The full details of the SWIG - * license and copyrights can be found in the LICENSE and COPYRIGHT files - * included with the SWIG source code as distributed by the SWIG developers - * and at http://www.swig.org/legal.html. - * - * uffi.cxx - * - * Uffi language module for SWIG. - * ----------------------------------------------------------------------------- */ - -// TODO: remove remnants of lisptype - -#include "swigmod.h" - -static const char *usage = "\ -UFFI Options (available with -uffi)\n\ - -identifier-converter - \n\ - Specifies the type of conversion to do on C identifiers\n\ - to convert them to symbols. There are two built-in\n\ - converters: 'null' and 'lispify'. The default is\n\ - 'null'. If you supply a name other than one of the\n\ - built-ins, then a function by that name will be\n\ - called to convert identifiers to symbols.\n\ -"; - -class UFFI:public Language { -public: - - virtual void main(int argc, char *argv[]); - virtual int top(Node *n); - virtual int functionWrapper(Node *n); - virtual int constantWrapper(Node *n); - virtual int classHandler(Node *n); - virtual int membervariableHandler(Node *n); - -}; - -static File *f_cl = 0; - -static struct { - int count; - String **entries; -} defined_foreign_types; - -static String *identifier_converter = NewString("identifier-convert-null"); - -static int any_varargs(ParmList *pl) { - Parm *p; - - for (p = pl; p; p = nextSibling(p)) { - if (SwigType_isvarargs(Getattr(p, "type"))) - return 1; - } - - return 0; -} - - -/* utilities */ -/* returns new string w/ parens stripped */ -static String *strip_parens(String *string) { - char *s = Char(string), *p; - int len = Len(string); - String *res; - - if (len == 0 || s[0] != '(' || s[len - 1] != ')') { - return NewString(string); - } - - p = (char *) malloc(len - 2 + 1); - if (!p) { - Printf(stderr, "Malloc failed\n"); - SWIG_exit(EXIT_FAILURE); - } - - strncpy(p, s + 1, len - 1); - p[len - 2] = 0; /* null terminate */ - - res = NewString(p); - free(p); - - return res; -} - - -static String *convert_literal(String *num_param, String *type) { - String *num = strip_parens(num_param), *res; - char *s = Char(num); - - /* Make sure doubles use 'd' instead of 'e' */ - if (!Strcmp(type, "double")) { - String *updated = Copy(num); - if (Replace(updated, "e", "d", DOH_REPLACE_ANY) > 1) { - Printf(stderr, "Weird!! number %s looks invalid.\n", num); - SWIG_exit(EXIT_FAILURE); - } - Delete(num); - return updated; - } - - if (SwigType_type(type) == T_CHAR) { - /* Use CL syntax for character literals */ - return NewStringf("#\\%s", num_param); - } else if (SwigType_type(type) == T_STRING) { - /* Use CL syntax for string literals */ - return NewStringf("\"%s\"", num_param); - } - - if (Len(num) < 2 || s[0] != '0') { - return num; - } - - /* octal or hex */ - - res = NewStringf("#%c%s", s[1] == 'x' ? 'x' : 'o', s + 2); - Delete(num); - - return res; -} - -static void add_defined_foreign_type(String *type) { - if (!defined_foreign_types.count) { - /* Make fresh */ - defined_foreign_types.count = 1; - defined_foreign_types.entries = (String **) malloc(sizeof(String *)); - } else { - /* make room */ - defined_foreign_types.count++; - defined_foreign_types.entries = (String **) - realloc(defined_foreign_types.entries, defined_foreign_types.count * sizeof(String *)); - } - - if (!defined_foreign_types.entries) { - Printf(stderr, "Out of memory\n"); - SWIG_exit(EXIT_FAILURE); - } - - /* Fill in the new data */ - defined_foreign_types.entries[defined_foreign_types.count - 1] = Copy(type); - -} - - -static String *get_ffi_type(Node *n, SwigType *ty, const_String_or_char_ptr name) { - Node *node = NewHash(); - Setattr(node, "type", ty); - Setattr(node, "name", name); - Setfile(node, Getfile(n)); - Setline(node, Getline(n)); - const String *tm = Swig_typemap_lookup("ffitype", node, "", 0); - Delete(node); - - if (tm) { - return NewString(tm); - } else { - SwigType *tr = SwigType_typedef_resolve_all(ty); - char *type_reduced = Char(tr); - int i; - - //Printf(stdout,"convert_type %s\n", ty); - if (SwigType_isconst(tr)) { - SwigType_pop(tr); - type_reduced = Char(tr); - } - - if (SwigType_ispointer(type_reduced) || SwigType_isarray(ty) || !strncmp(type_reduced, "p.f", 3)) { - return NewString(":pointer-void"); - } - - for (i = 0; i < defined_foreign_types.count; i++) { - if (!Strcmp(ty, defined_foreign_types.entries[i])) { - return NewStringf("#.(%s \"%s\" :type :type)", identifier_converter, ty); - } - } - - if (!Strncmp(type_reduced, "enum ", 5)) { - return NewString(":int"); - } - - Printf(stderr, "Unsupported data type: %s (was: %s)\n", type_reduced, ty); - SWIG_exit(EXIT_FAILURE); - } - return 0; -} - -static String *get_lisp_type(Node *n, SwigType *ty, const_String_or_char_ptr name) { - Node *node = NewHash(); - Setattr(node, "type", ty); - Setattr(node, "name", name); - Setfile(node, Getfile(n)); - Setline(node, Getline(n)); - const String *tm = Swig_typemap_lookup("lisptype", node, "", 0); - Delete(node); - - return tm ? NewString(tm) : NewString(""); -} - -void UFFI::main(int argc, char *argv[]) { - int i; - - Preprocessor_define("SWIGUFFI 1", 0); - SWIG_library_directory("uffi"); - SWIG_config_file("uffi.swg"); - - - for (i = 1; i < argc; i++) { - if (!strcmp(argv[i], "-identifier-converter")) { - char *conv = argv[i + 1]; - - if (!conv) - Swig_arg_error(); - - Swig_mark_arg(i); - Swig_mark_arg(i + 1); - i++; - - /* check for built-ins */ - if (!strcmp(conv, "lispify")) { - Delete(identifier_converter); - identifier_converter = NewString("identifier-convert-lispify"); - } else if (!strcmp(conv, "null")) { - Delete(identifier_converter); - identifier_converter = NewString("identifier-convert-null"); - } else { - /* Must be user defined */ - Delete(identifier_converter); - identifier_converter = NewString(conv); - } - } - - if (!strcmp(argv[i], "-help")) { - Printf(stdout, "%s\n", usage); - } - } -} - -int UFFI::top(Node *n) { - String *module = Getattr(n, "name"); - String *output_filename = NewString(""); - File *f_null = NewString(""); - - Printf(output_filename, "%s%s.cl", SWIG_output_directory(), module); - - - f_cl = NewFile(output_filename, "w", SWIG_output_files()); - if (!f_cl) { - FileErrorDisplay(output_filename); - SWIG_exit(EXIT_FAILURE); - } - - Swig_register_filebyname("header", f_null); - Swig_register_filebyname("begin", f_null); - Swig_register_filebyname("runtime", f_null); - Swig_register_filebyname("wrapper", f_cl); - - Swig_banner_target_lang(f_cl, ";;"); - - Printf(f_cl, "\n" - ";; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10; package: %s -*-\n\n(defpackage :%s\n (:use :common-lisp :uffi))\n\n(in-package :%s)\n", - module, module, module); - Printf(f_cl, "(eval-when (compile load eval)\n (defparameter *swig-identifier-converter* '%s))\n", identifier_converter); - - Language::top(n); - - Delete(f_cl); // Delete the handle, not the file - Delete(f_null); - - return SWIG_OK; -} - -int UFFI::functionWrapper(Node *n) { - String *funcname = Getattr(n, "sym:name"); - ParmList *pl = Getattr(n, "parms"); - Parm *p; - int argnum = 0, first = 1; -// int varargs = 0; - - //Language::functionWrapper(n); - - Printf(f_cl, "(swig-defun \"%s\"\n", funcname); - Printf(f_cl, " ("); - - /* Special cases */ - - if (ParmList_len(pl) == 0) { - Printf(f_cl, ":void"); - } else if (any_varargs(pl)) { - Printf(f_cl, "#| varargs |#"); -// varargs = 1; - } else { - for (p = pl; p; p = nextSibling(p), argnum++) { - String *argname = Getattr(p, "name"); - SwigType *argtype = Getattr(p, "type"); - String *ffitype = get_ffi_type(n, argtype, argname); - String *lisptype = get_lisp_type(n, argtype, argname); - int tempargname = 0; - - if (!argname) { - argname = NewStringf("arg%d", argnum); - tempargname = 1; - } - - if (!first) { - Printf(f_cl, "\n "); - } - Printf(f_cl, "(%s %s %s)", argname, ffitype, lisptype); - first = 0; - - Delete(ffitype); - Delete(lisptype); - if (tempargname) - Delete(argname); - - } - } - Printf(f_cl, ")\n"); /* finish arg list */ - Printf(f_cl, " :returning %s\n" - //" :strings-convert t\n" - //" :call-direct %s\n" - //" :optimize-for-space t" - ")\n", get_ffi_type(n, Getattr(n, "type"), Swig_cresult_name()) - //,varargs ? "nil" : "t" - ); - - - return SWIG_OK; -} - -int UFFI::constantWrapper(Node *n) { - String *type = Getattr(n, "type"); - String *converted_value = convert_literal(Getattr(n, "value"), type); - String *name = Getattr(n, "sym:name"); - -#if 0 - Printf(stdout, "constant %s is of type %s. value: %s\n", name, type, converted_value); -#endif - - Printf(f_cl, "(swig-defconstant \"%s\" %s)\n", name, converted_value); - - Delete(converted_value); - - return SWIG_OK; -} - -// Includes structs -int UFFI::classHandler(Node *n) { - - String *name = Getattr(n, "sym:name"); - String *kind = Getattr(n, "kind"); - Node *c; - - if (Strcmp(kind, "struct")) { - Printf(stderr, "Don't know how to deal with %s kind of class yet.\n", kind); - Printf(stderr, " (name: %s)\n", name); - SWIG_exit(EXIT_FAILURE); - } - - Printf(f_cl, "(swig-def-struct \"%s\"\n \n", name); - - for (c = firstChild(n); c; c = nextSibling(c)) { - SwigType *type = Getattr(c, "type"); - SwigType *decl = Getattr(c, "decl"); - if (type) { - type = Copy(type); - SwigType_push(type, decl); - String *lisp_type; - - if (Strcmp(nodeType(c), "cdecl")) { - Printf(stderr, "Structure %s has a slot that we can't deal with.\n", name); - Printf(stderr, "nodeType: %s, name: %s, type: %s\n", nodeType(c), Getattr(c, "name"), Getattr(c, "type")); - SWIG_exit(EXIT_FAILURE); - } - - /* Printf(stdout, "Converting %s in %s\n", type, name); */ - lisp_type = get_ffi_type(n, type, Getattr(c, "sym:name")); - - Printf(f_cl, " (#.(%s \"%s\" :type :slot) %s)\n", identifier_converter, Getattr(c, "sym:name"), lisp_type); - - Delete(lisp_type); - } - } - - // Language::classHandler(n); - - Printf(f_cl, " )\n"); - - /* Add this structure to the known lisp types */ - //Printf(stdout, "Adding %s foreign type\n", name); - add_defined_foreign_type(name); - - return SWIG_OK; -} - -int UFFI::membervariableHandler(Node *n) { - Language::membervariableHandler(n); - return SWIG_OK; -} - - -extern "C" Language *swig_uffi(void) { - return new UFFI(); -} diff --git a/Source/Preprocessor/cpp.c b/Source/Preprocessor/cpp.c index 557b5482b..1ede58354 100644 --- a/Source/Preprocessor/cpp.c +++ b/Source/Preprocessor/cpp.c @@ -113,7 +113,7 @@ static int is_digits(const String *str) { const char *s = Char(str); int isdigits = (*s != 0); while (*s) { - if (!isdigit(*s)) { + if (!isdigit((int)*s)) { isdigits = 0; break; } @@ -1686,7 +1686,7 @@ String *Preprocessor_parse(String *s) { Seek(value, 0, SEEK_SET); Swig_warning(WARN_PP_EVALUATION, Getfile(value), Getline(value), "Could not evaluate expression '%s'\n", value); if (msg) - Swig_warning(WARN_PP_EVALUATION, Getfile(value), Getline(value), "Error: '%s'\n", msg); + Swig_warning(WARN_PP_EVALUATION, Getfile(value), Getline(value), "%s\n", msg); allow = 0; } else { if (val == 0) @@ -1720,7 +1720,7 @@ String *Preprocessor_parse(String *s) { Seek(value, 0, SEEK_SET); Swig_warning(WARN_PP_EVALUATION, Getfile(value), Getline(value), "Could not evaluate expression '%s'\n", value); if (msg) - Swig_warning(WARN_PP_EVALUATION, Getfile(value), Getline(value), "Error: '%s'\n", msg); + Swig_warning(WARN_PP_EVALUATION, Getfile(value), Getline(value), "%s\n", msg); allow = 0; } else { if (val) diff --git a/Source/Preprocessor/expr.c b/Source/Preprocessor/expr.c index a36588983..d7a65a77e 100644 --- a/Source/Preprocessor/expr.c +++ b/Source/Preprocessor/expr.c @@ -18,8 +18,19 @@ static Scanner *scan = 0; typedef struct { + /* One of the EXPR_xxx values defined below. */ int op; + /* op == EXPR_OP: value is the token specifying which operator. + * + * op == EXPR_VALUE && svalue == NULL: Numeric expression value. + * + * Otherwise unused. + */ long value; + /* op == EXPR_VALUE: If non-NULL, string expression value; if NULL see value. + * + * Otherwise unused. + */ String *svalue; } exprval; @@ -27,7 +38,12 @@ typedef struct { #define EXPR_VALUE 2 #define EXPR_OP 3 #define EXPR_GROUP 4 -#define EXPR_UMINUS 100 + +/* Special token values used here to distinguish from SWIG_TOKEN_MINUS + * and SWIG_TOKEN_PLUS (which we use here for a two argument versions). + */ +#define OP_UMINUS 100 +#define OP_UPLUS 101 static exprval stack[256]; /* Parsing stack */ static int sp = 0; /* Stack pointer */ @@ -38,7 +54,8 @@ static const char *errmsg = 0; /* Parsing error */ /* Initialize the precedence table for various operators. Low values have higher precedence */ static void init_precedence() { prec[SWIG_TOKEN_NOT] = 10; - prec[EXPR_UMINUS] = 10; + prec[OP_UMINUS] = 10; + prec[OP_UPLUS] = 10; prec[SWIG_TOKEN_STAR] = 20; prec[SWIG_TOKEN_SLASH] = 20; prec[SWIG_TOKEN_PERCENT] = 20; @@ -63,7 +80,8 @@ static void init_precedence() { #define UNARY_OP(token) (((token) == SWIG_TOKEN_NOT) || \ ((token) == SWIG_TOKEN_LNOT) || \ - ((token) == EXPR_UMINUS)) + ((token) == OP_UMINUS) || \ + ((token) == OP_UPLUS)) /* Reduce a single operator on the stack */ /* return 0 on failure, 1 on success */ @@ -183,10 +201,14 @@ static int reduce_op() { stack[sp - 1].value = !stack[sp].value; sp--; break; - case EXPR_UMINUS: + case OP_UMINUS: stack[sp - 1].value = -stack[sp].value; sp--; break; + case OP_UPLUS: + stack[sp - 1].value = stack[sp].value; + sp--; + break; case SWIG_TOKEN_SLASH: if (stack[sp].value != 0) { stack[sp - 2].value = stack[sp - 2].value / stack[sp].value; @@ -278,13 +300,15 @@ int Preprocessor_expr(DOH *s, int *error) { /* Put initial state onto the stack */ stack[sp].op = EXPR_TOP; - stack[sp].value = 0; while (1) { /* Look at the top of the stack */ switch (stack[sp].op) { case EXPR_TOP: - /* An expression. Can be a number or another expression enclosed in parens */ + /* EXPR_TOP is a place-holder which can only appear on the top of the + * stack. We can reduce it to any expression - a number, a string, an + * unary operator, or another expression enclosed in parentheses. + */ token = expr_token(scan); if (!token) { errmsg = "Expected an expression"; @@ -296,26 +320,28 @@ int Preprocessor_expr(DOH *s, int *error) { char *c = Char(Scanner_text(scan)); stack[sp].value = (long) strtol(c, 0, 0); stack[sp].svalue = 0; - /* stack[sp].value = (long) atol(Char(Scanner_text(scan))); */ stack[sp].op = EXPR_VALUE; - } else if (token == SWIG_TOKEN_PLUS) { - } else if ((token == SWIG_TOKEN_MINUS) || (token == SWIG_TOKEN_LNOT) || (token == SWIG_TOKEN_NOT)) { + } else if ((token == SWIG_TOKEN_MINUS) || (token == SWIG_TOKEN_PLUS) || (token == SWIG_TOKEN_LNOT) || (token == SWIG_TOKEN_NOT)) { if (token == SWIG_TOKEN_MINUS) - token = EXPR_UMINUS; + token = OP_UMINUS; + else if (token == SWIG_TOKEN_PLUS) + token = OP_UPLUS; stack[sp].value = token; - stack[sp++].op = EXPR_OP; + stack[sp].op = EXPR_OP; + sp++; stack[sp].op = EXPR_TOP; - stack[sp].svalue = 0; } else if (token == SWIG_TOKEN_LPAREN) { - stack[sp++].op = EXPR_GROUP; + stack[sp].op = EXPR_GROUP; + sp++; stack[sp].op = EXPR_TOP; - stack[sp].value = 0; - stack[sp].svalue = 0; } else if (token == SWIG_TOKEN_ENDLINE) { } else if (token == SWIG_TOKEN_STRING) { stack[sp].svalue = NewString(Scanner_text(scan)); stack[sp].op = EXPR_VALUE; } else if (token == SWIG_TOKEN_ID) { + /* Defined macros have been expanded already so this is an unknown + * macro, which gets treated as zero. + */ stack[sp].value = 0; stack[sp].svalue = 0; stack[sp].op = EXPR_VALUE; @@ -327,7 +353,9 @@ int Preprocessor_expr(DOH *s, int *error) { goto syntax_error; break; case EXPR_VALUE: - /* A value is on the stack. We may reduce or evaluate depending on what the next token is */ + /* A value is on top of the stack. We may reduce or evaluate depending + * on what the next token is. + */ token = expr_token(scan); if (!token) { /* End of input. Might have to reduce if an operator is on stack */ @@ -371,7 +399,6 @@ int Preprocessor_expr(DOH *s, int *error) { stack[sp].value = token; sp++; stack[sp].op = EXPR_TOP; - stack[sp].value = 0; } else { if (stack[sp - 1].op != EXPR_OP) goto syntax_error_expected_operator; @@ -390,7 +417,6 @@ int Preprocessor_expr(DOH *s, int *error) { stack[sp].value = token; sp++; stack[sp].op = EXPR_TOP; - stack[sp].value = 0; } break; case SWIG_TOKEN_RPAREN: @@ -406,6 +432,7 @@ int Preprocessor_expr(DOH *s, int *error) { goto extra_rparen; stack[sp - 1].op = EXPR_VALUE; stack[sp - 1].value = stack[sp].value; + stack[sp - 1].svalue = stack[sp].svalue; sp--; break; default: diff --git a/Source/README b/Source/README index 814ec45bd..088933308 100644 --- a/Source/README +++ b/Source/README @@ -13,13 +13,3 @@ SWIG Source directory Source/Modules - Language modules. Source/Include - Include files. - -Historic directories which may be in CVS, but have been removed: - - Source/Modules1.1 - Old SWIG-1.1 modules. Empty. - - Source/LParse - Experimental parser. Officially dead - as CParse is more capable. - - Source/SWIG1.1 - Old SWIG1.1 core. Completely empty now. - diff --git a/Source/Swig/cwrap.c b/Source/Swig/cwrap.c index d6e5e0cdc..ebe9fa702 100644 --- a/Source/Swig/cwrap.c +++ b/Source/Swig/cwrap.c @@ -632,7 +632,7 @@ String *Swig_cppconstructor_director_call(const_String_or_char_ptr name, ParmLis * If you define SWIG_FAST_REC_SEARCH, the method will set the found * 'attr' in the target class 'n'. If not, the method will set the * 'noattr' one. This prevents of having to navigate the entire - * hierarchy tree everytime, so, it is an O(1) method... or something + * hierarchy tree every time, so, it is an O(1) method... or something * like that. However, it populates all the parsed classes with the * 'attr' and/or 'noattr' attributes. * @@ -1076,9 +1076,18 @@ int Swig_MethodToFunction(Node *n, const_String_or_char_ptr nspace, String *clas /* Check if the method is overloaded. If so, and it has code attached, we append an extra suffix to avoid a name-clash in the generated wrappers. This allows overloaded methods to be defined - in C. */ - if (Getattr(n, "sym:overloaded") && code) { - Append(mangled, Getattr(defaultargs ? defaultargs : n, "sym:overname")); + in C. + + But when not using the suffix used for overloaded functions, we still need to ensure that the + wrapper name doesn't conflict with any wrapper functions, so make it sufficiently unique by + appending a suffix similar to the one used for overloaded functions to it. + */ + if (code) { + if (Getattr(n, "sym:overloaded")) { + Append(mangled, Getattr(defaultargs ? defaultargs : n, "sym:overname")); + } else { + Append(mangled, "__SWIG"); + } } /* See if there is any code that we need to emit */ diff --git a/Source/Swig/fragment.c b/Source/Swig/fragment.c index 5b30e86e0..4ec26f955 100644 --- a/Source/Swig/fragment.c +++ b/Source/Swig/fragment.c @@ -29,7 +29,7 @@ static int debug = 0; * Swig_fragment_register() * * Add a fragment. Use the original Node*, so, if something needs to be - * changed, lang.cxx doesn't nedd to be touched again. + * changed, lang.cxx doesn't need to be touched again. * ----------------------------------------------------------------------------- */ void Swig_fragment_register(Node *fragment) { diff --git a/Source/Swig/misc.c b/Source/Swig/misc.c index ef6fcc02f..d92d4e410 100644 --- a/Source/Swig/misc.c +++ b/Source/Swig/misc.c @@ -1157,47 +1157,15 @@ int Swig_scopename_check(const String *s) { /* ----------------------------------------------------------------------------- * Swig_string_command() * - * Executes a external command via popen with the string as a command - * line parameter. For example: - * - * Printf(stderr,"%(command:sed 's/[a-z]/\U\\1/' <<<)s","hello") -> Hello + * Feature removed in SWIG 4.1.0. * ----------------------------------------------------------------------------- */ -#if defined(_MSC_VER) -# define popen _popen -# define pclose _pclose -# if !defined(HAVE_POPEN) -# define HAVE_POPEN 1 -# endif -#else -# if !defined(_WIN32) -/* These Posix functions are not ISO C and so are not always defined in stdio.h */ -extern FILE *popen(const char *command, const char *type); -extern int pclose(FILE *stream); -# endif -#endif String *Swig_string_command(String *s) { - String *res = NewStringEmpty(); -#if defined(HAVE_POPEN) - if (Len(s)) { - char *command = Char(s); - FILE *fp = popen(command, "r"); - if (fp) { - char buffer[1025]; - while (fscanf(fp, "%1024s", buffer) != EOF) { - Append(res, buffer); - } - pclose(fp); - } else { - Swig_error("SWIG", Getline(s), "Command encoder fails attempting '%s'.\n", s); - SWIG_exit(EXIT_FAILURE); - } - } -#endif - return res; + Swig_error("SWIG", Getline(s), "Command encoder no longer supported - use regex encoder instead.\n"); + SWIG_exit(EXIT_FAILURE); + return 0; } - /* ----------------------------------------------------------------------------- * Swig_string_strip() * @@ -1312,7 +1280,8 @@ void Swig_offset_string(String *s, int number) { #ifdef HAVE_PCRE -#include +#define PCRE2_CODE_UNIT_WIDTH 8 +#include static int split_regex_pattern_subst(String *s, String **pattern, String **subst, const char **input) { @@ -1375,7 +1344,7 @@ static void copy_with_maybe_case_conversion(String *dst, const char *src, int le } } -String *replace_captures(int num_captures, const char *input, String *subst, int captures[], String *pattern, String *s) +String *replace_captures(int num_captures, const char *input, String *subst, size_t captures[], String *pattern, String *s) { int convertCase = 0, convertNextOnly = 0; String *result = NewStringEmpty(); @@ -1397,7 +1366,7 @@ String *replace_captures(int num_captures, const char *input, String *subst, int } else if (isdigit((unsigned char)*p)) { int group = *p++ - '0'; if (group < num_captures) { - int l = captures[group*2], r = captures[group*2 + 1]; + int l = (int)captures[group*2], r = (int)captures[group*2 + 1]; if (l != -1) { copy_with_maybe_case_conversion(result, input + l, r - l, &convertCase, convertNextOnly); } @@ -1449,26 +1418,31 @@ String *Swig_string_regex(String *s) { const int pcre_options = 0; String *res = 0; - pcre *compiled_pat = 0; - const char *pcre_error, *input; - int pcre_errorpos; + pcre2_code *compiled_pat = 0; + const char *input; + PCRE2_UCHAR pcre_error[256]; + int pcre_errornum; + size_t pcre_errorpos; String *pattern = 0, *subst = 0; - int captures[30]; - + size_t *captures = 0; + pcre2_match_data *match_data = 0; if (split_regex_pattern_subst(s, &pattern, &subst, &input)) { int rc; - compiled_pat = pcre_compile( - Char(pattern), pcre_options, &pcre_error, &pcre_errorpos, NULL); + compiled_pat = pcre2_compile( + (PCRE2_SPTR8)Char(pattern), PCRE2_ZERO_TERMINATED, pcre_options, &pcre_errornum, &pcre_errorpos, NULL); if (!compiled_pat) { + pcre2_get_error_message (pcre_errornum, pcre_error, sizeof pcre_error); Swig_error("SWIG", Getline(s), "PCRE compilation failed: '%s' in '%s':%i.\n", pcre_error, Char(pattern), pcre_errorpos); SWIG_exit(EXIT_FAILURE); } - rc = pcre_exec(compiled_pat, NULL, input, (int)strlen(input), 0, 0, captures, 30); + match_data = pcre2_match_data_create_from_pattern (compiled_pat, NULL); + rc = pcre2_match(compiled_pat, (PCRE2_SPTR8)input, PCRE2_ZERO_TERMINATED, 0, 0, match_data, NULL); + captures = pcre2_get_ovector_pointer (match_data); if (rc >= 0) { res = replace_captures(rc, input, subst, captures, pattern, s); - } else if (rc != PCRE_ERROR_NOMATCH) { + } else if (rc != PCRE2_ERROR_NOMATCH) { Swig_error("SWIG", Getline(s), "PCRE execution failed: error %d while matching \"%s\" using \"%s\".\n", rc, Char(pattern), input); SWIG_exit(EXIT_FAILURE); @@ -1477,12 +1451,19 @@ String *Swig_string_regex(String *s) { DohDelete(pattern); DohDelete(subst); - pcre_free(compiled_pat); + pcre2_code_free(compiled_pat); + pcre2_match_data_free(match_data); return res ? res : NewStringEmpty(); } String *Swig_pcre_version(void) { - return NewStringf("PCRE Version: %s", pcre_version()); + int len = pcre2_config(PCRE2_CONFIG_VERSION, NULL); + char *buf = malloc(len); + String *result; + pcre2_config(PCRE2_CONFIG_VERSION, buf); + result = NewStringf("PCRE2 Version: %s", buf); + free(buf); + return result; } #else diff --git a/Source/Swig/naming.c b/Source/Swig/naming.c index 6689ceb7a..c9456637b 100644 --- a/Source/Swig/naming.c +++ b/Source/Swig/naming.c @@ -1092,26 +1092,32 @@ static DOH *get_lattr(Node *n, List *lattr) { } #ifdef HAVE_PCRE -#include +#define PCRE2_CODE_UNIT_WIDTH 8 +#include static int name_regexmatch_value(Node *n, String *pattern, String *s) { - pcre *compiled_pat; - const char *err; - int errpos; + pcre2_code *compiled_pat; + PCRE2_UCHAR err[256]; + int errornum; + size_t errpos; int rc; - compiled_pat = pcre_compile(Char(pattern), 0, &err, &errpos, NULL); + compiled_pat = pcre2_compile((PCRE2_SPTR8)Char(pattern), PCRE2_ZERO_TERMINATED, 0, &errornum, &errpos, NULL); if (!compiled_pat) { + pcre2_get_error_message (errornum, err, sizeof err); Swig_error("SWIG", Getline(n), "Invalid regex \"%s\": compilation failed at %d: %s\n", Char(pattern), errpos, err); SWIG_exit(EXIT_FAILURE); } - rc = pcre_exec(compiled_pat, NULL, Char(s), Len(s), 0, 0, NULL, 0); - pcre_free(compiled_pat); + pcre2_match_data *match_data = 0; + match_data = pcre2_match_data_create_from_pattern (compiled_pat, NULL); + rc = pcre2_match(compiled_pat, (PCRE2_SPTR8)Char(s), PCRE2_ZERO_TERMINATED, 0, 0, match_data, 0); + pcre2_code_free(compiled_pat); + pcre2_match_data_free(match_data); - if (rc == PCRE_ERROR_NOMATCH) + if (rc == PCRE2_ERROR_NOMATCH) return 0; if (rc < 0 ) { @@ -1132,6 +1138,7 @@ static int name_regexmatch_value(Node *n, String *pattern, String *s) { Swig_error("SWIG", Getline(n), "PCRE regex matching is not available in this SWIG build.\n"); SWIG_exit(EXIT_FAILURE); + return 0; } #endif /* HAVE_PCRE/!HAVE_PCRE */ @@ -1510,20 +1517,30 @@ String *Swig_name_make(Node *n, String *prefix, const_String_or_char_ptr cname, result = apply_rename(n, rename, fullname, prefix, name); if ((msg) && (Len(msg))) { if (!Getmeta(nname, "already_warned")) { + String* suffix = 0; + if (Strcmp(result, "$ignore") == 0) { + suffix = NewStringf(": ignoring '%s'\n", name); + } else if (Strcmp(result, name) != 0) { + suffix = NewStringf(", renaming to '%s'\n", result); + } else { + /* No rename was performed */ + suffix = NewString("\n"); + } if (n) { /* Parameter renaming is not fully implemented. Mainly because there is no C/C++ syntax to * for %rename to fully qualify a function's parameter name from outside the function. Hence it - * is not possible to implemented targetted warning suppression on one parameter in one function. */ + * is not possible to implemented targeted warning suppression on one parameter in one function. */ int suppress_parameter_rename_warning = Equal(nodeType(n), "parm"); if (!suppress_parameter_rename_warning) { SWIG_WARN_NODE_BEGIN(n); - Swig_warning(0, Getfile(n), Getline(n), "%s\n", msg); + Swig_warning(0, Getfile(n), Getline(n), "%s%s", msg, suffix); SWIG_WARN_NODE_END(n); } } else { - Swig_warning(0, Getfile(name), Getline(name), "%s\n", msg); + Swig_warning(0, Getfile(name), Getline(name), "%s%s", msg, suffix); } Setmeta(nname, "already_warned", "1"); + Delete(suffix); } } } diff --git a/Source/Swig/scanner.c b/Source/Swig/scanner.c index e5a267ae5..f53454b4b 100644 --- a/Source/Swig/scanner.c +++ b/Source/Swig/scanner.c @@ -636,7 +636,7 @@ static int look(Scanner *s) { } else if (c == '.') - state = 100; /* Maybe a number, maybe just a period */ + state = 100; /* Maybe a number, maybe ellipsis, just a period */ else if (isdigit(c)) state = 8; /* A numerical value */ else @@ -1330,19 +1330,34 @@ static int look(Scanner *s) { } break; - /* A period or maybe a floating point number */ + /* A period or an ellipsis or maybe a floating point number */ case 100: if ((c = nextchar(s)) == 0) return (0); if (isdigit(c)) state = 81; + else if (c == '.') + state = 101; else { retract(s, 1); return SWIG_TOKEN_PERIOD; } break; + /* An ellipsis */ + + case 101: + if ((c = nextchar(s)) == 0) + return (0); + if (c == '.') { + return SWIG_TOKEN_ELLIPSIS; + } else { + retract(s, 2); + return SWIG_TOKEN_PERIOD; + } + break; + case 200: /* PLUS, PLUSPLUS, PLUSEQUAL */ if ((c = nextchar(s)) == 0) return SWIG_TOKEN_PLUS; diff --git a/Source/Swig/stype.c b/Source/Swig/stype.c index 66518f50c..5f876ff04 100644 --- a/Source/Swig/stype.c +++ b/Source/Swig/stype.c @@ -134,7 +134,7 @@ SwigType *NewSwigType(int t) { return NewString("double"); break; case T_COMPLEX: - return NewString("complex"); + return NewString("_Complex"); break; case T_CHAR: return NewString("char"); @@ -1291,11 +1291,29 @@ void SwigType_typename_replace(SwigType *t, String *pat, String *rep) { Replace(e, pat, rep, DOH_REPLACE_ANY); } else if (SwigType_istemplate(e)) { /* Replaces a type of the form 'pat' with 'rep' */ - if (Equal(e, pat)) { - String *repbase = SwigType_templateprefix(rep); - Replace(e, pat, repbase, DOH_REPLACE_ID | DOH_REPLACE_FIRST); - Delete(repbase); + { + /* To match "e=TemplateTemplateT<(float)>" + * with "pat=TemplateTemplateT" + * we need to compare only the first part of the string e. + */ + int len = Len(pat); + + /* Len(e) > len, not >= (because we expect at least a + * character '<' following the template typename) + */ + if (Len(e) > len) { + String *firstPartOfType = NewStringWithSize(e, len); + const char* e_as_char = Char(e); + + if (Equal(firstPartOfType, pat) && e_as_char[len] == '<') { + String *repbase = SwigType_templateprefix(rep); + Replace(e, pat, repbase, DOH_REPLACE_ID | DOH_REPLACE_FIRST); + Delete(repbase); + } + Delete(firstPartOfType); + } } + { String *tsuffix; List *tparms = SwigType_parmlist(e); diff --git a/Source/Swig/swigscan.h b/Source/Swig/swigscan.h index 740a93610..4f66de8a2 100644 --- a/Source/Swig/swigscan.h +++ b/Source/Swig/swigscan.h @@ -70,6 +70,7 @@ extern void Scanner_locator(Scanner *, String *loc); #define SWIG_TOKEN_BOOL 32 /* true or false */ #define SWIG_TOKEN_WSTRING 33 /* L"str" */ #define SWIG_TOKEN_WCHAR 34 /* L'c' */ +#define SWIG_TOKEN_ELLIPSIS 35 /* ... */ #define SWIG_TOKEN_ILLEGAL 99 #define SWIG_TOKEN_ERROR -1 diff --git a/Source/Swig/symbol.c b/Source/Swig/symbol.c index aacaf24be..d3bc720ff 100644 --- a/Source/Swig/symbol.c +++ b/Source/Swig/symbol.c @@ -12,7 +12,7 @@ * ----------------------------------------------------------------------------- */ #include "swig.h" -#include "swigwarn.h" +#include "cparse.h" #include /* #define SWIG_DEBUG*/ @@ -641,10 +641,11 @@ void Swig_symbol_cadd(const_String_or_char_ptr name, Node *n) { { Node *td = n; - while (td && Checkattr(td, "nodeType", "cdecl") && Checkattr(td, "storage", "typedef")) { + while (td && ((Equal(nodeType(td), "cdecl") && Checkattr(td, "storage", "typedef")) || (Equal(nodeType(td), "using") && !Getattr(n, "namespace")))) { SwigType *type; Node *td1; - type = Copy(Getattr(td, "type")); + int using_not_typedef = Equal(nodeType(td), "using"); + type = Copy(Getattr(td, using_not_typedef ? "uname" : "type")); SwigType_push(type, Getattr(td, "decl")); td1 = Swig_symbol_clookup(type, 0); @@ -665,9 +666,13 @@ void Swig_symbol_cadd(const_String_or_char_ptr name, Node *n) { ie, when Foo -> FooBar -> Foo, jump one scope up when possible. */ - if (td1 && Checkattr(td1, "storage", "typedef")) { - String *st = Getattr(td1, "type"); + if (td1) { + String *st = 0; String *sn = Getattr(td, "name"); + if (Equal(nodeType(td1), "cdecl") && Checkattr(td1, "storage", "typedef")) + st = Getattr(td1, "type"); + else if (Equal(nodeType(td1), "using") && !Getattr(td1, "namespace")) + st = Getattr(td1, "uname"); if (st && sn && Equal(st, sn)) { Symtab *sc = Getattr(current_symtab, "parentNode"); if (sc) @@ -1177,7 +1182,9 @@ 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_WARN_NODE_BEGIN(s); Swig_warning(WARN_PARSE_USING_UNDEF, Getfile(s), Getline(s), "Nothing known about '%s'.\n", SwigType_namestr(Getattr(s, "uname"))); + SWIG_WARN_NODE_END(s); } s = ss; } @@ -1249,7 +1256,9 @@ 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_WARN_NODE_BEGIN(s); Swig_warning(WARN_PARSE_USING_UNDEF, Getfile(s), Getline(s), "Nothing known about '%s'.\n", SwigType_namestr(Getattr(s, "uname"))); + SWIG_WARN_NODE_END(s); } s = ss; } @@ -1300,7 +1309,9 @@ 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_WARN_NODE_BEGIN(s); Swig_warning(WARN_PARSE_USING_UNDEF, Getfile(s), Getline(s), "Nothing known about '%s'.\n", SwigType_namestr(Getattr(s, "uname"))); + SWIG_WARN_NODE_END(s); } s = ss; } @@ -1348,7 +1359,9 @@ 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_WARN_NODE_BEGIN(s); Swig_warning(WARN_PARSE_USING_UNDEF, Getfile(s), Getline(s), "Nothing known about '%s'.\n", SwigType_namestr(Getattr(s, "uname"))); + SWIG_WARN_NODE_END(s); } s = ss; } diff --git a/Source/Swig/tree.c b/Source/Swig/tree.c index 46571fc09..e2162b7f1 100644 --- a/Source/Swig/tree.c +++ b/Source/Swig/tree.c @@ -225,7 +225,7 @@ void removeNode(Node *n) { /* Delete attributes */ Delattr(n,"parentNode"); Delattr(n,"nextSibling"); - Delattr(n,"prevSibling"); + Delattr(n,"previousSibling"); } /* ----------------------------------------------------------------------------- diff --git a/Source/Swig/typemap.c b/Source/Swig/typemap.c index c0f5397c1..3273c19db 100644 --- a/Source/Swig/typemap.c +++ b/Source/Swig/typemap.c @@ -1256,6 +1256,59 @@ static String *typemap_warn(const_String_or_char_ptr tmap_method, Parm *p) { return w ? Copy(w) : 0; } +/* ----------------------------------------------------------------------------- + * typemap_merge_fragment_kwargs() + * + * If multiple 'fragment' attributes are provided to a typemap, combine them by + * concatenating with commas. + * ----------------------------------------------------------------------------- */ + +static void typemap_merge_fragment_kwargs(Parm *kw) { + Parm *reattach_kw = NULL; + Parm *prev_kw = NULL; + Parm *next_kw = NULL; + String *fragment = NULL; + while (kw) { + next_kw = nextSibling(kw); + if (Strcmp(Getattr(kw, "name"), "fragment") == 0) { + String *thisfragment = Getattr(kw, "value"); + String *kwtype = Getattr(kw, "type"); + if (!fragment) { + /* First fragment found; it should remain in the list */ + fragment = thisfragment; + prev_kw = kw; + } else { + /* Concatenate to previously found fragment */ + Printv(fragment, ",", thisfragment, NULL); + reattach_kw = prev_kw; + } + if (kwtype) { + String *mangle = Swig_string_mangle(kwtype); + Append(fragment, mangle); + Delete(mangle); + /* Remove 'type' from kwargs so it's not duplicated later */ + Setattr(kw, "type", NULL); + } + } else { + /* Not a fragment */ + if (reattach_kw) { + /* Update linked list to remove duplicate fragment */ + DohIncref(kw); + set_nextSibling(reattach_kw, kw); + set_previousSibling(kw, reattach_kw); + Delete(reattach_kw); + reattach_kw = NULL; + } + prev_kw = kw; + } + kw = next_kw; + } + if (reattach_kw) { + /* Update linked list to remove duplicate fragment */ + set_nextSibling(reattach_kw, kw); + } +} + /* ----------------------------------------------------------------------------- * Swig_typemap_lookup() * @@ -1463,6 +1516,7 @@ static String *Swig_typemap_lookup_impl(const_String_or_char_ptr tmap_method, No /* Attach kwargs - ie the typemap attributes */ kw = Getattr(tm, "kwargs"); + typemap_merge_fragment_kwargs(kw); while (kw) { String *value = Copy(Getattr(kw, "value")); String *kwtype = Getattr(kw, "type"); @@ -1577,6 +1631,7 @@ String *Swig_typemap_lookup(const_String_or_char_ptr tmap_method, Node *node, co static void typemap_attach_kwargs(Hash *tm, const_String_or_char_ptr tmap_method, Parm *firstp, int nmatch) { String *temp = NewStringEmpty(); Parm *kw = Getattr(tm, "kwargs"); + typemap_merge_fragment_kwargs(kw); while (kw) { String *value = Copy(Getattr(kw, "value")); String *type = Getattr(kw, "type"); diff --git a/Source/Swig/typeobj.c b/Source/Swig/typeobj.c index 8e64bad92..3e376fb07 100644 --- a/Source/Swig/typeobj.c +++ b/Source/Swig/typeobj.c @@ -488,6 +488,7 @@ SwigType *SwigType_del_reference(SwigType *t) { char *c = Char(t); int check = strncmp(c, "r.", 2); assert(check == 0); + (void)check; Delslice(t, 0, 2); return t; } @@ -523,6 +524,7 @@ SwigType *SwigType_del_rvalue_reference(SwigType *t) { char *c = Char(t); int check = strncmp(c, "z.", 2); assert(check == 0); + (void)check; Delslice(t, 0, 2); return t; } @@ -613,6 +615,7 @@ SwigType *SwigType_del_qualifier(SwigType *t) { char *c = Char(t); int check = strncmp(c, "q(", 2); assert(check == 0); + (void)check; Delslice(t, 0, element_size(c)); return t; } @@ -681,6 +684,7 @@ SwigType *SwigType_del_memberpointer(SwigType *t) { char *c = Char(t); int check = strncmp(c, "m(", 2); assert(check == 0); + (void)check; Delslice(t, 0, element_size(c)); return t; } @@ -725,6 +729,7 @@ SwigType *SwigType_del_array(SwigType *t) { char *c = Char(t); int check = strncmp(c, "a(", 2); assert(check == 0); + (void)check; Delslice(t, 0, element_size(c)); return t; } diff --git a/Source/Swig/typesys.c b/Source/Swig/typesys.c index 7564db1a6..d6d6bcc88 100644 --- a/Source/Swig/typesys.c +++ b/Source/Swig/typesys.c @@ -1453,11 +1453,11 @@ int SwigType_type(const SwigType *t) { return T_DOUBLE; if (strcmp(c, "long double") == 0) return T_LONGDOUBLE; - if (!cparse_cplusplus && (strcmp(c, "float complex") == 0)) + if (!cparse_cplusplus && (strcmp(c, "float _Complex") == 0)) return T_FLTCPLX; - if (!cparse_cplusplus && (strcmp(c, "double complex") == 0)) + if (!cparse_cplusplus && (strcmp(c, "double _Complex") == 0)) return T_DBLCPLX; - if (!cparse_cplusplus && (strcmp(c, "complex") == 0)) + if (!cparse_cplusplus && (strcmp(c, "_Complex") == 0)) return T_COMPLEX; if (strcmp(c, "void") == 0) return T_VOID; diff --git a/TODO b/TODO index 38ab4605d..1fcc992ac 100644 --- a/TODO +++ b/TODO @@ -201,12 +201,7 @@ PHP ** When returning wrapped objects via alternate constructors if that pointer value already exists "out there" as a resource we should use the same resource, we can't have multiple ref-counted resources - mapping to the same object in case it gets twice destroyed. And check - if ref count destroying is even working, see smart_pointer_rename - -* Work out how classes without even inherited constructors should - interact with the php "new " notation. - See: abstract_inherit_wrap.cpptest + mapping to the same object in case it gets twice destroyed. ** Look at pass by point and passby ref, Make sometype** to be auto allocated diff --git a/Tools/CI-linux-environment.sh b/Tools/CI-linux-environment.sh new file mode 100644 index 000000000..e854c5b0e --- /dev/null +++ b/Tools/CI-linux-environment.sh @@ -0,0 +1,33 @@ +#!/bin/bash +# Expected to be called from elsewhere with same variables set as CI-linux-install.sh +# e.g. RETRY=travis-retry SWIGLANG=python +# Sets up environment for using various target languages +# For Github Actions where the environment is not preserved between steps +set -e # exit on failure (same as -o errexit) + +case "$SWIGLANG" in + "go") + if [[ "$VER" ]]; then + eval "$($HOME/bin/gimme ${VER}.x)" + $HOME/bin/gimme --list + fi + ;; + "javascript") + case "$ENGINE" in + "node") + export NVM_DIR="$HOME/.nvm" + [ -s "$NVM_DIR/nvm.sh" ] && source "$NVM_DIR/nvm.sh" + nvm use ${VER} + ;; + *) ;; + esac + ;; + "ruby") + if ! command -v rvm; then + set +x + source $HOME/.rvm/scripts/rvm + set -x + fi + ;; + *) ;; +esac diff --git a/Tools/CI-linux-install.sh b/Tools/CI-linux-install.sh new file mode 100644 index 000000000..4dad7ba29 --- /dev/null +++ b/Tools/CI-linux-install.sh @@ -0,0 +1,154 @@ +#!/bin/bash +# Expected to be called from elsewhere with certain variables set +# e.g. RETRY=travis-retry SWIGLANG=python GCC=7 +set -e # exit on failure (same as -o errexit) + +if [[ -n "$GCC" ]]; then + $RETRY sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test + $RETRY sudo apt-get -qq update + $RETRY sudo apt-get install -qq g++-$GCC +else + $RETRY sudo apt-get -qq update +fi + +$RETRY sudo apt-get -qq install libboost-dev libpcre3-dev +# testflags.py needs python +$RETRY sudo apt-get install -qq python + +WITHLANG=$SWIGLANG + +case "$SWIGLANG" in + "") ;; + "csharp") + $RETRY sudo apt-get -qq install mono-devel + ;; + "d") + $RETRY wget http://downloads.dlang.org/releases/2.x/${VER}/dmd_${VER}-0_amd64.deb + $RETRY sudo dpkg -i dmd_${VER}-0_amd64.deb + ;; + "go") + if [[ "$VER" ]]; then + mkdir -p $HOME/bin + curl -sL -o $HOME/bin/gimme https://raw.githubusercontent.com/travis-ci/gimme/master/gimme + chmod +x $HOME/bin/gimme + eval "$($HOME/bin/gimme ${VER}.x)" + $HOME/bin/gimme --list + fi + ;; + "javascript") + case "$ENGINE" in + "node") + $RETRY wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.10/install.sh | bash + export NVM_DIR="$HOME/.nvm" + [ -s "$NVM_DIR/nvm.sh" ] && source "$NVM_DIR/nvm.sh" + $RETRY nvm install ${VER} + nvm use ${VER} + if [ "$VER" == "0.10" ] || [ "$VER" == "0.12" ] || [ "$VER" == "4" ] || [ "$VER" == "6" ] ; then +# $RETRY sudo apt-get install -qq nodejs node-gyp + $RETRY npm install -g node-gyp@$VER + elif [ "$VER" == "8" ] ; then + $RETRY npm install -g node-gyp@6 + elif [ "$VER" == "10" ] || [ "$VER" == "12" ] || [ "$VER" == "14" ] || [ "$VER" == "16" ]; then + $RETRY npm install -g node-gyp@7 + else + $RETRY npm install -g node-gyp + fi + ;; + "jsc") + $RETRY sudo apt-get install -qq libjavascriptcoregtk-4.0-dev + ;; + "v8") + $RETRY sudo apt-get install -qq libv8-dev + ;; + esac + ;; + "guile") + $RETRY sudo apt-get -qq install guile-2.0-dev + ;; + "lua") + if [[ -z "$VER" ]]; then + $RETRY sudo apt-get -qq install lua5.2 liblua5.2-dev + else + $RETRY sudo apt-get -qq install lua${VER} liblua${VER}-dev + fi + ;; + "mzscheme") + $RETRY sudo apt-get -qq install racket + ;; + "ocaml") + $RETRY sudo apt-get -qq install ocaml camlp4 + ;; + "octave") + if [[ "$VER" ]]; then + $RETRY sudo add-apt-repository -y ppa:devacom/science + $RETRY sudo apt-get -qq update + $RETRY sudo apt-get -qq install "liboctave-dev=$VER.*" + else + $RETRY sudo apt-get -qq update + $RETRY sudo apt-get -qq install liboctave-dev + fi + ;; + "php") + if [[ "$VER" ]]; then + $RETRY sudo apt-get -qq remove "php*-cli" "php*-dev" # Multiple versions are pre-installed + $RETRY sudo add-apt-repository -y ppa:ondrej/php + $RETRY sudo apt-get -qq update + $RETRY sudo apt-get -qq install php$VER-cli php$VER-dev + fi + ;; + "python") + pip install --user pycodestyle + if [[ "$VER" ]]; then + $RETRY sudo add-apt-repository -y ppa:deadsnakes/ppa + $RETRY sudo apt-get -qq update + $RETRY sudo apt-get -qq install python${VER}-dev + WITHLANG=$SWIGLANG$PY3=$SWIGLANG$VER + else + $RETRY sudo apt-get install -qq python${PY3}-dev + WITHLANG=$SWIGLANG$PY3 + fi + ;; + "r") + $RETRY sudo apt-get -qq install r-base + ;; + "ruby") + if ! command -v rvm; then + case "$VER" in + 1.9 | 2.0 | 2.1 | 2.2 | 2.3 ) + $RETRY sudo apt-get -qq install libgdbm-dev libncurses5-dev libyaml-dev libssl1.0-dev + ;; + esac + # YOLO + curl -sSL https://rvm.io/mpapis.asc | gpg --import - + curl -sSL https://rvm.io/pkuczynski.asc | gpg --import - + curl -sSL https://get.rvm.io | bash -s stable + set +x + source $HOME/.rvm/scripts/rvm + set -x + fi + if [[ "$VER" == "2.7" || "$VER" == "3.0" ]]; then + # Ruby 2.7+ support is currently only rvm master (30 Dec 2019) + $RETRY rvm get master + rvm reload + rvm list known + fi + if [[ "$VER" ]]; then + $RETRY rvm install $VER + fi + ;; + "scilab") + if [[ -z "$VER" ]]; then + $RETRY sudo apt-get -qq install scilab + else + $RETRY wget --progress=dot:giga "https://www.scilab.org/download/$VER/scilab-$VER.bin.linux-x86_64.tar.gz" + # $HOME/.local/bin is in PATH and writeable + mkdir -p "$HOME/.local" + tar -xzf "scilab-$VER.bin.linux-x86_64.tar.gz" --strip-components=1 -C "$HOME/.local" + fi + ;; + "tcl") + $RETRY sudo apt-get -qq install tcl-dev + ;; +esac + +set +e # turn off exit on failure (same as +o errexit) diff --git a/Tools/GHA-linux-install.sh b/Tools/GHA-linux-install.sh new file mode 100644 index 000000000..ea2108fce --- /dev/null +++ b/Tools/GHA-linux-install.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +#lsb_release -a +# find location of current script (only works in bash) +script_dir="$( dirname "${BASH_SOURCE[0]}")" + +# run generic script +RETRY= +source "$script_dir"/CI-linux-install.sh diff --git a/Tools/brew-install b/Tools/brew-install deleted file mode 100755 index 408ae13bb..000000000 --- a/Tools/brew-install +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/bash - -# Wrapper around 'brew install' emitting a message every minute if the command is still running. -# This is used on Travis to ensure the install isn't killed when there is no output over a long period (10 minutes). -# Usage: brew-install package, where package is the name of the package for brew to install. - -seconds=0 -minutes=0 -brew install $1 & -while true; do - ps -p$! 2>& 1>/dev/null - if [ $? = 0 ]; then - if [ $seconds = 60 ]; then - let seconds=0 - let minutes=minutes+1 - echo "brew install $1 still running ($minutes min)" - fi - sleep 1 - let seconds=seconds+1 - else - break - fi -done -wait $! -exit $? diff --git a/Tools/check-include-path.pike b/Tools/check-include-path.pike deleted file mode 100644 index 2bfb2b901..000000000 --- a/Tools/check-include-path.pike +++ /dev/null @@ -1,20 +0,0 @@ -/** - * This is a helper script to identify the proper include path - * for Pike header files. It should be run with the full path - * to the Pike executable as its single argument, e.g. - * - * pike check-include-path.pike /usr/local/bin/pike - * - * and its output should be the correct path to the header - * files, e.g. - * - * /usr/local/pike/7.2.239/include/pike - * - */ - -int main(int argc, array(string) argv) -{ - string prefix = replace(argv[1], "/bin/pike", ""); - write(prefix + "/pike/" + __MAJOR__ + "." + __MINOR__ + "." + __BUILD__ + "/include/pike"); - return 0; -} diff --git a/Tools/cmake/FindPCRE2.cmake b/Tools/cmake/FindPCRE2.cmake new file mode 100644 index 000000000..08c216347 --- /dev/null +++ b/Tools/cmake/FindPCRE2.cmake @@ -0,0 +1,21 @@ +# - Find PCRE2 +# Perl Compatible Regular Expressions +# https://www.pcre.org/ + +# The following variables are set: +# PCRE2_FOUND - System has the PCRE library +# PCRE2_LIBRARIES - The PCRE library file +# PCRE2_INCLUDE_DIRS - The folder with the PCRE headers + +find_library(PCRE2_LIBRARY NAMES pcre2 pcre2-8) +find_path(PCRE2_INCLUDE_DIR pcre2.h) + +set (PCRE2_LIBRARIES ${PCRE2_LIBRARY}) +set (PCRE2_INCLUDE_DIRS ${PCRE2_INCLUDE_DIR}) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(PCRE2 DEFAULT_MSG PCRE2_LIBRARIES PCRE2_INCLUDE_DIRS) + +mark_as_advanced ( + PCRE2_LIBRARY + PCRE2_INCLUDE_DIR) diff --git a/Tools/cmake/swigconfig.h.in b/Tools/cmake/swigconfig.h.in new file mode 100644 index 000000000..94cee1646 --- /dev/null +++ b/Tools/cmake/swigconfig.h.in @@ -0,0 +1,95 @@ +/* swigconfig.h. Generated by cmake from Tools/cmake/swigconfig.h.in */ + +/* define if the Boost library is available */ +#cmakedefine HAVE_BOOST 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the `dl' library (-ldl). */ +#cmakedefine HAVE_LIBDL 1 + +/* Define to 1 if you have the `dld' library (-ldld). */ +#cmakedefine HAVE_LIBDLD 1 + +/* Define if you have PCRE library */ +#cmakedefine HAVE_PCRE 1 + +/* Define if popen is available */ +#cmakedefine HAVE_POPEN 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STDIO_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STDLIB_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STRING_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_UNISTD_H 1 + +/* Name of package */ +#define PACKAGE "swig" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "http://www.swig.org" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "swig" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "swig @SWIG_VERSION@" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "swig" + +/* Define to the home page for this package. */ +#define PACKAGE_URL "" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "@SWIG_VERSION@" + +/* The size of `void *', as computed by sizeof. */ +/* #undef SIZEOF_VOID_P */ + +/* Define to 1 if all of the C90 standard headers exist (not just the ones + required in a freestanding environment). This macro is provided for + backward compatibility; new code need not use it. */ +#cmakedefine STDC_HEADERS 1 + +/* Compiler that built SWIG */ +#define SWIG_CXX "@CMAKE_CXX_COMPILER@" + +/* Directory for SWIG system-independent libraries */ +#define SWIG_LIB "@CMAKE_INSTALL_PREFIX@/@SWIG_LIB@" + +/* Directory for SWIG system-independent libraries (Unix install on native + Windows) */ +#define SWIG_LIB_WIN_UNIX "@SWIG_LIB_WIN_UNIX@" + +/* Platform that SWIG is built for */ +#define SWIG_PLATFORM "@CMAKE_SYSTEM_NAME@" + +/* Version number of package */ +#define VERSION "@SWIG_VERSION@" + + +/* Deal with attempt by Microsoft to deprecate C standard runtime functions */ +#if defined(_MSC_VER) +# define _CRT_SECURE_NO_DEPRECATE +#endif + diff --git a/Tools/config/ac_compile_warnings.m4 b/Tools/config/ac_compile_warnings.m4 index 7e4239a3c..04f146387 100644 --- a/Tools/config/ac_compile_warnings.m4 +++ b/Tools/config/ac_compile_warnings.m4 @@ -34,7 +34,7 @@ AC_MSG_CHECKING([maximum warning verbosity option]) then if test "$GXX" = "yes" then - ac_compile_warnings_opt='-Wall -W -ansi -pedantic' + ac_compile_warnings_opt='-Wall -W -pedantic' fi CXXFLAGS="$CXXFLAGS $ac_compile_warnings_opt" ac_compile_warnings_msg="$ac_compile_warnings_opt for C++" @@ -44,7 +44,7 @@ AC_MSG_CHECKING([maximum warning verbosity option]) then if test "$GCC" = "yes" then - ac_compile_warnings_opt='-Wall -W -ansi -pedantic' + ac_compile_warnings_opt='-Wall -W -pedantic' fi CFLAGS="$CFLAGS $ac_compile_warnings_opt" ac_compile_warnings_msg="$ac_compile_warnings_msg $ac_compile_warnings_opt for C" diff --git a/Tools/config/ax_boost_base.m4 b/Tools/config/ax_boost_base.m4 index f5a935cd6..94fb2a0d4 100644 --- a/Tools/config/ax_boost_base.m4 +++ b/Tools/config/ax_boost_base.m4 @@ -10,7 +10,7 @@ # # Test for the Boost C++ libraries of a particular version (or newer) # -# If no path to the installed boost library is given the macro searchs +# If no path to the installed boost library is given the macro searches # under /usr, /usr/local, /opt and /opt/local and evaluates the # $BOOST_ROOT environment variable. Further documentation is available at # . diff --git a/Tools/config/ax_cxx_compile_stdcxx_11.m4 b/Tools/config/ax_cxx_compile_stdcxx_11.m4 deleted file mode 100644 index 138ca2aca..000000000 --- a/Tools/config/ax_cxx_compile_stdcxx_11.m4 +++ /dev/null @@ -1,121 +0,0 @@ -# ============================================================================ -# http://www.gnu.org/software/autoconf-archive/ax_cxx_compile_stdcxx_11.html -# ============================================================================ -# -# SYNOPSIS -# -# AX_CXX_COMPILE_STDCXX_11([ext|noext], [nostop]) -# -# DESCRIPTION -# -# Check for baseline language coverage in the compiler for the C++11 -# standard; if necessary, add switches to CXXFLAGS to enable support. -# CXX11FLAGS will also contain any necessary switches to enable support. -# HAVE_CXX11_COMPILER will additionally be set to yes if there is support. -# If the second argument is not specified, errors out if no mode that -# supports C++11 baseline syntax can be found. The first argument, if -# specified, indicates whether you insist on an extended mode -# (e.g. -std=gnu++11) or a strict conformance mode (e.g. -std=c++11). -# If neither is specified, you get whatever works, with preference for an -# extended mode. -# -# LICENSE -# -# Copyright (c) 2008 Benjamin Kosnik -# Copyright (c) 2012 Zack Weinberg -# Copyright (c) 2012 William Fulton -# -# Copying and distribution of this file, with or without modification, are -# permitted in any medium without royalty provided the copyright notice -# and this notice are preserved. This file is offered as-is, without any -# warranty. - -#serial 1 - -m4_define([_AX_CXX_COMPILE_STDCXX_11_testbody], [ - template - struct check - { - static_assert(sizeof(int) <= sizeof(T), "not big enough"); - }; - - typedef check> right_angle_brackets; - - int a; - decltype(a) b; - - typedef check check_type; - check_type c; - check_type&& cr = static_cast(c); -]) - -AC_DEFUN([AX_CXX_COMPILE_STDCXX_11], [dnl - m4_if([$1], [], [], - [$1], [ext], [], - [$1], [noext], [], - [m4_fatal([invalid argument `$1' to AX_CXX_COMPILE_STDCXX_11])])dnl - m4_if([$2], [], [], - [$2], [nostop], [], - [m4_fatal([invalid argument `$2' to AX_CXX_COMPILE_STDCXX_11])])dnl - AC_LANG_ASSERT([C++])dnl - ac_success=no - CXX11FLAGS= - AC_CACHE_CHECK(whether $CXX supports C++11 features by default, - ax_cv_cxx_compile_cxx11, - [AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_11_testbody])], - [ax_cv_cxx_compile_cxx11=yes], - [ax_cv_cxx_compile_cxx11=no])]) - if test x$ax_cv_cxx_compile_cxx11 = xyes; then - ac_success=yes - fi - - m4_if([$1], [noext], [], [dnl - if test x$ac_success = xno; then - for switch in -std=gnu++11 -std=gnu++0x; do - cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx11_$switch]) - AC_CACHE_CHECK(whether $CXX supports C++11 features with $switch, - $cachevar, - [ac_save_CXXFLAGS="$CXXFLAGS" - CXXFLAGS="$CXXFLAGS $switch" - AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_11_testbody])], - [eval $cachevar=yes], - [eval $cachevar=no]) - CXXFLAGS="$ac_save_CXXFLAGS"]) - if eval test x\$$cachevar = xyes; then - CXXFLAGS="$CXXFLAGS $switch" - CXX11FLAGS=$switch - ac_success=yes - break - fi - done - fi]) - - m4_if([$1], [ext], [], [dnl - if test x$ac_success = xno; then - for switch in -std=c++11 -std=c++0x; do - cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx11_$switch]) - AC_CACHE_CHECK(whether $CXX supports C++11 features with $switch, - $cachevar, - [ac_save_CXXFLAGS="$CXXFLAGS" - CXXFLAGS="$CXXFLAGS $switch" - AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_11_testbody])], - [eval $cachevar=yes], - [eval $cachevar=no]) - CXXFLAGS="$ac_save_CXXFLAGS"]) - if eval test x\$$cachevar = xyes; then - CXXFLAGS="$CXXFLAGS $switch" - CXX11FLAGS=$switch - ac_success=yes - break - fi - done - fi]) - - if test x$ac_success = xno; then - if test x$2 != xnostop; then - AC_MSG_ERROR([*** A compiler with support for C++11 language features is required.]) - fi - else - HAVE_CXX11_COMPILER=yes - fi -]) diff --git a/Tools/config/m4_ax_cxx_compile_stdcxx.m4 b/Tools/config/m4_ax_cxx_compile_stdcxx.m4 new file mode 100644 index 000000000..9413da624 --- /dev/null +++ b/Tools/config/m4_ax_cxx_compile_stdcxx.m4 @@ -0,0 +1,962 @@ +# =========================================================================== +# https://www.gnu.org/software/autoconf-archive/ax_cxx_compile_stdcxx.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_CXX_COMPILE_STDCXX(VERSION, [ext|noext], [mandatory|optional]) +# +# DESCRIPTION +# +# Check for baseline language coverage in the compiler for the specified +# version of the C++ standard. If necessary, add switches to CXX and +# CXXCPP to enable support. VERSION may be '11' (for the C++11 standard) +# or '14' (for the C++14 standard). +# +# The second argument, if specified, indicates whether you insist on an +# extended mode (e.g. -std=gnu++11) or a strict conformance mode (e.g. +# -std=c++11). If neither is specified, you get whatever works, with +# preference for no added switch, and then for an extended mode. +# +# The third argument, if specified 'mandatory' or if left unspecified, +# indicates that baseline support for the specified C++ standard is +# required and that the macro should error out if no mode with that +# support is found. If specified 'optional', then configuration proceeds +# regardless, after defining HAVE_CXX${VERSION} if and only if a +# supporting mode is found. +# +# LICENSE +# +# Copyright (c) 2008 Benjamin Kosnik +# Copyright (c) 2012 Zack Weinberg +# Copyright (c) 2013 Roy Stogner +# Copyright (c) 2014, 2015 Google Inc.; contributed by Alexey Sokolov +# Copyright (c) 2015 Paul Norman +# Copyright (c) 2015 Moritz Klammler +# Copyright (c) 2016, 2018 Krzesimir Nowak +# Copyright (c) 2019 Enji Cooper +# Copyright (c) 2020 Jason Merrill +# +# Copying and distribution of this file, with or without modification, are +# permitted in any medium without royalty provided the copyright notice +# and this notice are preserved. This file is offered as-is, without any +# warranty. + +#serial 12 + +dnl This macro is based on the code from the AX_CXX_COMPILE_STDCXX_11 macro +dnl (serial version number 13). + +AC_DEFUN([AX_CXX_COMPILE_STDCXX], [dnl + m4_if([$1], [11], [ax_cxx_compile_alternatives="11 0x"], + [$1], [14], [ax_cxx_compile_alternatives="14 1y"], + [$1], [17], [ax_cxx_compile_alternatives="17 1z"], + [m4_fatal([invalid first argument `$1' to AX_CXX_COMPILE_STDCXX])])dnl + m4_if([$2], [], [], + [$2], [ext], [], + [$2], [noext], [], + [m4_fatal([invalid second argument `$2' to AX_CXX_COMPILE_STDCXX])])dnl + m4_if([$3], [], [ax_cxx_compile_cxx$1_required=true], + [$3], [mandatory], [ax_cxx_compile_cxx$1_required=true], + [$3], [optional], [ax_cxx_compile_cxx$1_required=false], + [m4_fatal([invalid third argument `$3' to AX_CXX_COMPILE_STDCXX])]) + AC_LANG_PUSH([C++])dnl + ac_success=no + + m4_if([$2], [], [dnl + AC_CACHE_CHECK(whether $CXX supports C++$1 features by default, + ax_cv_cxx_compile_cxx$1, + [AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])], + [ax_cv_cxx_compile_cxx$1=yes], + [ax_cv_cxx_compile_cxx$1=no])]) + if test x$ax_cv_cxx_compile_cxx$1 = xyes; then + ac_success=yes + fi]) + + m4_if([$2], [noext], [], [dnl + if test x$ac_success = xno; then + for alternative in ${ax_cxx_compile_alternatives}; do + switch="-std=gnu++${alternative}" + cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx$1_$switch]) + AC_CACHE_CHECK(whether $CXX supports C++$1 features with $switch, + $cachevar, + [ac_save_CXX="$CXX" + CXX="$CXX $switch" + AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])], + [eval $cachevar=yes], + [eval $cachevar=no]) + CXX="$ac_save_CXX"]) + if eval test x\$$cachevar = xyes; then + CXX="$CXX $switch" + if test -n "$CXXCPP" ; then + CXXCPP="$CXXCPP $switch" + fi + ac_success=yes + break + fi + done + fi]) + + m4_if([$2], [ext], [], [dnl + if test x$ac_success = xno; then + dnl HP's aCC needs +std=c++11 according to: + dnl http://h21007.www2.hp.com/portal/download/files/unprot/aCxx/PDF_Release_Notes/769149-001.pdf + dnl Cray's crayCC needs "-h std=c++11" + for alternative in ${ax_cxx_compile_alternatives}; do + for switch in -std=c++${alternative} +std=c++${alternative} "-h std=c++${alternative}"; do + cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx$1_$switch]) + AC_CACHE_CHECK(whether $CXX supports C++$1 features with $switch, + $cachevar, + [ac_save_CXX="$CXX" + CXX="$CXX $switch" + AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])], + [eval $cachevar=yes], + [eval $cachevar=no]) + CXX="$ac_save_CXX"]) + if eval test x\$$cachevar = xyes; then + CXX="$CXX $switch" + if test -n "$CXXCPP" ; then + CXXCPP="$CXXCPP $switch" + fi + ac_success=yes + break + fi + done + if test x$ac_success = xyes; then + break + fi + done + fi]) + AC_LANG_POP([C++]) + if test x$ax_cxx_compile_cxx$1_required = xtrue; then + if test x$ac_success = xno; then + AC_MSG_ERROR([*** A compiler with support for C++$1 language features is required.]) + fi + fi + if test x$ac_success = xno; then + HAVE_CXX$1=0 + AC_MSG_NOTICE([No compiler with C++$1 support was found]) + else + HAVE_CXX$1=1 + AC_DEFINE(HAVE_CXX$1,1, + [define if the compiler supports basic C++$1 syntax]) + fi + AC_SUBST(HAVE_CXX$1) +]) + + +dnl Test body for checking C++11 support + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_11], + _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 +) + + +dnl Test body for checking C++14 support + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_14], + _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 +) + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_17], + _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_17 +) + +dnl Tests for new features in C++11 + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_11], [[ + +// If the compiler admits that it is not ready for C++11, why torture it? +// Hopefully, this will speed up the test. + +#ifndef __cplusplus + +#error "This is not a C++ compiler" + +#elif __cplusplus < 201103L + +#error "This is not a C++11 compiler" + +#else + +namespace cxx11 +{ + + namespace test_static_assert + { + + template + struct check + { + static_assert(sizeof(int) <= sizeof(T), "not big enough"); + }; + + } + + namespace test_final_override + { + + struct Base + { + virtual ~Base() {} + virtual void f() {} + }; + + struct Derived : public Base + { + virtual ~Derived() override {} + virtual void f() override {} + }; + + } + + namespace test_double_right_angle_brackets + { + + template < typename T > + struct check {}; + + typedef check single_type; + typedef check> double_type; + typedef check>> triple_type; + typedef check>>> quadruple_type; + + } + + namespace test_decltype + { + + int + f() + { + int a = 1; + decltype(a) b = 2; + return a + b; + } + + } + + namespace test_type_deduction + { + + template < typename T1, typename T2 > + struct is_same + { + static const bool value = false; + }; + + template < typename T > + struct is_same + { + static const bool value = true; + }; + + template < typename T1, typename T2 > + auto + add(T1 a1, T2 a2) -> decltype(a1 + a2) + { + return a1 + a2; + } + + int + test(const int c, volatile int v) + { + static_assert(is_same::value == true, ""); + static_assert(is_same::value == false, ""); + static_assert(is_same::value == false, ""); + auto ac = c; + auto av = v; + auto sumi = ac + av + 'x'; + auto sumf = ac + av + 1.0; + static_assert(is_same::value == true, ""); + static_assert(is_same::value == true, ""); + static_assert(is_same::value == true, ""); + static_assert(is_same::value == false, ""); + static_assert(is_same::value == true, ""); + return (sumf > 0.0) ? sumi : add(c, v); + } + + } + + namespace test_noexcept + { + + int f() { return 0; } + int g() noexcept { return 0; } + + static_assert(noexcept(f()) == false, ""); + static_assert(noexcept(g()) == true, ""); + + } + + namespace test_constexpr + { + + template < typename CharT > + unsigned long constexpr + strlen_c_r(const CharT *const s, const unsigned long acc) noexcept + { + return *s ? strlen_c_r(s + 1, acc + 1) : acc; + } + + template < typename CharT > + unsigned long constexpr + strlen_c(const CharT *const s) noexcept + { + return strlen_c_r(s, 0UL); + } + + static_assert(strlen_c("") == 0UL, ""); + static_assert(strlen_c("1") == 1UL, ""); + static_assert(strlen_c("example") == 7UL, ""); + static_assert(strlen_c("another\0example") == 7UL, ""); + + } + + namespace test_rvalue_references + { + + template < int N > + struct answer + { + static constexpr int value = N; + }; + + answer<1> f(int&) { return answer<1>(); } + answer<2> f(const int&) { return answer<2>(); } + answer<3> f(int&&) { return answer<3>(); } + + void + test() + { + int i = 0; + const int c = 0; + static_assert(decltype(f(i))::value == 1, ""); + static_assert(decltype(f(c))::value == 2, ""); + static_assert(decltype(f(0))::value == 3, ""); + } + + } + + namespace test_uniform_initialization + { + + struct test + { + static const int zero {}; + static const int one {1}; + }; + + static_assert(test::zero == 0, ""); + static_assert(test::one == 1, ""); + + } + + namespace test_lambdas + { + + void + test1() + { + auto lambda1 = [](){}; + auto lambda2 = lambda1; + lambda1(); + lambda2(); + } + + int + test2() + { + auto a = [](int i, int j){ return i + j; }(1, 2); + auto b = []() -> int { return '0'; }(); + auto c = [=](){ return a + b; }(); + auto d = [&](){ return c; }(); + auto e = [a, &b](int x) mutable { + const auto identity = [](int y){ return y; }; + for (auto i = 0; i < a; ++i) + a += b--; + return x + identity(a + b); + }(0); + return a + b + c + d + e; + } + + int + test3() + { + const auto nullary = [](){ return 0; }; + const auto unary = [](int x){ return x; }; + using nullary_t = decltype(nullary); + using unary_t = decltype(unary); + const auto higher1st = [](nullary_t f){ return f(); }; + const auto higher2nd = [unary](nullary_t f1){ + return [unary, f1](unary_t f2){ return f2(unary(f1())); }; + }; + return higher1st(nullary) + higher2nd(nullary)(unary); + } + + } + + namespace test_variadic_templates + { + + template + struct sum; + + template + struct sum + { + static constexpr auto value = N0 + sum::value; + }; + + template <> + struct sum<> + { + static constexpr auto value = 0; + }; + + static_assert(sum<>::value == 0, ""); + static_assert(sum<1>::value == 1, ""); + static_assert(sum<23>::value == 23, ""); + static_assert(sum<1, 2>::value == 3, ""); + static_assert(sum<5, 5, 11>::value == 21, ""); + static_assert(sum<2, 3, 5, 7, 11, 13>::value == 41, ""); + + } + + // http://stackoverflow.com/questions/13728184/template-aliases-and-sfinae + // Clang 3.1 fails with headers of libstd++ 4.8.3 when using std::function + // because of this. + namespace test_template_alias_sfinae + { + + struct foo {}; + + template + using member = typename T::member_type; + + template + void func(...) {} + + template + void func(member*) {} + + void test(); + + void test() { func(0); } + + } + +} // namespace cxx11 + +#endif // __cplusplus >= 201103L + +]]) + + +dnl Tests for new features in C++14 + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_14], [[ + +// If the compiler admits that it is not ready for C++14, why torture it? +// Hopefully, this will speed up the test. + +#ifndef __cplusplus + +#error "This is not a C++ compiler" + +#elif __cplusplus < 201402L + +#error "This is not a C++14 compiler" + +#else + +namespace cxx14 +{ + + namespace test_polymorphic_lambdas + { + + int + test() + { + const auto lambda = [](auto&&... args){ + const auto istiny = [](auto x){ + return (sizeof(x) == 1UL) ? 1 : 0; + }; + const int aretiny[] = { istiny(args)... }; + return aretiny[0]; + }; + return lambda(1, 1L, 1.0f, '1'); + } + + } + + namespace test_binary_literals + { + + constexpr auto ivii = 0b0000000000101010; + static_assert(ivii == 42, "wrong value"); + + } + + namespace test_generalized_constexpr + { + + template < typename CharT > + constexpr unsigned long + strlen_c(const CharT *const s) noexcept + { + auto length = 0UL; + for (auto p = s; *p; ++p) + ++length; + return length; + } + + static_assert(strlen_c("") == 0UL, ""); + static_assert(strlen_c("x") == 1UL, ""); + static_assert(strlen_c("test") == 4UL, ""); + static_assert(strlen_c("another\0test") == 7UL, ""); + + } + + namespace test_lambda_init_capture + { + + int + test() + { + auto x = 0; + const auto lambda1 = [a = x](int b){ return a + b; }; + const auto lambda2 = [a = lambda1(x)](){ return a; }; + return lambda2(); + } + + } + + namespace test_digit_separators + { + + constexpr auto ten_million = 100'000'000; + static_assert(ten_million == 100000000, ""); + + } + + namespace test_return_type_deduction + { + + auto f(int& x) { return x; } + decltype(auto) g(int& x) { return x; } + + template < typename T1, typename T2 > + struct is_same + { + static constexpr auto value = false; + }; + + template < typename T > + struct is_same + { + static constexpr auto value = true; + }; + + int + test() + { + auto x = 0; + static_assert(is_same::value, ""); + static_assert(is_same::value, ""); + return x; + } + + } + +} // namespace cxx14 + +#endif // __cplusplus >= 201402L + +]]) + + +dnl Tests for new features in C++17 + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_17], [[ + +// If the compiler admits that it is not ready for C++17, why torture it? +// Hopefully, this will speed up the test. + +#ifndef __cplusplus + +#error "This is not a C++ compiler" + +#elif __cplusplus < 201703L + +#error "This is not a C++17 compiler" + +#else + +#include +#include +#include + +namespace cxx17 +{ + + namespace test_constexpr_lambdas + { + + constexpr int foo = [](){return 42;}(); + + } + + namespace test::nested_namespace::definitions + { + + } + + namespace test_fold_expression + { + + template + int multiply(Args... args) + { + return (args * ... * 1); + } + + template + bool all(Args... args) + { + return (args && ...); + } + + } + + namespace test_extended_static_assert + { + + static_assert (true); + + } + + namespace test_auto_brace_init_list + { + + auto foo = {5}; + auto bar {5}; + + static_assert(std::is_same, decltype(foo)>::value); + static_assert(std::is_same::value); + } + + namespace test_typename_in_template_template_parameter + { + + template typename X> struct D; + + } + + namespace test_fallthrough_nodiscard_maybe_unused_attributes + { + + int f1() + { + return 42; + } + + [[nodiscard]] int f2() + { + [[maybe_unused]] auto unused = f1(); + + switch (f1()) + { + case 17: + f1(); + [[fallthrough]]; + case 42: + f1(); + } + return f1(); + } + + } + + namespace test_extended_aggregate_initialization + { + + struct base1 + { + int b1, b2 = 42; + }; + + struct base2 + { + base2() { + b3 = 42; + } + int b3; + }; + + struct derived : base1, base2 + { + int d; + }; + + derived d1 {{1, 2}, {}, 4}; // full initialization + derived d2 {{}, {}, 4}; // value-initialized bases + + } + + namespace test_general_range_based_for_loop + { + + struct iter + { + int i; + + int& operator* () + { + return i; + } + + const int& operator* () const + { + return i; + } + + iter& operator++() + { + ++i; + return *this; + } + }; + + struct sentinel + { + int i; + }; + + bool operator== (const iter& i, const sentinel& s) + { + return i.i == s.i; + } + + bool operator!= (const iter& i, const sentinel& s) + { + return !(i == s); + } + + struct range + { + iter begin() const + { + return {0}; + } + + sentinel end() const + { + return {5}; + } + }; + + void f() + { + range r {}; + + for (auto i : r) + { + [[maybe_unused]] auto v = i; + } + } + + } + + namespace test_lambda_capture_asterisk_this_by_value + { + + struct t + { + int i; + int foo() + { + return [*this]() + { + return i; + }(); + } + }; + + } + + namespace test_enum_class_construction + { + + enum class byte : unsigned char + {}; + + byte foo {42}; + + } + + namespace test_constexpr_if + { + + template + int f () + { + if constexpr(cond) + { + return 13; + } + else + { + return 42; + } + } + + } + + namespace test_selection_statement_with_initializer + { + + int f() + { + return 13; + } + + int f2() + { + if (auto i = f(); i > 0) + { + return 3; + } + + switch (auto i = f(); i + 4) + { + case 17: + return 2; + + default: + return 1; + } + } + + } + + namespace test_template_argument_deduction_for_class_templates + { + + template + struct pair + { + pair (T1 p1, T2 p2) + : m1 {p1}, + m2 {p2} + {} + + T1 m1; + T2 m2; + }; + + void f() + { + [[maybe_unused]] auto p = pair{13, 42u}; + } + + } + + namespace test_non_type_auto_template_parameters + { + + template + struct B + {}; + + B<5> b1; + B<'a'> b2; + + } + + namespace test_structured_bindings + { + + int arr[2] = { 1, 2 }; + std::pair pr = { 1, 2 }; + + auto f1() -> int(&)[2] + { + return arr; + } + + auto f2() -> std::pair& + { + return pr; + } + + struct S + { + int x1 : 2; + volatile double y1; + }; + + S f3() + { + return {}; + } + + auto [ x1, y1 ] = f1(); + auto& [ xr1, yr1 ] = f1(); + auto [ x2, y2 ] = f2(); + auto& [ xr2, yr2 ] = f2(); + const auto [ x3, y3 ] = f3(); + + } + + namespace test_exception_spec_type_system + { + + struct Good {}; + struct Bad {}; + + void g1() noexcept; + void g2(); + + template + Bad + f(T*, T*); + + template + Good + f(T1*, T2*); + + static_assert (std::is_same_v); + + } + + namespace test_inline_variables + { + + template void f(T) + {} + + template inline T g(T) + { + return T{}; + } + + template<> inline void f<>(int) + {} + + template<> int g<>(int) + { + return 5; + } + + } + +} // namespace cxx17 + +#endif // __cplusplus < 201703L + +]]) diff --git a/Tools/javascript/Makefile.in b/Tools/javascript/Makefile.in index 5eeec0785..6335d0a65 100644 --- a/Tools/javascript/Makefile.in +++ b/Tools/javascript/Makefile.in @@ -32,12 +32,6 @@ JSCENABLED = @JSCENABLED@ srcdir = @srcdir@ -ifneq (, $(V8_VERSION)) - JSV8_VERSION=$(V8_VERSION) -else - JSV8_VERSION=0x031110 -endif - # Regenerate Makefile if Makefile.in or config.status have changed. Makefile: $(srcdir)/Makefile.in ../../config.status cd ../.. && $(SHELL) ./config.status Tools/javascript/Makefile @@ -45,7 +39,7 @@ Makefile: $(srcdir)/Makefile.in ../../config.status # These settings are provided by 'configure' (see '/configure.in') ifeq (1, $(JSV8ENABLED)) JS_INTERPRETER_SRC_V8 = v8_shell.cxx -JS_INTERPRETER_ENABLE_V8 = -DENABLE_V8 -DSWIG_V8_VERSION=$(JSV8_VERSION) -DV8_DEPRECATION_WARNINGS +JS_INTERPRETER_ENABLE_V8 = -DENABLE_V8 -DV8_DEPRECATION_WARNINGS endif ifeq (1, $(JSCENABLED)) diff --git a/Tools/javascript/jsc_shell.cxx b/Tools/javascript/jsc_shell.cxx index 292c4042b..f17744ad6 100644 --- a/Tools/javascript/jsc_shell.cxx +++ b/Tools/javascript/jsc_shell.cxx @@ -18,7 +18,7 @@ typedef int (*JSCIntializer)(JSGlobalContextRef context, JSObjectRef *module); public: - JSCShell() {}; + JSCShell() { context = 0; } virtual ~JSCShell(); diff --git a/Tools/javascript/v8_shell.cxx b/Tools/javascript/v8_shell.cxx index 5001bc25a..336edb2a6 100644 --- a/Tools/javascript/v8_shell.cxx +++ b/Tools/javascript/v8_shell.cxx @@ -13,57 +13,24 @@ typedef int (*V8ExtensionInitializer) (v8::Handle module); // Note: these typedefs and defines are used to deal with v8 API changes since version 3.19.00 -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) -typedef v8::Handle SwigV8ReturnValue; -typedef v8::Arguments SwigV8Arguments; -typedef v8::AccessorInfo SwigV8PropertyCallbackInfo; -#define SWIGV8_RETURN(val) return scope.Close(val) -#define SWIGV8_RETURN_INFO(val, info) return scope.Close(val) -#else typedef void SwigV8ReturnValue; typedef v8::FunctionCallbackInfo SwigV8Arguments; typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfo; #define SWIGV8_RETURN(val) args.GetReturnValue().Set(val); return #define SWIGV8_RETURN_INFO(val, info) info.GetReturnValue().Set(val); return -#endif - -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032117) -#define SWIGV8_HANDLESCOPE() v8::HandleScope scope -#define SWIGV8_HANDLESCOPE_ESC() v8::HandleScope scope -#define SWIGV8_ESCAPE(val) return scope.Close(val) -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032318) -#define SWIGV8_HANDLESCOPE() v8::HandleScope scope(v8::Isolate::GetCurrent()); -#define SWIGV8_HANDLESCOPE_ESC() v8::HandleScope scope(v8::Isolate::GetCurrent()); -#define SWIGV8_ESCAPE(val) return scope.Close(val) -#else #define SWIGV8_HANDLESCOPE() v8::HandleScope scope(v8::Isolate::GetCurrent()); #define SWIGV8_HANDLESCOPE_ESC() v8::EscapableHandleScope scope(v8::Isolate::GetCurrent()); #define SWIGV8_ESCAPE(val) return scope.Escape(val) -#endif -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032318) -#define SWIGV8_CURRENT_CONTEXT() v8::Context::GetCurrent() -#define SWIGV8_STRING_NEW(str) v8::String::New(str) -#define SWIGV8_FUNCTEMPLATE_NEW(func) v8::FunctionTemplate::New(func) -#define SWIGV8_OBJECT_NEW() v8::Object::New() -#define SWIGV8_EXTERNAL_NEW(val) v8::External::New(val) -#define SWIGV8_UNDEFINED() v8::Undefined() -#else #define SWIGV8_CURRENT_CONTEXT() v8::Isolate::GetCurrent()->GetCurrentContext() #define SWIGV8_STRING_NEW(str) v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), str) #define SWIGV8_FUNCTEMPLATE_NEW(func) v8::FunctionTemplate::New(v8::Isolate::GetCurrent(), func) #define SWIGV8_OBJECT_NEW() v8::Object::New(v8::Isolate::GetCurrent()) #define SWIGV8_EXTERNAL_NEW(val) v8::External::New(v8::Isolate::GetCurrent(), val) #define SWIGV8_UNDEFINED() v8::Undefined(v8::Isolate::GetCurrent()) -#endif - -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) -typedef v8::Persistent SwigV8Context; -#else typedef v8::Local SwigV8Context; -#endif class V8Shell: public JSShell { @@ -149,13 +116,7 @@ bool V8Shell::RunScript(const std::string &scriptPath) { context->Exit(); -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) - context.Dispose(); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) - context.Dispose(v8::Isolate::GetCurrent()); -#else // context.Dispose(); -#endif // v8::V8::Dispose(); @@ -193,13 +154,7 @@ bool V8Shell::RunShell() { context->Exit(); -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) - context.Dispose(); -#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) - context.Dispose(v8::Isolate::GetCurrent()); -#else // context.Dispose(); -#endif // v8::V8::Dispose(); @@ -249,13 +204,8 @@ SwigV8Context V8Shell::CreateShellContext() { global->Set(SWIGV8_STRING_NEW("require"), SWIGV8_FUNCTEMPLATE_NEW(V8Shell::Require)); global->Set(SWIGV8_STRING_NEW("version"), SWIGV8_FUNCTEMPLATE_NEW(V8Shell::Version)); -#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) - SwigV8Context context = v8::Context::New(NULL, global); - return context; -#else SwigV8Context context = v8::Context::New(v8::Isolate::GetCurrent(), NULL, global); return context; -#endif } v8::Handle V8Shell::Import(const std::string &module_path) @@ -307,7 +257,7 @@ SwigV8ReturnValue V8Shell::Require(const SwigV8Arguments &args) { if (args.Length() != 1) { printf("Illegal arguments for `require`"); - }; + } v8::String::Utf8Value str(args[0]); const char *cstr = V8Shell::ToCString(str); diff --git a/Tools/mkdist.py b/Tools/mkdist.py index 47cf8e765..3d631607a 100755 --- a/Tools/mkdist.py +++ b/Tools/mkdist.py @@ -3,6 +3,7 @@ import sys import os import subprocess +from utils import * def failed(): print("mkdist.py failed to complete") @@ -22,6 +23,15 @@ dirname = "swig-" + version force_tag = args.force_tag skip_checks = args.skip_checks +# Tools directory path $ENV/swig/Tools +toolsdir = os.path.dirname(os.path.abspath(__file__)) +# Root directory path (swig) $ENV/swig +rootdir = os.path.abspath(os.path.join(toolsdir, os.pardir)) +# current directory +current_dir = os.getcwd() +# version directory path $ENV/swig/ +dirpath = os.path.join(current_dir, dirname) + if sys.version_info[0:2] < (2, 7): print("Error: Python 2.7 or higher is required") sys.exit(3) @@ -32,22 +42,27 @@ if dirname.lower() != dirname: sys.exit(3) # If directory and tarball exist, remove it -print("Removing " + dirname) -os.system("rm -rf " + dirname) +if check_dir_exists(dirpath): + print("Removing " + dirpath) + run_command("rm", "-rf", dirpath) -print("Removing " + dirname + ".tar if exists") -os.system("rm -f " + dirname + ".tar.gz") +filename = dirpath + ".tar" +if check_file_exists(filename): + print("Removing " + filename) + run_command("rm", "-rf", filename) -print("Removing " + dirname + ".tar.gz if exists") -os.system("rm -f " + dirname + ".tar") +filename += ".gz" +if check_file_exists(filename): + print("Removing " + filename) + run_command("rm", "-rf", filename) # Grab the code from git print("Checking there are no local changes in git repo") -os.system("git remote update origin") == 0 or failed() +run_command("git", "remote", "update", "origin") == 0 or failed() command = ["git", "status", "--porcelain", "-uno"] out = subprocess.check_output(command) -if out.strip() != "": +if out.strip(): print("Local git repository has modifications") print(" ".join(command)) print(out) @@ -57,7 +72,7 @@ if not skip_checks: print("Checking git repository is in sync with remote repository") command = ["git", "log", "--oneline", branch + "..origin/" + branch] out = subprocess.check_output(command) - if out.strip() != "": + if out.strip(): print("Remote repository has additional modifications to local repository") print(" ".join(command)) print(out) @@ -65,7 +80,7 @@ if not skip_checks: command = ["git", "log", "--oneline", "origin/" + branch + ".." + branch] out = subprocess.check_output(command) - if out.strip() != "": + if out.strip(): print("Local repository has modifications not pushed to the remote repository") print("These should be pushed and checked that they pass Continuous Integration testing before continuing") print(" ".join(command)) @@ -73,31 +88,49 @@ if not skip_checks: sys.exit(3) print("Tagging release") -tag = "'rel-" + version + "'" -force = "-f " if force_tag else "" -os.system("git tag -a -m " + tag + " " + force + tag) == 0 or failed() +tag = "v" + version +force = "-f" if force_tag else "" +command = ["git", "tag", "-a", "-m", "'Release version " + version + "'"] +force and command.append(force) +command.append(tag) +run_command(*command) == 0 or failed() -outdir = os.path.basename(os.getcwd()) + "/" + dirname + "/" +outdir = dirname + "/" print("Grabbing tagged release git repository using 'git archive' into " + outdir) -os.system("(cd .. && git archive --prefix=" + outdir + " " + tag + " . | tar -xf -)") == 0 or failed() + +# using pipe operator without shell=True; split commands into individual ones. +# git archive command +command = ["git", "archive", "--prefix=" + outdir, tag, "."] +archive_ps = subprocess.Popen(command, cwd=rootdir, stdout=subprocess.PIPE) +# tar -xf - +tar_ps = subprocess.Popen(("tar", "-xf", "-"), stdin=archive_ps.stdout, stdout=subprocess.PIPE) +archive_ps.stdout.close() # Allow archive_ps to receive a SIGPIPE if tar_ps exits. +output = tar_ps.communicate() # Go build the system print("Building system") -os.system("cd " + dirname + " && ./autogen.sh") == 0 or failed() -os.system("cd " + dirname + "/Source/CParse && bison -y -d parser.y && mv y.tab.c parser.c && mv y.tab.h parser.h") == 0 or failed() -os.system("cd " + dirname + " && make -f Makefile.in libfiles srcdir=./") == 0 or failed() +run_command("mkdir", "-p", dirpath) +run_command("./autogen.sh", cwd=dirpath) == 0 or failed() + +cmdpath = os.path.join(dirpath, "Source", "CParse") +run_command("bison", "-y", "-d", "parser.y", cwd=cmdpath) == 0 or failed() +run_command("mv", "y.tab.c", "parser.c", cwd=cmdpath) == 0 or failed() +run_command("mv", "y.tab.h", "parser.h", cwd=cmdpath) == 0 or failed() + +run_command("make", "-f", "Makefile.in", "libfiles", "srcdir=./", cwd=dirpath) == 0 or failed() # Remove autoconf files -os.system("find " + dirname + " -name autom4te.cache -exec rm -rf {} \\;") +run_command("find", dirname, "-name", "autom4te.cache", "-exec", "rm", "-rf", "{}", ";", cwd=rootdir) # Build documentation print("Building html documentation") -os.system("cd " + dirname + "/Doc/Manual && make all clean-baks") == 0 or failed() +docpath = os.path.join(dirpath, "Doc", "Manual") +run_command("make", "all", "clean-baks", cwd=docpath) == 0 or failed() # Build the tar-ball -os.system("tar -cf " + dirname + ".tar " + dirname) == 0 or failed() -os.system("gzip " + dirname + ".tar") == 0 or failed() +run_command("tar", "-cf", dirname + ".tar", dirname, stdout=open(dirname + ".tar", "w")) == 0 or failed() +run_command("gzip", dirname + ".tar", stdout=open(dirname + ".tar.gz", "w")) == 0 or failed() print("Finished building " + dirname + ".tar.gz") diff --git a/Tools/mkrelease.py b/Tools/mkrelease.py index 014cef227..28dca265b 100755 --- a/Tools/mkrelease.py +++ b/Tools/mkrelease.py @@ -2,6 +2,7 @@ import sys import os +from utils import * def failed(message): if message == "": @@ -27,15 +28,17 @@ skip_checks = args.skip_checks username = args.username print("Looking for rsync") -os.system("which rsync") and failed("rsync not installed/found. Please install.") +run_command("which", "rsync") and failed("rsync not installed/found. Please install.") print("Making source tarball") force = "--force-tag" if force_tag else "" skip = "--skip-checks" if skip_checks else "" -os.system("python ./mkdist.py {} {} --branch {} {}".format(force, skip, branch, version)) and failed("") +toolsdir = os.path.dirname(os.path.abspath(__file__)) +cmd = "python {}/mkdist.py {} {} --branch {} {}".format(toolsdir, force, skip, branch, version).split() +run_command(*cmd) and failed("") print("Build Windows package") -os.system("./mkwindows.sh " + version) and failed("") +run_command("{}/mkwindows.sh".format(toolsdir), version) and failed("") if username: print("Uploading to SourceForge") @@ -45,11 +48,11 @@ if username: # If a file with 'readme' in the name exists in the same folder as the zip/tarball, it gets automatically displayed as the release notes by SF full_readme_file = "readme-" + version + ".txt" - os.system("rm -f " + full_readme_file) - os.system("cat swig-" + version + "/README " + "swig-" + version + "/CHANGES.current " + "swig-" + version + "/RELEASENOTES " + "> " + full_readme_file) + run_command("rm", "-f", full_readme_file) + run_command("cat", "swig-" + version + "/README", "swig-" + version + "/CHANGES.current", "swig-" + version + "/RELEASENOTES", ">", full_readme_file) - os.system("rsync --archive --verbose -P --times -e ssh " + "swig-" + version + ".tar.gz " + full_readme_file + " " + swig_dir_sf) and failed("") - os.system("rsync --archive --verbose -P --times -e ssh " + "swigwin-" + version + ".zip " + full_readme_file + " " + swigwin_dir_sf) and failed("") + run_command("rsync", "--archive", "--verbose", "-P", "--times", "-e", "ssh", "swig-" + version + ".tar.gz", full_readme_file, swig_dir_sf) and failed("") + run_command("rsync", "--archive", "--verbose", "-P", "--times", "-e", "ssh", "swigwin-" + version + ".zip", full_readme_file, swigwin_dir_sf) and failed("") print("Finished") diff --git a/Tools/mkwindows.sh b/Tools/mkwindows.sh index e6ae84350..ed78a2e8e 100755 --- a/Tools/mkwindows.sh +++ b/Tools/mkwindows.sh @@ -1,6 +1,6 @@ #!/bin/sh -# Build Windows distribution (swigwin-2.0.x.zip) from source tarball (swig-2.0.x.tar.gz) +# Build Windows distribution (swigwin-x.y.z.zip) from source tarball (swig-x.y.x.tar.gz) # Requires running in either: # - MinGW environment # - Linux using MinGW cross compiler @@ -23,8 +23,8 @@ if test x$1 != x; then fi else echo "Usage: mkwindows.sh version [zip]" - echo " Build SWIG Windows distribution from source tarball. Works on Cygwin, MinGW or Linux" - echo " version should be 2.0.x" + echo " Build SWIG Windows distribution from source tarball. Works on Cygwin, MinGW or Linux." + echo " version should be in format x.y.z, for example 4.1.0" echo " zip is full path to zip program - default is /c/cygwin/bin/zip on MinGW, zip on Linux and Cygwin" exit 1 fi @@ -84,10 +84,10 @@ export CXXFLAGS="$compileflags" swigbasename=swig-$version swigwinbasename=swigwin-$version tarball=$swigbasename.tar.gz -pcre_tarball=`ls pcre-*.tar.*` +pcre_tarball=`ls pcre2-*.tar.*` if ! test -f "$pcre_tarball"; then - echo "Could not find PCRE tarball. Please download a PCRE source tarball from http://www.pcre.org" + echo "Could not find PCRE2 tarball. Please download a PCRE2 source tarball from http://www.pcre.org" echo "and place in the same directory as the SWIG tarball." exit 1 fi @@ -115,8 +115,9 @@ if test -f "$tarball"; then ./configure $extraconfigureoptions --without-alllang echo "Compiling (quietly)..." make > build.log - echo "Simple check to see if swig.exe runs..." + echo "Simple check to see if swig.exe runs and show versions..." env LD_LIBRARY_PATH= PATH= $wine ./swig.exe -version || exit 1 + env LD_LIBRARY_PATH= PATH= $wine ./swig.exe -pcreversion || exit 1 echo "Simple check to see if ccache-swig.exe runs..." env LD_LIBRARY_PATH= PATH= $wine ./CCache/ccache-swig.exe -V || exit 1 echo "Creating $swigwinbasename.zip..." diff --git a/Tools/nuget-install.cmd b/Tools/nuget-install.cmd deleted file mode 100644 index eec7f8787..000000000 --- a/Tools/nuget-install.cmd +++ /dev/null @@ -1,28 +0,0 @@ -rem Workaround 'nuget install' not being reliable by retrying a few times -@echo off -rem initiate the retry number -set errorCode=1 -set retryNumber=0 -set maxRetries=5 - -:RESTORE -nuget install %* - -rem problem? -IF ERRORLEVEL %errorCode% GOTO :RETRY - -rem everything is fine! -@echo Installed nuget, retries: %reTryNumber% -GOTO :EXIT - -:RETRY -@echo Oops, nuget restore exited with code %errorCode% - let us try again! -set /a retryNumber=%retryNumber%+1 -IF %reTryNumber% LSS %maxRetries% (GOTO :RESTORE) -IF %retryNumber% EQU %maxRetries% (GOTO :ERR) - -:ERR -@echo Sorry, we tried restoring nuget packages for %maxRetries% times and all attempts were unsuccessful! -EXIT /B 1 - -:EXIT diff --git a/Tools/pcre-build.sh b/Tools/pcre-build.sh index 92f645da2..e986d682f 100755 --- a/Tools/pcre-build.sh +++ b/Tools/pcre-build.sh @@ -4,17 +4,17 @@ pcre_subdir=pcre/pcre-swig-install pcre_install_dir=`pwd`/$pcre_subdir usage() { - echo "Helper script to build PCRE as a static library from a tarball just for use during the" - echo "SWIG build. It does not install PCRE for global use on your system." + echo "Helper script to build PCRE2 as a static library from a tarball just for use during the" + echo "SWIG build. It does not install PCRE2 for global use on your system." echo "Usage: pcre-build.sh [--help] [args]" - echo " args - optional additional arguments passed on to the PCRE configure script (leave out" + echo " args - optional additional arguments passed on to the PCRE2 configure script (leave out" echo " unless you are an expert at configure)" echo " --help - Display this help information." echo "Instructions:" - echo " - Download the latest PCRE source tarball from http://www.pcre.org and place in the" + echo " - Download the latest PCRE2 source tarball from http://www.pcre.org and place in the" echo " directory that you will configure and build SWIG." echo " - Run this script in the same directory that you intend to configure and build SWIG in." - echo " This will configure and build PCRE as a static library." + echo " This will configure and build PCRE2 as a static library." echo " - Afterwards run the SWIG configure script which will then find and use the PCRE static" echo " libraries in the $pcre_subdir subdirectory." exit 0 @@ -35,21 +35,21 @@ if test -f "pcre-build.sh" ; then usage fi -echo "Looking for PCRE tarball..." +echo "Looking for PCRE2 tarball..." rm -rf pcre -pcre_tarball=`ls pcre-*.tar*` -test -n "$pcre_tarball" || bail "Could not find tarball matching pattern: pcre-*.tar*" -test -f "$pcre_tarball" || bail "Could not find a single PCRE tarball. Found: $pcre_tarball" +pcre_tarball=`ls pcre2-*.tar*` +test -n "$pcre_tarball" || bail "Could not find tarball matching pattern: pcre2-*.tar*" +test -f "$pcre_tarball" || bail "Could not find a single PCRE2 tarball. Found: $pcre_tarball" echo "Extracting tarball: $pcre_tarball" tar -xf $pcre_tarball || bail "Could not untar $pcre_tarball" pcre_dir=`echo $pcre_tarball | sed -e "s/\.tar.*//"` echo "Configuring PCRE in directory: pcre" mv $pcre_dir pcre || bail "Could not create pcre directory" -cd pcre && ./configure --prefix=$pcre_install_dir --disable-shared $* || bail "PCRE configure failed" -echo "Building PCRE..." -${MAKE:-make} -s || bail "Could not build PCRE" -echo "Installing PCRE locally to $pcre_install_dir..." -${MAKE:-make} -s install || bail "Could not install PCRE" +cd pcre && ./configure --prefix=$pcre_install_dir --disable-shared $* || bail "PCRE2 configure failed" +echo "Building PCRE2..." +${MAKE:-make} -s || bail "Could not build PCRE2" +echo "Installing PCRE2 locally to $pcre_install_dir..." +${MAKE:-make} -s install || bail "Could not install PCRE2" echo "" -echo "The SWIG configure script can now be run, whereupon PCRE will automatically be detected and used from $pcre_install_dir/bin/pcre-config." +echo "The SWIG configure script can now be run, whereupon PCRE2 will automatically be detected and used from $pcre_install_dir/bin/pcre-config." diff --git a/Tools/testflags.py b/Tools/testflags.py index f3d216b59..16e4d8aee 100755 --- a/Tools/testflags.py +++ b/Tools/testflags.py @@ -3,11 +3,15 @@ def get_cflags(language, std, compiler): if std == None or len(std) == 0: std = "gnu89" - c_common = "-fdiagnostics-show-option -std=" + std + " -Wno-long-long -Wreturn-type -Wdeclaration-after-statement -Wmissing-field-initializers" + c_common = "-fdiagnostics-show-option -std=" + std + " -Wno-long-long -Wreturn-type -Wmissing-field-initializers" + if std == "gnu89" or std == "gnu90": + # gnu89 standard allows declaration after headers + # use c99 or gnu99 if feature is necessary for using target language + c_common = c_common + " -Wdeclaration-after-statement" cflags = { "csharp":"-Werror " + c_common, "d":"-Werror " + c_common, - "go":"-Werror " + c_common + " -Wno-declaration-after-statement", + "go":"-Werror " + c_common, "guile":"-Werror " + c_common, "java":"-Werror " + c_common, "javascript":"-Werror " + c_common, diff --git a/Tools/travis-linux-install.sh b/Tools/travis-linux-install.sh deleted file mode 100755 index e25b85f04..000000000 --- a/Tools/travis-linux-install.sh +++ /dev/null @@ -1,122 +0,0 @@ -#!/bin/bash - -# Install Linux packages where the version has been overidden in .travis.yml - -set -e # exit on failure (same as -o errexit) - -lsb_release -a -travis_retry sudo apt-get -qq update - -if [[ -n "$GCC" ]]; then - travis_retry sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test - travis_retry sudo apt-get -qq update - travis_retry sudo apt-get install -qq g++-$GCC -fi - -travis_retry sudo apt-get -qq install libboost-dev libpcre3-dev - -WITHLANG=$SWIGLANG - -case "$SWIGLANG" in - "") ;; - "csharp") - travis_retry sudo apt-get -qq install mono-devel - ;; - "d") - travis_retry wget http://downloads.dlang.org/releases/2.x/${VER}/dmd_${VER}-0_amd64.deb - travis_retry sudo dpkg -i dmd_${VER}-0_amd64.deb - ;; - "go") - if [[ "$VER" ]]; then - eval "$(gimme ${VER}.x)" - fi - ;; - "javascript") - case "$ENGINE" in - "node") - travis_retry wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.10/install.sh | bash - export NVM_DIR="$HOME/.nvm" - [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" - travis_retry nvm install ${VER} - nvm use ${VER} - if [ "$VER" == "0.10" ] || [ "$VER" == "0.12" ] || [ "$VER" == "4" ] || [ "$VER" == "6" ] ; then -# travis_retry sudo apt-get install -qq nodejs node-gyp - travis_retry npm install -g node-gyp@$VER - elif [ "$VER" == "8" ] ; then - travis_retry npm install -g node-gyp@6 - else - travis_retry npm install -g node-gyp - fi - ;; - "jsc") - travis_retry sudo apt-get install -qq libwebkitgtk-dev - ;; - "v8") - travis_retry sudo apt-get install -qq libv8-dev - ;; - esac - ;; - "guile") - travis_retry sudo apt-get -qq install guile-2.0-dev - ;; - "lua") - if [[ -z "$VER" ]]; then - travis_retry sudo apt-get -qq install lua5.2 liblua5.2-dev - else - travis_retry sudo apt-get -qq install lua${VER} liblua${VER}-dev - fi - ;; - "mzscheme") - travis_retry sudo apt-get -qq install racket - ;; - "ocaml") - travis_retry sudo apt-get -qq install ocaml camlp4 - ;; - "octave") - travis_retry sudo apt-get -qq install liboctave-dev - ;; - "php") - travis_retry sudo add-apt-repository -y ppa:ondrej/php - travis_retry sudo apt-get -qq update - travis_retry sudo apt-get -qq install php$VER-cli php$VER-dev - ;; - "python") - pip install --user pycodestyle - if [[ "$PY3" ]]; then - travis_retry sudo apt-get install -qq python3-dev - fi - WITHLANG=$SWIGLANG$PY3 - if [[ "$VER" ]]; then - travis_retry sudo add-apt-repository -y ppa:deadsnakes/ppa - travis_retry sudo apt-get -qq update - travis_retry sudo apt-get -qq install python${VER}-dev - WITHLANG=$SWIGLANG$PY3=$SWIGLANG$VER - fi - ;; - "r") - travis_retry sudo apt-get -qq install r-base - ;; - "ruby") - if [[ "$VER" == "2.7" ]]; then - # Ruby 2.7 support is currently only rvm master (30 Dec 2019) - travis_retry rvm get master - rvm reload - rvm list known - fi - if [[ "$VER" ]]; then - travis_retry rvm install $VER - fi - ;; - "scilab") - # Travis has the wrong version of Java pre-installed resulting in error using scilab: - # /usr/bin/scilab-bin: error while loading shared libraries: libjava.so: cannot open shared object file: No such file or directory - echo "JAVA_HOME was set to $JAVA_HOME" - unset JAVA_HOME - travis_retry sudo apt-get -qq install scilab - ;; - "tcl") - travis_retry sudo apt-get -qq install tcl-dev - ;; -esac - -set +e # turn off exit on failure (same as +o errexit) diff --git a/Tools/travis-osx-install.sh b/Tools/travis-osx-install.sh deleted file mode 100755 index 71d2b2dd0..000000000 --- a/Tools/travis-osx-install.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/bash - -# Install MacOS packages where the version has been overidden in .travis.yml - -set -e # exit on failure (same as -o errexit) - -# Disable 'brew cleanup', just wastes Travis job run time -export HOMEBREW_NO_INSTALL_CLEANUP=1 - -sw_vers -travis_retry brew update -travis_retry brew list -# travis_retry brew install pcre # Travis Xcode-7.3 has pcre -# travis_retry brew install boost - -WITHLANG=$SWIGLANG - -case "$SWIGLANG" in - "csharp") - travis_retry brew install mono - ;; - "guile") - travis_retry Tools/brew-install guile - ;; - "lua") - travis_retry brew install lua - ;; - "octave") - travis_retry Tools/brew-install octave - ;; - "python") - WITHLANG=$SWIGLANG$PY3 - ;; -esac - -# Workaround for https://github.com/travis-ci/travis-ci/issues/6522 -set +e # turn off exit on failure (same as +o errexit) diff --git a/Tools/utils.py b/Tools/utils.py new file mode 100644 index 000000000..496882f19 --- /dev/null +++ b/Tools/utils.py @@ -0,0 +1,26 @@ +import os, subprocess + + +def check_file_exists(path): + """ + Checks if a file exists or not. + """ + return os.path.isfile(path) + + +def check_dir_exists(path): + """ + Checks if a folder exists or not. + """ + return os.path.isdir(path) + + +def run_command(*args, **kwargs): + """ + Runs an os command using subprocess module. + """ + redirect_out = list(map(str.strip, " ".join(args).split(" > "))) + if len(redirect_out) > 1: + args, filepath = redirect_out[0].split(), redirect_out[-1] + kwargs.update(stdout=open(filepath, "w")) + return subprocess.call(args, **kwargs) diff --git a/appveyor.yml b/appveyor.yml index 004dee321..5a57c5fa2 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -2,11 +2,18 @@ platform: - x86 - x64 +skip_commits: + files: + - '.github/**' + - 'CHANGES*' + - 'Doc/**' + - 'Tools/CI-*' + environment: global: MAKEJOBS: 2 -matrix: + matrix: - SWIGLANG: csharp VSVER: 12 - SWIGLANG: csharp @@ -16,23 +23,42 @@ matrix: - SWIGLANG: python VSVER: 14 VER: 27 -# - SWIGLANG: python -# VSVER: 14 -# VER: 36 -# PY3: 3 - SWIGLANG: python + VSVER: 15 + VER: 38 + PY3: 3 + APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 + - SWIGLANG: python + VSVER: 16 + VER: 39 + PY3: 3 + APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 + - SWIGLANG: python + OSVARIANT: cygwin + - SWIGLANG: java OSVARIANT: mingw - VER: 27 + APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 - SWIGLANG: python OSVARIANT: mingw WITHLANG: python VER: 37 PY3: 3 + APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 + - BUILDSYSTEM: cmake + VSVER: 14 -allow_failures: -# Currently failing due to not detecting header files/include paths - - swiglang: python - osvariant: cygwin +matrix: + allow_failures: + - SWIGLANG: python + OSVARIANT: cygwin + +# Skip stale commits (pull requests only), see https://github.com/appveyor/ci/issues/38#issuecomment-70628826 +init: +- ps: | + if ($env:APPVEYOR_PULL_REQUEST_NUMBER -and $env:APPVEYOR_BUILD_NUMBER -ne ((Invoke-RestMethod ` + https://ci.appveyor.com/api/projects/$env:APPVEYOR_ACCOUNT_NAME/$env:APPVEYOR_PROJECT_SLUG/history?recordsNumber=50).builds | ` + Where-Object pullRequestId -eq $env:APPVEYOR_PULL_REQUEST_NUMBER)[0].buildNumber) { ` + throw "There are newer queued builds for this pull request, failing early." } install: - date /T & time /T @@ -48,9 +74,10 @@ install: $env:MINGWBIN="C:\msys64\mingw32\bin" $env:MBITS="32" $env:MARCH="i686" + $env:VSARCH="" } else { $env:PCRE_PLATFORM="x64" - $env:JAVA_HOME="C:/Program Files/Java/jdk1.8.0" + $env:JAVA_HOME="C:/Program Files/Java/jdk15" $env:VCVARS_PLATFORM="amd64" $env:LANG_PLATFORM="-x64" $env:CYGWINBIN="C:\cygwin64\bin" @@ -59,14 +86,26 @@ install: $env:MINGWBIN="C:\msys64\mingw64\bin" $env:MBITS="64" $env:MARCH="x86_64" + $env:VSARCH=" Win64" } - ps: >- if (!$env:OSVARIANT) { $env:PATH="$env:CYGWINBIN;$env:PATH" $env:CYGWIN="nodosfilewarning" - $env:VSCOMNTOOLS=(Get-Content ("env:VS" + "$env:VSVER" + "0COMNTOOLS")) $env:CC="cccl" $env:CXX="cccl" + if ($env:VSVER -ge 16) { + $env:VCVARSBAT="C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars$env:MBITS.bat" + $env:BOOSTROOT="C:/Libraries/boost_1_73_0" + } elseif ($env:VSVER -eq 15) { + $env:VCVARSBAT="C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars$env:MBITS.bat" + $env:BOOSTROOT="C:/Libraries/boost_1_69_0" + } else { + $env:VSCOMNTOOLS=(Get-Content ("env:VS" + "$env:VSVER" + "0COMNTOOLS")) + $env:VCVARSBAT="$env:VSCOMNTOOLS..\..\VC\vcvarsall.bat" + $env:VCVARSARG="$env:VCVARS_PLATFORM" + $env:BOOSTROOT="C:/Libraries/boost_1_69_0" + } } elseif ($env:OSVARIANT -eq "cygwin") { $env:PATH="$env:CYGWINBIN;$env:PATH" $env:CYGWIN="nodosfilewarning" @@ -82,18 +121,18 @@ install: $env:CHECK_OPTIONS2="CFLAGS+=-DMS_WIN64 CXXFLAGS+=-DMS_WIN64" } } -- if "%OSVARIANT%"=="" bash -c "cd /usr/bin && curl --retry 15 -s -L https://github.com/swig/cccl/archive/cccl-1.0.tar.gz | tar -xz --strip 1 cccl-cccl-1.0/cccl" -- if "%OSVARIANT%"=="" echo Using Visual Studio %VSVER%.0 at %VSCOMNTOOLS% -- if "%OSVARIANT%"=="" call "%VSCOMNTOOLS%\..\..\VC\vcvarsall.bat" %VCVARS_PLATFORM% -- if "%OSVARIANT%"=="" Tools\nuget-install.cmd pcre -Verbosity quiet -Version 8.33.0.1 -OutputDirectory C:\pcre -- if "%OSVARIANT%"=="" set PCRE_ROOT=C:/pcre/pcre.8.33.0.1/build/native +- if "%OSVARIANT%"=="" bash -c "cd /usr/bin && curl --retry 15 -s -L https://github.com/swig/cccl/archive/cccl-1.2.tar.gz | tar -xz --strip 1 cccl-cccl-1.2/cccl" +- if "%OSVARIANT%"=="" call "%VCVARSBAT%" %VCVARSARG% +- if "%OSVARIANT%"=="" appveyor-retry appveyor DownloadFile https://github.com/PhilipHazel/pcre2/archive/refs/tags/pcre2-10.39.zip +- if "%OSVARIANT%"=="" 7z x pcre2-10.39.zip +- if "%OSVARIANT%"=="" set PCRE_ROOT=C:/pcre - if not "%OSVARIANT%"=="cygwin" set PATH=C:\Python%VER%%LANG_PLATFORM%;%PATH% - if "%OSVARIANT%"=="" bash -c "which cl.exe" - if "%OSVARIANT%"=="" bash -c "cl.exe /? 2>&1 | head -n 1" - if "%OSVARIANT%"=="" bash -c "which csc.exe" - if "%OSVARIANT%"=="" bash -c "csc.exe /? | head -n 1" -- if "%OSVARIANT%"=="cygwin" %CYGWINSETUP% --quiet-mode --packages python2-devel,libpcre-devel,libboost-devel > cygwin-install.txt || bash -c "cat cygwin-install.txt" -- if "%OSVARIANT%"=="mingw" bash -c "pacman --noconfirm --sync mingw%MBITS%/mingw-w64-%MARCH%-pcre mingw%MBITS%/mingw-w64-%MARCH%-boost" +- if "%OSVARIANT%"=="cygwin" %CYGWINSETUP% --quiet-mode --packages python2-devel,libpcre2-devel,libboost-devel > cygwin-install.txt || bash -c "cat cygwin-install.txt" +- if "%OSVARIANT%"=="mingw" bash -c "pacman --noconfirm --sync mingw%MBITS%/mingw-w64-%MARCH%-autotools mingw%MBITS%/mingw-w64-%MARCH%-pcre2 mingw%MBITS%/mingw-w64-%MARCH%-boost" - if not "%WITHLANG%"=="" set SWIGWITHLANG==%WITHLANG% - if not "%WITHLANG%"=="" where %WITHLANG% - bash -c "which $CC" @@ -110,14 +149,18 @@ install: build_script: - set CCCL_OPTIONS=--cccl-muffle /W3 /EHsc - set CHECK_OPTIONS=CSHARPOPTIONS=-platform:%Platform% +- if "%BUILDSYSTEM%"=="cmake" cd pcre2-pcre2-10.39 && cmake -G "Visual Studio 14 2015%VSARCH%" -DCMAKE_INSTALL_PREFIX="%PCRE_ROOT:\=/%" . && cmake --build . --config Release --target install && cd .. +- if "%BUILDSYSTEM%"=="cmake" cmake --version && cmake -G "Visual Studio 14 2015%VSARCH%" -DCMAKE_INSTALL_PREFIX="%CD:\=/%/install2" -DCMAKE_C_FLAGS="/WX /DPCRE_STATIC" -DCMAKE_CXX_FLAGS="/WX /DPCRE2_STATIC" -DPCRE2_INCLUDE_DIR=%PCRE_ROOT%/include -DPCRE2_LIBRARY=%PCRE_ROOT%/lib/pcre2-8-static.lib -DBISON_EXECUTABLE=C:/cygwin/bin/bison.exe . && cmake --build . --config Release --target install && ctest --output-on-failure -V -C Release && appveyor exit +- if "%OSVARIANT%"=="" bash -c "exec 0], , TCLINCLUDE="") +AC_PREPROC_IFELSE([AC_LANG_SOURCE([[#include ]])],[],[TCLINCLUDE=""]) if test -z "$TCLINCLUDE"; then dirs="/usr/local/include /usr/include /opt/local/include" for i in $dirs ; do @@ -558,7 +598,7 @@ fi AC_MSG_CHECKING(for Tcl library) if test -z "$TCLLIB"; then -dirs="/usr/local/lib /usr/lib /opt/local/lib" +dirs="/usr/local/lib /usr/lib /opt/local/lib /opt/freeware/lib" for i in $dirs ; do if test -r $i/libtcl.a; then AC_MSG_RESULT($i) @@ -576,9 +616,16 @@ fi # Cygwin (Windows) needs the library for dynamic linking case $host in *-*-cygwin* | *-*-mingw*) TCLDYNAMICLINKING="$TCLLIB";; +*-*-aix*) TCLDYNAMICLINKING="$TCLLIB";; *)TCLDYNAMICLINKING="";; esac +# AIX needs -ltcl for linking at test time +case $host in +*-*-aix*) TCLLINK="-ltcl";; +*)TCLLINK="";; +esac + case $host in *-*-darwin*) TCLLDSHARED='$(CC) -dynamiclib -undefined suppress -flat_namespace' @@ -597,6 +644,7 @@ AC_SUBST(TCLLIB) AC_SUBST(TCLDYNAMICLINKING) AC_SUBST(TCLLDSHARED) AC_SUBST(TCLCXXSHARED) +AC_SUBST(TCLLINK) #---------------------------------------------------------------- # Look for Python @@ -766,7 +814,7 @@ else if test x"$PYOSNAME" = x"nt" -a x"$PYSEPARATOR" = x"\\" -a $PYVER -ge 3; then PYTHON3="$PYTHON" else - for py_ver in 3 3.9 3.8 3.7 3.6 3.5 3.4 3.3 3.2 ""; do + for py_ver in 3 3.10 3.9 3.8 3.7 3.6 3.5 3.4 3.3 3.2 ""; do AC_CHECK_PROGS(PYTHON3, [python$py_ver]) if test -n "$PYTHON3"; then AC_CHECK_PROGS(PY3CONFIG, [$PYTHON3-config]) @@ -919,30 +967,6 @@ if test -n "$PYINCLUDE" || test -n "$PY3INCLUDE" ; then fi fi -AC_ARG_WITH(2to3, AS_HELP_STRING([--with-2to3=path], [Set location of Python 2to3 tool]), [PY2TO3BIN="$withval"], [PY2TO3BIN="yes"]) -if test -n "$PYTHON3"; then - if test "x$PY2TO3BIN" = xyes; then - py3to2=`echo $PYTHON3 | sed -e "s/python/2to3-/"` - AC_CHECK_PROGS(PY2TO3, $py3to2 2to3) - if test -z "$PY2TO3"; then - # Windows distributions don't always have the 2to3 executable - AC_MSG_CHECKING(for 2to3.py) - py2to3script="$PY3PREFIX/Tools/scripts/2to3.py" - if test -f "$py2to3script"; then - AC_MSG_RESULT($py2to3script) - PY2TO3="$PYTHON3 $py2to3script" - else - AC_MSG_RESULT(Not found) - fi - fi - else - PY2TO3="$PY2TO3BIN" - fi - if test -z "$PY2TO3"; then - PYTHON3= - fi -fi - #---------------------------------------------------------------- # Look for Perl5 #---------------------------------------------------------------- @@ -961,7 +985,7 @@ else # First figure out what the name of Perl5 is if test "x$PERLBIN" = xyes; then -AC_CHECK_PROGS(PERL, perl perl5.6.1 perl5.6.0 perl5.004 perl5.003 perl5.002 perl5.001 perl5 perl) +AC_CHECK_PROGS(PERL, perl perl5) else PERL="$PERLBIN" fi @@ -1194,7 +1218,7 @@ if test x"${SCILABBIN}" = xno; then else # Check for Scilab executable if test "x$SCILABBIN" = xyes; then - AC_CHECK_PROGS(SCILAB, scilab) + AC_PATH_PROG(SCILAB, scilab) else AC_MSG_CHECKING(for scilab) if test -f "$SCILABBIN"; then @@ -1207,18 +1231,18 @@ else if test -n "$SCILAB"; then # Check for Scilab version (needs api_scilab so needs version 5.3.3 or higher) - SCILAB_FULL_VERSION=`$SCILAB -version | head -1 | sed -e 's|Scilab version \"\(.*\)\"|\1|g'` + SCILAB_VERSION=`$SCILAB -nwni -version | head -1 | sed -e 's|Scilab version \"\(.*\)\"|\1|g'` AC_MSG_CHECKING(Scilab version is 5.3.3 or higher) - SCILAB_MAJOR_VERSION=`echo $SCILAB_FULL_VERSION | cut -d. -f1` - SCILAB_MINOR_VERSION=`echo $SCILAB_FULL_VERSION | cut -d. -f2` - SCILAB_MAINTENANCE_VERSION=`echo $SCILAB_FULL_VERSION | cut -d. -f3` - SCILAB_VERSION="$SCILAB_MAJOR_VERSION$SCILAB_MINOR_VERSION$SCILAB_MAINTENANCE_VERSION" + SCILAB_MAJOR_VERSION=`echo $SCILAB_VERSION | cut -d. -f1` + SCILAB_MINOR_VERSION=`echo $SCILAB_VERSION | cut -d. -f2` + SCILAB_MAINTENANCE_VERSION=`echo $SCILAB_VERSION | cut -d. -f3` + SCILAB_VERSION_NO_DOTS="$SCILAB_MAJOR_VERSION$SCILAB_MINOR_VERSION$SCILAB_MAINTENANCE_VERSION" - if test $SCILAB_VERSION -ge 533; then - AC_MSG_RESULT(yes) + if test -n "$SCILAB_VERSION_NO_DOTS" && test "$SCILAB_VERSION_NO_DOTS" -ge 533; then + AC_MSG_RESULT(yes - $SCILAB_VERSION) else - AC_MSG_RESULT(no) + AC_MSG_RESULT(no - $SCILAB_VERSION) SCILAB= fi @@ -1226,19 +1250,27 @@ else # Set Scilab startup options depending on version AC_MSG_CHECKING(for Scilab startup options) SCILABOPT="-nwni -nb" - if test $SCILAB_VERSION -ge 540; then + if test $SCILAB_VERSION_NO_DOTS -ge 540; then SCILABOPT+=" -noatomsautoload" fi + if test $SCILAB_VERSION_NO_DOTS -ge 600; then + SCILABOPT+=" -quit" + fi AC_MSG_RESULT($SCILABOPT) # Check for Scilab header files AC_MSG_CHECKING(for Scilab header files) + headers="`AS_DIRNAME(["$SCILAB"])`/../include" if test "$SCILABINCDIR" != ""; then dirs="$SCILABINCDIR" - elif test -n "$PKGCONFIG"; then - dirs=`$PKGCONFIG scilab --cflags-only-I | sed -e 's/-I//g'` + elif test -d "$SCI"; then + dirs="$SCI/include $SCI/../../include" + elif test -d "$headers"; then + dirs="$headers" + elif test -n "$PKG_CONFIG "; then + dirs=`$PKG_CONFIG scilab --cflags-only-I | sed -e 's/-I//g'` else - dirs="" + dirs="/usr/include" fi for i in $dirs; do if test -r $i/api_scilab.h; then @@ -1263,6 +1295,7 @@ fi AC_SUBST(SCILAB) AC_SUBST(SCILABINCLUDE) AC_SUBST(SCILABOPT) +AC_SUBST(SCILAB_VERSION) #---------------------------------------------------------------- @@ -1568,7 +1601,7 @@ else # Look for Node.js which is the default Javascript engine #---------------------------------------------------------------- - AC_CHECK_PROGS(NODEJS, [nodejs node]) + AC_CHECK_PROGS(NODEJS, [node nodejs]) if test -n "$NODEJS"; then # node-gyp is needed to run the test-suite/examples @@ -1620,11 +1653,19 @@ else # check for JavaScriptCore/Webkit libraries AC_ARG_WITH(jscorelib,[ --with-jscorelib=path Set location of the JavaScriptCore/Webkit library directory],[JSCORELIB="-L$withval"], [JSCORELIB=]) - if test -z "$JSCORELIB" -a -n "$PKGCONFIG"; then + if test -z "$JSCORELIB" -a -n "$PKG_CONFIG "; then AC_MSG_CHECKING(for JavaScriptCore/Webkit library) - if $PKGCONFIG javascriptcoregtk-1.0; then - JSCORELIB=`$PKGCONFIG --libs javascriptcoregtk-1.0` - JSCOREVERSION=`$PKGCONFIG --modversion javascriptcoregtk-1.0` + if $PKG_CONFIG javascriptcoregtk-4.0 2>/dev/null ; then + JSCORELIB=`$PKG_CONFIG --libs javascriptcoregtk-4.0` + JSCOREINC=`$PKG_CONFIG --cflags-only-I javascriptcoregtk-4.0` + JSCOREVERSION=`$PKG_CONFIG --modversion javascriptcoregtk-4.0` + elif $PKG_CONFIG javascriptcoregtk-3.0 2>/dev/null ; then + JSCORELIB=`$PKG_CONFIG --libs javascriptcoregtk-3.0` + JSCOREINC=`$PKG_CONFIG --cflags-only-I javascriptcoregtk-3.0` + JSCOREVERSION=`$PKG_CONFIG --modversion javascriptcoregtk-3.0` + elif $PKG_CONFIG javascriptcoregtk-1.0 2>/dev/null ; then + JSCORELIB=`$PKG_CONFIG --libs javascriptcoregtk-1.0` + JSCOREVERSION=`$PKG_CONFIG --modversion javascriptcoregtk-1.0` fi if test -z "$JSCORELIB"; then AC_MSG_RESULT(not found) @@ -2035,7 +2076,7 @@ AC_SUBST(RUBYSO) AC_SUBST(RUBYDYNAMICLINKING) #------------------------------------------------------------------------- -# Look for PHP7 +# Look for PHP #------------------------------------------------------------------------- PHPBIN= @@ -2049,7 +2090,7 @@ if test x"${PHPBIN}" = xno; then PHP= else if test "x$PHPBIN" = xyes; then - AC_CHECK_PROGS(PHP, [php7.3 php7.2 php7.1 php7.0 php]) + AC_CHECK_PROGS(PHP, [php8.1 php8.0 php7.4 php7.3 php7.2 php7.1 php7.0 php]) else PHP=$PHPBIN fi @@ -2060,12 +2101,14 @@ else case $PHP in *7.*) PHPCONFIG=`echo "$PHP"|sed 's/7\...*$/-config&/'` ;; + *8.*) + PHPCONFIG=`echo "$PHP"|sed 's/8\...*$/-config&/'` ;; *) PHPCONFIG=$PHP-config ;; esac php_version=`$PHPCONFIG --version 2>/dev/null` case $php_version in - 7.*) + 7.*|8.*) PHPINC=`$PHPCONFIG --includes 2>/dev/null` if test -n "$PHPINC"; then AC_MSG_RESULT($PHPINC) @@ -2076,7 +2119,7 @@ else "") AC_MSG_RESULT([could not find $PHPCONFIG or obtain PHP version from it]) ;; *) - AC_MSG_RESULT([found PHP $php_version - not PHP 7]) ;; + AC_MSG_RESULT([found PHP $php_version - not PHP 7 or 8]) ;; esac fi fi