From 2b4b1cc157bc4950afc70df566b6f70c4f7dce4f Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Thu, 4 Jun 2009 23:25:39 +0000 Subject: [PATCH 001/481] Added support for template double brackets for C++0x. Added test cases. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11245 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 2 + .../test-suite/template_double_brackets.i | 26 +++++ .../template_double_brackets_broke.i | 26 +++++ Source/Swig/scanner.c | 94 ++++++++++++++++++- 4 files changed, 144 insertions(+), 4 deletions(-) create mode 100644 Examples/test-suite/template_double_brackets.i create mode 100644 Examples/test-suite/template_double_brackets_broke.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 5c6a332a4..d2a06c94a 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -82,6 +82,7 @@ CPP_TEST_BROKEN += \ nested_struct \ overload_complicated \ template_default_pointer \ + template_double_brackets_broke \ template_expr @@ -311,6 +312,7 @@ CPP_TEST_CASES += \ template_default_inherit \ template_default_qualify \ template_default_vw \ + template_double_brackets \ template_enum \ template_enum_ns_inherit \ template_enum_typedef \ diff --git a/Examples/test-suite/template_double_brackets.i b/Examples/test-suite/template_double_brackets.i new file mode 100644 index 000000000..3a8ccd47f --- /dev/null +++ b/Examples/test-suite/template_double_brackets.i @@ -0,0 +1,26 @@ +%module foo +#include +std::map> m; +std::map > n; +std::map< std::map<(6>>1), double>, double> o; +//std::map< std::map<6>>1, double>, double> p; // fails as it should + +class ABC { +public: + int a; + int operator>>(ABC &); + int operator<<(ABC &); +}; + +template +class ABC2 { +public: + int a; + + template + int operator>>(ABC &, U); + + template + int operator<<(ABC &, U); +}; + diff --git a/Examples/test-suite/template_double_brackets_broke.i b/Examples/test-suite/template_double_brackets_broke.i new file mode 100644 index 000000000..987f9d269 --- /dev/null +++ b/Examples/test-suite/template_double_brackets_broke.i @@ -0,0 +1,26 @@ +%module foo +#include +std::map> m; +std::map > n; +std::map< std::map<(6>>1), double>, double> o; +std::map< std::map<6>>1, double>, double> p; // fails as it should + +class ABC { +public: + int a; + int operator>>(ABC &); + int operator<<(ABC &); +}; + +template +class ABC2 { +public: + int a; + + template + int operator>>(ABC &, U); + + template + int operator<<(ABC &, U); +}; + diff --git a/Source/Swig/scanner.c b/Source/Swig/scanner.c index 53f1ad4a0..f5b0d5155 100644 --- a/Source/Swig/scanner.c +++ b/Source/Swig/scanner.c @@ -31,8 +31,12 @@ struct Scanner { String *error; /* Last error message (if any) */ int error_line; /* Error line number */ int freeze_line; /* Suspend line number updates */ + List *brackets; /* Current level of < > brackets on each level */ }; +void Scanner_push_brackets(Scanner*); +void Scanner_clear_brackets(Scanner*); + /* ----------------------------------------------------------------------------- * NewScanner() * @@ -53,6 +57,8 @@ Scanner *NewScanner(void) { s->str = 0; s->error = 0; s->freeze_line = 0; + s->brackets = NewList(); + Scanner_push_brackets(s); return s; } @@ -65,6 +71,7 @@ Scanner *NewScanner(void) { void DelScanner(Scanner * s) { assert(s); Delete(s->scanobjs); + Delete(s->brackets); Delete(s->text); Delete(s->file); Delete(s->error); @@ -84,6 +91,7 @@ void Scanner_clear(Scanner * s) { Delete(s->str); Clear(s->text); Clear(s->scanobjs); + Scanner_clear_brackets(s); Delete(s->error); s->error = 0; s->line = 1; @@ -245,6 +253,74 @@ Scanner_freeze_line(Scanner *s, int val) { s->freeze_line = val; } +/* ----------------------------------------------------------------------------- + * Scanner_brackets() + * + * Returns the number of brackets at the current depth. + * ----------------------------------------------------------------------------- */ +int* +Scanner_brackets(Scanner *s) { + return (int*)(**((void***)Getitem(s->brackets, 0))); /* TODO: Use VoidObj*->ptr instead of void** */ +} + +/* ----------------------------------------------------------------------------- + * Scanner_clear_brackets() + * + * Resets the current depth and clears all brackets. + * Usually called at the end of statements; + * ----------------------------------------------------------------------------- */ +void +Scanner_clear_brackets(Scanner *s) { + Clear(s->brackets); + Scanner_push_brackets(s); /* base bracket count should always be created */ +} + +/* ----------------------------------------------------------------------------- + * Scanner_inc_brackets() + * + * Increases the number of brackets at the current depth. + * Usually called when '<' was found. + * ----------------------------------------------------------------------------- */ +void +Scanner_inc_brackets(Scanner *s) { + (*Scanner_brackets(s))++; +} + +/* ----------------------------------------------------------------------------- + * Scanner_dec_brackets() + * + * Decreases the number of brackets at the current depth. + * Usually called when '>' was found. + * ----------------------------------------------------------------------------- */ +void +Scanner_dec_brackets(Scanner *s) { + (*Scanner_brackets(s))--; +} + +/* ----------------------------------------------------------------------------- + * Scanner_push_brackets() + * + * Increases the depth of brackets. + * Usually called when '(' was found. + * ----------------------------------------------------------------------------- */ +void +Scanner_push_brackets(Scanner *s) { + int *newInt = malloc(sizeof(int)); + *newInt = 0; + Push(s->brackets, NewVoid(newInt, free)); +} + +/* ----------------------------------------------------------------------------- + * Scanner_pop_brackets() + * + * Decreases the depth of brackets. + * Usually called when ')' was found. + * ----------------------------------------------------------------------------- */ +void +Scanner_pop_brackets(Scanner *s) { + Delitem(s->brackets, 0); +} + /* ----------------------------------------------------------------------------- * retract() * @@ -432,12 +508,18 @@ static int look(Scanner * s) { /* Look for single character symbols */ - else if (c == '(') + else if (c == '(') { + Scanner_push_brackets(s); return SWIG_TOKEN_LPAREN; - else if (c == ')') + } + else if (c == ')') { + Scanner_pop_brackets(s); return SWIG_TOKEN_RPAREN; - else if (c == ';') + } + else if (c == ';') { + Scanner_clear_brackets(s); return SWIG_TOKEN_SEMI; + } else if (c == ',') return SWIG_TOKEN_COMMA; else if (c == '*') @@ -704,6 +786,7 @@ static int look(Scanner * s) { break; case 60: /* shift operators */ + Scanner_inc_brackets(s); if ((c = nextchar(s)) == 0) return SWIG_TOKEN_LESSTHAN; if (c == '<') @@ -716,9 +799,10 @@ static int look(Scanner * s) { } break; case 61: + Scanner_dec_brackets(s); if ((c = nextchar(s)) == 0) return SWIG_TOKEN_GREATERTHAN; - if (c == '>') + if (c == '>' && ((*Scanner_brackets(s))<0)) /* go to double >> only, if no template < has been used */ state = 250; else if (c == '=') return SWIG_TOKEN_GTEQUAL; @@ -1024,6 +1108,7 @@ static int look(Scanner * s) { break; case 240: /* LSHIFT, LSEQUAL */ + Scanner_inc_brackets(s); if ((c = nextchar(s)) == 0) return SWIG_TOKEN_LSHIFT; else if (c == '=') @@ -1035,6 +1120,7 @@ static int look(Scanner * s) { break; case 250: /* RSHIFT, RSEQUAL */ + Scanner_dec_brackets(s); if ((c = nextchar(s)) == 0) return SWIG_TOKEN_RSHIFT; else if (c == '=') From 1af6d8a1b00fb05091ac0ffe0b2f4e30fc656cd8 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Sat, 6 Jun 2009 16:25:24 +0000 Subject: [PATCH 002/481] Renamed template_double_brackets -> cpp0x_template_double_brackets. Added CPP0X_TEST_CASES and CPP0X_TEST_BROKEN in common.mk. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11248 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 16 ++++++++++++---- ...ackets.i => cpp0x_template_double_brackets.i} | 0 ...i => cpp0x_template_double_brackets_broken.i} | 0 3 files changed, 12 insertions(+), 4 deletions(-) rename Examples/test-suite/{template_double_brackets.i => cpp0x_template_double_brackets.i} (100%) rename Examples/test-suite/{template_double_brackets_broke.i => cpp0x_template_double_brackets_broken.i} (100%) diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index d2a06c94a..8615a47c3 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -82,8 +82,8 @@ CPP_TEST_BROKEN += \ nested_struct \ overload_complicated \ template_default_pointer \ - template_double_brackets_broke \ - template_expr + template_expr \ + $(CPP0X_TEST_BROKEN) # Broken C test cases. (Can be run individually using make testcase.ctest.) @@ -312,7 +312,6 @@ CPP_TEST_CASES += \ template_default_inherit \ template_default_qualify \ template_default_vw \ - template_double_brackets \ template_enum \ template_enum_ns_inherit \ template_enum_typedef \ @@ -396,7 +395,16 @@ CPP_TEST_CASES += \ virtual_destructor \ virtual_poly \ voidtest \ - wrapmacro + wrapmacro \ + $(CPP0X_TEST_CASES) + +# C++0x test cases. +CPP0X_TEST_CASES = \ + cpp0x_template_double_brackets + +# Broken C++0x test cases. +CPP0X_TEST_BROKEN = \ + cpp0x_template_double_brackets_broken # # Put all the heavy STD/STL cases here, where they can be skipped if needed diff --git a/Examples/test-suite/template_double_brackets.i b/Examples/test-suite/cpp0x_template_double_brackets.i similarity index 100% rename from Examples/test-suite/template_double_brackets.i rename to Examples/test-suite/cpp0x_template_double_brackets.i diff --git a/Examples/test-suite/template_double_brackets_broke.i b/Examples/test-suite/cpp0x_template_double_brackets_broken.i similarity index 100% rename from Examples/test-suite/template_double_brackets_broke.i rename to Examples/test-suite/cpp0x_template_double_brackets_broken.i From 5fd3ccae1857546886673cec36bd61bd8c2eaa3f Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Fri, 26 Jun 2009 20:24:22 +0000 Subject: [PATCH 003/481] Introduced new CXXFLAGS symbol for the compilation of test suite. Added -std=c++0x to g++ compiler to enable compilation of the new C++0x tests. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11321 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/Makefile.in | 95 ++++++++++++++++++++++---------------------- configure.in | 7 ++++ 2 files changed, 55 insertions(+), 47 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index d6dbfdeeb..37a02c59f 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -25,6 +25,7 @@ TARGET = CC = @CC@ CXX = @CXX@ CFLAGS = @PLATFLAGS@ +CXXFLAGS = @PLATCXXFLAGS@ prefix = @prefix@ exec_prefix= @exec_prefix@ SRCS = @@ -113,7 +114,7 @@ tclsh: $(SRCS) tclsh_cpp: $(SRCS) $(SWIG) -tcl8 -c++ $(SWIGOPT) $(TCL_SWIGOPTS) -ltclsh.i $(INTERFACEPATH) - $(CXX) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) \ + $(CXX) $(CXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) \ $(TCL_LIB) $(TCL_OPTS) $(LIBS) $(SYSLIBS) -o $(TARGET) # ----------------------------------------------------------- @@ -128,7 +129,7 @@ wish: $(SRCS) wish_cpp: $(SRCS) $(SWIG) -tcl8 -c++ $(SWIGOPT) $(TCL_SWIGOPTS) -lwish.i $(INTERFACEPATH) - $(CXX) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) \ + $(CXX) $(CXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) \ $(XINCLUDE) $(TCL_LIB) $(TK_OPTS) $(XLIB) $(LIBS) $(SYSLIBS) -o $(TARGET) # ----------------------------------------------------------- @@ -146,8 +147,8 @@ tcl: $(SRCS) tcl_cpp: $(SRCS) $(SWIG) -tcl8 -c++ $(SWIGOPT) $(TCL_SWIGOPTS) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) - $(TCLCXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(TCL_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(TCL_SO) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) + $(TCLCXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(TCL_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(TCL_SO) # ----------------------------------------------------------------- # Cleaning the Tcl examples @@ -187,8 +188,8 @@ perl5: $(SRCS) perl5_cpp: $(SRCS) $(SWIG) -perl5 -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(PERL5_CCFLAGS) -I$(PERL5_INCLUDE) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(PERL5_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(PERL5_CCFLAGS) -I$(PERL5_INCLUDE) + $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(PERL5_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ---------------------------------------------------------------- # Build a module from existing XS C source code. (ie. from xsubpp). @@ -209,7 +210,7 @@ perl5_static: $(SRCS) perl5_static_cpp: $(SRCS) $(SWIG) -perl5 -c++ -static -lperlmain.i $(SWIGOPT) $(INTERFACEPATH) - $(CXX) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) -I$(PERL5_INCLUDE) $(PERL5_LIB) $(LIBS) -o $(TARGET) + $(CXX) $(CXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) -I$(PERL5_INCLUDE) $(PERL5_LIB) $(LIBS) -o $(TARGET) # ----------------------------------------------------------------- # Cleaning the Perl5 examples @@ -267,8 +268,8 @@ python: $(SRCS) python_cpp: $(SRCS) $(SWIGPYTHON) -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(PYTHON_INCLUDE) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(PYTHON_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)_$(TARGET)$(PYTHON_SO) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(PYTHON_INCLUDE) + $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(PYTHON_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)_$(TARGET)$(PYTHON_SO) # ----------------------------------------------------------------- # Build statically linked Python interpreter @@ -288,7 +289,7 @@ python_static: $(SRCS) python_static_cpp: $(SRCS) $(SWIGPYTHON) -c++ -lembed.i $(SWIGOPT) $(INTERFACEPATH) - $(CXX) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \ + $(CXX) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \ $(PYTHON_INCLUDE) $(LIBS) -L$(PYTHON_LIB) $(PYTHON_LIBOPTS) -o $(TARGET) # ----------------------------------------------------------------- @@ -339,7 +340,7 @@ OCTAVE_SO = @OCTAVE_SO@ octave: $(SRCS) $(SWIG) -octave $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -g -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(CXXSRCS) $(INCLUDES) -I$(OCTAVE_INCLUDE) + $(CXX) -g -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(CXXSRCS) $(INCLUDES) -I$(OCTAVE_INCLUDE) $(CC) -g -c $(CCSHARED) $(CFLAGS) $(SRCS) $(INCLUDES) $(OCTAVE_INCLUDE) $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(OCTAVE_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(OCTAVE_SO) @@ -349,8 +350,8 @@ octave: $(SRCS) octave_cpp: $(SRCS) $(SWIG) -c++ -octave $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -g -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) -I$(OCTAVE_INCLUDE) - $(CXXSHARED) -g $(CFLAGS) $(OBJS) $(IOBJS) $(OCTAVE_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(OCTAVE_SO) + $(CXX) -g -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) -I$(OCTAVE_INCLUDE) + $(CXXSHARED) -g $(CXXFLAGS) $(OBJS) $(IOBJS) $(OCTAVE_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(OCTAVE_SO) # ----------------------------------------------------------------- # Cleaning the octave examples @@ -381,8 +382,8 @@ guile: $(SRCS) guile_cpp: $(SRCS) $(SWIG) -c++ -guile -scm -Linkage passive $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(INCLUDES) $(GUILE_INCLUDE) $(ICXXSRCS) $(SRCS) $(CXXSRCS) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(INCLUDES) $(GUILE_INCLUDE) $(ICXXSRCS) $(SRCS) $(CXXSRCS) + $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO) guile_externalhdr: $(SWIG) -guile -external-runtime $(TARGET) @@ -397,8 +398,8 @@ guile_gh: $(SRCS) guile_gh_cpp: $(SRCS) $(SWIG) -c++ -guile -gh -Linkage passive $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(INCLUDES) $(GUILE_INCLUDE) $(ICXXSRCS) $(SRCS) $(CXXSRCS) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(INCLUDES) $(GUILE_INCLUDE) $(ICXXSRCS) $(SRCS) $(CXXSRCS) + $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO) # ----------------------------------------------------------------- # Build a dynamically loadable module with passive linkage @@ -411,8 +412,8 @@ guile_passive: $(SRCS) guile_passive_cpp: $(SRCS) $(SWIG) -c++ -guile -Linkage passive $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(INCLUDES) $(GUILE_INCLUDE) $(ICXXSRCS) $(SRCS) $(CXXSRCS) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(INCLUDES) $(GUILE_INCLUDE) $(ICXXSRCS) $(SRCS) $(CXXSRCS) + $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO) # ----------------------------------------------------------------- # Build statically linked Guile interpreter @@ -428,7 +429,7 @@ guile_static: $(SRCS) guile_static_cpp: $(SRCS) $(SWIG) -c++ -guile -lguilemain.i -Linkage ltdlmod $(SWIGOPT) $(INTERFACEPATH) - $(CXX) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \ + $(CXX) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \ -DSWIGINIT="SCM scm_init_$(TARGET)_module(void); scm_init_$(TARGET)_module();" \ $(GUILE_INCLUDE) $(LIBS) -L$(GUILE_LIB) $(GUILE_LIBOPTS) -o $(TARGET)-guile @@ -439,7 +440,7 @@ guile_simple: $(SRCS) guile_simple_cpp: $(SRCS) $(SWIG) -c++ -guile -lguilemain.i -Linkage simple $(SWIGOPT) $(INTERFACEPATH) - $(CXX) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \ + $(CXX) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \ $(GUILE_INCLUDE) $(LIBS) -L$(GUILE_LIB) $(GUILE_LIBOPTS) -o $(TARGET)-guile # ----------------------------------------------------------------- @@ -483,8 +484,8 @@ java: $(SRCS) java_cpp: $(SRCS) $(SWIG) -java -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(JAVACFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(JAVA_INCLUDE) - $(JAVACXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JAVA_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(JAVA_LIBPREFIX)$(TARGET)$(JAVASO) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(JAVACFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(JAVA_INCLUDE) + $(JAVACXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(JAVA_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(JAVA_LIBPREFIX)$(TARGET)$(JAVASO) # ----------------------------------------------------------------- # Cleaning the java examples @@ -542,7 +543,7 @@ mzscheme: $(SRCS) mzscheme_cpp: $(SRCS) $(SWIG) -mzscheme -c++ $(SWIGOPT) $(INTERFACEPATH) $(COMPILETOOL) $(MZC) `echo $(INCLUDES) | sed 's/-I/++ccf -I/g'` --cc $(ICXXSRCS) $(SRCS) $(CXXSRCS) - $(CXXSHARED) $(CFLAGS) -o $(LIBPREFIX)$(TARGET)$(MZSCHEME_SO) $(OBJS) $(IOBJS) $(MZDYNOBJ) $(CPP_DLLIBS) + $(CXXSHARED) $(CXXFLAGS) -o $(LIBPREFIX)$(TARGET)$(MZSCHEME_SO) $(OBJS) $(IOBJS) $(MZDYNOBJ) $(CPP_DLLIBS) # ----------------------------------------------------------------- # Cleaning the mzscheme examples @@ -592,7 +593,7 @@ ocaml_dynamic: $(SRCS) $(OCAMLCORE) $(SWIG) -ocaml $(SWIGOPT) $(INTERFACEPATH) $(OCC) -g -c -ccopt -g -ccopt "$(INCLUDES)" $(ISRCS) $(SRCS) - $(CXXSHARED) $(CFLAGS) $(CCSHARED) $(CFLAGS) -o $(INTERFACE:%.i=%@SO@) \ + $(CXXSHARED) $(CXXFLAGS) $(CCSHARED) $(CFLAGS) -o $(INTERFACE:%.i=%@SO@) \ $(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) $(LIBS) $(OCAMLDLGEN) $(INTERFACE:%.i=%.ml) $(INTERFACE:%.i=%@SO@) > \ $(INTERFACE:%.i=%_dynamic.ml) @@ -663,7 +664,7 @@ ocaml_dynamic_cpp: $(SRCS) cp $(ICXXSRCS) $(ICXXSRCS:%.cxx=%.c) $(OCC) -cc '$(CXX)' -g -c -ccopt -g -ccopt "-xc++ $(INCLUDES)" \ $(ICXXSRCS:%.cxx=%.c) $(SRCS) $(CXXSRCS) -ccopt -fPIC - $(CXXSHARED) $(CFLAGS) -o $(INTERFACE:%.i=%@SO@) \ + $(CXXSHARED) $(CXXFLAGS) -o $(INTERFACE:%.i=%@SO@) \ $(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) \ $(CPP_DLLIBS) $(LIBS) $(OCAMLDLGEN) $(INTERFACE:%.i=%.ml) $(INTERFACE:%.i=%@SO@) > \ @@ -710,8 +711,8 @@ ruby: $(SRCS) ruby_cpp: $(SRCS) $(SWIG) -c++ -ruby $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(RUBY_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(RUBY_INCLUDE) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(RUBY_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(RUBY_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(RUBY_INCLUDE) + $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(RUBY_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- # Build statically linked Ruby interpreter @@ -729,7 +730,7 @@ ruby_static: $(SRCS) ruby_cpp_static: $(SRCS) $(SWIG) -c++ -ruby -lembed.i $(SWIGOPT) $(INTERFACEPATH) - $(CXX) $(CFLAGS) $(RUBY_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \ + $(CXX) $(CXXFLAGS) $(RUBY_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \ $(RUBY_INCLUDE) $(LIBS) -L$(RUBY_LIB) $(RUBY_LIBOPTS) -o $(TARGET) @@ -764,8 +765,8 @@ php: $(SRCS) php_cpp: $(SRCS) $(SWIG) -php -cppext cxx -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(PHP_INCLUDE) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(PHP_SO) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(PHP_INCLUDE) + $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(PHP_SO) # ----------------------------------------------------------------- # Running a PHP example @@ -811,7 +812,7 @@ pike: $(SRCS) pike_cpp: $(SRCS) $(SWIG) -c++ -pike $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(PIKE_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(PIKE_INCLUDE) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(PIKE_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(PIKE_INCLUDE) $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(PIKE_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- @@ -830,7 +831,7 @@ pike_static: $(SRCS) pike_cpp_static: $(SRCS) $(SWIG) -c++ -pike -lembed.i $(SWIGOPT) $(INTERFACEPATH) - $(CXX) $(CFLAGS) $(PIKE_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \ + $(CXX) $(CXXFLAGS) $(PIKE_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \ $(PIKE_INCLUDE) $(LIBS) -L$(PIKE_LIB) $(PIKE_LIBOPTS) -o $(TARGET) # ----------------------------------------------------------------- @@ -885,9 +886,9 @@ chicken_direct_cpp: $(CXXSRCS) $(CHICKSRCS) $(CHICKEN) $(CHICKEN_GENERATED_SCHEME) $(CHICKENOPTS) \ -dynamic -feature chicken-compile-shared \ -output-file $(CHICKEN_COMPILED_SCHEME) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(CHICKEN_CFLAGS) \ + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(CHICKEN_CFLAGS) \ $(INCLUDES) $(CHICKEN_INCLUDE) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(CHICKEN_COMPILED_SCHEME) - $(CXXSHARED) $(CFLAGS) $(CHICKEN_COMPILED_OBJECT) $(OBJS) $(IOBJS) \ + $(CXXSHARED) $(CXXFLAGS) $(CHICKEN_COMPILED_OBJECT) $(OBJS) $(IOBJS) \ $(LIBS) $(CPP_DLLIBS) $(CHICKEN_SHAREDLIBOPTS) -o $(LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- @@ -913,7 +914,7 @@ chicken_static_cpp: $(CXXSRCS) $(CHICKSRCS) -output-file $(CHICKEN_COMPILED_SCHEME) $(CHICKEN) $(CHICKEN_MAIN) $(CHICKENOPTS) \ -output-file $(CHICKEN_MAIN:.scm=_chicken.c) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(CHICKEN_CFLAGS) \ + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(CHICKEN_CFLAGS) \ $(INCLUDES) $(CHICKEN_INCLUDE) $(ICXXSRCS) $(SRCS) $(CXXSRCS) \ $(CHICKEN_COMPILED_SCHEME) $(CHICKEN_COMPILED_MAIN) $(CXX) $(CHICKEN_COMPILED_OBJECT) $(CHICKEN_COMPILED_MAIN_OBJECT) \ @@ -966,8 +967,8 @@ csharp: $(SRCS) csharp_cpp: $(SRCS) $(SWIG) -csharp -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(CSHARPCFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(CSHARP_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(CSHARP_LIBPREFIX)$(TARGET)$(CSHARPSO) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(CSHARPCFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) + $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(CSHARP_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(CSHARP_LIBPREFIX)$(TARGET)$(CSHARPSO) # ---------------------------------------------------------------- # Compile CSharp files @@ -1015,8 +1016,8 @@ lua: $(SRCS) lua_cpp: $(SRCS) $(SWIG) -c++ -lua $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(LUA_INCLUDE) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(LUA_LIB) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(LUA_SO) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(LUA_INCLUDE) + $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(LUA_LIB) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(LUA_SO) # ----------------------------------------------------------------- # Build statically linked Lua interpreter @@ -1029,7 +1030,7 @@ lua_static: $(SRCS) lua_static_cpp: $(SRCS) $(SWIG) -c++ -lua -module example $(SWIGOPT) $(INTERFACEPATH) - $(CXX) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(LUA_INTERP) $(INCLUDES) \ + $(CXX) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(LUA_INTERP) $(INCLUDES) \ $(LUA_INCLUDE) $(LIBS) $(LUA_LIB) -o $(TARGET) # ----------------------------------------------------------------- @@ -1052,8 +1053,8 @@ allegrocl: $(SRCS) allegrocl_cpp: $(SRCS) $(SWIG) -c++ -allegrocl $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) + $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) allegrocl_clean: rm -f *_wrap* *~ .~* @@ -1086,8 +1087,8 @@ cffi: $(SRCS) cffi_cpp: $(SRCS) $(SWIG) -c++ -cffi $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) + $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) cffi_clean: rm -f *_wrap* *~ .~* @@ -1105,8 +1106,8 @@ uffi: $(SRCS) uffi_cpp: $(SRCS) $(SWIG) -c++ -uffi $(SWIGOPT) $(INTERFACEPATH) -# $(CXX) -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) -# $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) +# $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) +# $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) uffi_clean: rm -f *_wrap* *~ .~* diff --git a/configure.in b/configure.in index 4edc8e1ae..b64bc860a 100644 --- a/configure.in +++ b/configure.in @@ -321,6 +321,13 @@ case $host in *) PLATFLAGS="";; esac +# Add switch to enable C++0x support +AC_SUBST(PLATCXXFLAGS) +if test "$GCC" = yes; then + PLATCXXFLAGS=$PLATFLAGS" -std=c++0x " +else + PLATCXXFLAGS=$PLATFLAGS +fi # Check for specific libraries. Used for SWIG examples AC_CHECK_LIB(dl, dlopen) # Dynamic linking for SunOS/Solaris and SYSV From d8012716edf99362fd1d6abd5f8834aba7cdcd97 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Fri, 26 Jun 2009 21:48:48 +0000 Subject: [PATCH 004/481] Added constexpr keywords and CONSTEXPR terminal to Swig parser. Added cpp0x_constexpr.i testcase. Fixed compilation bug of cpp0x_template_double_brackets.i testcase. Removed obsolete cpp0x_template_double_brackets_broken. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11322 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 10 +++---- Examples/test-suite/cpp0x_constexpr.i | 8 ++++++ .../cpp0x_template_double_brackets.i | 10 +++---- .../cpp0x_template_double_brackets_broken.i | 26 ------------------- Source/CParse/cscanner.c | 2 ++ Source/CParse/parser.y | 3 ++- 6 files changed, 22 insertions(+), 37 deletions(-) create mode 100644 Examples/test-suite/cpp0x_constexpr.i delete mode 100644 Examples/test-suite/cpp0x_template_double_brackets_broken.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 8615a47c3..d7ef3e889 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -93,6 +93,7 @@ C_TEST_BROKEN += \ # C++ test cases. (Can be run individually using make testcase.cpptest.) CPP_TEST_CASES += \ + $(CPP0X_TEST_CASES) \ abstract_access \ abstract_inherit \ abstract_inherit_ok \ @@ -395,16 +396,15 @@ CPP_TEST_CASES += \ virtual_destructor \ virtual_poly \ voidtest \ - wrapmacro \ - $(CPP0X_TEST_CASES) + wrapmacro # C++0x test cases. CPP0X_TEST_CASES = \ cpp0x_template_double_brackets +# cpp0x_constexpr # not supported by any compilers yet # Broken C++0x test cases. -CPP0X_TEST_BROKEN = \ - cpp0x_template_double_brackets_broken +CPP0X_TEST_BROKEN = # # Put all the heavy STD/STL cases here, where they can be skipped if needed @@ -497,7 +497,7 @@ ALL_CLEAN = $(CPP_TEST_CASES:=.clean) \ ####################################################################### # The following applies for all module languages ####################################################################### -all: $(BROKEN_TEST_CASES) $(NOT_BROKEN_TEST_CASES) +all: $(NOT_BROKEN_TEST_CASES) $(BROKEN_TEST_CASES) check: $(NOT_BROKEN_TEST_CASES) diff --git a/Examples/test-suite/cpp0x_constexpr.i b/Examples/test-suite/cpp0x_constexpr.i new file mode 100644 index 000000000..6314d20c0 --- /dev/null +++ b/Examples/test-suite/cpp0x_constexpr.i @@ -0,0 +1,8 @@ +%module foo + +%inline %{ +class TestClass { + constexpr int func() { return 10; } +}; +%} + diff --git a/Examples/test-suite/cpp0x_template_double_brackets.i b/Examples/test-suite/cpp0x_template_double_brackets.i index 3a8ccd47f..1a12e0457 100644 --- a/Examples/test-suite/cpp0x_template_double_brackets.i +++ b/Examples/test-suite/cpp0x_template_double_brackets.i @@ -1,9 +1,8 @@ %module foo +%inline %{ #include std::map> m; -std::map > n; -std::map< std::map<(6>>1), double>, double> o; -//std::map< std::map<6>>1, double>, double> p; // fails as it should +std::map< int,std::map > n; class ABC { public: @@ -18,9 +17,10 @@ public: int a; template - int operator>>(ABC &, U); + U operator>>(ABC &); template - int operator<<(ABC &, U); + U operator<<(ABC &); }; +%} diff --git a/Examples/test-suite/cpp0x_template_double_brackets_broken.i b/Examples/test-suite/cpp0x_template_double_brackets_broken.i deleted file mode 100644 index 987f9d269..000000000 --- a/Examples/test-suite/cpp0x_template_double_brackets_broken.i +++ /dev/null @@ -1,26 +0,0 @@ -%module foo -#include -std::map> m; -std::map > n; -std::map< std::map<(6>>1), double>, double> o; -std::map< std::map<6>>1, double>, double> p; // fails as it should - -class ABC { -public: - int a; - int operator>>(ABC &); - int operator<<(ABC &); -}; - -template -class ABC2 { -public: - int a; - - template - int operator>>(ABC &, U); - - template - int operator<<(ABC &, U); -}; - diff --git a/Source/CParse/cscanner.c b/Source/CParse/cscanner.c index 8734c7d0e..a2a0631c1 100644 --- a/Source/CParse/cscanner.c +++ b/Source/CParse/cscanner.c @@ -630,6 +630,8 @@ int yylex(void) { return (PROTECTED); if (strcmp(yytext, "friend") == 0) return (FRIEND); + if (strcmp(yytext, "constexpr") == 0) + return (CONSTEXPR); if (strcmp(yytext, "virtual") == 0) return (VIRTUAL); if (strcmp(yytext, "operator") == 0) { diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 0babfbbb8..b4c2b4fb4 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1492,7 +1492,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %token ILLEGAL CONSTANT %token NAME RENAME NAMEWARN EXTEND PRAGMA FEATURE VARARGS %token ENUM -%token CLASS TYPENAME PRIVATE PUBLIC PROTECTED COLON STATIC VIRTUAL FRIEND THROW CATCH EXPLICIT +%token CLASS TYPENAME PRIVATE PUBLIC PROTECTED COLON STATIC VIRTUAL FRIEND THROW CATCH EXPLICIT CONSTEXPR %token USING %token NAMESPACE %token NATIVE INLINE @@ -4490,6 +4490,7 @@ storage_class : EXTERN { $$ = "extern"; } | VIRTUAL { $$ = "virtual"; } | FRIEND { $$ = "friend"; } | EXPLICIT { $$ = "explicit"; } + | CONSTEXPR { $$ = "constexpr"; } | empty { $$ = 0; } ; From 49467481641861e1bb4299f14c59c0720b04e868 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Fri, 26 Jun 2009 22:23:07 +0000 Subject: [PATCH 005/481] Added test case for explicit conversion operators. Some cosmetic fixes. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11323 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 3 +- Examples/test-suite/cpp0x_constexpr.i | 3 ++ .../cpp0x_explicit_conversion_operators.i | 28 +++++++++++++++++++ .../cpp0x_template_double_brackets.i | 4 +++ 4 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 Examples/test-suite/cpp0x_explicit_conversion_operators.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index d7ef3e889..a95830f3f 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -400,7 +400,8 @@ CPP_TEST_CASES += \ # C++0x test cases. CPP0X_TEST_CASES = \ - cpp0x_template_double_brackets + cpp0x_template_double_brackets \ + cpp0x_explicit_conversion_operators # cpp0x_constexpr # not supported by any compilers yet # Broken C++0x test cases. diff --git a/Examples/test-suite/cpp0x_constexpr.i b/Examples/test-suite/cpp0x_constexpr.i index 6314d20c0..4345ec0af 100644 --- a/Examples/test-suite/cpp0x_constexpr.i +++ b/Examples/test-suite/cpp0x_constexpr.i @@ -1,3 +1,6 @@ +/* This interface tests whether Swig supports the new "constexpr" keyword + introduced by C++0x. +*/ %module foo %inline %{ diff --git a/Examples/test-suite/cpp0x_explicit_conversion_operators.i b/Examples/test-suite/cpp0x_explicit_conversion_operators.i new file mode 100644 index 000000000..ae97ec185 --- /dev/null +++ b/Examples/test-suite/cpp0x_explicit_conversion_operators.i @@ -0,0 +1,28 @@ +/* This interface checks whether Swig correctly compiles the new + explicit conversion operators feature introduced in C++0x. +*/ +%module foo + +%inline %{ + +class U { +public: + int u; +}; + +class V { +public: + int v; +}; + +class TestClass { +public: + //implicit converting constructor + TestClass( U const &val ) { t=val.u; } + // explicit constructor + explicit TestClass( V const &val ) { t=val.v; } + + int t; +}; +%} + diff --git a/Examples/test-suite/cpp0x_template_double_brackets.i b/Examples/test-suite/cpp0x_template_double_brackets.i index 1a12e0457..31c9c7248 100644 --- a/Examples/test-suite/cpp0x_template_double_brackets.i +++ b/Examples/test-suite/cpp0x_template_double_brackets.i @@ -1,3 +1,7 @@ +/* This interface checks whether Swig supports the new double angled brackets + in the template syntax without having a space inbetween. This feature was + introduced in new C++0x standard. +*/ %module foo %inline %{ #include From 0f2786aa540e509a5d74fc9be2f8ca297b6f501c Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Sun, 28 Jun 2009 14:51:10 +0000 Subject: [PATCH 006/481] Added support for unicode strings and fixed support for wstrings. Added test case cpp0x_raw_string_literals.i. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11327 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 3 +- .../test-suite/cpp0x_raw_string_literals.i | 30 ++++++++ Source/Swig/scanner.c | 73 +++++++++++++++---- 3 files changed, 92 insertions(+), 14 deletions(-) create mode 100644 Examples/test-suite/cpp0x_raw_string_literals.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index a95830f3f..fc00c1243 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -401,7 +401,8 @@ CPP_TEST_CASES += \ # C++0x test cases. CPP0X_TEST_CASES = \ cpp0x_template_double_brackets \ - cpp0x_explicit_conversion_operators + cpp0x_explicit_conversion_operators \ + cpp0x_raw_string_literals # cpp0x_constexpr # not supported by any compilers yet # Broken C++0x test cases. diff --git a/Examples/test-suite/cpp0x_raw_string_literals.i b/Examples/test-suite/cpp0x_raw_string_literals.i new file mode 100644 index 000000000..0b7ba244b --- /dev/null +++ b/Examples/test-suite/cpp0x_raw_string_literals.i @@ -0,0 +1,30 @@ +/* This module tests whether Swig correctly parses: + - ordinary strings (char_t) + - L wide strings (wchar_t) + - u8 unicode8 strings (char_t) + - u unicode16 strings (char16_t) + - U unicode32 strings (char32_t) + + This module also tests whether Swig correctly parses custom string delimiters. +*/ + +%module raw_string_literals + +%inline %{ +#include +#include + +using namespace std; + +string a="ABC"; +wstring wide=L"ABC"; +string c=u8"ABC"; +string b=u"ABC"; +string d=U"ABC"; + +/*string e=R"XXX[ABC"blah]XXX"; +string g=u8R"XXX[ABC"blah]XXX"; +string f=uR"XXX[ABC"blah]XXX"; +string h=UR"XXX[ABC"blah]XXX"; +*/ +%} diff --git a/Source/Swig/scanner.c b/Source/Swig/scanner.c index f5b0d5155..a4ac36ac4 100644 --- a/Source/Swig/scanner.c +++ b/Source/Swig/scanner.c @@ -32,6 +32,8 @@ struct Scanner { int error_line; /* Error line number */ int freeze_line; /* Suspend line number updates */ List *brackets; /* Current level of < > brackets on each level */ + int str_delimiter; /* Custom string delimiter: true, false */ + String *str_delimiter_val; /* Custom string delimiter. eg. R"XXX[my custom string "value"]XXX" */ }; void Scanner_push_brackets(Scanner*); @@ -58,6 +60,8 @@ Scanner *NewScanner(void) { s->error = 0; s->freeze_line = 0; s->brackets = NewList(); + s->str_delimiter = 0; + s->str_delimiter_val = NewStringEmpty(); Scanner_push_brackets(s); return s; } @@ -76,8 +80,9 @@ void DelScanner(Scanner * s) { Delete(s->file); Delete(s->error); Delete(s->str); + Delete(s->str_delimiter_val); free(s->idstart); - free(s); + free(s); } /* ----------------------------------------------------------------------------- @@ -93,6 +98,8 @@ void Scanner_clear(Scanner * s) { Clear(s->scanobjs); Scanner_clear_brackets(s); Delete(s->error); + Clear(s->str_delimiter_val); + s->str_delimiter = 0; s->error = 0; s->line = 1; s->nexttoken = -1; @@ -496,15 +503,16 @@ static int look(Scanner * s) { case 1000: if ((c = nextchar(s)) == 0) - return (0); + return (0); if (c == '%') state = 4; /* Possibly a SWIG directive */ - - /* Look for possible identifiers */ + + /* Look for possible identifiers or unicode strings */ else if ((isalpha(c)) || (c == '_') || - (s->idstart && strchr(s->idstart, c))) + (s->idstart && strchr(s->idstart, c))) { state = 7; + } /* Look for single character symbols */ @@ -569,16 +577,16 @@ static int look(Scanner * s) { state = 1; /* Comment (maybe) */ s->start_line = s->line; } - else if (c == '\"') { - state = 2; /* Possibly a string */ - s->start_line = s->line; - Clear(s->text); - } else if (c == ':') state = 5; /* maybe double colon */ else if (c == '0') state = 83; /* An octal or hex value */ + else if (c == '\"') { + state = 2; /* A string or Unicode string constant */ + s->start_line = s->line; + Clear(s->text); + } else if (c == '\'') { s->start_line = s->line; Clear(s->text); @@ -811,22 +819,61 @@ static int look(Scanner * s) { return SWIG_TOKEN_GREATERTHAN; } break; - case 7: /* Identifier */ + case 7: /* Identifier or unicode string */ + if (c!='u' && c!='U' && c!='L') { /* Definitely an identifier */ + state = 70; + break; + } + + if ((c = nextchar(s)) == 0) { + return SWIG_TOKEN_ID; + } + else if (c=='\"') { /* u or U string */ + retract(s, 1); + state = 1000; + } + else if (c=='8') { /* Possibly u8 string */ + state = 71; + break; + } + else { + retract(s, 1); /* Definitely an identifier */ + state = 70; + break; + } + break; + + case 70: /* Identifier */ if ((c = nextchar(s)) == 0) return SWIG_TOKEN_ID; if (isalnum(c) || (c == '_') || (c == '$')) { - state = 7; + state = 70; } else { retract(s, 1); return SWIG_TOKEN_ID; } break; + + case 71: /* Possibly u8 string */ + if ((c = nextchar(s)) == 0) { + return SWIG_TOKEN_ID; + } + if (c=='\"') { + retract(s, 1); + state = 1000; + } + else { + retract(s, 2); /* Definitely an identifier. Retract 8" */ + state = 70; + } + + break; case 75: /* Special identifier $ */ if ((c = nextchar(s)) == 0) return SWIG_TOKEN_DOLLAR; if (isalnum(c) || (c == '_') || (c == '*') || (c == '&')) { - state = 7; + state = 70; } else { retract(s,1); if (Len(s->text) == 1) return SWIG_TOKEN_DOLLAR; From ee8bebb668f780943d3a29fdd1219dc16971627c Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Sun, 28 Jun 2009 19:35:05 +0000 Subject: [PATCH 007/481] Added support for custom string delimiters. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11328 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .../test-suite/cpp0x_raw_string_literals.i | 32 +++-- Source/Swig/scanner.c | 125 ++++++++++++++---- 2 files changed, 122 insertions(+), 35 deletions(-) diff --git a/Examples/test-suite/cpp0x_raw_string_literals.i b/Examples/test-suite/cpp0x_raw_string_literals.i index 0b7ba244b..7e0814768 100644 --- a/Examples/test-suite/cpp0x_raw_string_literals.i +++ b/Examples/test-suite/cpp0x_raw_string_literals.i @@ -16,15 +16,27 @@ using namespace std; -string a="ABC"; -wstring wide=L"ABC"; -string c=u8"ABC"; -string b=u"ABC"; -string d=U"ABC"; +int L = 100; +int u8 = 100; +int u = 100; +int U = 100; + +int R = 100; +int LR = 100; +int u8R = 100; +int uR = 100; +int UR = 100; + +string a ="ABC"; +wstring wide =L"ABC"; +string b =u8"ABC"; +string c =u"ABC"; +string d =U"ABC"; + +string e =R"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX"; +wstring wide2 =LR"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX"; +string f =u8R"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX"; +string g =uR"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX"; +string h =UR"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX"; -/*string e=R"XXX[ABC"blah]XXX"; -string g=u8R"XXX[ABC"blah]XXX"; -string f=uR"XXX[ABC"blah]XXX"; -string h=UR"XXX[ABC"blah]XXX"; -*/ %} diff --git a/Source/Swig/scanner.c b/Source/Swig/scanner.c index a4ac36ac4..5dc2a091b 100644 --- a/Source/Swig/scanner.c +++ b/Source/Swig/scanner.c @@ -32,8 +32,6 @@ struct Scanner { int error_line; /* Error line number */ int freeze_line; /* Suspend line number updates */ List *brackets; /* Current level of < > brackets on each level */ - int str_delimiter; /* Custom string delimiter: true, false */ - String *str_delimiter_val; /* Custom string delimiter. eg. R"XXX[my custom string "value"]XXX" */ }; void Scanner_push_brackets(Scanner*); @@ -60,8 +58,6 @@ Scanner *NewScanner(void) { s->error = 0; s->freeze_line = 0; s->brackets = NewList(); - s->str_delimiter = 0; - s->str_delimiter_val = NewStringEmpty(); Scanner_push_brackets(s); return s; } @@ -80,7 +76,6 @@ void DelScanner(Scanner * s) { Delete(s->file); Delete(s->error); Delete(s->str); - Delete(s->str_delimiter_val); free(s->idstart); free(s); } @@ -98,8 +93,6 @@ void Scanner_clear(Scanner * s) { Clear(s->scanobjs); Scanner_clear_brackets(s); Delete(s->error); - Clear(s->str_delimiter_val); - s->str_delimiter = 0; s->error = 0; s->line = 1; s->nexttoken = -1; @@ -475,13 +468,15 @@ static void get_escape(Scanner *s) { * ----------------------------------------------------------------------------- */ static int look(Scanner * s) { - int state; + int state = 0; int c = 0; + String *str_delimiter = 0; - state = 0; Clear(s->text); s->start_line = s->line; Setfile(s->text, Getfile(s->str)); + + while (1) { switch (state) { case 0: @@ -507,7 +502,7 @@ static int look(Scanner * s) { if (c == '%') state = 4; /* Possibly a SWIG directive */ - /* Look for possible identifiers or unicode strings */ + /* Look for possible identifiers or unicode/delimiter strings */ else if ((isalpha(c)) || (c == '_') || (s->idstart && strchr(s->idstart, c))) { @@ -583,7 +578,7 @@ static int look(Scanner * s) { else if (c == '0') state = 83; /* An octal or hex value */ else if (c == '\"') { - state = 2; /* A string or Unicode string constant */ + state = 2; /* A string constant */ s->start_line = s->line; Clear(s->text); } @@ -665,18 +660,63 @@ static int look(Scanner * s) { break; case 2: /* Processing a string */ + if (!str_delimiter) { + state=20; + break; + } + if ((c = nextchar(s)) == 0) { Swig_error(cparse_file, cparse_start_line, "Unterminated string\n"); return SWIG_TOKEN_ERROR; } - if (c == '\"') { - Delitem(s->text, DOH_END); - return SWIG_TOKEN_STRING; - } else if (c == '\\') { - Delitem(s->text, DOH_END); - get_escape(s); - } else - state = 2; + else if (c == '[') { + state = 20; + } + else { + char temp[2] = { 0, 0 }; + temp[0] = c; + Append( str_delimiter, temp ); + } + + break; + + case 20: /* Inside the string */ + if ((c = nextchar(s)) == 0) { + Swig_error(cparse_file, cparse_start_line, "Unterminated string\n"); + return SWIG_TOKEN_ERROR; + } + + if (!str_delimiter) { /* Ordinary string: "value" */ + if (c == '\"') { + Delitem(s->text, DOH_END); + return SWIG_TOKEN_STRING; + } else if (c == '\\') { + Delitem(s->text, DOH_END); + get_escape(s); + } + } else { /* Custom delimiter string: R"XXXX[value]XXXX" */ + if (c==']') { + int i=0; + String *end_delimiter = NewStringEmpty(); + while ((c = nextchar(s)) != 0 && c!='\"') { + char temp[2] = { 0, 0 }; + temp[0] = c; + Append( end_delimiter, temp ); + i++; + } + + if (Strcmp( str_delimiter, end_delimiter )==0) { + Delete( end_delimiter ); /* Correct end delimiter ]XXXX" occured */ + Delete( str_delimiter ); + str_delimiter = 0; + return SWIG_TOKEN_STRING; + } else { /* Incorrect end delimiter occured */ + retract( s, i ); + Delete( end_delimiter ); + } + } + } + break; case 3: /* Maybe a not equals */ @@ -819,8 +859,13 @@ static int look(Scanner * s) { return SWIG_TOKEN_GREATERTHAN; } break; - case 7: /* Identifier or unicode string */ - if (c!='u' && c!='U' && c!='L') { /* Definitely an identifier */ + + case 7: /* Identifier or unicode/custom delimiter string */ + if (c=='R') { /* Possibly CUSTOM DELIMITER string */ + state = 72; + break; + } + else if (c!='u' && c!='U' && c!='L') { /* Definitely an identifier */ state = 70; break; } @@ -828,18 +873,19 @@ static int look(Scanner * s) { if ((c = nextchar(s)) == 0) { return SWIG_TOKEN_ID; } - else if (c=='\"') { /* u or U string */ + else if (c=='\"') { /* Definitely u, U or L string */ retract(s, 1); state = 1000; } + else if (c=='R') { /* Possibly CUSTOM DELIMITER u, U, L string */ + state = 73; + } else if (c=='8') { /* Possibly u8 string */ state = 71; - break; } else { retract(s, 1); /* Definitely an identifier */ state = 70; - break; } break; @@ -859,9 +905,12 @@ static int look(Scanner * s) { return SWIG_TOKEN_ID; } if (c=='\"') { - retract(s, 1); + retract(s, 1); /* Definitely u8 string */ state = 1000; } + else if (c=='R') { + state = 74; /* Possibly CUSTOM DELIMITER u8 string */ + } else { retract(s, 2); /* Definitely an identifier. Retract 8" */ state = 70; @@ -869,6 +918,32 @@ static int look(Scanner * s) { break; + case 72: /* Possibly CUSTOM DELIMITER string */ + case 73: + case 74: + if ((c = nextchar(s)) == 0) { + return SWIG_TOKEN_ID; + } + if (c=='\"') { + retract(s, 1); /* Definitely custom delimiter u, U or L string */ + str_delimiter = NewStringEmpty(); + state = 1000; + } + else { + if (state==72) { + retract(s, 1); /* Definitely an identifier. Retract ? */ + } + else if (state==73) { + retract(s, 2); /* Definitely an identifier. Retract R? */ + } + else if (state==74) { + retract(s, 3); /* Definitely an identifier. Retract 8R? */ + } + state = 70; + } + + break; + case 75: /* Special identifier $ */ if ((c = nextchar(s)) == 0) return SWIG_TOKEN_DOLLAR; From 72708ea1732df4b09adcb3151257c4f9eb31d503 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Sun, 5 Jul 2009 14:33:40 +0000 Subject: [PATCH 008/481] Added support for C++0x static_assert(). git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11369 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 3 ++- Examples/test-suite/cpp0x_static_assert.i | 17 +++++++++++++++++ Source/CParse/cscanner.c | 2 ++ Source/CParse/parser.y | 14 +++++++++++++- 4 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 Examples/test-suite/cpp0x_static_assert.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index fc00c1243..c0fdd0d96 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -402,7 +402,8 @@ CPP_TEST_CASES += \ CPP0X_TEST_CASES = \ cpp0x_template_double_brackets \ cpp0x_explicit_conversion_operators \ - cpp0x_raw_string_literals + cpp0x_raw_string_literals \ + cpp0x_static_assert # cpp0x_constexpr # not supported by any compilers yet # Broken C++0x test cases. diff --git a/Examples/test-suite/cpp0x_static_assert.i b/Examples/test-suite/cpp0x_static_assert.i new file mode 100644 index 000000000..112168f5e --- /dev/null +++ b/Examples/test-suite/cpp0x_static_assert.i @@ -0,0 +1,17 @@ +/* This test case checks whether swig correctly parses and ignores the + keywords "static_assert()" inside the class or struct. +*/ +%module static_assert + +%inline %{ +template +struct Check1 { + static_assert(sizeof(int) <= sizeof(T), "not big enough"); +}; + +template +class Check2 { + static_assert(sizeof(int) <= sizeof(T), "not big enough"); +}; +%} + diff --git a/Source/CParse/cscanner.c b/Source/CParse/cscanner.c index a2a0631c1..e4f16bf1c 100644 --- a/Source/CParse/cscanner.c +++ b/Source/CParse/cscanner.c @@ -634,6 +634,8 @@ int yylex(void) { return (CONSTEXPR); if (strcmp(yytext, "virtual") == 0) return (VIRTUAL); + if (strcmp(yytext, "static_assert") == 0) + return (STATIC_ASSERT); if (strcmp(yytext, "operator") == 0) { int nexttok; String *s = NewString("operator "); diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index b4c2b4fb4..47dc091f4 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1493,6 +1493,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %token NAME RENAME NAMEWARN EXTEND PRAGMA FEATURE VARARGS %token ENUM %token CLASS TYPENAME PRIVATE PUBLIC PROTECTED COLON STATIC VIRTUAL FRIEND THROW CATCH EXPLICIT CONSTEXPR +%token STATIC_ASSERT %token USING %token NAMESPACE %token NATIVE INLINE @@ -1539,7 +1540,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { /* C++ declarations */ %type cpp_declaration cpp_class_decl cpp_forward_class_decl cpp_template_decl; %type cpp_members cpp_member; -%type cpp_constructor_decl cpp_destructor_decl cpp_protection_decl cpp_conversion_operator; +%type cpp_constructor_decl cpp_destructor_decl cpp_protection_decl cpp_conversion_operator cpp_static_assert; %type cpp_swig_directive cpp_temp_possible cpp_nested cpp_opt_declarators ; %type cpp_using_decl cpp_namespace_decl cpp_catch_decl ; %type kwargs options; @@ -3864,6 +3865,9 @@ cpp_temp_possible: c_decl { | cpp_constructor_decl { $$ = $1; } + | cpp_static_assert { + $$ = $1; + } | cpp_template_decl { $$ = 0; } @@ -4110,6 +4114,7 @@ cpp_member : c_declaration { $$ = $1; } default_arguments($$); } | cpp_destructor_decl { $$ = $1; } + | cpp_static_assert { $$ = $1; } | cpp_protection_decl { $$ = $1; } | cpp_swig_directive { $$ = $1; } | cpp_conversion_operator { $$ = $1; } @@ -4281,6 +4286,13 @@ cpp_catch_decl : CATCH LPAREN parms RPAREN LBRACE { } ; +/* static_assert(bool, const char*); */ +cpp_static_assert : STATIC_ASSERT LPAREN { + skip_balanced('(',')'); + $$ = 0; + } + ; + /* public: */ cpp_protection_decl : PUBLIC COLON { $$ = new_node("access"); From e1b5d43cd8e3cf899fa771333d337dff59d00a4f Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Sat, 11 Jul 2009 20:13:36 +0000 Subject: [PATCH 009/481] Added C++0x support for 'extern' explicit template instantiation without the translation unit. Added test cases. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11385 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 3 ++- Examples/test-suite/cpp0x_constexpr.i | 3 ++- Examples/test-suite/cpp0x_explicit_conversion_operators.i | 2 +- Examples/test-suite/cpp0x_raw_string_literals.i | 3 +-- Examples/test-suite/cpp0x_static_assert.i | 2 +- Examples/test-suite/cpp0x_template_double_brackets.i | 2 +- Source/CParse/parser.y | 8 ++++++-- 7 files changed, 14 insertions(+), 9 deletions(-) diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index c0fdd0d96..bd5f7b983 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -403,7 +403,8 @@ CPP0X_TEST_CASES = \ cpp0x_template_double_brackets \ cpp0x_explicit_conversion_operators \ cpp0x_raw_string_literals \ - cpp0x_static_assert + cpp0x_static_assert \ + cpp0x_template_explicit # cpp0x_constexpr # not supported by any compilers yet # Broken C++0x test cases. diff --git a/Examples/test-suite/cpp0x_constexpr.i b/Examples/test-suite/cpp0x_constexpr.i index 4345ec0af..6cae41825 100644 --- a/Examples/test-suite/cpp0x_constexpr.i +++ b/Examples/test-suite/cpp0x_constexpr.i @@ -1,10 +1,11 @@ /* This interface tests whether Swig supports the new "constexpr" keyword introduced by C++0x. */ -%module foo +%module cpp0x_constexpr %inline %{ class TestClass { +public: constexpr int func() { return 10; } }; %} diff --git a/Examples/test-suite/cpp0x_explicit_conversion_operators.i b/Examples/test-suite/cpp0x_explicit_conversion_operators.i index ae97ec185..6532efb23 100644 --- a/Examples/test-suite/cpp0x_explicit_conversion_operators.i +++ b/Examples/test-suite/cpp0x_explicit_conversion_operators.i @@ -1,7 +1,7 @@ /* This interface checks whether Swig correctly compiles the new explicit conversion operators feature introduced in C++0x. */ -%module foo +%module cpp0x_explicit_conversion_operators %inline %{ diff --git a/Examples/test-suite/cpp0x_raw_string_literals.i b/Examples/test-suite/cpp0x_raw_string_literals.i index 7e0814768..4da565264 100644 --- a/Examples/test-suite/cpp0x_raw_string_literals.i +++ b/Examples/test-suite/cpp0x_raw_string_literals.i @@ -7,8 +7,7 @@ This module also tests whether Swig correctly parses custom string delimiters. */ - -%module raw_string_literals +%module cpp0x_raw_string_literals %inline %{ #include diff --git a/Examples/test-suite/cpp0x_static_assert.i b/Examples/test-suite/cpp0x_static_assert.i index 112168f5e..28c244c87 100644 --- a/Examples/test-suite/cpp0x_static_assert.i +++ b/Examples/test-suite/cpp0x_static_assert.i @@ -1,7 +1,7 @@ /* This test case checks whether swig correctly parses and ignores the keywords "static_assert()" inside the class or struct. */ -%module static_assert +%module cpp0x_static_assert %inline %{ template diff --git a/Examples/test-suite/cpp0x_template_double_brackets.i b/Examples/test-suite/cpp0x_template_double_brackets.i index 31c9c7248..74d2fc768 100644 --- a/Examples/test-suite/cpp0x_template_double_brackets.i +++ b/Examples/test-suite/cpp0x_template_double_brackets.i @@ -2,7 +2,7 @@ in the template syntax without having a space inbetween. This feature was introduced in new C++0x standard. */ -%module foo +%module cpp0x_template_double_brackets %inline %{ #include std::map> m; diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 47dc091f4..67cf2dd53 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -3850,10 +3850,14 @@ cpp_template_decl : TEMPLATE LESSTHAN template_parms GREATERTHAN { template_para Namespaceprefix = Swig_symbol_qualifiedscopename(0); if (error) $$ = 0; } - | TEMPLATE cpptype idcolon { + | TEMPLATE cpptype idcolon { /* Explicit template instantiation */ Swig_warning(WARN_PARSE_EXPLICIT_TEMPLATE, cparse_file, cparse_line, "Explicit template instantiation ignored.\n"); $$ = 0; - } + } + | EXTERN TEMPLATE cpptype idcolon { /* Explicit template instantiation without the translation unit */ + Swig_warning(WARN_PARSE_EXPLICIT_TEMPLATE, cparse_file, cparse_line, "Explicit template instantiation ignored.\n"); + $$ = 0; + } ; cpp_temp_possible: c_decl { From 31436be60f7242f88add85dc1eae0be9f245a3a5 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Sat, 11 Jul 2009 20:14:35 +0000 Subject: [PATCH 010/481] Added test case. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11386 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/cpp0x_template_explicit.i | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Examples/test-suite/cpp0x_template_explicit.i diff --git a/Examples/test-suite/cpp0x_template_explicit.i b/Examples/test-suite/cpp0x_template_explicit.i new file mode 100644 index 000000000..e0ff71073 --- /dev/null +++ b/Examples/test-suite/cpp0x_template_explicit.i @@ -0,0 +1,22 @@ +/* This unit tests whether Swig correctly parses the code and makes wrappers + for the new C++0x extern templates (explicit template instantiation without + using the translation unit). +*/ +%module cpp0x_template_explicit + +%inline %{ +#include + +class A { +public: + int member; + int memberFunction() { return 100; } +}; + +template class std::vector; +extern template class std::vector; + +template class std::vector; +extern template class std::vector; +%} + From 74d8325cdfb8cd8bddb92ed97e66ef00e858158b Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Tue, 14 Jul 2009 12:05:05 +0000 Subject: [PATCH 011/481] Added keyword 'thread_local' to Swig. Added testcase. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11393 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 3 ++- Examples/test-suite/cpp0x_thread_local.i | 11 +++++++++++ Source/CParse/cscanner.c | 2 ++ Source/CParse/parser.y | 5 +++-- 4 files changed, 18 insertions(+), 3 deletions(-) create mode 100644 Examples/test-suite/cpp0x_thread_local.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index bd5f7b983..f81c00f36 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -404,7 +404,8 @@ CPP0X_TEST_CASES = \ cpp0x_explicit_conversion_operators \ cpp0x_raw_string_literals \ cpp0x_static_assert \ - cpp0x_template_explicit + cpp0x_template_explicit \ + cpp0x_thread_local # cpp0x_constexpr # not supported by any compilers yet # Broken C++0x test cases. diff --git a/Examples/test-suite/cpp0x_thread_local.i b/Examples/test-suite/cpp0x_thread_local.i new file mode 100644 index 000000000..35ad970e7 --- /dev/null +++ b/Examples/test-suite/cpp0x_thread_local.i @@ -0,0 +1,11 @@ +/* This testcase checks whether Swig correctly parses the 'thread_local' + keyword before the member type and name. */ + +%module cpp0x_thread_local + +%inline %{ +struct A { + thread_local int val; +}; +%} + diff --git a/Source/CParse/cscanner.c b/Source/CParse/cscanner.c index e4f16bf1c..6ad3b2c5a 100644 --- a/Source/CParse/cscanner.c +++ b/Source/CParse/cscanner.c @@ -632,6 +632,8 @@ int yylex(void) { return (FRIEND); if (strcmp(yytext, "constexpr") == 0) return (CONSTEXPR); + if (strcmp(yytext, "thread_local") == 0) + return (THREAD_LOCAL); if (strcmp(yytext, "virtual") == 0) return (VIRTUAL); if (strcmp(yytext, "static_assert") == 0) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 67cf2dd53..61dc79a4e 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1492,8 +1492,8 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %token ILLEGAL CONSTANT %token NAME RENAME NAMEWARN EXTEND PRAGMA FEATURE VARARGS %token ENUM -%token CLASS TYPENAME PRIVATE PUBLIC PROTECTED COLON STATIC VIRTUAL FRIEND THROW CATCH EXPLICIT CONSTEXPR -%token STATIC_ASSERT +%token CLASS TYPENAME PRIVATE PUBLIC PROTECTED COLON STATIC VIRTUAL FRIEND THROW CATCH EXPLICIT +%token STATIC_ASSERT CONSTEXPR THREAD_LOCAL /* C++0x keywords */ %token USING %token NAMESPACE %token NATIVE INLINE @@ -4507,6 +4507,7 @@ storage_class : EXTERN { $$ = "extern"; } | FRIEND { $$ = "friend"; } | EXPLICIT { $$ = "explicit"; } | CONSTEXPR { $$ = "constexpr"; } + | THREAD_LOCAL { $$ = "thread_local"; } | empty { $$ = 0; } ; From 55268bbc2d44af219af1a658cbe394374791046f Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Tue, 14 Jul 2009 12:26:26 +0000 Subject: [PATCH 012/481] Added testcase for shared_ptr, unique_ptr and weak_ptr. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11394 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 1 + Examples/test-suite/cpp0x_smart_pointers.i | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 Examples/test-suite/cpp0x_smart_pointers.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index f81c00f36..fce242e70 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -406,6 +406,7 @@ CPP0X_TEST_CASES = \ cpp0x_static_assert \ cpp0x_template_explicit \ cpp0x_thread_local +# cpp0x_smart_pointers # not supported by standard library yet # cpp0x_constexpr # not supported by any compilers yet # Broken C++0x test cases. diff --git a/Examples/test-suite/cpp0x_smart_pointers.i b/Examples/test-suite/cpp0x_smart_pointers.i new file mode 100644 index 000000000..4f04e1941 --- /dev/null +++ b/Examples/test-suite/cpp0x_smart_pointers.i @@ -0,0 +1,19 @@ +/* This testcase checks whether Swig correctly uses the new general-purpose + smart pointers introduced in C++0x: + - shared_ptr + - weak_ptr + - unique_ptr +*/ +%module cpp0x_smart_pointers + +%inline %{ +#include +#include +#include + +struct A { + std::shared_ptr a1(new double); + std::unique_ptr a2(new double); + std::weak_ptr a3(a1); +}; +%} From 9fe598cd971d2986af6b7b74b4325c0f8895fb36 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Wed, 15 Jul 2009 21:03:04 +0000 Subject: [PATCH 013/481] Fixed cpp0x_raw_string_literals.i test case. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11402 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .../test-suite/cpp0x_raw_string_literals.i | 23 ++++++++++--------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/Examples/test-suite/cpp0x_raw_string_literals.i b/Examples/test-suite/cpp0x_raw_string_literals.i index 4da565264..12c68cd63 100644 --- a/Examples/test-suite/cpp0x_raw_string_literals.i +++ b/Examples/test-suite/cpp0x_raw_string_literals.i @@ -26,16 +26,17 @@ int u8R = 100; int uR = 100; int UR = 100; -string a ="ABC"; -wstring wide =L"ABC"; -string b =u8"ABC"; -string c =u"ABC"; -string d =U"ABC"; - -string e =R"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX"; -wstring wide2 =LR"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX"; -string f =u8R"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX"; -string g =uR"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX"; -string h =UR"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX"; +char *a = "ABC"; +wstring wide = L"ABC"; +//char *b = u8"ABC"; // not supported by GCC +char16_t *c = u"ABC"; +char32_t *d = U"ABC"; +/* Raw string literals are not supported by GCC yet */ +/*char *e = R"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX"; +wstring wide2 = LR"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX"; +char *f = u8R"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX"; +char16_t *g = uR"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX"; +char32_t *h = UR"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX"; +*/ %} From 63a7f06afbf546c091b7695186ac85a579d5787e Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Fri, 17 Jul 2009 10:21:25 +0000 Subject: [PATCH 014/481] Added support for cpp0x uniform initialization. Added testcases. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11413 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 3 ++- .../test-suite/cpp0x_uniform_initialization.i | 20 +++++++++++++++++++ Source/CParse/parser.y | 11 ++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 Examples/test-suite/cpp0x_uniform_initialization.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index fce242e70..f9f0de807 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -405,7 +405,8 @@ CPP0X_TEST_CASES = \ cpp0x_raw_string_literals \ cpp0x_static_assert \ cpp0x_template_explicit \ - cpp0x_thread_local + cpp0x_thread_local \ + cpp0x_uniform_initialization # cpp0x_smart_pointers # not supported by standard library yet # cpp0x_constexpr # not supported by any compilers yet diff --git a/Examples/test-suite/cpp0x_uniform_initialization.i b/Examples/test-suite/cpp0x_uniform_initialization.i new file mode 100644 index 000000000..a56178930 --- /dev/null +++ b/Examples/test-suite/cpp0x_uniform_initialization.i @@ -0,0 +1,20 @@ +%module cpp0x_uniform_initialization + +%inline %{ +struct BasicStruct { + int x; + double y; +}; + +struct AltStruct { + AltStruct(int x, double y) : x_{x}, y_{y} {} + +private: + int x_; + double y_; +}; + +BasicStruct var1{5, 3.2}; // only fills the struct components +AltStruct var2{2, 4.3}; // calls the constructor + +%} diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 61dc79a4e..35b625b0c 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -5846,6 +5846,17 @@ mem_initializer : idcolon LPAREN { skip_balanced('(',')'); Clear(scanner_ccode); } + | idcolon LBRACE { + /* Uniform initialization. eg. + struct MyStruct { + MyStruct(int x, double y) : x_{x}, y_{y} {} + int x_; + double y_; + }; + */ + skip_balanced('{','}'); + Clear(scanner_ccode); + } ; template_decl : LESSTHAN valparms GREATERTHAN { From 03db5b499151aa9c544cd97f5cbe3a3027045a8a Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Fri, 17 Jul 2009 11:17:01 +0000 Subject: [PATCH 015/481] Added support for C++0x alternate function syntax. Added testcase. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11414 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 3 +- .../cpp0x_alternate_function_syntax.i | 11 +++++ Source/CParse/cscanner.c | 6 +++ Source/CParse/parser.y | 43 ++++++++++++------- Source/Swig/stype.c | 3 ++ Source/Swig/swig.h | 1 + Source/Swig/typesys.c | 2 + 7 files changed, 53 insertions(+), 16 deletions(-) create mode 100644 Examples/test-suite/cpp0x_alternate_function_syntax.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index f9f0de807..4ab20575a 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -406,7 +406,8 @@ CPP0X_TEST_CASES = \ cpp0x_static_assert \ cpp0x_template_explicit \ cpp0x_thread_local \ - cpp0x_uniform_initialization + cpp0x_uniform_initialization \ + cpp0x_alternate_function_syntax # cpp0x_smart_pointers # not supported by standard library yet # cpp0x_constexpr # not supported by any compilers yet diff --git a/Examples/test-suite/cpp0x_alternate_function_syntax.i b/Examples/test-suite/cpp0x_alternate_function_syntax.i new file mode 100644 index 000000000..ed3cb6729 --- /dev/null +++ b/Examples/test-suite/cpp0x_alternate_function_syntax.i @@ -0,0 +1,11 @@ +%module cpp0x_alternate_function_syntax + +%inline %{ +struct SomeStruct { + auto FuncName(int x, int y) -> int; +}; + +auto SomeStruct::FuncName(int x, int y) -> int { + return x + y; +} +%} diff --git a/Source/CParse/cscanner.c b/Source/CParse/cscanner.c index 6ad3b2c5a..1fe0735db 100644 --- a/Source/CParse/cscanner.c +++ b/Source/CParse/cscanner.c @@ -340,6 +340,8 @@ int yylook(void) { return GREATERTHANOREQUALTO; case SWIG_TOKEN_RSHIFT: return RSHIFT; + case SWIG_TOKEN_ARROW: + return ARROW; case SWIG_TOKEN_PERIOD: return PERIOD; case SWIG_TOKEN_MODULO: @@ -593,6 +595,10 @@ int yylex(void) { yylval.type = NewSwigType(T_BOOL); return (TYPE_BOOL); } + if (strcmp(yytext, "auto") == 0) { + yylval.type = NewSwigType(T_AUTO); + return (TYPE_AUTO); + } /* Non ISO (Windows) C extensions */ if (strcmp(yytext, "__int8") == 0) { diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 35b625b0c..093c4d315 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1486,7 +1486,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %token CHARCONST %token NUM_INT NUM_FLOAT NUM_UNSIGNED NUM_LONG NUM_ULONG NUM_LONGLONG NUM_ULONGLONG %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 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 TYPE_AUTO %token LPAREN RPAREN COMMA SEMI EXTERN INIT LBRACE RBRACE PERIOD %token CONST_QUAL VOLATILE REGISTER STRUCT UNION EQUAL SIZEOF MODULE LBRACKET RBRACKET %token ILLEGAL CONSTANT @@ -1501,6 +1501,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %token WARN %token LESSTHAN GREATERTHAN MODULO DELETE_KW %token LESSTHANOREQUALTO GREATERTHANOREQUALTO EQUALTO NOTEQUALTO +%token ARROW %token QUESTIONMARK %token TYPES PARMS %token NONID DSTAR DCNOT @@ -1534,7 +1535,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %type types_directive template_directive warn_directive ; /* C declarations */ -%type c_declaration c_decl c_decl_tail c_enum_decl c_enum_forward_decl c_constructor_decl ; +%type c_declaration c_decl c_decl_tail c_enum_decl c_enum_forward_decl c_constructor_decl c_rettype ; %type enumlist edecl; /* C++ declarations */ @@ -2939,25 +2940,25 @@ c_declaration : c_decl { A C global declaration of some kind (may be variable, function, typedef, etc.) ------------------------------------------------------------ */ -c_decl : storage_class type declarator initializer c_decl_tail { +c_decl : storage_class type declarator c_rettype initializer c_decl_tail { $$ = new_node("cdecl"); - if ($4.qualifier) SwigType_push($3.type,$4.qualifier); + if ($5.qualifier) SwigType_push($3.type,$5.qualifier); Setattr($$,"type",$2); Setattr($$,"storage",$1); Setattr($$,"name",$3.id); Setattr($$,"decl",$3.type); Setattr($$,"parms",$3.parms); - Setattr($$,"value",$4.val); - Setattr($$,"throws",$4.throws); - Setattr($$,"throw",$4.throwf); - if (!$5) { + Setattr($$,"value",$5.val); + Setattr($$,"throws",$5.throws); + Setattr($$,"throw",$5.throwf); + if (!$6) { if (Len(scanner_ccode)) { String *code = Copy(scanner_ccode); Setattr($$,"code",code); Delete(code); } } else { - Node *n = $5; + Node *n = $6; /* Inherit attributes */ while (n) { String *type = Copy($2); @@ -2967,8 +2968,8 @@ c_decl : storage_class type declarator initializer c_decl_tail { Delete(type); } } - if ($4.bitfield) { - Setattr($$,"bitfield", $4.bitfield); + if ($5.bitfield) { + Setattr($$,"bitfield", $5.bitfield); } /* Look for "::" declarations (ignored) */ @@ -2982,22 +2983,33 @@ c_decl : storage_class type declarator initializer c_decl_tail { String *lstr = Swig_scopename_last($3.id); Setattr($$,"name",lstr); Delete(lstr); - set_nextSibling($$,$5); + set_nextSibling($$,$6); } else { Delete($$); - $$ = $5; + $$ = $6; } Delete(p); } else { Delete($$); - $$ = $5; + $$ = $6; } } else { - set_nextSibling($$,$5); + set_nextSibling($$,$6); } } ; +/* Alternate function syntax: + auto funcName(int x, int y) -> int; */ + +c_rettype : ARROW type { + $$ = new_node("rettype"); + Setattr($$,"type",$2); + } + | empty { + $$ = 0; + } + ; /* Allow lists of variables and functions to be built up */ c_decl_tail : SEMI { @@ -5209,6 +5221,7 @@ type_right : primitive_type { $$ = $1; } | TYPE_BOOL { $$ = $1; } | TYPE_VOID { $$ = $1; } + | TYPE_AUTO { $$ = $1; } | TYPE_TYPEDEF template_decl { $$ = NewStringf("%s%s",$1,$2); } | ENUM idcolon { $$ = NewStringf("enum %s", $2); } | TYPE_RAW { $$ = $1; } diff --git a/Source/Swig/stype.c b/Source/Swig/stype.c index 8a7700bec..3b56e98cb 100644 --- a/Source/Swig/stype.c +++ b/Source/Swig/stype.c @@ -141,6 +141,9 @@ SwigType *NewSwigType(int t) { case T_VOID: return NewString("void"); break; + case T_AUTO: + return NewString("auto"); + break; default: break; } diff --git a/Source/Swig/swig.h b/Source/Swig/swig.h index 2b2c797c9..7eb9ef210 100644 --- a/Source/Swig/swig.h +++ b/Source/Swig/swig.h @@ -73,6 +73,7 @@ extern "C" { #define T_FLTCPLX 23 #define T_DBLCPLX 24 #define T_NUMERIC 25 +#define T_AUTO 26 #define T_COMPLEX T_DBLCPLX diff --git a/Source/Swig/typesys.c b/Source/Swig/typesys.c index 2562e12f8..9b11a08e5 100644 --- a/Source/Swig/typesys.c +++ b/Source/Swig/typesys.c @@ -1257,6 +1257,8 @@ int SwigType_type(SwigType *t) { return T_ULONGLONG; if (strncmp(c, "enum ", 5) == 0) return T_INT; + if (strcmp(c, "auto") == 0) + return T_AUTO; if (strcmp(c, "v(...)") == 0) return T_VARARGS; From 048fa1253344676671f44d0c836a1f8776d84a84 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Sat, 18 Jul 2009 19:15:36 +0000 Subject: [PATCH 016/481] Added C++0x test case for the hash_tables. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11417 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/cpp0x_hash_tables.i | 39 +++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Examples/test-suite/cpp0x_hash_tables.i diff --git a/Examples/test-suite/cpp0x_hash_tables.i b/Examples/test-suite/cpp0x_hash_tables.i new file mode 100644 index 000000000..0888590cd --- /dev/null +++ b/Examples/test-suite/cpp0x_hash_tables.i @@ -0,0 +1,39 @@ +%module cpp0x_hash_tables + +%inline %{ +#include +#include +#include +#include +%} + +%include "std_set.i" +%include "std_map.i" +%template (SetInt) std::set; +%template (MapIntInt) std::map; +%template (UnorderedSetInt) std::unordered_set; +%template (UnorderedMapIntInt) std::unordered_map; + +%inline %{ +using namespace std; + +class MyClass { +public: + set getSet() { return _set; } + void addSet(int elt) { _set.insert(_set.begin(), elt); } + map getMap() { return _map; } + void addMap(int elt1, int elt2) { _map.insert(make_pair(elt1, elt2)); } + + unordered_set getUnorderedSet() { return _unordered_set; } + void addUnorderedSet(int elt) { _unordered_set.insert(_unordered_set.begin(), elt); } + unordered_map getUnorderedMap() { return _unordered_map; } + void addUnorderedMap(int elt1, int elt2) { _unordered_map.insert(make_pair(elt1, elt2)); } +private: + set _set; + map _map; + + unordered_set _unordered_set; + unordered_map _unordered_map; +}; +%} + From 523817e4ee33fd5495030285222bc66e1419facd Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Sat, 18 Jul 2009 21:34:53 +0000 Subject: [PATCH 017/481] Added initial support for hash tables unordered_ types. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11418 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/cpp0x_hash_tables.i | 24 +-- Lib/python/std_unordered_map.i | 251 ++++++++++++++++++++++++ Lib/python/std_unordered_multimap.i | 79 ++++++++ Lib/python/std_unordered_multiset.i | 41 ++++ Lib/python/std_unordered_set.i | 55 ++++++ Lib/std/std_multimap.i | 2 +- Lib/std/std_multiset.i | 2 +- Lib/std/std_unordered_map.i | 124 ++++++++++++ Lib/std/std_unordered_multimap.i | 87 ++++++++ Lib/std/std_unordered_multiset.i | 83 ++++++++ Lib/std/std_unordered_set.i | 116 +++++++++++ 11 files changed, 851 insertions(+), 13 deletions(-) create mode 100644 Lib/python/std_unordered_map.i create mode 100644 Lib/python/std_unordered_multimap.i create mode 100644 Lib/python/std_unordered_multiset.i create mode 100644 Lib/python/std_unordered_set.i create mode 100644 Lib/std/std_unordered_map.i create mode 100644 Lib/std/std_unordered_multimap.i create mode 100644 Lib/std/std_unordered_multiset.i create mode 100644 Lib/std/std_unordered_set.i diff --git a/Examples/test-suite/cpp0x_hash_tables.i b/Examples/test-suite/cpp0x_hash_tables.i index 0888590cd..a4829ce1f 100644 --- a/Examples/test-suite/cpp0x_hash_tables.i +++ b/Examples/test-suite/cpp0x_hash_tables.i @@ -2,17 +2,19 @@ %inline %{ #include -#include +//#include #include -#include +//#include %} %include "std_set.i" -%include "std_map.i" +//%include "std_map.i" +%include "std_unordered_set.i" +//%include "std_unordered_map.i" %template (SetInt) std::set; -%template (MapIntInt) std::map; +//%template (MapIntInt) std::map; %template (UnorderedSetInt) std::unordered_set; -%template (UnorderedMapIntInt) std::unordered_map; +//%template (UnorderedMapIntInt) std::unordered_map; %inline %{ using namespace std; @@ -21,19 +23,19 @@ class MyClass { public: set getSet() { return _set; } void addSet(int elt) { _set.insert(_set.begin(), elt); } - map getMap() { return _map; } - void addMap(int elt1, int elt2) { _map.insert(make_pair(elt1, elt2)); } +// map getMap() { return _map; } +// void addMap(int elt1, int elt2) { _map.insert(make_pair(elt1, elt2)); } unordered_set getUnorderedSet() { return _unordered_set; } void addUnorderedSet(int elt) { _unordered_set.insert(_unordered_set.begin(), elt); } - unordered_map getUnorderedMap() { return _unordered_map; } - void addUnorderedMap(int elt1, int elt2) { _unordered_map.insert(make_pair(elt1, elt2)); } +// unordered_map getUnorderedMap() { return _unordered_map; } +// void addUnorderedMap(int elt1, int elt2) { _unordered_map.insert(make_pair(elt1, elt2)); } private: set _set; - map _map; +// map _map; unordered_set _unordered_set; - unordered_map _unordered_map; +// unordered_map _unordered_map; }; %} diff --git a/Lib/python/std_unordered_map.i b/Lib/python/std_unordered_map.i new file mode 100644 index 000000000..b456035e2 --- /dev/null +++ b/Lib/python/std_unordered_map.i @@ -0,0 +1,251 @@ +/* + Unordered Maps +*/ + +%fragment("StdMapTraits","header",fragment="StdSequenceTraits") +{ + namespace swig { + template + inline void + assign(const SwigPySeq& swigpyseq, std::unordered_map *unordered_map) { + typedef typename std::unordered_map::value_type value_type; + typename SwigPySeq::const_iterator it = swigpyseq.begin(); + for (;it != swigpyseq.end(); ++it) { + unordered_map->insert(value_type(it->first, it->second)); + } + } + + template + struct traits_asptr > { + typedef std::unordered_map unordered_map_type; + static int asptr(PyObject *obj, unordered_map_type **val) { + int res = SWIG_ERROR; + if (PyDict_Check(obj)) { + SwigVar_PyObject items = PyObject_CallMethod(obj,(char *)"items",NULL); +%#if PY_VERSION_HEX >= 0x03000000 + /* In Python 3.x the ".items()" method return a dict_items object */ + items = PySequence_Fast(items, ".items() havn't returned a sequence!"); +%#endif + res = traits_asptr_stdseq, std::pair >::asptr(items, val); + } else { + unordered_map_type *p; + res = SWIG_ConvertPtr(obj,(void**)&p,swig::type_info(),0); + if (SWIG_IsOK(res) && val) *val = p; + } + return res; + } + }; + + template + struct traits_from > { + typedef std::unordered_map unordered_map_type; + typedef typename unordered_map_type::const_iterator const_iterator; + typedef typename unordered_map_type::size_type size_type; + + static PyObject *from(const unordered_map_type& unordered_map) { + swig_type_info *desc = swig::type_info(); + if (desc && desc->clientdata) { + return SWIG_NewPointerObj(new unordered_map_type(unordered_map), desc, SWIG_POINTER_OWN); + } else { + size_type size = unordered_map.size(); + int pysize = (size <= (size_type) INT_MAX) ? (int) size : -1; + if (pysize < 0) { + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + PyErr_SetString(PyExc_OverflowError, + "unordered_map size not valid in python"); + SWIG_PYTHON_THREAD_END_BLOCK; + return NULL; + } + PyObject *obj = PyDict_New(); + for (const_iterator i= unordered_map.begin(); i!= unordered_map.end(); ++i) { + swig::SwigVar_PyObject key = swig::from(i->first); + swig::SwigVar_PyObject val = swig::from(i->second); + PyDict_SetItem(obj, key, val); + } + return obj; + } + } + }; + + template + struct from_key_oper + { + typedef const ValueType& argument_type; + typedef PyObject *result_type; + result_type operator()(argument_type v) const + { + return swig::from(v.first); + } + }; + + template + struct from_value_oper + { + typedef const ValueType& argument_type; + typedef PyObject *result_type; + result_type operator()(argument_type v) const + { + return swig::from(v.second); + } + }; + + template + struct SwigPyMapIterator_T : SwigPyIteratorClosed_T + { + SwigPyMapIterator_T(OutIterator curr, OutIterator first, OutIterator last, PyObject *seq) + : SwigPyIteratorClosed_T(curr, first, last, seq) + { + } + }; + + + template > + struct SwigPyMapKeyIterator_T : SwigPyMapIterator_T + { + SwigPyMapKeyIterator_T(OutIterator curr, OutIterator first, OutIterator last, PyObject *seq) + : SwigPyMapIterator_T(curr, first, last, seq) + { + } + }; + + template + inline SwigPyIterator* + make_output_key_iterator(const OutIter& current, const OutIter& begin, const OutIter& end, PyObject *seq = 0) + { + return new SwigPyMapKeyIterator_T(current, begin, end, seq); + } + + template > + struct SwigPyMapValueITerator_T : SwigPyMapIterator_T + { + SwigPyMapValueITerator_T(OutIterator curr, OutIterator first, OutIterator last, PyObject *seq) + : SwigPyMapIterator_T(curr, first, last, seq) + { + } + }; + + + template + inline SwigPyIterator* + make_output_value_iterator(const OutIter& current, const OutIter& begin, const OutIter& end, PyObject *seq = 0) + { + return new SwigPyMapValueITerator_T(current, begin, end, seq); + } + } +} + +%define %swig_unordered_map_common(Map...) + %swig_sequence_iterator(Map); + %swig_container_methods(Map) + + %extend { + mapped_type __getitem__(const key_type& key) const throw (std::out_of_range) { + Map::const_iterator i = self->find(key); + if (i != self->end()) + return i->second; + else + throw std::out_of_range("key not found"); + } + + void __delitem__(const key_type& key) throw (std::out_of_range) { + Map::iterator i = self->find(key); + if (i != self->end()) + self->erase(i); + else + throw std::out_of_range("key not found"); + } + + bool has_key(const key_type& key) const { + Map::const_iterator i = self->find(key); + return i != self->end(); + } + + PyObject* keys() { + Map::size_type size = self->size(); + int pysize = (size <= (Map::size_type) INT_MAX) ? (int) size : -1; + if (pysize < 0) { + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + PyErr_SetString(PyExc_OverflowError, + "unordered_map size not valid in python"); + SWIG_PYTHON_THREAD_END_BLOCK; + return NULL; + } + PyObject* keyList = PyList_New(pysize); + Map::const_iterator i = self->begin(); + for (int j = 0; j < pysize; ++i, ++j) { + PyList_SET_ITEM(keyList, j, swig::from(i->first)); + } + return keyList; + } + + PyObject* values() { + Map::size_type size = self->size(); + int pysize = (size <= (Map::size_type) INT_MAX) ? (int) size : -1; + if (pysize < 0) { + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + PyErr_SetString(PyExc_OverflowError, + "unordered_map size not valid in python"); + SWIG_PYTHON_THREAD_END_BLOCK; + return NULL; + } + PyObject* valList = PyList_New(pysize); + Map::const_iterator i = self->begin(); + for (int j = 0; j < pysize; ++i, ++j) { + PyList_SET_ITEM(valList, j, swig::from(i->second)); + } + return valList; + } + + PyObject* items() { + Map::size_type size = self->size(); + int pysize = (size <= (Map::size_type) INT_MAX) ? (int) size : -1; + if (pysize < 0) { + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + PyErr_SetString(PyExc_OverflowError, + "unordered_map size not valid in python"); + SWIG_PYTHON_THREAD_END_BLOCK; + return NULL; + } + PyObject* itemList = PyList_New(pysize); + Map::const_iterator i = self->begin(); + for (int j = 0; j < pysize; ++i, ++j) { + PyList_SET_ITEM(itemList, j, swig::from(*i)); + } + return itemList; + } + + // Python 2.2 methods + bool __contains__(const key_type& key) { + return self->find(key) != self->end(); + } + + %newobject key_iterator(PyObject **PYTHON_SELF); + swig::SwigPyIterator* key_iterator(PyObject **PYTHON_SELF) { + return swig::make_output_key_iterator(self->begin(), self->begin(), self->end(), *PYTHON_SELF); + } + + %newobject value_iterator(PyObject **PYTHON_SELF); + swig::SwigPyIterator* value_iterator(PyObject **PYTHON_SELF) { + return swig::make_output_value_iterator(self->begin(), self->begin(), self->end(), *PYTHON_SELF); + } + + %pythoncode {def __iter__(self): return self.key_iterator()} + %pythoncode {def iterkeys(self): return self.key_iterator()} + %pythoncode {def itervalues(self): return self.value_iterator()} + %pythoncode {def iteritems(self): return self.iterator()} + } +%enddef + +%define %swig_unordered_map_methods(Map...) + %swig_unordered_map_common(Map) + %extend { + void __setitem__(const key_type& key, const mapped_type& x) throw (std::out_of_range) { + (*self)[key] = x; + } + } +%enddef + + +%include diff --git a/Lib/python/std_unordered_multimap.i b/Lib/python/std_unordered_multimap.i new file mode 100644 index 000000000..adf86f251 --- /dev/null +++ b/Lib/python/std_unordered_multimap.i @@ -0,0 +1,79 @@ +/* + Unordered Multimaps +*/ +%include + +%fragment("StdUnorderedMultimapTraits","header",fragment="StdSequenceTraits") +{ + namespace swig { + template + inline void + assign(const SwigPySeq& swigpyseq, std::unordered_multimap *unordered_multimap) { + typedef typename std::unordered_multimap::value_type value_type; + typename SwigPySeq::const_iterator it = swigpyseq.begin(); + for (;it != swigpyseq.end(); ++it) { + unordered_multimap->insert(value_type(it->first, it->second)); + } + } + + template + struct traits_asptr > { + typedef std::unordered_multimap unordered_multimap_type; + static int asptr(PyObject *obj, std::unordered_multimap **val) { + int res = SWIG_ERROR; + if (PyDict_Check(obj)) { + SwigVar_PyObject items = PyObject_CallMethod(obj,(char *)"items",NULL); + return traits_asptr_stdseq, std::pair >::asptr(items, val); + } else { + unordered_multimap_type *p; + res = SWIG_ConvertPtr(obj,(void**)&p,swig::type_info(),0); + if (SWIG_IsOK(res) && val) *val = p; + } + return res; + } + }; + + template + struct traits_from > { + typedef std::unordered_multimap unordered_multimap_type; + typedef typename unordered_multimap_type::const_iterator const_iterator; + typedef typename unordered_multimap_type::size_type size_type; + + static PyObject *from(const unordered_multimap_type& unordered_multimap) { + swig_type_info *desc = swig::type_info(); + if (desc && desc->clientdata) { + return SWIG_NewPointerObj(new unordered_multimap_type(unordered_multimap), desc, SWIG_POINTER_OWN); + } else { + size_type size = unordered_multimap.size(); + int pysize = (size <= (size_type) INT_MAX) ? (int) size : -1; + if (pysize < 0) { + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + PyErr_SetString(PyExc_OverflowError, + "unordered_multimap size not valid in python"); + SWIG_PYTHON_THREAD_END_BLOCK; + return NULL; + } + PyObject *obj = PyDict_New(); + for (const_iterator i= unordered_multimap.begin(); i!= unordered_multimap.end(); ++i) { + swig::SwigVar_PyObject key = swig::from(i->first); + swig::SwigVar_PyObject val = swig::from(i->second); + PyDict_SetItem(obj, key, val); + } + return obj; + } + } + }; + } +} + +%define %swig_unordered_multimap_methods(Type...) + %swig_map_common(Type); + %extend { + void __setitem__(const key_type& key, const mapped_type& x) throw (std::out_of_range) { + self->insert(Type::value_type(key,x)); + } + } +%enddef + +%include + diff --git a/Lib/python/std_unordered_multiset.i b/Lib/python/std_unordered_multiset.i new file mode 100644 index 000000000..d5b9ff61c --- /dev/null +++ b/Lib/python/std_unordered_multiset.i @@ -0,0 +1,41 @@ +/* + Unordered Multisets +*/ + +%include + +%fragment("StdUnorderedMultisetTraits","header",fragment="StdSequenceTraits") +%{ + namespace swig { + template + inline void + assign(const SwigPySeq& swigpyseq, std::unordered_multiset* seq) { + // seq->insert(swigpyseq.begin(), swigpyseq.end()); // not used as not always implemented + typedef typename SwigPySeq::value_type value_type; + typename SwigPySeq::const_iterator it = swigpyseq.begin(); + for (;it != swigpyseq.end(); ++it) { + seq->insert(seq->end(),(value_type)(*it)); + } + } + + template + struct traits_asptr > { + static int asptr(PyObject *obj, std::unordered_multiset **m) { + return traits_asptr_stdseq >::asptr(obj, m); + } + }; + + template + struct traits_from > { + static PyObject *from(const std::unordered_multiset& vec) { + return traits_from_stdseq >::from(vec); + } + }; + } +%} + +#define %swig_unordered_multiset_methods(Set...) %swig_set_methods(Set) + + + +%include diff --git a/Lib/python/std_unordered_set.i b/Lib/python/std_unordered_set.i new file mode 100644 index 000000000..a021cb4ed --- /dev/null +++ b/Lib/python/std_unordered_set.i @@ -0,0 +1,55 @@ +/* + Unordered Sets +*/ + +%fragment("StdUnorderedSetTraits","header",fragment="StdSequenceTraits") +%{ + namespace swig { + template + inline void + assign(const SwigPySeq& swigpyseq, std::unordered_set* seq) { + // seq->insert(swigpyseq.begin(), swigpyseq.end()); // not used as not always implemented + typedef typename SwigPySeq::value_type value_type; + typename SwigPySeq::const_iterator it = swigpyseq.begin(); + for (;it != swigpyseq.end(); ++it) { + seq->insert(seq->end(),(value_type)(*it)); + } + } + + template + struct traits_asptr > { + static int asptr(PyObject *obj, std::unordered_set **s) { + return traits_asptr_stdseq >::asptr(obj, s); + } + }; + + template + struct traits_from > { + static PyObject *from(const std::unordered_set& vec) { + return traits_from_stdseq >::from(vec); + } + }; + } +%} + +%define %swig_unordered_set_methods(unordered_set...) + %swig_sequence_iterator(unordered_set); + %swig_container_methods(unordered_set); + + %extend { + void append(value_type x) { + self->insert(x); + } + + bool __contains__(value_type x) { + return self->find(x) != self->end(); + } + + value_type __getitem__(difference_type i) const throw (std::out_of_range) { + return *(swig::cgetpos(self, i)); + } + + }; +%enddef + +%include diff --git a/Lib/std/std_multimap.i b/Lib/std/std_multimap.i index f165e5f33..829d1b9de 100644 --- a/Lib/std/std_multimap.i +++ b/Lib/std/std_multimap.i @@ -1,5 +1,5 @@ // -// std::map +// std::multimap // %include diff --git a/Lib/std/std_multiset.i b/Lib/std/std_multiset.i index 98a7fb9d7..b63fb92b9 100644 --- a/Lib/std/std_multiset.i +++ b/Lib/std/std_multiset.i @@ -1,5 +1,5 @@ // -// std::set +// std::multiset // %include diff --git a/Lib/std/std_unordered_map.i b/Lib/std/std_unordered_map.i new file mode 100644 index 000000000..f205bd573 --- /dev/null +++ b/Lib/std/std_unordered_map.i @@ -0,0 +1,124 @@ +// +// std::unordered_map +// + +%include +%include + +%define %std_unordered_map_methods_common(unordered_map...) + %std_container_methods(unordered_map); + + size_type erase(const key_type& x); + size_type count(const key_type& x) const; + +#ifdef SWIG_EXPORT_ITERATOR_METHODS +// iterator insert(iterator position, const value_type& x); + void erase(iterator position); + void erase(iterator first, iterator last); + + iterator find(const key_type& x); + iterator lower_bound(const key_type& x); + iterator upper_bound(const key_type& x); +#endif +%enddef + +%define %std_unordered_map_methods(unordered_map...) + %std_unordered_map_methods_common(unordered_map); + + #ifdef SWIG_EXPORT_ITERATOR_METHODS +// iterator insert(const value_type& x); + #endif +%enddef + + +// ------------------------------------------------------------------------ +// std::unordered_map +// +// const declarations are used to guess the intent of the function being +// exported; therefore, the following rationale is applied: +// +// -- f(std::unordered_map), f(const std::unordered_map&): +// the parameter being read-only, either a sequence or a +// previously wrapped std::unordered_map can be passed. +// -- f(std::unordered_map&), f(std::unordered_map*): +// the parameter may be modified; therefore, only a wrapped std::unordered_map +// can be passed. +// -- std::unordered_map f(), const std::unordered_map& f(): +// the unordered_map is returned by copy; therefore, a sequence of T:s +// is returned which is most easily used in other functions +// -- std::unordered_map& f(), std::unordered_map* f(): +// the unordered_map is returned by reference; therefore, a wrapped std::unordered_map +// is returned +// -- const std::unordered_map* f(), f(const std::unordered_map*): +// for consistency, they expect and return a plain unordered_map pointer. +// ------------------------------------------------------------------------ + +%{ +#include +#include +#include +%} + +// exported class + +namespace std { + + template, + class _Alloc = allocator > > + class unordered_map { + public: + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef _Key key_type; + typedef _Tp mapped_type; + typedef std::pair value_type; + + typedef value_type* pointer; + typedef const value_type* const_pointer; + typedef value_type& reference; + typedef const value_type& const_reference; + typedef _Alloc allocator_type; + + %traits_swigtype(_Key); + %traits_swigtype(_Tp); + + %fragment(SWIG_Traits_frag(std::pair< _Key, _Tp >), "header", + fragment=SWIG_Traits_frag(_Key), + fragment=SWIG_Traits_frag(_Tp), + fragment="StdPairTraits") { + namespace swig { + template <> struct traits > { + typedef pointer_category category; + static const char* type_name() { + return "std::pair<" #_Key "," #_Tp " >"; + } + }; + } + } + + %fragment(SWIG_Traits_frag(std::unordered_map<_Key, _Tp, _Compare, _Alloc >), "header", + fragment=SWIG_Traits_frag(std::pair<_Key, _Tp >), + fragment="StdMapTraits") { + namespace swig { + template <> struct traits > { + typedef pointer_category category; + static const char* type_name() { + return "std::unordered_map<" #_Key "," #_Tp "," #_Compare "," #_Alloc " >"; + } + }; + } + } + + %typemap_traits_ptr(SWIG_TYPECHECK_MAP, std::unordered_map<_Key, _Tp, _Compare, _Alloc >); + + unordered_map( const _Compare& ); + +#ifdef %swig_unordered_map_methods + // Add swig/language extra methods + %swig_unordered_map_methods(std::unordered_map<_Key, _Tp, _Compare, _Alloc >); +#endif + + %std_unordered_map_methods(unordered_map); + }; + +} diff --git a/Lib/std/std_unordered_multimap.i b/Lib/std/std_unordered_multimap.i new file mode 100644 index 000000000..bbdfeb82d --- /dev/null +++ b/Lib/std/std_unordered_multimap.i @@ -0,0 +1,87 @@ +// +// std::unordered_multimap +// + +%include + + +%define %std_unordered_multimap_methods(mmap...) + %std_map_methods_common(mmap); + +#ifdef SWIG_EXPORT_ITERATOR_METHODS + std::pair equal_range(const key_type& x); + std::pair equal_range(const key_type& x) const; +#endif +%enddef + +// ------------------------------------------------------------------------ +// std::unordered_multimap +// +// const declarations are used to guess the intent of the function being +// exported; therefore, the following rationale is applied: +// +// -- f(std::unordered_multimap), f(const std::unordered_multimap&): +// the parameter being read-only, either a sequence or a +// previously wrapped std::unordered_multimap can be passed. +// -- f(std::unordered_multimap&), f(std::unordered_multimap*): +// the parameter may be modified; therefore, only a wrapped std::unordered_multimap +// can be passed. +// -- std::unordered_multimap f(), const std::unordered_multimap& f(): +// the map is returned by copy; therefore, a sequence of T:s +// is returned which is most easily used in other functions +// -- std::unordered_multimap& f(), std::unordered_multimap* f(): +// the map is returned by reference; therefore, a wrapped std::unordered_multimap +// is returned +// -- const std::unordered_multimap* f(), f(const std::unordered_multimap*): +// for consistency, they expect and return a plain map pointer. +// ------------------------------------------------------------------------ + + +// exported class + + +namespace std { + template, + class _Alloc = allocator > > + class unordered_multimap { + public: + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef _Key key_type; + typedef _Tp mapped_type; + typedef std::pair value_type; + + typedef value_type* pointer; + typedef const value_type* const_pointer; + typedef value_type& reference; + typedef const value_type& const_reference; + typedef _Alloc allocator_type; + + %traits_swigtype(_Key); + %traits_swigtype(_Tp); + + %fragment(SWIG_Traits_frag(std::unordered_multimap<_Key, _Tp, _Compare, _Alloc >), "header", + fragment=SWIG_Traits_frag(std::pair<_Key, _Tp >), + fragment="StdMultimapTraits") { + namespace swig { + template <> struct traits > { + typedef pointer_category category; + static const char* type_name() { + return "std::unordered_multimap<" #_Key "," #_Tp "," #_Compare "," #_Alloc " >"; + } + }; + } + } + + %typemap_traits_ptr(SWIG_TYPECHECK_MULTIMAP, std::unordered_multimap<_Key, _Tp, _Compare, _Alloc >); + + unordered_multimap( const _Compare& ); + +#ifdef %swig_unordered_multimap_methods + // Add swig/language extra methods + %swig_unordered_multimap_methods(std::unordered_multimap<_Key, _Tp, _Compare, _Alloc >); +#endif + + %std_unordered_multimap_methods(unordered_multimap); + }; +} diff --git a/Lib/std/std_unordered_multiset.i b/Lib/std/std_unordered_multiset.i new file mode 100644 index 000000000..5ef76612d --- /dev/null +++ b/Lib/std/std_unordered_multiset.i @@ -0,0 +1,83 @@ +// +// std::unordered_multiset +// + +%include + +// Unordered Multiset + +%define %std_unordered_multiset_methods(unordered_multiset...) + %std_unordered_set_methods_common(unordered_multiset); +%enddef + + +// ------------------------------------------------------------------------ +// std::unordered_multiset +// +// const declarations are used to guess the intent of the function being +// exported; therefore, the following rationale is applied: +// +// -- f(std::unordered_multiset), f(const std::unordered_multiset&): +// the parameter being read-only, either a sequence or a +// previously wrapped std::unordered_multiset can be passed. +// -- f(std::unordered_multiset&), f(std::unordered_multiset*): +// the parameter may be modified; therefore, only a wrapped std::unordered_multiset +// can be passed. +// -- std::unordered_multiset f(), const std::unordered_multiset& f(): +// the set is returned by copy; therefore, a sequence of T:s +// is returned which is most easily used in other functions +// -- std::unordered_multiset& f(), std::unordered_multiset* f(): +// the set is returned by reference; therefore, a wrapped std::unordered_multiset +// is returned +// -- const std::unordered_multiset* f(), f(const std::unordered_multiset*): +// for consistency, they expect and return a plain set pointer. +// ------------------------------------------------------------------------ + + +// exported classes + +namespace std { + + //unordered_multiset + + template , + class _Alloc = allocator<_Key> > + class unordered_multiset { + public: + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef _Key value_type; + typedef _Key key_type; + typedef value_type* pointer; + typedef const value_type* const_pointer; + typedef value_type& reference; + typedef const value_type& const_reference; + typedef _Alloc allocator_type; + + %traits_swigtype(_Key); + + %fragment(SWIG_Traits_frag(std::unordered_multiset<_Key, _Compare, _Alloc >), "header", + fragment=SWIG_Traits_frag(_Key), + fragment="StdMultisetTraits") { + namespace swig { + template <> struct traits > { + typedef pointer_category category; + static const char* type_name() { + return "std::unordered_multiset<" #_Key "," #_Compare "," #_Alloc " >"; + } + }; + } + } + + %typemap_traits_ptr(SWIG_TYPECHECK_MULTISET, std::unordered_multiset<_Key, _Compare, _Alloc >); + + unordered_multiset( const _Compare& ); + +#ifdef %swig_unordered_multiset_methods + // Add swig/language extra methods + %swig_unordered_multiset_methods(std::unordered_multiset<_Key, _Compare, _Alloc >); +#endif + + %std_unordered_multiset_methods(unordered_multiset); + }; +} diff --git a/Lib/std/std_unordered_set.i b/Lib/std/std_unordered_set.i new file mode 100644 index 000000000..0eac339e0 --- /dev/null +++ b/Lib/std/std_unordered_set.i @@ -0,0 +1,116 @@ +// +// std::unordered_set +// + +%include +%include + +// Unordered Set +%define %std_unordered_set_methods_common(unordered_set...) + unordered_set(); + unordered_set( const unordered_set& ); + + bool empty() const; + size_type size() const; + void clear(); + + void swap(unordered_set& v); + + + size_type erase(const key_type& x); + size_type count(const key_type& x) const; + +#ifdef SWIG_EXPORT_ITERATOR_METHODS + class iterator; + + iterator begin(); + iterator end(); + + void erase(iterator pos); + void erase(iterator first, iterator last); + + iterator find(const key_type& x); + std::pair equal_range(const key_type& x); +#endif +%enddef + +%define %std_unordered_set_methods(unordered_set...) + %std_unordered_set_methods_common(unordered_set); +#ifdef SWIG_EXPORT_ITERATOR_METHODS + std::pair insert(const value_type& __x); +#endif +%enddef + +// ------------------------------------------------------------------------ +// std::unordered_set +// +// const declarations are used to guess the intent of the function being +// exported; therefore, the following rationale is applied: +// +// -- f(std::unordered_set), f(const std::unordered_set&): +// the parameter being read-only, either a sequence or a +// previously wrapped std::unordered_set can be passed. +// -- f(std::unordered_set&), f(std::unordered_set*): +// the parameter may be modified; therefore, only a wrapped std::unordered_set +// can be passed. +// -- std::unordered_set f(), const std::unordered_set& f(): +// the unordered_set is returned by copy; therefore, a sequence of T:s +// is returned which is most easily used in other functions +// -- std::unordered_set& f(), std::unordered_set* f(): +// the unordered_set is returned by reference; therefore, a wrapped std::unordered_set +// is returned +// -- const std::unordered_set* f(), f(const std::unordered_set*): +// for consistency, they expect and return a plain unordered_set pointer. +// ------------------------------------------------------------------------ + +%{ +#include +%} + +// exported classes + +namespace std { + + template , + class _Compare = std::equal_to<_Key>, + class _Alloc = allocator<_Key> > + class unordered_set { + public: + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef _Hash hasher; + typedef _Key value_type; + typedef _Key key_type; + typedef value_type* pointer; + typedef const value_type* const_pointer; + typedef value_type& reference; + typedef const value_type& const_reference; + typedef _Alloc allocator_type; + + %traits_swigtype(_Key); + + %fragment(SWIG_Traits_frag(std::unordered_set<_Key, _Hash, _Compare, _Alloc >), "header", + fragment=SWIG_Traits_frag(_Key), + fragment="StdUnorderedSetTraits") { + namespace swig { + template <> struct traits > { + typedef pointer_category category; + static const char* type_name() { + return "std::unordered_set<" #_Key "," #_Hash "," #_Compare "," #_Alloc " >"; + } + }; + } + } + + %typemap_traits_ptr(SWIG_TYPECHECK_SET, std::unordered_set<_Key, _Hash, _Compare, _Alloc >); + + unordered_set( const _Compare& ); + +#ifdef %swig_unordered_set_methods + // Add swig/language extra methods + %swig_unordered_set_methods(std::unordered_set<_Key, _Hash, _Compare, _Alloc >); +#endif + + %std_unordered_set_methods(unordered_set); + }; +} From e949fa3cc7924f75c31b459ded4dc1d3c91b3a4c Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Sat, 18 Jul 2009 22:13:40 +0000 Subject: [PATCH 018/481] Added testcase for function objects. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11419 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 6 ++++-- Examples/test-suite/cpp0x_function_objects.i | 18 ++++++++++++++++++ .../python/cpp0x_function_objects_runme.py | 12 ++++++++++++ 3 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 Examples/test-suite/cpp0x_function_objects.i create mode 100644 Examples/test-suite/python/cpp0x_function_objects_runme.py diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 4ab20575a..76504dd0f 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -405,11 +405,13 @@ CPP0X_TEST_CASES = \ cpp0x_raw_string_literals \ cpp0x_static_assert \ cpp0x_template_explicit \ - cpp0x_thread_local \ cpp0x_uniform_initialization \ - cpp0x_alternate_function_syntax + cpp0x_alternate_function_syntax \ + cpp0x_function_objects +# cpp0x_hash_types # not fully implemented yet # cpp0x_smart_pointers # not supported by standard library yet # cpp0x_constexpr # not supported by any compilers yet +# cpp0x_thread_local # not supported by any compilers yet # Broken C++0x test cases. CPP0X_TEST_BROKEN = diff --git a/Examples/test-suite/cpp0x_function_objects.i b/Examples/test-suite/cpp0x_function_objects.i new file mode 100644 index 000000000..f480addc7 --- /dev/null +++ b/Examples/test-suite/cpp0x_function_objects.i @@ -0,0 +1,18 @@ +/* This testcase checks whether Swig correctly parses function objects + and the templates for the functions (signature). + Function objects are objects which overload the operator() function. */ +%module cpp0x_function_objects + +%inline %{ +//function pF; // not supported yet by the compiler + +struct Test { + int value; + + void operator()(short x, short y) { + value=10; + } + +} test; +%} + diff --git a/Examples/test-suite/python/cpp0x_function_objects_runme.py b/Examples/test-suite/python/cpp0x_function_objects_runme.py new file mode 100644 index 000000000..edbd88e1c --- /dev/null +++ b/Examples/test-suite/python/cpp0x_function_objects_runme.py @@ -0,0 +1,12 @@ +import cpp0x_function_objects +import sys + +t = cpp0x_function_objects.Test() +if t.value != 0: + raise RuntimeError,"Runtime cpp0x_function_objects failed. t.value should be 0, but is", t.value + +t(1,2) # sets value + +if t.value != 10: + raise RuntimeError,"Runtime cpp0x_function_objects failed. t.value not changed - should be 10, but is", t.value + From 54e6910631bfb2f2bbd23f25fe40aebae9686e74 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Sat, 18 Jul 2009 22:35:03 +0000 Subject: [PATCH 019/481] Disabled alternate function syntax testcase. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11422 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 76504dd0f..add8a2422 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -406,8 +406,8 @@ CPP0X_TEST_CASES = \ cpp0x_static_assert \ cpp0x_template_explicit \ cpp0x_uniform_initialization \ - cpp0x_alternate_function_syntax \ cpp0x_function_objects +# cpp0x_alternate_function_syntax # not fully implemented yet # cpp0x_hash_types # not fully implemented yet # cpp0x_smart_pointers # not supported by standard library yet # cpp0x_constexpr # not supported by any compilers yet From f9a385c6a6bb60757fa4a83e00cb7ee7382579c1 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Wed, 22 Jul 2009 17:48:38 +0000 Subject: [PATCH 020/481] Added testcase for cpp0x unrestricted unions. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11435 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 1 + Examples/test-suite/cpp0x_unrestricted_unions.i | 16 ++++++++++++++++ 2 files changed, 17 insertions(+) create mode 100644 Examples/test-suite/cpp0x_unrestricted_unions.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index add8a2422..627847d83 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -409,6 +409,7 @@ CPP0X_TEST_CASES = \ cpp0x_function_objects # cpp0x_alternate_function_syntax # not fully implemented yet # cpp0x_hash_types # not fully implemented yet +# cpp0x_unrestricted_unions # not supported by any compilers yet # cpp0x_smart_pointers # not supported by standard library yet # cpp0x_constexpr # not supported by any compilers yet # cpp0x_thread_local # not supported by any compilers yet diff --git a/Examples/test-suite/cpp0x_unrestricted_unions.i b/Examples/test-suite/cpp0x_unrestricted_unions.i new file mode 100644 index 000000000..87d7af9a9 --- /dev/null +++ b/Examples/test-suite/cpp0x_unrestricted_unions.i @@ -0,0 +1,16 @@ +%module cpp0x_unrestricted_unions + +%inline %{ +struct point { +// point() {} +// point(int x, int y) : x_(x), y_(y) {} + int x_, y_; +}; + +union P { + int z; + double w; + point p; +} p1; +%} + From fd981a58ddc445532641f83172b979087204b841 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Fri, 24 Jul 2009 08:52:35 +0000 Subject: [PATCH 021/481] Fixed bug in cpp0x testcase. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11447 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/cpp0x_unrestricted_unions.i | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Examples/test-suite/cpp0x_unrestricted_unions.i b/Examples/test-suite/cpp0x_unrestricted_unions.i index 87d7af9a9..d3364ef83 100644 --- a/Examples/test-suite/cpp0x_unrestricted_unions.i +++ b/Examples/test-suite/cpp0x_unrestricted_unions.i @@ -2,8 +2,8 @@ %inline %{ struct point { -// point() {} -// point(int x, int y) : x_(x), y_(y) {} + point() {} + point(int x, int y) : x_(x), y_(y) {} int x_, y_; }; From 29004c3fcf42ca07d63a5249ed9a41a944a4a8b6 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Sat, 25 Jul 2009 16:48:30 +0000 Subject: [PATCH 022/481] Added initial support for parsing C++0x strongly typed enumerations. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11449 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 3 +- .../cpp0x_strongly_typed_enumerations.i | 36 ++++++++ Source/CParse/parser.y | 83 +++++++++++++------ 3 files changed, 95 insertions(+), 27 deletions(-) create mode 100644 Examples/test-suite/cpp0x_strongly_typed_enumerations.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 627847d83..cd97ae245 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -406,7 +406,8 @@ CPP0X_TEST_CASES = \ cpp0x_static_assert \ cpp0x_template_explicit \ cpp0x_uniform_initialization \ - cpp0x_function_objects + cpp0x_function_objects \ + cpp0x_strongly_typed_enumerations # cpp0x_alternate_function_syntax # not fully implemented yet # cpp0x_hash_types # not fully implemented yet # cpp0x_unrestricted_unions # not supported by any compilers yet diff --git a/Examples/test-suite/cpp0x_strongly_typed_enumerations.i b/Examples/test-suite/cpp0x_strongly_typed_enumerations.i new file mode 100644 index 000000000..0f281a195 --- /dev/null +++ b/Examples/test-suite/cpp0x_strongly_typed_enumerations.i @@ -0,0 +1,36 @@ +%module cpp0x_strongly_typed_enumerations + +%inline %{ +enum class Enum1 { + Val1, + Val2, + Val3 = 100, + Val4 /* = 101 */ +}; + +enum class Enum2 : short { + Val1, + Val2, + Val3 = 100, + Val4 +}; + +/* Forward declarations. GCC doesn't support them */ +//enum Enum3; // Illegal in C++ and C++0x; no size is explicitly specified. +//enum Enum4 : unsigned int; // Legal in C++0x. +//enum class Enum5; // Legal in C++0x, because enum class declarations have a default type of "int". +//enum class Enum6 : unsigned int; // Legal C++0x. +//enum Enum2 : unsigned short; // Illegal in C++0x, because Enum2 was previously declared with a different type. + +enum Enum4 : unsigned int { + Val1, Val2, Val3 = 100, Val4 +}; + +enum class Enum5 { + Val1, Val2, Val3 = 100, Val4 +}; + +enum class Enum6 : unsigned int { + Val1, Val2, Val3 = 300, Val4 +}; +%} diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 093c4d315..1469efe20 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1,4 +1,4 @@ -/* ----------------------------------------------------------------------------- + /* ----------------------------------------------------------------------------- * See the LICENSE file for information on copyright, usage and redistribution * of SWIG, and the README file for authors - http://www.swig.org/release.html. * @@ -1535,7 +1535,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %type types_directive template_directive warn_directive ; /* C declarations */ -%type c_declaration c_decl c_decl_tail c_enum_decl c_enum_forward_decl c_constructor_decl c_rettype ; +%type c_declaration c_decl c_decl_tail c_enum_keyword c_enum_inherit c_enum_decl c_enum_forward_decl c_constructor_decl c_rettype ; %type enumlist edecl; /* C++ declarations */ @@ -3071,15 +3071,40 @@ initializer : def_args { ; + /* ------------------------------------------------------------ - enum Name; + enum + or + enum class ------------------------------------------------------------ */ -c_enum_forward_decl : storage_class ENUM ID SEMI { +c_enum_keyword : ENUM { + $$ = (char*)"enumkeyword"; + } + | ENUM CLASS { + $$ = (char*)"enumclasskeyword"; + } + ; + +/* ------------------------------------------------------------ + base enum type (eg. unsigned short) + ------------------------------------------------------------ */ + +c_enum_inherit : COLON primitive_type { + $$ = $2; + } + | empty { $$ = 0; } + ; +/* ------------------------------------------------------------ + enum [class] Name; + ------------------------------------------------------------ */ + +c_enum_forward_decl : storage_class c_enum_keyword c_enum_inherit ID SEMI { SwigType *ty = 0; $$ = new_node("enumforward"); - ty = NewStringf("enum %s", $3); - Setattr($$,"name",$3); + ty = NewStringf("enum %s", $4); + Setattr($$,"enumkeyword",$2); + Setattr($$,"name",$4); Setattr($$,"type",ty); Setattr($$,"sym:weak", "1"); add_symbols($$); @@ -3087,52 +3112,58 @@ c_enum_forward_decl : storage_class ENUM ID SEMI { ; /* ------------------------------------------------------------ - enum { ... } + enum [class] Name [: base_type] { ... }; + or + enum [class] Name [: base_type] { ... } MyEnum [= ...]; * ------------------------------------------------------------ */ -c_enum_decl : storage_class ENUM ename LBRACE enumlist RBRACE SEMI { +c_enum_decl : storage_class c_enum_keyword ename c_enum_inherit LBRACE enumlist RBRACE SEMI { SwigType *ty = 0; $$ = new_node("enum"); ty = NewStringf("enum %s", $3); + Setattr($$,"enumkeyword",$2); Setattr($$,"name",$3); + Setattr($$,"inherit",$4); Setattr($$,"type",ty); - appendChild($$,$5); - add_symbols($$); /* Add to tag space */ - add_symbols($5); /* Add enum values to id space */ + appendChild($$,$6); + add_symbols($$); /* Add to tag space */ + add_symbols($6); /* Add enum values to id space */ } - | storage_class ENUM ename LBRACE enumlist RBRACE declarator c_decl_tail { + | storage_class c_enum_keyword ename c_enum_inherit LBRACE enumlist RBRACE declarator c_decl_tail { Node *n; SwigType *ty = 0; String *unnamed = 0; int unnamedinstance = 0; $$ = new_node("enum"); + Setattr($$,"enumkeyword",$2); + Setattr($$,"inherit",$4); if ($3) { Setattr($$,"name",$3); ty = NewStringf("enum %s", $3); - } else if ($7.id) { + } else if ($8.id) { unnamed = make_unnamed(); ty = NewStringf("enum %s", unnamed); Setattr($$,"unnamed",unnamed); /* name is not set for unnamed enum instances, e.g. enum { foo } Instance; */ if ($1 && Cmp($1,"typedef") == 0) { - Setattr($$,"name",$7.id); + Setattr($$,"name",$8.id); } else { unnamedinstance = 1; } Setattr($$,"storage",$1); } - if ($7.id && Cmp($1,"typedef") == 0) { - Setattr($$,"tdname",$7.id); + if ($8.id && Cmp($1,"typedef") == 0) { + Setattr($$,"tdname",$8.id); Setattr($$,"allows_typedef","1"); } - appendChild($$,$5); + appendChild($$,$6); n = new_node("cdecl"); Setattr(n,"type",ty); - Setattr(n,"name",$7.id); + Setattr(n,"name",$8.id); Setattr(n,"storage",$1); - Setattr(n,"decl",$7.type); - Setattr(n,"parms",$7.parms); + Setattr(n,"decl",$8.type); + Setattr(n,"parms",$8.parms); Setattr(n,"unnamed",unnamed); if (unnamedinstance) { @@ -3142,8 +3173,8 @@ c_enum_decl : storage_class ENUM ename LBRACE enumlist RBRACE SEMI { Setattr(n,"unnamedinstance","1"); Delete(cty); } - if ($8) { - Node *p = $8; + if ($9) { + Node *p = $9; set_nextSibling(n,p); while (p) { SwigType *cty = Copy(ty); @@ -3163,8 +3194,8 @@ c_enum_decl : storage_class ENUM ename LBRACE enumlist RBRACE SEMI { /* Ensure that typedef enum ABC {foo} XYZ; uses XYZ for sym:name, like structs. * Note that class_rename/yyrename are bit of a mess so used this simple approach to change the name. */ - if ($7.id && $3 && Cmp($1,"typedef") == 0) { - String *name = NewString($7.id); + if ($8.id && $3 && Cmp($1,"typedef") == 0) { + String *name = NewString($8.id); Setattr($$, "parser:makename", name); Delete(name); } @@ -3172,7 +3203,7 @@ c_enum_decl : storage_class ENUM ename LBRACE enumlist RBRACE SEMI { add_symbols($$); /* Add enum to tag space */ set_nextSibling($$,n); Delete(n); - add_symbols($5); /* Add enum values to id space */ + add_symbols($6); /* Add enum values to id space */ add_symbols(n); Delete(unnamed); } @@ -5223,7 +5254,7 @@ type_right : primitive_type { $$ = $1; | TYPE_VOID { $$ = $1; } | TYPE_AUTO { $$ = $1; } | TYPE_TYPEDEF template_decl { $$ = NewStringf("%s%s",$1,$2); } - | ENUM idcolon { $$ = NewStringf("enum %s", $2); } + | c_enum_keyword idcolon { $$ = NewStringf("enum %s", $2); } | TYPE_RAW { $$ = $1; } | idcolon { From a8209bfd68e9e6f4a952b77f26e44167cddcc3d1 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Sat, 25 Jul 2009 18:51:37 +0000 Subject: [PATCH 023/481] Added support for C++0x rvalue and move semantics. Added testcase. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11450 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 3 ++- Examples/test-suite/cpp0x_rvalue_reference.i | 23 +++++++++++++++++++ .../python/cpp0x_rvalue_reference_runme.py | 22 ++++++++++++++++++ Source/CParse/parser.y | 13 +++++++++-- 4 files changed, 58 insertions(+), 3 deletions(-) create mode 100644 Examples/test-suite/cpp0x_rvalue_reference.i create mode 100644 Examples/test-suite/python/cpp0x_rvalue_reference_runme.py diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index cd97ae245..2d5082398 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -407,7 +407,8 @@ CPP0X_TEST_CASES = \ cpp0x_template_explicit \ cpp0x_uniform_initialization \ cpp0x_function_objects \ - cpp0x_strongly_typed_enumerations + cpp0x_strongly_typed_enumerations \ + cpp0x_rvalue_reference # cpp0x_alternate_function_syntax # not fully implemented yet # cpp0x_hash_types # not fully implemented yet # cpp0x_unrestricted_unions # not supported by any compilers yet diff --git a/Examples/test-suite/cpp0x_rvalue_reference.i b/Examples/test-suite/cpp0x_rvalue_reference.i new file mode 100644 index 000000000..0a7fa9147 --- /dev/null +++ b/Examples/test-suite/cpp0x_rvalue_reference.i @@ -0,0 +1,23 @@ +%module cpp0x_rvalue_reference + +%inline %{ +class A { +public: + int getAcopy() { return _a; } + int *getAptr() { return &_a; } + int &getAref() { return _a; } + int &&getAmove() { return _a; } + + void setAcopy(int a) { _a = a; } + void setAptr(int *a) { _a = *a; } + void setAref(int &a) { _a = a; } + void setAmove(int &&a) { _a = a; } + + void arg(int a); + void arg(int *a); + void arg(int &a); +// void arg(int &&a); // redefinition not allowed +private: + int _a; +}; +%} diff --git a/Examples/test-suite/python/cpp0x_rvalue_reference_runme.py b/Examples/test-suite/python/cpp0x_rvalue_reference_runme.py new file mode 100644 index 000000000..1f74cfaa8 --- /dev/null +++ b/Examples/test-suite/python/cpp0x_rvalue_reference_runme.py @@ -0,0 +1,22 @@ +import cpp0x_rvalue_reference + +a = cpp0x_rvalue_reference.A() + +a.setAcopy(5) +if a.getAcopy() != 5: + raise RunTimeError, "int A::getAcopy() value is ", a.getAcopy(), " should be 5" + +ptr = a.getAptr() + +a.setAptr(ptr) +if a.getAcopy() != 5: + raise RunTimeError, "after A::setAptr(): int A::getAcopy() value is ", a.getAcopy(), " should be 5" + +a.setAref(ptr) +if a.getAcopy() != 5: + raise RunTimeError, "after A::setAref(): int A::getAcopy() value is ", a.getAcopy(), " should be 5" + +a.setAmove(ptr) +if a.getAcopy() != 5: + raise RunTimeError, "after A::setAmove(): int A::getAcopy() value is ", a.getAcopy(), " should be 5" + diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 1469efe20..f42e9657a 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -4804,7 +4804,16 @@ declarator : pointer notso_direct_declarator { $$ = $1; if (!$$.type) $$.type = NewStringEmpty(); } - | AND notso_direct_declarator { + | AND notso_direct_declarator { + $$ = $2; + $$.type = NewStringEmpty(); + SwigType_add_reference($$.type); + if ($2.type) { + SwigType_push($$.type,$2.type); + Delete($2.type); + } + } + | LAND notso_direct_declarator { $$ = $2; $$.type = NewStringEmpty(); SwigType_add_reference($$.type); @@ -5082,7 +5091,7 @@ abstract_declarator : pointer { Delete($2.type); } } - | AND { + | AND { $$.id = 0; $$.parms = 0; $$.have_parms = 0; From 94e94dce02c1dfc14f38211e18b1c6aa8b0a6e00 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Sat, 25 Jul 2009 19:14:17 +0000 Subject: [PATCH 024/481] Added partial support for unordered_ STL types. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11451 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/python/pyiterators.swg | 10 ---------- Lib/python/pystdcommon.swg | 2 ++ 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/Lib/python/pyiterators.swg b/Lib/python/pyiterators.swg index 8719f73ce..1d7f415be 100644 --- a/Lib/python/pyiterators.swg +++ b/Lib/python/pyiterators.swg @@ -226,9 +226,6 @@ namespace swig { SwigPyIterator *decr(size_t n = 1) { - while (n--) { - --base::current; - } return this; } }; @@ -277,13 +274,6 @@ namespace swig { SwigPyIterator *decr(size_t n = 1) { - while (n--) { - if (base::current == begin) { - throw stop_iteration(); - } else { - --base::current; - } - } return this; } diff --git a/Lib/python/pystdcommon.swg b/Lib/python/pystdcommon.swg index 7e9720cc0..f71425616 100644 --- a/Lib/python/pystdcommon.swg +++ b/Lib/python/pystdcommon.swg @@ -257,3 +257,5 @@ namespace swig { #define specialize_std_deque(Type,Check,As,From) %specialize_std_container(%arg(Type),Check,As,From) #define specialize_std_set(Type,Check,As,From) %specialize_std_container(%arg(Type),Check,As,From) #define specialize_std_multiset(Type,Check,As,From) %specialize_std_container(%arg(Type),Check,As,From) +#define specialize_std_unordered_set(Type,Check,As,From) %specialize_std_container(%arg(Type),Check,As,From) +#define specialize_std_unordered_multiset(Type,Check,As,From) %specialize_std_container(%arg(Type),Check,As,From) From 85ae38cceefb94c52e36431e42f23c815bb6f41f Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Mon, 27 Jul 2009 19:07:38 +0000 Subject: [PATCH 025/481] Added initial support for variadic templates. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11458 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 3 ++- Examples/test-suite/cpp0x_variadic_templates.i | 8 ++++++++ Source/CParse/parser.y | 8 ++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 Examples/test-suite/cpp0x_variadic_templates.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 2d5082398..24dd4f6e3 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -408,7 +408,8 @@ CPP0X_TEST_CASES = \ cpp0x_uniform_initialization \ cpp0x_function_objects \ cpp0x_strongly_typed_enumerations \ - cpp0x_rvalue_reference + cpp0x_rvalue_reference \ + cpp0x_variadic_templates # cpp0x_alternate_function_syntax # not fully implemented yet # cpp0x_hash_types # not fully implemented yet # cpp0x_unrestricted_unions # not supported by any compilers yet diff --git a/Examples/test-suite/cpp0x_variadic_templates.i b/Examples/test-suite/cpp0x_variadic_templates.i new file mode 100644 index 000000000..51314c2a2 --- /dev/null +++ b/Examples/test-suite/cpp0x_variadic_templates.i @@ -0,0 +1,8 @@ +%module cpp0x_variadic_templates + +%inline %{ +template +class tuple { +}; + +%} diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index f42e9657a..02493a280 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -5808,6 +5808,14 @@ templcpptype : CLASS { $$ = (char *)"typename"; if (!inherit_list) last_cpptype = $$; } + | CLASS PERIOD PERIOD PERIOD { + $$ = (char*)"class"; + if (!inherit_list) last_cpptype = $$; + } + | TYPENAME PERIOD PERIOD PERIOD { + $$ = (char *)"typename"; + if (!inherit_list) last_cpptype = $$; + } ; cpptype : templcpptype { From 2e01562965208de1c08c00077918e85aed1ca026 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Wed, 29 Jul 2009 13:38:22 +0000 Subject: [PATCH 026/481] Added variadic '...' syntax for inheritance introduced in C++0x. Added sizeof... syntax introduced in C++0x. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11467 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .../test-suite/cpp0x_variadic_templates.i | 61 ++++++++++++++++++- Source/CParse/parser.y | 57 ++++++++++++++--- 2 files changed, 107 insertions(+), 11 deletions(-) diff --git a/Examples/test-suite/cpp0x_variadic_templates.i b/Examples/test-suite/cpp0x_variadic_templates.i index 51314c2a2..090645966 100644 --- a/Examples/test-suite/cpp0x_variadic_templates.i +++ b/Examples/test-suite/cpp0x_variadic_templates.i @@ -1,8 +1,67 @@ +/* This testcase checks whether Swig correctly parses and generates the code + for variadic templates. This covers the variadic number of arguments inside + the template brackets, new functions sizeof... and multiple inheritance + using variadic number of classes. +*/ %module cpp0x_variadic_templates +//////////////////////// +// Variadic templates // +//////////////////////// %inline %{ +#include +#include +#include + template -class tuple { +class MultiArgs { }; +class MultiArgs, std::map>> multiArgs; + %} + +// TODO +//%template (MultiArgs) MultiArgs, std::map>>; + +//////////////////////// +// Variadic sizeof... // +//////////////////////// +%inline %{ +template struct SizeOf { + static const int size = sizeof...(Args); +}; +%} + +// TODO +//%template (SizeOf) SizeOf; + +////////////////////////// +// Variadic inheritance // +////////////////////////// +%inline %{ +class A { +public: + A() { + a = 100; + } + + int a; +}; + +class B { +public: + B() { + b = 200; + } + int b; +}; + +template class MultiInherit : public BaseClasses... { +public: + MultiInherit(BaseClasses&&... baseClasses) : BaseClasses(baseClasses)... {} +}; +%} + +// TODO +//%template (MultiInherit) MultiInherit; diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 02493a280..60ac7c3d2 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1,4 +1,4 @@ - /* ----------------------------------------------------------------------------- +/* ----------------------------------------------------------------------------- * See the LICENSE file for information on copyright, usage and redistribution * of SWIG, and the README file for authors - http://www.swig.org/release.html. * @@ -1549,7 +1549,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { /* Misc */ %type initializer cpp_const ; %type storage_class; -%type parms ptail rawparms varargs_parms; +%type parms ptail rawparms varargs_parms ; %type templateparameters templateparameterstail; %type

parm valparm rawvalparms valparms valptail ; %type

typemap_parm tm_list tm_tail ; @@ -4814,6 +4814,7 @@ declarator : pointer notso_direct_declarator { } } | LAND notso_direct_declarator { + /* Introduced in C++0x, move operator && */ $$ = $2; $$.type = NewStringEmpty(); SwigType_add_reference($$.type); @@ -5538,6 +5539,11 @@ valexpr : exprnum { $$ = $1; } $$.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)); + $$.type = T_ULONG; + } | exprcompound { $$ = $1; } | CHARCONST { $$.val = NewString($1); @@ -5792,6 +5798,30 @@ base_specifier : opt_virtual idcolon { cparse_line,"%s inheritance ignored.\n", $2); } } + | opt_virtual idcolon PERIOD PERIOD PERIOD { /* Variadic inheritance */ + $$ = NewHash(); + Setfile($$,cparse_file); + Setline($$,cparse_line); + Setattr($$,"name",$2); + if (last_cpptype && (Strcmp(last_cpptype,"struct") != 0)) { + Setattr($$,"access","private"); + Swig_warning(WARN_PARSE_NO_ACCESS,cparse_file,cparse_line, + "No access specifier given for base class %s (ignored).\n",$2); + } else { + Setattr($$,"access","public"); + } + } + | opt_virtual access_specifier opt_virtual idcolon PERIOD PERIOD PERIOD { /* Variadic inheritance */ + $$ = NewHash(); + Setfile($$,cparse_file); + Setline($$,cparse_line); + Setattr($$,"name",$4); + Setattr($$,"access",$2); + if (Strcmp($2,"public") != 0) { + Swig_warning(WARN_PARSE_PRIVATE_INHERIT, cparse_file, + cparse_line,"%s inheritance ignored.\n", $2); + } + } ; access_specifier : PUBLIC { $$ = (char*)"public"; } @@ -5903,21 +5933,24 @@ mem_initializer_list : mem_initializer | mem_initializer_list COMMA mem_initializer ; -mem_initializer : idcolon LPAREN { - skip_balanced('(',')'); +mem_initializer : idcolon LPAREN parms RPAREN { +/* skip_balanced('(',')'); Clear(scanner_ccode); - } - | idcolon LBRACE { - /* Uniform initialization. eg. +*/ } + | idcolon LBRACE parms RBRACE { + /* Uniform initialization in C++0x. + Example: struct MyStruct { MyStruct(int x, double y) : x_{x}, y_{y} {} int x_; double y_; }; */ - skip_balanced('{','}'); +/* skip_balanced('{','}'); Clear(scanner_ccode); - } +*/ } + | idcolon LPAREN parms RPAREN PERIOD PERIOD PERIOD { } + | idcolon LBRACE parms RBRACE PERIOD PERIOD PERIOD { } ; template_decl : LESSTHAN valparms GREATERTHAN { @@ -5936,7 +5969,7 @@ idstring : ID { $$ = $1; } idstringopt : idstring { $$ = $1; } | empty { $$ = 0; } ; - + idcolon : idtemplate idcolontail { $$ = 0; if (!$$) $$ = NewStringf("%s%s", $1,$2); @@ -5946,6 +5979,10 @@ idcolon : idtemplate idcolontail { $$ = NewStringf("::%s%s",$3,$4); Delete($4); } + | PERIOD PERIOD PERIOD idtemplate { + /* Introduced in C++0x, variadic constructor args */ + $$ = NewString($4); + } | idtemplate { $$ = NewString($1); } From e7fd659ae50fbe1b90f59bdde6bdc7d92470953a Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Thu, 30 Jul 2009 19:18:37 +0000 Subject: [PATCH 027/481] Fixed S/R and R/R conflicts. Fixed testcase for rvalue reference. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11483 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/cpp0x_rvalue_reference.i | 4 - .../python/cpp0x_rvalue_reference_runme.py | 8 +- Source/CParse/cscanner.c | 6 +- Source/CParse/parser.y | 157 ++++++++++++------ 4 files changed, 110 insertions(+), 65 deletions(-) diff --git a/Examples/test-suite/cpp0x_rvalue_reference.i b/Examples/test-suite/cpp0x_rvalue_reference.i index 0a7fa9147..e45d91e27 100644 --- a/Examples/test-suite/cpp0x_rvalue_reference.i +++ b/Examples/test-suite/cpp0x_rvalue_reference.i @@ -13,10 +13,6 @@ public: void setAref(int &a) { _a = a; } void setAmove(int &&a) { _a = a; } - void arg(int a); - void arg(int *a); - void arg(int &a); -// void arg(int &&a); // redefinition not allowed private: int _a; }; diff --git a/Examples/test-suite/python/cpp0x_rvalue_reference_runme.py b/Examples/test-suite/python/cpp0x_rvalue_reference_runme.py index 1f74cfaa8..acf296716 100644 --- a/Examples/test-suite/python/cpp0x_rvalue_reference_runme.py +++ b/Examples/test-suite/python/cpp0x_rvalue_reference_runme.py @@ -4,19 +4,19 @@ a = cpp0x_rvalue_reference.A() a.setAcopy(5) if a.getAcopy() != 5: - raise RunTimeError, "int A::getAcopy() value is ", a.getAcopy(), " should be 5" + raise RunTimeError, ("int A::getAcopy() value is ", a.getAcopy(), " should be 5") ptr = a.getAptr() a.setAptr(ptr) if a.getAcopy() != 5: - raise RunTimeError, "after A::setAptr(): int A::getAcopy() value is ", a.getAcopy(), " should be 5" + raise RunTimeError, ("after A::setAptr(): int A::getAcopy() value is ", a.getAcopy(), " should be 5") a.setAref(ptr) if a.getAcopy() != 5: - raise RunTimeError, "after A::setAref(): int A::getAcopy() value is ", a.getAcopy(), " should be 5" + raise RunTimeError, ("after A::setAref(): int A::getAcopy() value is ", a.getAcopy(), " should be 5") a.setAmove(ptr) if a.getAcopy() != 5: - raise RunTimeError, "after A::setAmove(): int A::getAcopy() value is ", a.getAcopy(), " should be 5" + raise RunTimeError, ("after A::setAmove(): int A::getAcopy() value is ", a.getAcopy(), " should be 5") diff --git a/Source/CParse/cscanner.c b/Source/CParse/cscanner.c index 1fe0735db..f923bc3b6 100644 --- a/Source/CParse/cscanner.c +++ b/Source/CParse/cscanner.c @@ -595,10 +595,6 @@ int yylex(void) { yylval.type = NewSwigType(T_BOOL); return (TYPE_BOOL); } - if (strcmp(yytext, "auto") == 0) { - yylval.type = NewSwigType(T_AUTO); - return (TYPE_AUTO); - } /* Non ISO (Windows) C extensions */ if (strcmp(yytext, "__int8") == 0) { @@ -788,6 +784,8 @@ int yylex(void) { return (yylex()); if (strcmp(yytext, "explicit") == 0) return (EXPLICIT); + if (strcmp(yytext, "auto") == 0) + return (AUTO); if (strcmp(yytext, "export") == 0) return (yylex()); if (strcmp(yytext, "typename") == 0) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 60ac7c3d2..c8e7e284d 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1486,13 +1486,13 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %token CHARCONST %token NUM_INT NUM_FLOAT NUM_UNSIGNED NUM_LONG NUM_ULONG NUM_LONGLONG NUM_ULONGLONG %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 TYPE_AUTO +%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 CONST_QUAL VOLATILE REGISTER STRUCT UNION EQUAL SIZEOF MODULE LBRACKET RBRACKET %token ILLEGAL CONSTANT %token NAME RENAME NAMEWARN EXTEND PRAGMA FEATURE VARARGS %token ENUM -%token CLASS TYPENAME PRIVATE PUBLIC PROTECTED COLON STATIC VIRTUAL FRIEND THROW CATCH EXPLICIT +%token CLASS TYPENAME PRIVATE PUBLIC PROTECTED COLON STATIC VIRTUAL FRIEND THROW CATCH EXPLICIT AUTO %token STATIC_ASSERT CONSTEXPR THREAD_LOCAL /* C++0x keywords */ %token USING %token NAMESPACE @@ -1509,6 +1509,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %token OPERATOR %token COPERATOR %token PARSETYPE PARSEPARM PARSEPARMS +%token TEST1 TEST2 TEST3 %left CAST %left QUESTIONMARK @@ -1535,11 +1536,11 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %type types_directive template_directive warn_directive ; /* C declarations */ -%type c_declaration c_decl c_decl_tail c_enum_keyword c_enum_inherit c_enum_decl c_enum_forward_decl c_constructor_decl c_rettype ; +%type c_declaration c_decl c_decl_tail c_enum_keyword c_enum_inherit c_enum_decl c_enum_forward_decl c_constructor_decl ; %type enumlist edecl; /* C++ declarations */ -%type cpp_declaration cpp_class_decl cpp_forward_class_decl cpp_template_decl; +%type cpp_declaration cpp_class_decl cpp_forward_class_decl cpp_template_decl cpp_alternate_rettype; %type cpp_members cpp_member; %type cpp_constructor_decl cpp_destructor_decl cpp_protection_decl cpp_conversion_operator cpp_static_assert; %type cpp_swig_directive cpp_temp_possible cpp_nested cpp_opt_declarators ; @@ -1556,7 +1557,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %type

templateparameter ; %type templcpptype cpptype access_specifier; %type base_specifier -%type type rawtype type_right ; +%type type rawtype type_right anon_bitfield_type ; %type base_list inherit raw_inherit; %type definetype def_args etype; %type expr exprnum exprcompound valexpr; @@ -2940,25 +2941,25 @@ c_declaration : c_decl { A C global declaration of some kind (may be variable, function, typedef, etc.) ------------------------------------------------------------ */ -c_decl : storage_class type declarator c_rettype initializer c_decl_tail { +c_decl : storage_class type declarator initializer c_decl_tail { $$ = new_node("cdecl"); - if ($5.qualifier) SwigType_push($3.type,$5.qualifier); + if ($4.qualifier) SwigType_push($3.type,$4.qualifier); Setattr($$,"type",$2); Setattr($$,"storage",$1); Setattr($$,"name",$3.id); Setattr($$,"decl",$3.type); Setattr($$,"parms",$3.parms); - Setattr($$,"value",$5.val); - Setattr($$,"throws",$5.throws); - Setattr($$,"throw",$5.throwf); - if (!$6) { + Setattr($$,"value",$4.val); + Setattr($$,"throws",$4.throws); + Setattr($$,"throw",$4.throwf); + if (!$5) { if (Len(scanner_ccode)) { String *code = Copy(scanner_ccode); Setattr($$,"code",code); Delete(code); } } else { - Node *n = $6; + Node *n = $5; /* Inherit attributes */ while (n) { String *type = Copy($2); @@ -2968,8 +2969,8 @@ c_decl : storage_class type declarator c_rettype initializer c_decl_tail { Delete(type); } } - if ($5.bitfield) { - Setattr($$,"bitfield", $5.bitfield); + if ($4.bitfield) { + Setattr($$,"bitfield", $4.bitfield); } /* Look for "::" declarations (ignored) */ @@ -2983,33 +2984,77 @@ c_decl : storage_class type declarator c_rettype initializer c_decl_tail { String *lstr = Swig_scopename_last($3.id); Setattr($$,"name",lstr); Delete(lstr); - set_nextSibling($$,$6); + set_nextSibling($$,$5); } else { Delete($$); - $$ = $6; + $$ = $5; } Delete(p); } else { Delete($$); - $$ = $6; + $$ = $5; } } else { - set_nextSibling($$,$6); + set_nextSibling($$,$5); } } + /* Alternate function syntax introduced in C++0x: + auto funcName(int x, int y) -> int; */ + | storage_class AUTO declarator ARROW cpp_alternate_rettype initializer c_decl_tail { +/* $$ = new_node("cdecl"); + if ($6.qualifier) SwigType_push($3.type,$6.qualifier); + Setattr($$,"type",$5); + Setattr($$,"storage",$1); + Setattr($$,"name",$3.id); + Setattr($$,"decl",$3.type); + Setattr($$,"parms",$3.parms); + Setattr($$,"value",$6.val); + Setattr($$,"throws",$6.throws); + Setattr($$,"throw",$6.throwf); + if (!$7) { + if (Len(scanner_ccode)) { + String *code = Copy(scanner_ccode); + Setattr($$,"code",code); + Delete(code); + } + } else { + Node *n = $7; + while (n) { + String *type = Copy($5); + Setattr(n,"type",type); + Setattr(n,"storage",$1); + n = nextSibling(n); + Delete(type); + } + } + if ($6.bitfield) { + Setattr($$,"bitfield", $6.bitfield); + } + + if (Strstr($3.id,"::")) { + String *p = Swig_scopename_prefix($3.id); + if (p) { + if ((Namespaceprefix && Strcmp(p,Namespaceprefix) == 0) || + (inclass && Strcmp(p,Classprefix) == 0)) { + String *lstr = Swig_scopename_last($3.id); + Setattr($$,"name",lstr); + Delete(lstr); + set_nextSibling($$,$7); + } else { + Delete($$); + $$ = $7; + } + Delete(p); + } else { + Delete($$); + $$ = $7; + } + } else { + set_nextSibling($$,$7); + } */ + } ; -/* Alternate function syntax: - auto funcName(int x, int y) -> int; */ - -c_rettype : ARROW type { - $$ = new_node("rettype"); - Setattr($$,"type",$2); - } - | empty { - $$ = 0; - } - ; /* Allow lists of variables and functions to be built up */ c_decl_tail : SEMI { @@ -3070,7 +3115,13 @@ initializer : def_args { } ; - +cpp_alternate_rettype : primitive_type { $$ = $1; } + | TYPE_BOOL { $$ = $1; } + | TYPE_VOID { $$ = $1; } + | TYPE_TYPEDEF template_decl { $$ = NewStringf("%s%s",$1,$2); } + | TYPE_RAW { $$ = $1; } + | idcolon { $$ = $1; } + ; /* ------------------------------------------------------------ enum @@ -4529,7 +4580,21 @@ cpp_vend : cpp_const SEMI { ; -anonymous_bitfield : storage_class type COLON expr SEMI { }; +anonymous_bitfield : storage_class anon_bitfield_type COLON expr SEMI { }; + +/* Equals type_right without the ENUM keyword and cpptype (templates etc.): */ +anon_bitfield_type : primitive_type { $$ = $1; + /* Printf(stdout,"primitive = '%s'\n", $$);*/ + } + | TYPE_BOOL { $$ = $1; } + | TYPE_VOID { $$ = $1; } + | TYPE_TYPEDEF template_decl { $$ = NewStringf("%s%s",$1,$2); } + | TYPE_RAW { $$ = $1; } + + | idcolon { + $$ = $1; + } + ; /* ====================================================================== * PRIMITIVES @@ -4815,6 +4880,7 @@ declarator : pointer notso_direct_declarator { } | LAND notso_direct_declarator { /* Introduced in C++0x, move operator && */ + /* Adds one S/R conflict */ $$ = $2; $$.type = NewStringEmpty(); SwigType_add_reference($$.type); @@ -5262,7 +5328,6 @@ type_right : primitive_type { $$ = $1; } | TYPE_BOOL { $$ = $1; } | TYPE_VOID { $$ = $1; } - | TYPE_AUTO { $$ = $1; } | TYPE_TYPEDEF template_decl { $$ = NewStringf("%s%s",$1,$2); } | c_enum_keyword idcolon { $$ = NewStringf("enum %s", $2); } | TYPE_RAW { $$ = $1; } @@ -5838,14 +5903,6 @@ templcpptype : CLASS { $$ = (char *)"typename"; if (!inherit_list) last_cpptype = $$; } - | CLASS PERIOD PERIOD PERIOD { - $$ = (char*)"class"; - if (!inherit_list) last_cpptype = $$; - } - | TYPENAME PERIOD PERIOD PERIOD { - $$ = (char *)"typename"; - if (!inherit_list) last_cpptype = $$; - } ; cpptype : templcpptype { @@ -5931,13 +5988,11 @@ 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 : idcolon LPAREN parms RPAREN { -/* skip_balanced('(',')'); - Clear(scanner_ccode); -*/ } - | idcolon LBRACE parms RBRACE { +mem_initializer : idcolon LPAREN { skip_balanced('(',')'); Clear(scanner_ccode); } /* Uniform initialization in C++0x. Example: struct MyStruct { @@ -5946,11 +6001,7 @@ mem_initializer : idcolon LPAREN parms RPAREN { double y_; }; */ -/* skip_balanced('{','}'); - Clear(scanner_ccode); -*/ } - | idcolon LPAREN parms RPAREN PERIOD PERIOD PERIOD { } - | idcolon LBRACE parms RBRACE PERIOD PERIOD PERIOD { } + | idcolon LBRACE { skip_balanced('{','}'); Clear(scanner_ccode); } ; template_decl : LESSTHAN valparms GREATERTHAN { @@ -5980,12 +6031,12 @@ idcolon : idtemplate idcolontail { Delete($4); } | PERIOD PERIOD PERIOD idtemplate { - /* Introduced in C++0x, variadic constructor args */ + /* Introduced in C++0x, variadic constructor args or inside template<> block */ $$ = NewString($4); - } + } | idtemplate { $$ = NewString($1); - } + } | NONID DCOLON idtemplate { $$ = NewStringf("::%s",$3); } From a7e9a105d9449c6f2853a8869c13d7c5230cf660 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Fri, 31 Jul 2009 10:13:31 +0000 Subject: [PATCH 028/481] Enabled alternate function syntax and added runtime testcases. Added support for null pointer constant introduced in C++0x. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11484 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 13 +++++++------ .../test-suite/cpp0x_alternate_function_syntax.i | 9 +++++++-- .../test-suite/cpp0x_null_pointer_constant.i | 16 ++++++++++++++++ .../cpp0x_alternate_function_syntax_runme.py | 13 +++++++++++++ .../python/cpp0x_null_pointer_constant_runme.py | 15 +++++++++++++++ Source/CParse/parser.y | 4 ++-- 6 files changed, 60 insertions(+), 10 deletions(-) create mode 100644 Examples/test-suite/cpp0x_null_pointer_constant.i create mode 100644 Examples/test-suite/python/cpp0x_alternate_function_syntax_runme.py create mode 100644 Examples/test-suite/python/cpp0x_null_pointer_constant_runme.py diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 24dd4f6e3..1e27b54b0 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -409,13 +409,14 @@ CPP0X_TEST_CASES = \ cpp0x_function_objects \ cpp0x_strongly_typed_enumerations \ cpp0x_rvalue_reference \ - cpp0x_variadic_templates -# cpp0x_alternate_function_syntax # not fully implemented yet + cpp0x_variadic_templates \ + cpp0x_alternate_function_syntax # cpp0x_hash_types # not fully implemented yet -# cpp0x_unrestricted_unions # not supported by any compilers yet -# cpp0x_smart_pointers # not supported by standard library yet -# cpp0x_constexpr # not supported by any compilers yet -# cpp0x_thread_local # not supported by any compilers yet +# cpp0x_null_pointer_constant # not supported by any compilers yet +# cpp0x_unrestricted_unions # not supported by any compilers yet +# cpp0x_smart_pointers # not supported by standard library yet +# cpp0x_constexpr # not supported by any compilers yet +# cpp0x_thread_local # not supported by any compilers yet # Broken C++0x test cases. CPP0X_TEST_BROKEN = diff --git a/Examples/test-suite/cpp0x_alternate_function_syntax.i b/Examples/test-suite/cpp0x_alternate_function_syntax.i index ed3cb6729..b17223626 100644 --- a/Examples/test-suite/cpp0x_alternate_function_syntax.i +++ b/Examples/test-suite/cpp0x_alternate_function_syntax.i @@ -2,10 +2,15 @@ %inline %{ struct SomeStruct { - auto FuncName(int x, int y) -> int; + int addNormal(int x, int y); + auto addAlternate(int x, int y) -> int; }; -auto SomeStruct::FuncName(int x, int y) -> int { +auto SomeStruct::addAlternate(int x, int y) -> int { + return x + y; +} + +int SomeStruct::addNormal(int x, int y) { return x + y; } %} diff --git a/Examples/test-suite/cpp0x_null_pointer_constant.i b/Examples/test-suite/cpp0x_null_pointer_constant.i new file mode 100644 index 000000000..9057f04be --- /dev/null +++ b/Examples/test-suite/cpp0x_null_pointer_constant.i @@ -0,0 +1,16 @@ +/* This testcase checks whether Swig correctly treats the new nullptr_t + constant introduced in C++0x. +*/ + +%module cpp0x_null_pointer_constant + +%inline %{ +#include + +class A { +public: + A() : _myA(std::nullptr) { } + + A *_myA; +}; +%} diff --git a/Examples/test-suite/python/cpp0x_alternate_function_syntax_runme.py b/Examples/test-suite/python/cpp0x_alternate_function_syntax_runme.py new file mode 100644 index 000000000..8005cfab7 --- /dev/null +++ b/Examples/test-suite/python/cpp0x_alternate_function_syntax_runme.py @@ -0,0 +1,13 @@ +import cpp0x_alternate_function_syntax + +a = cpp0x_alternate_function_syntax.SomeStruct() + +res = a.addNormal(4,5) +if res != 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.") + diff --git a/Examples/test-suite/python/cpp0x_null_pointer_constant_runme.py b/Examples/test-suite/python/cpp0x_null_pointer_constant_runme.py new file mode 100644 index 000000000..b80dcaf2f --- /dev/null +++ b/Examples/test-suite/python/cpp0x_null_pointer_constant_runme.py @@ -0,0 +1,15 @@ +import cpp0x_null_pointer_constant + +a = cpp0x_null_pointer_constant.A() + +if a._myA != None: + raise RuntimeError, ("cpp0x_null_pointer_constant: _myA should be None, but is ", a._myA) + +b = cpp0x_null_pointer_constant.A() +if a._myA != b._myA: + raise RuntimeError, ("cpp0x_null_pointer_constant: a._myA should be the same as b._myA, but ", a._myA, "!=", b._myA) + +a._myA = cpp0x_null_pointer_constant.A() +if a._myA == None: + raise RuntimeError, ("cpp0x_null_pointer_constant: _myA should be object, but is None") + diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index c8e7e284d..f3a73f38a 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -3001,7 +3001,7 @@ c_decl : storage_class type declarator initializer c_decl_tail { /* Alternate function syntax introduced in C++0x: auto funcName(int x, int y) -> int; */ | storage_class AUTO declarator ARROW cpp_alternate_rettype initializer c_decl_tail { -/* $$ = new_node("cdecl"); + $$ = new_node("cdecl"); if ($6.qualifier) SwigType_push($3.type,$6.qualifier); Setattr($$,"type",$5); Setattr($$,"storage",$1); @@ -3051,7 +3051,7 @@ c_decl : storage_class type declarator initializer c_decl_tail { } } else { set_nextSibling($$,$7); - } */ + } } ; From 24402abf7d174d0e126fbdd8808afe1973a5bd83 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Sat, 1 Aug 2009 22:00:36 +0000 Subject: [PATCH 029/481] Enabled support for variadic %template directive. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11487 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .../test-suite/cpp0x_variadic_templates.i | 10 +- Source/CParse/parser.y | 118 ++++++++++++++++-- 2 files changed, 116 insertions(+), 12 deletions(-) diff --git a/Examples/test-suite/cpp0x_variadic_templates.i b/Examples/test-suite/cpp0x_variadic_templates.i index 090645966..6317b1340 100644 --- a/Examples/test-suite/cpp0x_variadic_templates.i +++ b/Examples/test-suite/cpp0x_variadic_templates.i @@ -22,19 +22,19 @@ class MultiArgs, std::map>> %} // TODO -//%template (MultiArgs) MultiArgs, std::map>>; +%template (MultiArgs1) MultiArgs, std::map>>; //////////////////////// // Variadic sizeof... // //////////////////////// %inline %{ -template struct SizeOf { +template struct SizeOf { static const int size = sizeof...(Args); }; %} // TODO -//%template (SizeOf) SizeOf; +%template (SizeOf1) SizeOf; ////////////////////////// // Variadic inheritance // @@ -59,9 +59,9 @@ public: template class MultiInherit : public BaseClasses... { public: - MultiInherit(BaseClasses&&... baseClasses) : BaseClasses(baseClasses)... {} + MultiInherit(BaseClasses&... baseClasses) : BaseClasses(baseClasses)... {} }; %} // TODO -//%template (MultiInherit) MultiInherit; +%template (MultiInherit1) MultiInherit; diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index f3a73f38a..000958387 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -2621,6 +2621,7 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va Node *tnode = 0; Symtab *tscope = 0; int specialized = 0; + int variadic = 0; $$ = 0; @@ -2678,11 +2679,13 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va Parm *tparms = Getattr(nn,"templateparms"); if (!tparms) { specialized = 1; + } else if (Getattr(tparms,"variadic") && strncmp(Char(Getattr(tparms,"variadic")), "1", 1)==0) { + variadic = 1; } - if (nnisclass && !specialized && ((ParmList_len($7) > ParmList_len(tparms)))) { + if (nnisclass && !variadic && !specialized && (ParmList_len($7) > ParmList_len(tparms))) { Swig_error(cparse_file, cparse_line, "Too many template parameters. Maximum of %d.\n", ParmList_len(tparms)); - } else if (nnisclass && !specialized && ((ParmList_len($7) < ParmList_numrequired(tparms)))) { - Swig_error(cparse_file, cparse_line, "Not enough template parameters specified. %d required.\n", ParmList_numrequired(tparms)); + } else if (nnisclass && !specialized && ((ParmList_len($7) < (ParmList_numrequired(tparms) - (variadic?1:0))))) { /* Variadic parameter is optional */ + Swig_error(cparse_file, cparse_line, "Not enough template parameters specified. %d required.\n", (ParmList_numrequired(tparms)-(variadic?1:0)) ); } else if (!nnisclass && ((ParmList_len($7) != ParmList_len(tparms)))) { /* must be an overloaded templated method - ignore it as it is overloaded with a different number of template parameters */ nn = Getattr(nn,"sym:nextSibling"); /* repeat for overloaded templated functions */ @@ -2741,6 +2744,9 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va if (!p && tp) { p = tp; def_supplied = 1; + } else if (!tp) { /* Variadic tempalte - tp < p */ + Swig_warning(0,cparse_file, cparse_line,"Variadic templates not fully supported by Swig.\n"); + break; } } @@ -3994,6 +4000,12 @@ template_parms : templateparameters { if ((strncmp(type,"class ",6) == 0) || (strncmp(type,"typename ", 9) == 0)) { char *t = strchr(type,' '); Setattr(p,"name", t+1); + } else + /* Variadic template args */ + if ((strncmp(type,"class... ",9) == 0) || (strncmp(type,"typename... ", 12) == 0)) { + char *t = strchr(type,' '); + Setattr(p,"name", t+1); + Setattr(p,"variadic", "1"); } else { /* Swig_error(cparse_file, cparse_line, "Missing template parameter name\n"); @@ -4933,6 +4945,94 @@ declarator : pointer notso_direct_declarator { } $$.type = t; } + + /* Variadic versions eg. MyClasses&... myIds */ + + | pointer PERIOD PERIOD PERIOD notso_direct_declarator { + $$ = $5; + if ($$.type) { + SwigType_push($1,$$.type); + Delete($$.type); + } + $$.type = $1; + } + | pointer AND PERIOD PERIOD PERIOD notso_direct_declarator { + $$ = $6; + SwigType_add_reference($1); + if ($$.type) { + SwigType_push($1,$$.type); + Delete($$.type); + } + $$.type = $1; + } + | PERIOD PERIOD PERIOD direct_declarator { + $$ = $4; + if (!$$.type) $$.type = NewStringEmpty(); + } + | AND PERIOD PERIOD PERIOD notso_direct_declarator { + $$ = $5; + $$.type = NewStringEmpty(); + SwigType_add_reference($$.type); + if ($5.type) { + SwigType_push($$.type,$5.type); + Delete($5.type); + } + } + | LAND PERIOD PERIOD PERIOD notso_direct_declarator { + /* Introduced in C++0x, move operator && */ + /* Adds one S/R conflict */ + $$ = $5; + $$.type = NewStringEmpty(); + SwigType_add_reference($$.type); + if ($5.type) { + SwigType_push($$.type,$5.type); + Delete($5.type); + } + } + | idcolon DSTAR PERIOD PERIOD PERIOD notso_direct_declarator { + SwigType *t = NewStringEmpty(); + + $$ = $6; + SwigType_add_memberpointer(t,$1); + if ($$.type) { + SwigType_push(t,$$.type); + Delete($$.type); + } + $$.type = t; + } + | pointer idcolon DSTAR PERIOD PERIOD PERIOD notso_direct_declarator { + SwigType *t = NewStringEmpty(); + $$ = $7; + SwigType_add_memberpointer(t,$2); + SwigType_push($1,t); + if ($$.type) { + SwigType_push($1,$$.type); + Delete($$.type); + } + $$.type = $1; + Delete(t); + } + | pointer idcolon DSTAR AND PERIOD PERIOD PERIOD notso_direct_declarator { + $$ = $8; + SwigType_add_memberpointer($1,$2); + SwigType_add_reference($1); + if ($$.type) { + SwigType_push($1,$$.type); + Delete($$.type); + } + $$.type = $1; + } + | idcolon DSTAR AND PERIOD PERIOD PERIOD notso_direct_declarator { + SwigType *t = NewStringEmpty(); + $$ = $7; + SwigType_add_memberpointer(t,$1); + SwigType_add_reference(t); + if ($$.type) { + SwigType_push(t,$$.type); + Delete($$.type); + } + $$.type = t; + } ; notso_direct_declarator : idcolon { @@ -5903,6 +6003,14 @@ templcpptype : CLASS { $$ = (char *)"typename"; if (!inherit_list) last_cpptype = $$; } + | CLASS PERIOD PERIOD PERIOD { + $$ = (char *)"class..."; + if (!inherit_list) last_cpptype = $$; + } + | TYPENAME PERIOD PERIOD PERIOD { + $$ = (char *)"typename..."; + if (!inherit_list) last_cpptype = $$; + } ; cpptype : templcpptype { @@ -6030,10 +6138,6 @@ idcolon : idtemplate idcolontail { $$ = NewStringf("::%s%s",$3,$4); Delete($4); } - | PERIOD PERIOD PERIOD idtemplate { - /* Introduced in C++0x, variadic constructor args or inside template<> block */ - $$ = NewString($4); - } | idtemplate { $$ = NewString($1); } From 1993f926246f8e00e8fda5842f2a5f112302dbfc Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Sat, 1 Aug 2009 22:31:38 +0000 Subject: [PATCH 030/481] Fixed variadic template argument warning. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11488 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/CParse/parser.y | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 000958387..01ed40350 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -2744,8 +2744,8 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va if (!p && tp) { p = tp; def_supplied = 1; - } else if (!tp) { /* Variadic tempalte - tp < p */ - Swig_warning(0,cparse_file, cparse_line,"Variadic templates not fully supported by Swig.\n"); + } else if (p && !tp) { /* Variadic template - tp < p */ + Swig_warning(0,cparse_file, cparse_line,"Only the first variadic argument is currently supported by Swig.\n"); break; } } From ba2c8cff409890fa38aec7d0f4b4fa2e82a167bf Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Mon, 3 Aug 2009 15:03:41 +0000 Subject: [PATCH 031/481] Added syntax for lambda expressions and closures introduced in C++0x. Added testcase cpp0x_lambda_functions.i. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11491 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 1 + Examples/test-suite/cpp0x_lambda_functions.i | 34 ++++++++++++++++++++ Source/CParse/parser.y | 14 +++++++- 3 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 Examples/test-suite/cpp0x_lambda_functions.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 1e27b54b0..22bf646c3 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -412,6 +412,7 @@ CPP0X_TEST_CASES = \ cpp0x_variadic_templates \ cpp0x_alternate_function_syntax # cpp0x_hash_types # not fully implemented yet +# cpp0x_lambda_functions # not supported by GCC or MSVC yet # cpp0x_null_pointer_constant # not supported by any compilers yet # cpp0x_unrestricted_unions # not supported by any compilers yet # cpp0x_smart_pointers # not supported by standard library yet diff --git a/Examples/test-suite/cpp0x_lambda_functions.i b/Examples/test-suite/cpp0x_lambda_functions.i new file mode 100644 index 000000000..7719b59f4 --- /dev/null +++ b/Examples/test-suite/cpp0x_lambda_functions.i @@ -0,0 +1,34 @@ +/* This testcase checks whether Swig correctly parses the lambda expressions + and closure syntax introduced in C++0x. + Swig supports only lambda syntax and doesn't produce any wrapper code for + this. +*/ +%module cpp0x_lambda_functions + +%inline %{ +struct A { + /* Defined lambda function with return value. */ + auto lambda1 = [](int x, int y) -> int { return x+y; }; + + /* Defined lambda function without return value. + Return value is calculated by compiler, if the function contains a + single statement "return expr;". */ + auto lambda2 = [](int x, int y) { return x+y; }; +}; + +int runLambda1() { + A myA; + return myA.lambda1(5,6); +} + +int runLambda2() { + A myA; + return myA.lambda2(5,6); +} + +/* Inline defined lambda function. */ +int runLambda3() { + auto myLambda = [](int x, int y) { return x+y; }; + return myLambda(5,6); +} +%} diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 01ed40350..6335b03f9 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1536,7 +1536,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %type types_directive template_directive warn_directive ; /* C declarations */ -%type c_declaration c_decl c_decl_tail c_enum_keyword c_enum_inherit c_enum_decl c_enum_forward_decl c_constructor_decl ; +%type c_declaration c_decl c_decl_tail c_enum_keyword c_enum_inherit c_enum_decl c_enum_forward_decl c_constructor_decl c_lambda_decl c_lambda_decl_front ; %type enumlist edecl; /* C++ declarations */ @@ -2941,6 +2941,7 @@ c_declaration : c_decl { appendChild($$,firstChild($5)); } } + | c_lambda_decl { Swig_warning("Swig doesn't produce wrapper code for lambda expressions and closures yet.") $$ = $1; } ; /* ------------------------------------------------------------ @@ -3129,6 +3130,17 @@ cpp_alternate_rettype : primitive_type { $$ = $1; } | idcolon { $$ = $1; } ; +/* Lambda function syntax introduced in C++0x. + auto myFunc = [](int x, int y) -> int { return x+y; } + OR + auto myFunc = [](int x, int y) { return x+y; } +*/ +c_lambda_decl : c_lambda_decl_front LPAREN parms RPAREN LBRACE { skip_balanced('{','}'); } SEMI { $$ = 0; } + | c_lambda_decl_front LPAREN parms RPAREN ARROW type LBRACE { skip_balanced('{','}'); } SEMI { $$ = 0; } + +c_lambda_decl_front : storage_class AUTO idcolon EQUAL LBRACKET { skip_balanced('[',']'); $$ = 0; } + + /* ------------------------------------------------------------ enum or From c2f9904abe59fb0e08685dca555e4e1d6591bfc1 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Mon, 3 Aug 2009 15:42:54 +0000 Subject: [PATCH 032/481] Fixed compilation error. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11492 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/CParse/parser.y | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 6335b03f9..29d821ea5 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -2941,7 +2941,7 @@ c_declaration : c_decl { appendChild($$,firstChild($5)); } } - | c_lambda_decl { Swig_warning("Swig doesn't produce wrapper code for lambda expressions and closures yet.") $$ = $1; } + | c_lambda_decl { Swig_warning(WARN_LANG_NATIVE_UNIMPL, cparse_file, cparse_line,"Swig doesn't produce wrapper code for lambda expressions and closures yet.\n"); $$ = $1; } ; /* ------------------------------------------------------------ From 8a4efbc6d35134ed4aed1a622ef8183e44580155 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Tue, 4 Aug 2009 00:51:21 +0000 Subject: [PATCH 033/481] Added support for user-defined string literals. Added testcase cpp0x_userdefined_literals.i git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11494 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 3 ++- .../test-suite/cpp0x_userdefined_literals.i | 24 +++++++++++++++++++ Source/CParse/cscanner.c | 5 ++++ Source/CParse/parser.y | 23 +++++++++++++++++- 4 files changed, 53 insertions(+), 2 deletions(-) create mode 100644 Examples/test-suite/cpp0x_userdefined_literals.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 22bf646c3..1001b8ac8 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -410,7 +410,8 @@ CPP0X_TEST_CASES = \ cpp0x_strongly_typed_enumerations \ cpp0x_rvalue_reference \ cpp0x_variadic_templates \ - cpp0x_alternate_function_syntax + cpp0x_alternate_function_syntax \ + cpp0x_userdefined_literals # cpp0x_hash_types # not fully implemented yet # cpp0x_lambda_functions # not supported by GCC or MSVC yet # cpp0x_null_pointer_constant # not supported by any compilers yet diff --git a/Examples/test-suite/cpp0x_userdefined_literals.i b/Examples/test-suite/cpp0x_userdefined_literals.i new file mode 100644 index 000000000..f41823488 --- /dev/null +++ b/Examples/test-suite/cpp0x_userdefined_literals.i @@ -0,0 +1,24 @@ +/* This testcase checks whether Swig correctly parses the user-defined literals + for the string introduced in C++0x. */ +%module cpp0x_userdefined_literals + +%inline %{ +#include + +struct OutputType { + int val; + + OutputType(int v) { v=val; } +}; + +struct TT { +OutputType operator << (const char * string_values, size_t num_chars) { return OutputType(100); } +OutputType operator "" (const char * string_values, size_t num_chars) { return OutputType(100); } +OutputType operator "" _mySuffix1(const char * string_values, size_t num_chars) { return OutputType(100); } +OutputType operator "" _mySuffix2(const wchar_t * string_values, size_t num_chars) { return OutputType(200); } +OutputType operator "" _mySuffix3(const char16_t * string_values, size_t num_chars) { return OutputType(300); } +OutputType operator "" _mySuffix4(const char32_t * string_values, size_t num_chars) { return OutputType(400); } +OutputType operator "" _mySuffix5(int value) /* cooked version - ie. atoi() of string */ { return OutputType(500); } +}; + +%} diff --git a/Source/CParse/cscanner.c b/Source/CParse/cscanner.c index f923bc3b6..369c962e9 100644 --- a/Source/CParse/cscanner.c +++ b/Source/CParse/cscanner.c @@ -688,6 +688,11 @@ int yylex(void) { yylval.str = s; return OPERATOR; } + } else if (nexttok == SWIG_TOKEN_STRING) { + /* Operator "" or user-defined string literal ""_suffix */ + Append(s,"\"\""); + yylval.str = s; + return OPERATOR; } else if (nexttok == SWIG_TOKEN_ID) { /* We have an identifier. This could be any number of things. It could be a named version of an operator (e.g., 'and_eq') or it could be a conversion operator. To deal with this, we're diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 29d821ea5..b164690e1 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -5145,7 +5145,7 @@ direct_declarator : idcolon { $$.parms = 0; $$.have_parms = 0; } - + | NOT idcolon { $$.id = Char(NewStringf("~%s",$2)); $$.type = 0; @@ -5227,6 +5227,27 @@ direct_declarator : idcolon { Delete($$.type); $$.type = t; } + } + /* User-defined string literals. eg. + int operator""_mySuffix(const char* val, int length) {...} */ + /* This produces one S/R conflict. */ + | OPERATOR ID LPAREN parms RPAREN { + SwigType *t; + Append($1, Char($2)); + $$.id = Char($1); + t = NewStringEmpty(); + SwigType_add_function(t,$4); + if (!$$.have_parms) { + $$.parms = $4; + $$.have_parms = 1; + } + if (!$$.type) { + $$.type = t; + } else { + SwigType_push(t, $$.type); + Delete($$.type); + $$.type = t; + } } ; From e2e9b04b3d80de377a6accf2cdb761ce2d8cb4d0 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Mon, 10 Aug 2009 10:46:07 +0000 Subject: [PATCH 034/481] Added initial support for C++0x decltype(). Added testcase cpp0x_decltype. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11525 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 3 ++- Examples/test-suite/cpp0x_decltype.i | 19 +++++++++++++++++++ .../test-suite/python/cpp0x_decltype_runme.py | 19 +++++++++++++++++++ Source/CParse/cscanner.c | 2 ++ Source/CParse/parser.y | 18 ++++++++++++++++-- 5 files changed, 58 insertions(+), 3 deletions(-) create mode 100644 Examples/test-suite/cpp0x_decltype.i create mode 100644 Examples/test-suite/python/cpp0x_decltype_runme.py diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 1001b8ac8..d8fb30936 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -411,7 +411,8 @@ CPP0X_TEST_CASES = \ cpp0x_rvalue_reference \ cpp0x_variadic_templates \ cpp0x_alternate_function_syntax \ - cpp0x_userdefined_literals + cpp0x_userdefined_literals \ + cpp0x_decltype # cpp0x_hash_types # not fully implemented yet # cpp0x_lambda_functions # not supported by GCC or MSVC yet # cpp0x_null_pointer_constant # not supported by any compilers yet diff --git a/Examples/test-suite/cpp0x_decltype.i b/Examples/test-suite/cpp0x_decltype.i new file mode 100644 index 000000000..316c38962 --- /dev/null +++ b/Examples/test-suite/cpp0x_decltype.i @@ -0,0 +1,19 @@ +/* This testcase checks whether Swig correctly uses the new 'decltype()' + introduced in C++0x. +*/ +%module cpp0x_decltype + +%inline %{ +class A { +public: + int i; + decltype(i) j; + + auto foo( decltype(i) a ) -> decltype(i) { + if (a==5) + return 10; + else + return 0; + } +}; +%} diff --git a/Examples/test-suite/python/cpp0x_decltype_runme.py b/Examples/test-suite/python/cpp0x_decltype_runme.py new file mode 100644 index 000000000..ce742e6b2 --- /dev/null +++ b/Examples/test-suite/python/cpp0x_decltype_runme.py @@ -0,0 +1,19 @@ +import cpp0x_decltype + +a = cpp0x_decltype.A() +a.i = 5 +if a.i != 5: + raise RuntimeError, "Assignment to a.i failed." + +a.j = 10 +if a.j != 10: + raise RuntimeError, "Assignment to a.j failed." + +b = a.foo(5) +if b != 10: + raise RuntimeError, "foo(5) should return 10." + +b = a.foo(6) +if b != 0: + raise RuntimeError, "foo(6) should return 0." + diff --git a/Source/CParse/cscanner.c b/Source/CParse/cscanner.c index 369c962e9..626958169 100644 --- a/Source/CParse/cscanner.c +++ b/Source/CParse/cscanner.c @@ -636,6 +636,8 @@ int yylex(void) { return (CONSTEXPR); if (strcmp(yytext, "thread_local") == 0) return (THREAD_LOCAL); + if (strcmp(yytext, "decltype") == 0) + return (DECLTYPE); if (strcmp(yytext, "virtual") == 0) return (VIRTUAL); if (strcmp(yytext, "static_assert") == 0) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index b164690e1..2392e7705 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1493,7 +1493,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %token NAME RENAME NAMEWARN EXTEND PRAGMA FEATURE VARARGS %token ENUM %token CLASS TYPENAME PRIVATE PUBLIC PROTECTED COLON STATIC VIRTUAL FRIEND THROW CATCH EXPLICIT AUTO -%token STATIC_ASSERT CONSTEXPR THREAD_LOCAL /* C++0x keywords */ +%token STATIC_ASSERT CONSTEXPR THREAD_LOCAL DECLTYPE /* C++0x keywords */ %token USING %token NAMESPACE %token NATIVE INLINE @@ -1557,7 +1557,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %type

templateparameter ; %type templcpptype cpptype access_specifier; %type base_specifier -%type type rawtype type_right anon_bitfield_type ; +%type type rawtype type_right anon_bitfield_type decltype ; %type base_list inherit raw_inherit; %type definetype def_args etype; %type expr exprnum exprcompound valexpr; @@ -3128,6 +3128,7 @@ cpp_alternate_rettype : primitive_type { $$ = $1; } | TYPE_TYPEDEF template_decl { $$ = NewStringf("%s%s",$1,$2); } | TYPE_RAW { $$ = $1; } | idcolon { $$ = $1; } + | decltype { $$ = $1; } ; /* Lambda function syntax introduced in C++0x. @@ -5471,6 +5472,19 @@ type_right : primitive_type { $$ = $1; | cpptype idcolon { $$ = NewStringf("%s %s", $1, $2); } + | decltype { + $$ = $1; + } + ; + +decltype : DECLTYPE LPAREN idcolon RPAREN { + Node *n = Swig_symbol_clookup($3,0); + if (!n) { + Swig_error(cparse_file, cparse_line, "Identifier %s not defined.\n", $3); + } else { + $$ = Getattr(n, "type"); + } + } ; primitive_type : primitive_type_list { From 41a565dd5f73d9f45b5619f0939f3c208c74240f Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Tue, 11 Aug 2009 15:20:38 +0000 Subject: [PATCH 035/481] Added testcase cpp0x_constructors for delegating constructors and constructor inheritance. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11532 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 11 +++++---- Examples/test-suite/cpp0x_constructors.i | 30 ++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 5 deletions(-) create mode 100644 Examples/test-suite/cpp0x_constructors.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index d8fb30936..b29b65162 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -413,13 +413,14 @@ CPP0X_TEST_CASES = \ cpp0x_alternate_function_syntax \ cpp0x_userdefined_literals \ cpp0x_decltype -# cpp0x_hash_types # not fully implemented yet +# cpp0x_hash_types # not fully implemented yet +# cpp0x_constructors # not supported by any compiler yet # cpp0x_lambda_functions # not supported by GCC or MSVC yet -# cpp0x_null_pointer_constant # not supported by any compilers yet -# cpp0x_unrestricted_unions # not supported by any compilers yet +# cpp0x_null_pointer_constant # not supported by any compiler yet +# cpp0x_unrestricted_unions # not supported by any compiler yet # cpp0x_smart_pointers # not supported by standard library yet -# cpp0x_constexpr # not supported by any compilers yet -# cpp0x_thread_local # not supported by any compilers yet +# cpp0x_constexpr # not supported by any compiler yet +# cpp0x_thread_local # not supported by any compiler yet # Broken C++0x test cases. CPP0X_TEST_BROKEN = diff --git a/Examples/test-suite/cpp0x_constructors.i b/Examples/test-suite/cpp0x_constructors.i new file mode 100644 index 000000000..47f030a95 --- /dev/null +++ b/Examples/test-suite/cpp0x_constructors.i @@ -0,0 +1,30 @@ +/* This test checks whether Swig correctly parses the new delegating + constructors and constructor inheritance. +*/ +%module cpp0x_constructors + +%inline %{ +class BaseClass { +private: + int _val; +public: + BaseClass(int iValue) { _val = iValue; } +}; + +class DerivedClass: public BaseClass { +public: + using BaseClass::BaseClass; // Adds DerivedClass(int) constructor +}; + +class A { +public: + int a; + int b; + int c; + + A() : A( 10 ) {} + A(int aa) : A(aa, 20) {} + A(int aa, int bb) : A(aa, bb, 30) {} + A(int aa, int bb, int cc) { a=aa; b=bb; c=cc; } +}; +%} From 65c09323fcf12fa02f7426e49116ba392df6c43f Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Tue, 11 Aug 2009 18:27:33 +0000 Subject: [PATCH 036/481] Added syntax support for template aliasing and new 'using' syntax for typedefs introduced in C++0x. Added testcase cpp0x_template_typedefs. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11533 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 1 + Examples/test-suite/cpp0x_template_typedefs.i | 18 ++++++++++++++++++ Source/CParse/parser.y | 2 ++ 3 files changed, 21 insertions(+) create mode 100644 Examples/test-suite/cpp0x_template_typedefs.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index b29b65162..aa569bdea 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -413,6 +413,7 @@ CPP0X_TEST_CASES = \ cpp0x_alternate_function_syntax \ cpp0x_userdefined_literals \ cpp0x_decltype +# cpp0x_template_typedefs # not supported by any compiler yet # cpp0x_hash_types # not fully implemented yet # cpp0x_constructors # not supported by any compiler yet # cpp0x_lambda_functions # not supported by GCC or MSVC yet diff --git a/Examples/test-suite/cpp0x_template_typedefs.i b/Examples/test-suite/cpp0x_template_typedefs.i new file mode 100644 index 000000000..3164b86ae --- /dev/null +++ b/Examples/test-suite/cpp0x_template_typedefs.i @@ -0,0 +1,18 @@ +/* This testcase checks whether Swig correctly parses the template aliasing. */ +%module cpp0x_template_typedefs + +%inline %{ +template< typename T1, typename T2, int > +class SomeType { + T1 a; + T2 b; + int c; +}; + +template< typename T2 > +using TypedefName = SomeType; + +typedef void (*PFD)(double); // Old style +using PF = void (*)(double); // New introduced syntax +%} + diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 2392e7705..25731ee35 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -2942,6 +2942,8 @@ c_declaration : c_decl { } } | c_lambda_decl { Swig_warning(WARN_LANG_NATIVE_UNIMPL, cparse_file, cparse_line,"Swig doesn't produce wrapper code for lambda expressions and closures yet.\n"); $$ = $1; } + | USING idcolon EQUAL { skip_decl(); Swig_warning(WARN_LANG_NATIVE_UNIMPL, cparse_file, cparse_line,"Swig doesn't support 'using' typedefs yet.\n"); $$ = 0; } + | TEMPLATE LESSTHAN template_parms GREATERTHAN USING idcolon EQUAL { skip_decl(); Swig_warning(WARN_LANG_NATIVE_UNIMPL, cparse_file, cparse_line,"Swig doesn't support template aliasing yet.\n"); $$ = 0; } ; /* ------------------------------------------------------------ From 2f3a18e49b04bed6f25b9cf7ae6ca7228519df6c Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Tue, 11 Aug 2009 19:44:03 +0000 Subject: [PATCH 037/481] Added cpp0x_result_of testcase. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11534 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 3 ++- Examples/test-suite/cpp0x_result_of.i | 19 +++++++++++++++++++ .../python/cpp0x_result_of_runme.py | 3 +++ 3 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 Examples/test-suite/cpp0x_result_of.i create mode 100644 Examples/test-suite/python/cpp0x_result_of_runme.py diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index aa569bdea..8415197f4 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -412,7 +412,8 @@ CPP0X_TEST_CASES = \ cpp0x_variadic_templates \ cpp0x_alternate_function_syntax \ cpp0x_userdefined_literals \ - cpp0x_decltype + cpp0x_decltype \ + cpp0x_result_of # cpp0x_template_typedefs # not supported by any compiler yet # cpp0x_hash_types # not fully implemented yet # cpp0x_constructors # not supported by any compiler yet diff --git a/Examples/test-suite/cpp0x_result_of.i b/Examples/test-suite/cpp0x_result_of.i new file mode 100644 index 000000000..fb8586ba7 --- /dev/null +++ b/Examples/test-suite/cpp0x_result_of.i @@ -0,0 +1,19 @@ +/* This testcase checks whether Swig correctly uses the new result_of class + and its templating capabilities introduced in C++0x. */ +%module cpp0x_result_of + +%inline %{ +#include +#include + +double square(double x) { + return (x * x); +} + +template +typename std::result_of::type test_result_impl(Fun fun, Arg arg) { + return fun(arg); +} +%} + +%template(test_result) test_result_impl; diff --git a/Examples/test-suite/python/cpp0x_result_of_runme.py b/Examples/test-suite/python/cpp0x_result_of_runme.py new file mode 100644 index 000000000..5411cd1ce --- /dev/null +++ b/Examples/test-suite/python/cpp0x_result_of_runme.py @@ -0,0 +1,3 @@ +import cpp0x_result_of +if cpp0x_result_of.test_result(cpp0x_result_of.square, 3.0) != 9.0: + raise RuntimeError, "test_result(square, 3.0) is not 9.0." From 955c736164cadd0ec5a0482c2bf26712708e8d22 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Tue, 11 Aug 2009 20:06:23 +0000 Subject: [PATCH 038/481] Added testcase for default/delete arguments introduced in C++0x. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11535 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 3 ++- Examples/test-suite/cpp0x_default_delete.i | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 Examples/test-suite/cpp0x_default_delete.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 8415197f4..bfc1a4cb9 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -413,7 +413,8 @@ CPP0X_TEST_CASES = \ cpp0x_alternate_function_syntax \ cpp0x_userdefined_literals \ cpp0x_decltype \ - cpp0x_result_of + cpp0x_result_of \ + cpp0x_default_delete # cpp0x_template_typedefs # not supported by any compiler yet # cpp0x_hash_types # not fully implemented yet # cpp0x_constructors # not supported by any compiler yet diff --git a/Examples/test-suite/cpp0x_default_delete.i b/Examples/test-suite/cpp0x_default_delete.i new file mode 100644 index 000000000..2e2108494 --- /dev/null +++ b/Examples/test-suite/cpp0x_default_delete.i @@ -0,0 +1,22 @@ +%module cpp0x_default_delete + +%{ +#include + +class NonCopyable { +public: + NonCopyable & operator=(const NonCopyable&) = delete; /* Removes operator= */ + NonCopyable(const NonCopyable&) = delete; /* Removed copy constructor */ + NonCopyable() = default; /* Explicitly allows the empty constructor */ + void *operator new(size_t) = delete; /* Removes new NonCopyable */ +}; + +struct A1 { + void f(int i); + void f(double i) = delete; /* Don't cast double to int. Compiler returns an error */ +}; +struct A2 { + void f(int i); + template void f(T) = delete; /* Only accept int */ +}; +%} From bc8f86b6ec1b144147a74afe236002600250d687 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Wed, 12 Aug 2009 10:18:18 +0000 Subject: [PATCH 039/481] Fixed cpp0x_result_of testcase. Added testcase cpp0x_sizeof_object. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11538 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 3 ++- Examples/test-suite/cpp0x_result_of.i | 1 + Examples/test-suite/cpp0x_sizeof_object.i | 17 +++++++++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 Examples/test-suite/cpp0x_sizeof_object.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index bfc1a4cb9..268296f3c 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -414,7 +414,8 @@ CPP0X_TEST_CASES = \ cpp0x_userdefined_literals \ cpp0x_decltype \ cpp0x_result_of \ - cpp0x_default_delete + cpp0x_default_delete \ + cpp0x_sizeof_object # cpp0x_template_typedefs # not supported by any compiler yet # cpp0x_hash_types # not fully implemented yet # cpp0x_constructors # not supported by any compiler yet diff --git a/Examples/test-suite/cpp0x_result_of.i b/Examples/test-suite/cpp0x_result_of.i index fb8586ba7..4def13a38 100644 --- a/Examples/test-suite/cpp0x_result_of.i +++ b/Examples/test-suite/cpp0x_result_of.i @@ -17,3 +17,4 @@ typename std::result_of::type test_result_impl(Fun fun, Arg arg) { %} %template(test_result) test_result_impl; +%constant double (*SQUARE)(double) = square; diff --git a/Examples/test-suite/cpp0x_sizeof_object.i b/Examples/test-suite/cpp0x_sizeof_object.i new file mode 100644 index 000000000..89e659e81 --- /dev/null +++ b/Examples/test-suite/cpp0x_sizeof_object.i @@ -0,0 +1,17 @@ +/* This testcase checks whether Swig correctly uses the sizeof() on the + concrete objects and not only types introduced in C++0x. */ +%module cpp0x_sizeof_object + +%inline %{ +struct B { + unsigned long member1; + long long member2; + char member3; +}; + +struct A { + B member; +}; + +const int a = sizeof(A::member); +%} From dccbc68c70e43b3af063777cd0d3cf87d5770df7 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Wed, 12 Aug 2009 16:50:17 +0000 Subject: [PATCH 040/481] Added warning for initializer_list introduced in C++0x. Added testcase cpp0x_initializer_list. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11540 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 3 +- Examples/test-suite/cpp0x_initializer_list.i | 13 +++++++ Source/CParse/parser.y | 36 ++++++++++++-------- Source/Include/swigwarn.h | 1 + 4 files changed, 37 insertions(+), 16 deletions(-) create mode 100644 Examples/test-suite/cpp0x_initializer_list.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 268296f3c..992406535 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -415,7 +415,8 @@ CPP0X_TEST_CASES = \ cpp0x_decltype \ cpp0x_result_of \ cpp0x_default_delete \ - cpp0x_sizeof_object + cpp0x_sizeof_object \ + cpp0x_initializer_list # cpp0x_template_typedefs # not supported by any compiler yet # cpp0x_hash_types # not fully implemented yet # cpp0x_constructors # not supported by any compiler yet diff --git a/Examples/test-suite/cpp0x_initializer_list.i b/Examples/test-suite/cpp0x_initializer_list.i new file mode 100644 index 000000000..76bc741f5 --- /dev/null +++ b/Examples/test-suite/cpp0x_initializer_list.i @@ -0,0 +1,13 @@ +/* This testcase checks whether Swig correctly uses the new initializer_list + introduced in C++0x. */ +%module cpp0x_initializer_list + +%inline %{ +#include + +class A { +public: + A( std::initializer_list ) {} +}; +%} + diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 25731ee35..e12455197 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -4265,21 +4265,27 @@ cpp_member : c_declaration { $$ = $1; } cpp_constructor_decl : storage_class type LPAREN parms RPAREN ctor_end { if (Classprefix) { - SwigType *decl = NewStringEmpty(); - $$ = new_node("constructor"); - Setattr($$,"storage",$1); - Setattr($$,"name",$2); - Setattr($$,"parms",$4); - SwigType_add_function(decl,$4); - Setattr($$,"decl",decl); - Setattr($$,"throws",$6.throws); - Setattr($$,"throw",$6.throwf); - if (Len(scanner_ccode)) { - String *code = Copy(scanner_ccode); - Setattr($$,"code",code); - Delete(code); - } - SetFlag($$,"feature:new"); + if (Getattr($4,"type") && strstr(Char(Getattr($4,"type")), "initializer_list<")) { + /* Ignore constructors containing initializer_list<> introduced in C++0x */ + Swig_warning(WARN_LANG_INITIALIZER_LIST, cparse_file, cparse_line, "Constructor with std::initializer_list<> argument ignored.\n"); + $$ = 0; + } else { + SwigType *decl = NewStringEmpty(); + $$ = new_node("constructor"); + Setattr($$,"storage",$1); + Setattr($$,"name",$2); + Setattr($$,"parms",$4); + SwigType_add_function(decl,$4); + Setattr($$,"decl",decl); + Setattr($$,"throws",$6.throws); + Setattr($$,"throw",$6.throwf); + if (Len(scanner_ccode)) { + String *code = Copy(scanner_ccode); + Setattr($$,"code",code); + Delete(code); + } + SetFlag($$,"feature:new"); + } } else { $$ = 0; } diff --git a/Source/Include/swigwarn.h b/Source/Include/swigwarn.h index e25e4408b..292aa0ba6 100644 --- a/Source/Include/swigwarn.h +++ b/Source/Include/swigwarn.h @@ -189,6 +189,7 @@ #define WARN_LANG_DIRECTOR_ABSTRACT 517 #define WARN_LANG_PORTABILITY_FILENAME 518 #define WARN_LANG_TEMPLATE_METHOD_IGNORE 519 +#define WARN_LANG_INITIALIZER_LIST 520 /* -- Reserved (600-799) -- */ From a3e59636ce3875f77483e67f0889892f7790cc86 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Fri, 14 Aug 2009 16:14:48 +0000 Subject: [PATCH 041/481] Added draft user documentation for the C++0x. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11568 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Doc/Manual/Cpp0x.html | 303 ++++++++++++++++++++++++++++++++++++++++++ Doc/Manual/chapters | 1 + 2 files changed, 304 insertions(+) create mode 100644 Doc/Manual/Cpp0x.html diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html new file mode 100644 index 000000000..8ecb5f52a --- /dev/null +++ b/Doc/Manual/Cpp0x.html @@ -0,0 +1,303 @@ + + + + + SWIG and C++ + + + + + + + + + + +

7 Swig and C++0x

+ + + + + + + +

This chapter gives you a brief overview about the Swig +implementation of the C++0x standard. This area of Swig is a work in +progress. Initial C++0x support for Swig was written during the +Google Summer of Code 2009 period.

+

Swig supports all the new C++ syntax changes with some limitations +(decltype expressions, variadic templates number). Wrappers for the +new types (unordered_ types, result_of, tuples) are not supported +yet.

+

Rvalue +reference and move semantics

+

Swig correctly parses the new operator && the same as the +reference operator &.

+

Generalized +constant expressions

+

Swig correctly parses the keyword „constexpr“, but ignores its +functionality. Constant functions cannot be used as constants yet.

+

7.1 Extern template

+ + +

Swig correctly parses the keywords „extern template“. The +explicit template instantiation is disabled in Swig.

+

7.2 Initializer lists

+ + +

Constructors using the std::initializer_list class are removed +from the wrapped class, because the only way to acess such a +constructor is at the compile time using the „= {}“ assignment.

+

User should add another constructor with specific arguments +filling the class members manually.

+

Uniform +initialization

+

The curly brackets {} for memeber initialization are fully +supported by Swig.

+

7.3 Type inference

+ + +

Swig supports „decltype()“ with some limitations. Single +variable is allowed, however expressions are not supported yet. For +example:

+
int i; int j;
+decltype(i+j) k;

+will result in an error.

+

7.4 Range-based for-loop

+ + +

This feature is part of the implementation block only. Swig +ignores it.

+

Lambda +functions and expressions

+

Swig correctly parses the Lambda functions syntax. The functions +are removed from the wrapper class, because of the lack of support +for closures in target languages (scope of the lambda functions).

+

Alternate +function syntax

+

Swig fully supports the new definition of functions. For example:

+
float square(float, float);

+can now be written as

+
auto square(float, float) -> float;

+User can also use the type inference for the return type. For +example:

+
auto square(float a, float b) -> decltype(a);

+Object +construction improvement

+

Swig correctly parses and includes the external functions +(constructor delegation and constructor inheritance) into the class +using the „using“ keyword.

+

7.5 Null pointer constant

+ + +

Swig correctly maps the std::nullptr constant to the null pointer +constant in the target language.

+

Strongly typed +enumerations

+

Swig parses the new „enum class“ syntax, but does not support +nested classes yet. The strongly typed enumerations are treated the +same as the ordinary and anonymous enums for now.

+

7.6 Double angle brackets

+ + +

Swig correctly parses the symbols >> as the closure of the +template block, if found inside it at the top level, or as the right +shift operator >> otherwise.

+

User can force the bit shifting operator using the parenthesis +around the expressions. For example

+
template<(5>>3)>
class A {};

+Explicit +conversion operators

+

Swig correctly uses the keyword „explicit“ for function +objects.

+

7.7 Template typedefs

+ + +

Swig currently parses the new „using name =“ syntax, but +ignores the definition.

+

User should still define the typedefs using the old syntax.

+

7.8 Unrestricted unions

+ + +

Swig fully supports any type inside the union even if it does not +define the trivial constructor.

+

7.9 Variadic templates

+ + +

Swig fully supports the variadic templates syntax (inside the <> +block, variadic class inheritance and variadic constructor and +initializers) with some limitations.

+

The %template statement however, accepts only the amount of +arguments as defined in the original template<> block.

+

7.10 New string literals

+ + +

Swig fully supports custom delimiters and unicode string +constants.

+

Swig currently incorrectly parses the odd number of double quotes +inside the string. Other symbols are correctly parsed.

+

7.11 User-defined literals

+ + +

Swig correctly parses the new operator““_mysuffix() functions.

+

The %rename currently doesn't parse the double quotes so the user +should rename the functions in the code using the #define.

+

7.12 Thread-local storage

+ + +

Swig correctly parses the „thread_local“ keyword. The new +C++0x thread functionalities are currently ignored.

+

+Defaulting/deleting of standard functions on C++ objects

+

Swig correctly parses the „= delete“ and „= default“ +keywords. Swig overrides the standard C++ functions anyway (copy +constructor, operator= etc.).

+

7.13 Type long long int

+ + +

Swig correctly parses and uses the new „long long“ type.

+

7.14 Static assertions

+ + +

Swig correctly parses and calls the new „static_assert“ +function.

+

+Allow sizeof to work on members of classes without an explicit object

+

Swig correctly calls the sizeof() on types as well as on the +objects.

+

7.15 Threading facilities

+ + +

Swig does not currently wrap or use any of the new threading +classes introduced (thread, mutex, locks, condition variable, task).

+

7.16 Tuple types

+ + +

Swig does not wrap tuple types yet.

+

7.17 Hash tables

+ + +

Swig does not wrap the new unordered_ classes yet.

+

7.18 Regular expressions

+ + +

Swig does not wrap the new C++0x regular expressions classes, +because the target language uses its own facilities for this.

+

General-purpose +smart pointers

+

Swig ignores the new shared, weak and unique smart pointers.

+

Extensible +random number facility

+

This feature extends the standard library core only and does not +effect the C++ language.

+

7.19 Wrapper reference

+ + +

Swig does not wrap the new ref() function.

+

Polymorphous +wrappers for function objects

+

Swig fully supports the function templates and function objects.

+

Type traits +for metaprogramming

+

Swig explicitly requires concrete types when using the %template +directive.

+

+Uniform method for computing return type of function objects

+

Swig does not wrap the new result_of type.

+ + diff --git a/Doc/Manual/chapters b/Doc/Manual/chapters index bf180f1b4..af1c07773 100644 --- a/Doc/Manual/chapters +++ b/Doc/Manual/chapters @@ -4,6 +4,7 @@ Windows.html Scripting.html SWIG.html SWIGPlus.html +Cpp0x.html Preprocessor.html Library.html Arguments.html From 52149e219df7b790d3f8682d7e475695fbcc1019 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Fri, 14 Aug 2009 16:15:36 +0000 Subject: [PATCH 042/481] Removed decr-- Hash tables feature. Added some comments. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11569 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/python/pyiterators.swg | 10 ++++++++++ Lib/std/std_unordered_map.i | 3 +++ Lib/std/std_unordered_multimap.i | 3 +++ Lib/std/std_unordered_multiset.i | 3 +++ Lib/std/std_unordered_set.i | 3 +++ 5 files changed, 22 insertions(+) diff --git a/Lib/python/pyiterators.swg b/Lib/python/pyiterators.swg index 1d7f415be..301ae4cd9 100644 --- a/Lib/python/pyiterators.swg +++ b/Lib/python/pyiterators.swg @@ -226,6 +226,9 @@ namespace swig { SwigPyIterator *decr(size_t n = 1) { + while (n--) { + --base::current; + } return this; } }; @@ -274,6 +277,13 @@ namespace swig { SwigPyIterator *decr(size_t n = 1) { + while (n--) { + if (base::current == begin) { + throw stop_iteration(); + } else { + --base::current; + } + } return this; } diff --git a/Lib/std/std_unordered_map.i b/Lib/std/std_unordered_map.i index f205bd573..3c36d78e3 100644 --- a/Lib/std/std_unordered_map.i +++ b/Lib/std/std_unordered_map.i @@ -1,5 +1,8 @@ // // std::unordered_map +// Work in progress - the code is not compilable yet: +// operator--() and constructor(compare function) not available for unordered_ +// types // %include diff --git a/Lib/std/std_unordered_multimap.i b/Lib/std/std_unordered_multimap.i index bbdfeb82d..74efb2896 100644 --- a/Lib/std/std_unordered_multimap.i +++ b/Lib/std/std_unordered_multimap.i @@ -1,5 +1,8 @@ // // std::unordered_multimap +// Work in progress - the code is not compilable yet: +// operator--() and constructor(compare function) not available for unordered_ +// types // %include diff --git a/Lib/std/std_unordered_multiset.i b/Lib/std/std_unordered_multiset.i index 5ef76612d..56b971011 100644 --- a/Lib/std/std_unordered_multiset.i +++ b/Lib/std/std_unordered_multiset.i @@ -1,5 +1,8 @@ // // std::unordered_multiset +// Work in progress - the code is not compilable yet: +// operator--() and constructor(compare function) not available for unordered_ +// types // %include diff --git a/Lib/std/std_unordered_set.i b/Lib/std/std_unordered_set.i index 0eac339e0..4cdfd65a5 100644 --- a/Lib/std/std_unordered_set.i +++ b/Lib/std/std_unordered_set.i @@ -1,5 +1,8 @@ // // std::unordered_set +// Work in progress - the code is not compilable yet: +// operator--() and constructor(compare function) not available for unordered_ +// types // %include From b8198a51bbbabdf9046417ad7b020af7bd196610 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Mon, 17 Aug 2009 14:17:42 +0000 Subject: [PATCH 043/481] Updated C++0x User's manual. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11622 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Doc/Manual/Cpp0x.html | 881 ++++++++++++++++++++++++++++++------------ 1 file changed, 636 insertions(+), 245 deletions(-) diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html index 8ecb5f52a..9ec67861b 100644 --- a/Doc/Manual/Cpp0x.html +++ b/Doc/Manual/Cpp0x.html @@ -1,303 +1,694 @@ - - - - SWIG and C++ - - - - - - - - - - -

7 Swig and C++0x

+ + +SWIG and Python + + + + +

7 SWIG and C++0x

- -

This chapter gives you a brief overview about the Swig -implementation of the C++0x standard. This area of Swig is a work in +

7.1 Introduction

+ + +

This chapter gives you a brief overview about the Swig +implementation of the C++0x standard. This part of Swig is still a work in progress. Initial C++0x support for Swig was written during the -Google Summer of Code 2009 period.

-

Swig supports all the new C++ syntax changes with some limitations +Google Summer of Code 2009 period.

+

Swig supports all the new C++ syntax changes with some limitations (decltype expressions, variadic templates number). Wrappers for the new types (unordered_ types, result_of, tuples) are not supported -yet.

-

Rvalue -reference and move semantics

-

Swig correctly parses the new operator && the same as the -reference operator &.

-

Generalized -constant expressions

-

Swig correctly parses the keyword „constexpr“, but ignores its -functionality. Constant functions cannot be used as constants yet.

-

7.1 Extern template

+yet.

+ +

7.2 Core language changes

-

Swig correctly parses the keywords „extern template“. The -explicit template instantiation is disabled in Swig.

-

7.2 Initializer lists

+

7.2.1 Rvalue reference and move semantics

-

Constructors using the std::initializer_list class are removed +

Swig correctly parses the new operator && the same as the reference operator &.

+ +

The wrapper for the following code is correctly produced:

+
+class MyClass {
+  MyClass(MyClass&& p) : ptr(p.ptr) {p.ptr = 0;}
+  MyClass& operator=(MyClass&& p) {
+    std::swap(ptr, p.ptr);
+    return *this;
+  }
+};
+
+ +

7.2.2 Generalized constant expressions

+ + +

Swig correctly parses the keyword "constexpr", but ignores its functionality. Constant functions cannot be used as constants yet.

+ +
+constexpr int myConstFunc() { return 10; }
+const int a = myConstFunc(); // reslults in error
+
+ +

User needs to use values or predefined constants when defining the new constant value:

+ +
+#define MY_CONST 10
+constexpr int myConstFunc() { return MY_CONST; }
+const int a = MY_CONST; // ok
+
+ +

7.2.3 Extern template

+ + +

Swig correctly parses the keywords "extern template". However, the explicit template instantiation is not usable for Swig.

+ + +
+extern template class std::vector<MyClass>; // explicit instantiation
+
+...
+
+class MyClass {
+public:
+  int a;
+  int b;
+};
+
+ +

7.2.4 Initializer lists

+ + +

Constructors using the std::initializer_list class are removed from the wrapped class, because the only way to acess such a -constructor is at the compile time using the „= {}“ assignment.

-

User should add another constructor with specific arguments -filling the class members manually.

-

Uniform -initialization

-

The curly brackets {} for memeber initialization are fully -supported by Swig.

-

7.3 Type inference

+constructor is at the compile time using the "= {}" assignment.

+

User should add another constructor with specific arguments +filling the class members manually.

+ +

For now, if a user wants to fill the class components like this:

+ +
+class A {
+public:
+  A( std::initializer_list<int> );
+};
+A a1 = {1,2,3,4};
+
+ +

He should add another constructor using the std::vector for example:

+ +
+class A {
+public:
+  A( std::initializer_list<int> );
+  A( std::vector<int> );
+};
+A a1 = {1,2,3,4};
+
+ +

And call it in target language:

+
+>>> a2 = A( [1,2,3,4] )
+
+ +

7.2.5 Uniform initialization

-

Swig supports „decltype()“ with some limitations. Single +

The curly brackets {} for memeber initialization are fully +supported by Swig:

+ +
+struct BasicStruct {
+ int x;
+ double y;
+};
+ 
+struct AltStruct {
+  AltStruct(int x, double y) : x_{x}, y_{y} {}
+ 
+  int x_;
+  double y_;
+};
+
+BasicStruct var1{5, 3.2}; // only fills the struct components
+AltStruct var2{2, 4.3};   // calls the constructor
+
+ +

Usage in the target language is the same:

+ +
+>>> a = AltStruct(10, 142.15)
+>>> a.x_
+10
+>>> a.y_
+142.15
+
+ +

7.2.6 Type inference

+ + +

Swig supports "decltype()" with some limitations. Single variable is allowed, however expressions are not supported yet. For -example:

-
int i; int j;
-decltype(i+j) k;

-will result in an error.

-

7.4 Range-based for-loop

+example, the following code will work:

+
+int i;
+decltype(i) j;
+
+ +

However, using an expression inside the decltype results in syntax error:

+
+int i; int j;
+decltype(i+j) k;  // syntax error
+
+ +

7.2.7 Range-based for-loop

-

This feature is part of the implementation block only. Swig -ignores it.

-

Lambda -functions and expressions

-

Swig correctly parses the Lambda functions syntax. The functions -are removed from the wrapper class, because of the lack of support -for closures in target languages (scope of the lambda functions).

-

Alternate -function syntax

-

Swig fully supports the new definition of functions. For example:

-
float square(float, float);

-can now be written as

-
auto square(float, float) -> float;

-User can also use the type inference for the return type. For -example:

-
auto square(float a, float b) -> decltype(a);

-Object -construction improvement

-

Swig correctly parses and includes the external functions +

This feature is part of the implementation block only. Swig +ignores it.

+ +

7.2.8 Lambda functions and expressions

+ + +

Swig correctly parses the Lambda functions syntax. For example:

+
+auto myLambdaFunc = [this]() { this->SomePrivateMemberFunction() };
+
+ +

The lambda functions are removed from the wrapper class for now, because of the lack of support +for closures (scope of the lambda functions) in target languages though.

+ +

7.2.9 Alternate function syntax

+ + +

Swig fully supports the new definition of functions. For example:

+
+struct SomeStruct {
+  int FuncName(int x, int y);
+};
+
+ +

can now be written as:

+ +
+struct SomeStruct {
+  auto FuncName(int x, int y) -> int;
+};
+ 
+auto SomeStruct::FuncName(int x, int y) -> int {
+  return x + y;
+}
+
+ +

The usage in the target languages remains the same:

+ +
+>>> a = SomeStruct()
+>>> a.FuncName(10,5)
+15
+
+ +

User can also use the type inference for the return type. For example:

+
+auto square(float a, float b) -> decltype(a);
+
+ +

7.2.10 Object construction improvement

+ + +

Swig correctly parses and includes the external functions (constructor delegation and constructor inheritance) into the class -using the „using“ keyword.

-

7.5 Null pointer constant

+using the "using" keyword.

+ +
+class BaseClass {
+public:
+  BaseClass(int iValue);
+};
+
+class DerivedClass: public BaseClass {
+  public:
+  using BaseClass::BaseClass; // Adds DerivedClass(int) constructor
+};
+
+ +

7.2.11 Null pointer constant

-

Swig correctly maps the std::nullptr constant to the null pointer -constant in the target language.

-

Strongly typed -enumerations

-

Swig parses the new „enum class“ syntax, but does not support -nested classes yet. The strongly typed enumerations are treated the -same as the ordinary and anonymous enums for now.

-

7.6 Double angle brackets

+

Swig correctly maps the std::nullptr constant to the null pointer +constant in the target language.

+ +

7.2.12 Strongly typed enumerations

-

Swig correctly parses the symbols >> as the closure of the +

Swig parses the new "enum class" syntax and forward declarator for the enums:

+
+enum class MyEnum : unsigned int;
+
+ +

The strongly typed enumerations are treated the same as the ordinary and anonymous enums for now, +because Swig doesn't support the nested classes. For example, the following code:

+ +
+class Color {
+  enum class PrintingColors : unsigned int {
+    Cyan, Magenta, Yellow, Black
+  };
+  
+  enum class BasicColors {
+    Red, Green, Blue
+  };
+  
+  enum class AllColors {
+    // produces warnings because of duplicate names
+    Yellow, Orange, Red, Magenta, Blue, Cyan, Green, Pink, Black, White
+  };
+};
+
+ +

should be written as a series of separated classes containing anonymous enums:

+ +
+class PrintingColors {
+  enum : unsigned int {
+    Cyan, Magenta, Yellow, Black
+  };
+};
+
+class BasicColors {
+  enum : unsigned int {
+    Red, Green, Blue
+  };
+};
+
+class AllColors {
+  enum : unsigned int {
+    Yellow, Orange, Red, Magenta, Blue, Cyan, Green, Pink, Black, White
+  };
+};
+
+ +

7.2.13 Double angle brackets

+ + +

Swig correctly parses the symbols >> as the closure of the template block, if found inside it at the top level, or as the right -shift operator >> otherwise.

-

User can force the bit shifting operator using the parenthesis -around the expressions. For example

-
template<(5>>3)>
class A {};

-Explicit -conversion operators

-

Swig correctly uses the keyword „explicit“ for function -objects.

-

7.7 Template typedefs

+shift operator >> otherwise.

+ +
+std::vector<std::vector<int>> myIntTable;
+
+ +

User can force the bit shifting operator using the parenthesis +around the expressions. For example

+ +
+template<(5>>3)>
+class A {};
+
+ +

7.2.14 Explicit conversion operators

-

Swig currently parses the new „using name =“ syntax, but -ignores the definition.

-

User should still define the typedefs using the old syntax.

-

7.8 Unrestricted unions

+

Swig correctly parses the keyword "explicit" both for operators and constructors. +For example:

+ +
+class U {
+public:
+        int u;
+};
+
+class V {
+public:
+        int v;
+};
+
+class TestClass {
+public:
+        //implicit converting constructor
+        TestClass( U const &val ) { t=val.u; }
+        // explicit constructor
+        explicit TestClass( V const &val ) { t=val.v; }
+
+        int t;
+};
+
+ +

+The usage of explicit constructors and operators is somehow specific to C++ when assigning the value +of one object to another one of different type or translating one type to another. It requires both operator and function overloading features, +which are not supported by majority of Swig target languages. Also the constructors and operators are not particulary useful in any +Swig target languages, because all use their own faclities (eg. classes Cloneable and Comparable in Java) +to achieve particular copy and compare behaviours. +

+ +

7.2.15 Template typedefs

-

Swig fully supports any type inside the union even if it does not -define the trivial constructor.

-

7.9 Variadic templates

+

Swig currently parses the new "using name =" syntax, but +ignores the definition:

+ +
+using PFD = void (*)(double); // New introduced syntax
+
+ +

User should still define the typedefs using the old syntax:

+ +
+typedef void (*PFD)(double);  // The old style
+
+ +

7.2.16 Unrestricted unions

-

Swig fully supports the variadic templates syntax (inside the <> +

Swig fully supports any type inside the union even if it does not +define the trivial constructor. For example, the wrapper for the following +code is correctly produced:

+ +
+struct point {
+  point() {}
+  point(int x, int y): x_(x), y_(y) {}
+  int x_, y_;
+};
+
+union P {
+  int z;
+  double w;
+  point p;  // Illegal in C++; point has a non-trivial constructor.  However, this is legal in C++0x.
+} p1;
+
+ +

7.2.17 Variadic templates

+ + +

Swig fully supports the variadic templates syntax (inside the <> block, variadic class inheritance and variadic constructor and -initializers) with some limitations.

-

The %template statement however, accepts only the amount of -arguments as defined in the original template<> block.

-

7.10 New string literals

+initializers) with some limitations. The following code is correctly parsed:

+ +
+template <typename... BaseClasses> class ClassName : public BaseClasses... {
+public:
+   ClassName (BaseClasses&&... baseClasses) : BaseClasses(baseClasses)... {}
+}
+
+ +

Support for the variadic sizeof() function was also introduced:

+ +
+const int SIZE = sizeof...(ClassName<int, int>);
+
+ +

The %template statement however, accepts only at most as the amount of +arguments defined in the original template<> block for now:

+ +
+%template(MyVariant1) ClassName<>         // ok
+%template(MyVariant2) ClassName<int>      // ok
+%template(MyVariant3) ClassName<int, int> // too much arguments
+
+ +

7.2.18 New string literals

-

Swig fully supports custom delimiters and unicode string -constants.

-

Swig currently incorrectly parses the odd number of double quotes -inside the string. Other symbols are correctly parsed.

-

7.11 User-defined literals

+

Swig fully supports custom delimiters and unicode string +constants.

+ +
+// New string literals
+char      *a = "ABC";
+wstring wide = L"ABC";
+char      *b = u8"ABC";
+char16_t  *c = u"ABC";
+char32_t  *d = U"ABC";
+
+// Custom String delimiter
+char       *e = R"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX";
+wstring wide2 = LR"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX";
+char       *f = u8R"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX";
+char16_t   *g = uR"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX";
+char32_t   *h = UR"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX";
+
+ +

Note: Swig currently incorrectly parses the odd number of double quotes +inside the string due to Swig's C++ preprocessor.

+ +

7.2.19 User-defined literals

-

Swig correctly parses the new operator““_mysuffix() functions.

-

The %rename currently doesn't parse the double quotes so the user -should rename the functions in the code using the #define.

-

7.12 Thread-local storage

+

Swig correctly parses the new operator""_mysuffix() functions.

+ +
+OutputType operator "" _mySuffix(const char * string_values, size_t num_chars);
+OutputType operator "" _mySuffix(const wchar_t * string_values, size_t num_chars);
+OutputType operator "" _mySuffix(const char16_t * string_values, size_t num_chars);
+OutputType operator "" _mySuffix(const char32_t * string_values, size_t num_chars);
+OutputType operator "" _mySuffix(int value);
+
+ +

The %rename currently doesn't parse the double quotes so the user +should rename the functions in the code using the #define preprocessor directive.

+ +

7.2.20 Thread-local storage

-

Swig correctly parses the „thread_local“ keyword. The new -C++0x thread functionalities are currently ignored.

-

-Defaulting/deleting of standard functions on C++ objects

-

Swig correctly parses the „= delete“ and „= default“ -keywords. Swig overrides the standard C++ functions anyway (copy -constructor, operator= etc.).

-

7.13 Type long long int

+

Swig correctly parses the "thread_local" keyword. For example, a variable +reachable by the current thread can be defined as:

+ +
+struct A {
+   thread_local int val;
+};
+
+ +

The new C++0x threading libraries are ignored because each Swig target language offers +its own threading facilities.

+ +

7.2.21 Defaulting/deleting of standard functions on C++ objects

-

Swig correctly parses and uses the new „long long“ type.

-

7.14 Static assertions

+

Swig correctly parses the "= delete" and "= default" +keywords. For example:

+ +
+struct NonCopyable {
+  NonCopyable& operator=(const NonCopyable&) = delete; /* Removes operator= */
+  NonCopyable(const NonCopyable&) = delete;                /* Removed copy constructor */
+  NonCopyable() = default;                                     /* Explicitly allows the empty constructor */
+  void *operator new(std::size_t) = delete;                    /* Removes new NonCopyable */
+};
+
+ +

This feature is somehow specific to the C++ only. The defaulting/deleting is currently ignored, because Swig +automatically produces wrappers for special constructors and operators specific to the target language.

+ +

7.2.22 Type long long int

-

Swig correctly parses and calls the new „static_assert“ -function.

-

-Allow sizeof to work on members of classes without an explicit object

-

Swig correctly calls the sizeof() on types as well as on the -objects.

-

7.15 Threading facilities

+

Swig correctly parses and uses the new "long long" type already introduced in C99 some time ago.

+ +

7.2.23 Static assertions

-

Swig does not currently wrap or use any of the new threading -classes introduced (thread, mutex, locks, condition variable, task).

-

7.16 Tuple types

+

Swig correctly parses and calls the new "static_assert" function.

+ +
+template <typename T>
+struct Check {
+  static_assert(sizeof(int) <= sizeof(T), "not big enough");
+};
+
+ +

7.2.24 Allow sizeof to work on members of classes without an explicit object

-

Swig does not wrap tuple types yet.

-

7.17 Hash tables

+

Swig correctly calls the sizeof() on types as well as on the +objects. For example:

+ +
+struct A {
+  int member;
+};
+
+const int SIZE = sizeof(A::member); // does not work with C++03. Okay with C++0x
+
+ +

In Python:

+
+>>> SIZE
+8
+
+ +

7.3 Standard library changes

-

Swig does not wrap the new unordered_ classes yet.

-

7.18 Regular expressions

+

7.3.1 Threading facilities

-

Swig does not wrap the new C++0x regular expressions classes, -because the target language uses its own facilities for this.

-

General-purpose -smart pointers

-

Swig ignores the new shared, weak and unique smart pointers.

-

Extensible -random number facility

-

This feature extends the standard library core only and does not -effect the C++ language.

-

7.19 Wrapper reference

+

Swig does not currently wrap or use any of the new threading +classes introduced (thread, mutex, locks, condition variable, task). The main reason is that +Swig target languages offer their own threading facilities that do not rely on the C++.

+ +

7.3.2 Tuple types and hash tables

-

Swig does not wrap the new ref() function.

-

Polymorphous -wrappers for function objects

-

Swig fully supports the function templates and function objects.

-

Type traits -for metaprogramming

-

Swig explicitly requires concrete types when using the %template -directive.

-

-Uniform method for computing return type of function objects

-

Swig does not wrap the new result_of type.

+

Swig does not wrap the new tuple types and the unordered_ classes yet. Variadic support is there so the user can +include the tuple header file and is parsed without any problems.

+ +

7.3.3 Regular expressions

+ + +

Swig does not wrap the new C++0x regular expressions classes, because the Swig target languages use their own facilities for this.

+ +

7.3.4 General-purpose smart pointers

+ + +

Swig does not wrap the new shared, weak and unique smart pointers, because the Swig target languages offer their own garbage collectors.

+ +

7.3.5 Extensible random number facility

+ + +

This feature extends and standardizes the standard library only and does not effect the C++ language and Swig.

+ +

7.3.6 Wrapper reference

+ + +

The new ref and cref classes are used to instantiate a parameter as a reference of a template function. For example:

+ +
+void f( int &r )  { r++ ; }
+ 
+// Template function.
+template< class F, class P > void g( F f, P t )  { f(t); }
+ 
+int main() {
+  int i = 0 ;
+  g( f, i ) ;  // 'g<void ( int &r ), int>' is instantiated
+               // then 'i' will not be modified.
+  cout << i << endl ;  // Output -> 0
+ 
+  g( f, ref(i) ) ;  // 'g<void(int &r),reference_wrapper<int>>' is instanced
+                    // then 'i' will be modified.
+  cout << i << endl ;  // Output -> 1
+}
+
+ +

The ref and cref classes are not wrapped by Swig because the Swig target languages do not support referencing.

+ +

7.3.7 Polymorphous wrappers for function objects

+ + +

Swig fully supports the function template wrappers and function objects:

+ +
+function<int ( int, int )> pF;   // function template wrapper
+
+struct Test {
+  bool operator()( short x, short y ); // function object
+};
+
+ +

7.3.8 Type traits for metaprogramming

+ + +

The new C++ metaprogramming is useful at compile time and is aimed specifically for the C++ development:

+ +
+// First way of operating.
+template< bool B > struct algorithm {
+  template< class T1, class T2 > int do_it( T1&, T2& )  { /*...*/ }
+};
+// Second way of operating.
+template<> struct algorithm<true> {
+  template< class T1, class T2 > int do_it( T1, T2 )  { /*...*/ }
+};
+// Instantiating 'elaborate' will automatically instantiate the correct way to operate.
+template< class T1, class T2 > int elaborate( T1 A, T2 B ) {
+  // Use the second way only if 'T1' is an integer and if 'T2' is
+  // in floating point, otherwise use the first way.
+  return algorithm< is_integral<T1>::value && is_floating_point<T2>::value >::do_it( A, B );
+}
+
+ +

Swig correctly parses the template specialization, template types and values inside the <> block and the new helper functions is_convertible, is_integral, is_const etc. +However, Swig still explicitly requires concrete types when using the %template directive, so the C++ metaprogramming features are not really interesting at runtime in Swig target languages.

+ +

7.3.9 Uniform method for computing return type of function objects

+ + +

Swig does not wrap the new result_of class introduced in the <functional> header and map the result_of::type to the concrete type yet. For example:

+
+%inline %{
+#include <functional>
+double square(double x) {
+        return (x * x);
+}
+
+template<class Fun, class Arg>
+typename std::result_of<Fun(Arg)>::type test_result_impl(Fun fun, Arg arg) {
+        return fun(arg);
+}
+%}
+
+%template(test_result) test_result_impl<double(*)(double), double>;
+%constant double (*SQUARE)(double) = square;
+
+ +

will result in:

+ +
+>>> test_result_impl(SQUARE, 5.0)
+<Swig Object of type 'std::result_of< Fun(Arg) >::type *' at 0x7faf99ed8a50>
+
+ +

User should use decltype() where possible for now.

From 67b4ad70849e529945b1dcd265074a84d81840d3 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Mon, 17 Aug 2009 14:42:34 +0000 Subject: [PATCH 044/481] Documented C++0x testcases. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11623 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/cpp0x_alternate_function_syntax.i | 2 ++ Examples/test-suite/cpp0x_default_delete.i | 4 +++- Examples/test-suite/cpp0x_hash_tables.i | 2 ++ Examples/test-suite/cpp0x_rvalue_reference.i | 2 ++ Examples/test-suite/cpp0x_strongly_typed_enumerations.i | 3 +++ Examples/test-suite/cpp0x_uniform_initialization.i | 2 ++ Examples/test-suite/cpp0x_unrestricted_unions.i | 2 ++ 7 files changed, 16 insertions(+), 1 deletion(-) diff --git a/Examples/test-suite/cpp0x_alternate_function_syntax.i b/Examples/test-suite/cpp0x_alternate_function_syntax.i index b17223626..d8d0ec6c4 100644 --- a/Examples/test-suite/cpp0x_alternate_function_syntax.i +++ b/Examples/test-suite/cpp0x_alternate_function_syntax.i @@ -1,3 +1,5 @@ +/* This testcase checks whether Swig correctly uses the new alternate functions + declarations and definitions introduced in C++0x. */ %module cpp0x_alternate_function_syntax %inline %{ diff --git a/Examples/test-suite/cpp0x_default_delete.i b/Examples/test-suite/cpp0x_default_delete.i index 2e2108494..affcea58e 100644 --- a/Examples/test-suite/cpp0x_default_delete.i +++ b/Examples/test-suite/cpp0x_default_delete.i @@ -1,3 +1,5 @@ +/* This testcase checks whether Swig correctly parses the default and delete + keywords which keep or remove default C++ object construction functions. */ %module cpp0x_default_delete %{ @@ -5,7 +7,7 @@ class NonCopyable { public: - NonCopyable & operator=(const NonCopyable&) = delete; /* Removes operator= */ + NonCopyable& operator=(const NonCopyable&) = delete; /* Removes operator= */ NonCopyable(const NonCopyable&) = delete; /* Removed copy constructor */ NonCopyable() = default; /* Explicitly allows the empty constructor */ void *operator new(size_t) = delete; /* Removes new NonCopyable */ diff --git a/Examples/test-suite/cpp0x_hash_tables.i b/Examples/test-suite/cpp0x_hash_tables.i index a4829ce1f..b5eb505a4 100644 --- a/Examples/test-suite/cpp0x_hash_tables.i +++ b/Examples/test-suite/cpp0x_hash_tables.i @@ -1,3 +1,5 @@ +/* This testcase checks the new wrappers for the new unordered_ STL types + introduced in C++0x. */ %module cpp0x_hash_tables %inline %{ diff --git a/Examples/test-suite/cpp0x_rvalue_reference.i b/Examples/test-suite/cpp0x_rvalue_reference.i index e45d91e27..f6c764aca 100644 --- a/Examples/test-suite/cpp0x_rvalue_reference.i +++ b/Examples/test-suite/cpp0x_rvalue_reference.i @@ -1,3 +1,5 @@ +/* This testcase checks whether Swig correctly parses the double ampersand && + move operator which is currently mapped to the reference & operator. */ %module cpp0x_rvalue_reference %inline %{ diff --git a/Examples/test-suite/cpp0x_strongly_typed_enumerations.i b/Examples/test-suite/cpp0x_strongly_typed_enumerations.i index 0f281a195..78925c1c8 100644 --- a/Examples/test-suite/cpp0x_strongly_typed_enumerations.i +++ b/Examples/test-suite/cpp0x_strongly_typed_enumerations.i @@ -1,3 +1,6 @@ +/* This testcase checks whether Swig produces the correct wrapper for the + strongly typed enums. Enums with the same type are comparable. Enum classes + require support for nested classes. */ %module cpp0x_strongly_typed_enumerations %inline %{ diff --git a/Examples/test-suite/cpp0x_uniform_initialization.i b/Examples/test-suite/cpp0x_uniform_initialization.i index a56178930..39ed73180 100644 --- a/Examples/test-suite/cpp0x_uniform_initialization.i +++ b/Examples/test-suite/cpp0x_uniform_initialization.i @@ -1,3 +1,5 @@ +/* This testcase checks whether Swig syntactically correctly parses the curly + brackets {} for uniform member initialization. */ %module cpp0x_uniform_initialization %inline %{ diff --git a/Examples/test-suite/cpp0x_unrestricted_unions.i b/Examples/test-suite/cpp0x_unrestricted_unions.i index d3364ef83..a534df466 100644 --- a/Examples/test-suite/cpp0x_unrestricted_unions.i +++ b/Examples/test-suite/cpp0x_unrestricted_unions.i @@ -1,3 +1,5 @@ +/* This testcase checks whether Swig correctly parses the support for types + without the defined trivial constructor in the unions. */ %module cpp0x_unrestricted_unions %inline %{ From c9fcb01943110340ed980b7865409432fa377b45 Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Mon, 17 Aug 2009 15:27:48 +0000 Subject: [PATCH 045/481] Fixed testcase warnings. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11625 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/cpp0x_initializer_list.i | 4 +++- Examples/test-suite/cpp0x_raw_string_literals.i | 2 ++ Examples/test-suite/cpp0x_strongly_typed_enumerations.i | 4 ++++ Examples/test-suite/cpp0x_template_explicit.i | 2 ++ Examples/test-suite/cpp0x_userdefined_literals.i | 2 +- Examples/test-suite/cpp0x_variadic_templates.i | 3 +++ Source/CParse/parser.y | 4 ++-- 7 files changed, 17 insertions(+), 4 deletions(-) diff --git a/Examples/test-suite/cpp0x_initializer_list.i b/Examples/test-suite/cpp0x_initializer_list.i index 76bc741f5..3d6893033 100644 --- a/Examples/test-suite/cpp0x_initializer_list.i +++ b/Examples/test-suite/cpp0x_initializer_list.i @@ -1,13 +1,15 @@ /* This testcase checks whether Swig correctly uses the new initializer_list introduced in C++0x. */ %module cpp0x_initializer_list +%warnfilter(520) A; %inline %{ #include class A { public: - A( std::initializer_list ) {} + A( std::initializer_list ) {} + A() {} }; %} diff --git a/Examples/test-suite/cpp0x_raw_string_literals.i b/Examples/test-suite/cpp0x_raw_string_literals.i index 12c68cd63..1e8515504 100644 --- a/Examples/test-suite/cpp0x_raw_string_literals.i +++ b/Examples/test-suite/cpp0x_raw_string_literals.i @@ -8,6 +8,8 @@ This module also tests whether Swig correctly parses custom string delimiters. */ %module cpp0x_raw_string_literals +%warnfilter(454) c; +%warnfilter(454) d; %inline %{ #include diff --git a/Examples/test-suite/cpp0x_strongly_typed_enumerations.i b/Examples/test-suite/cpp0x_strongly_typed_enumerations.i index 78925c1c8..4476122fe 100644 --- a/Examples/test-suite/cpp0x_strongly_typed_enumerations.i +++ b/Examples/test-suite/cpp0x_strongly_typed_enumerations.i @@ -2,6 +2,10 @@ strongly typed enums. Enums with the same type are comparable. Enum classes require support for nested classes. */ %module cpp0x_strongly_typed_enumerations +%warnfilter(302) Val1; +%warnfilter(302) Val2; +%warnfilter(302) Val3; +%warnfilter(302) Val4; %inline %{ enum class Enum1 { diff --git a/Examples/test-suite/cpp0x_template_explicit.i b/Examples/test-suite/cpp0x_template_explicit.i index e0ff71073..f05bcf850 100644 --- a/Examples/test-suite/cpp0x_template_explicit.i +++ b/Examples/test-suite/cpp0x_template_explicit.i @@ -3,6 +3,8 @@ using the translation unit). */ %module cpp0x_template_explicit +%warnfilter(320) std::vector; +%warnfilter(320) std::vector; %inline %{ #include diff --git a/Examples/test-suite/cpp0x_userdefined_literals.i b/Examples/test-suite/cpp0x_userdefined_literals.i index f41823488..4488a573b 100644 --- a/Examples/test-suite/cpp0x_userdefined_literals.i +++ b/Examples/test-suite/cpp0x_userdefined_literals.i @@ -11,8 +11,8 @@ struct OutputType { OutputType(int v) { v=val; } }; +/* Note: GCC doesn't support user-defined literals yet! */ struct TT { -OutputType operator << (const char * string_values, size_t num_chars) { return OutputType(100); } OutputType operator "" (const char * string_values, size_t num_chars) { return OutputType(100); } OutputType operator "" _mySuffix1(const char * string_values, size_t num_chars) { return OutputType(100); } OutputType operator "" _mySuffix2(const wchar_t * string_values, size_t num_chars) { return OutputType(200); } diff --git a/Examples/test-suite/cpp0x_variadic_templates.i b/Examples/test-suite/cpp0x_variadic_templates.i index 6317b1340..b9320a0d1 100644 --- a/Examples/test-suite/cpp0x_variadic_templates.i +++ b/Examples/test-suite/cpp0x_variadic_templates.i @@ -4,6 +4,9 @@ using variadic number of classes. */ %module cpp0x_variadic_templates +%warnfilter(507) MultiArgs1; +%warnfilter(507) SizeOf1; +%warnfilter(507) MultiInherit1; //////////////////////// // Variadic templates // diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index e12455197..5645d7a8b 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -2745,7 +2745,7 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va p = tp; def_supplied = 1; } else if (p && !tp) { /* Variadic template - tp < p */ - Swig_warning(0,cparse_file, cparse_line,"Only the first variadic argument is currently supported by Swig.\n"); + Swig_warning(WARN_LANG_NATIVE_UNIMPL,cparse_file, cparse_line,"Only the first variadic argument is currently supported by Swig.\n"); break; } } @@ -4265,7 +4265,7 @@ cpp_member : c_declaration { $$ = $1; } cpp_constructor_decl : storage_class type LPAREN parms RPAREN ctor_end { if (Classprefix) { - if (Getattr($4,"type") && strstr(Char(Getattr($4,"type")), "initializer_list<")) { + if ($4 && Getattr($4,"type") && strstr(Char(Getattr($4,"type")), "initializer_list<")) { /* Ignore constructors containing initializer_list<> introduced in C++0x */ Swig_warning(WARN_LANG_INITIALIZER_LIST, cparse_file, cparse_line, "Constructor with std::initializer_list<> argument ignored.\n"); $$ = 0; From 8be21781e7140d290141e7fbc9f1b73876557b3a Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Mon, 17 Aug 2009 15:35:09 +0000 Subject: [PATCH 046/481] Added developer documentation for C++0x. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11626 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Doc/Devel/cpp0x.html | 788 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 788 insertions(+) create mode 100644 Doc/Devel/cpp0x.html diff --git a/Doc/Devel/cpp0x.html b/Doc/Devel/cpp0x.html new file mode 100644 index 000000000..4afc5ffe4 --- /dev/null +++ b/Doc/Devel/cpp0x.html @@ -0,0 +1,788 @@ + + + + + + + + + + + + + + + +

C++0x support for SWIG

+

Summary

+

This is a technical overview of the C++0x support for the Swig. +This area of Swig is a work in progress. Initial C++0x support for +Swig was written during the Google Summer of Code 2009 period by +Matevž Jekovec.

+

SVN branch

+

branches/gsoc2009-matevz

+

New C++0x features status

+

Wikipedia article: http://en.wikipedia.org/wiki/C%2B%2B0x +

+

Rvalue reference and move semantics [done]

+

The Rvalues are used in practice to speed up the move operations +on different containers.

+

In the following example, we want to swap the given elements:

+
template <class T> swap(T& a, T& b) {
+    T tmp(a);   // now we have two copies of a
+    a = b;      // now we have two copies of b
+    b = tmp;    // now we have two copies of tmp (aka a)
+}

+This can now be solved using the new function std::move():

+
template <class T> swap(T& a, T& b) {
+    T tmp(std::move(a));
+    a = std::move(b);   
+    b = std::move(tmp);
+}

+For the move function to take effect, user needs to reimplement the +move constructor (taking ClassType&& as an argument) and +operator=(ClassType&&):

+
class MyClass {
+  MyClass(MyClass&& p) : ptr(p.ptr) {p.ptr = 0;}
+  MyClass& operator=(MyClass&& p) {
+    std::swap(ptr, p.ptr);
+    return *this;
+  }
+};

+In practice, the Rvalues are used for temporaries (when passing the +result of one function as an argument to another).

+

Done: Added type&& to Swig parser. Added testcase +cpp0x_rvalue_reference.i. Operator && is treated the same as +operator &. R11450

+

Article: +http://www.artima.com/cppsource/rvalue.html

+

Generalized constant expressions [done]

+

In C++0x you can define functions as constant expressions. +Functions need to return constant value in form "return expr", +where expr is a constant expression. +

+

A keyword "constexpr" is introduced for this. eg.: +constexpr int getNumber() { return 5; } const int MY_CONSTANT = +getNumber(); +

+

Constants are treated as normal variables in interpreted languages +because they are not compiled into the executable. Java "final" +constants are defined runtime as well. C++ constants need to be +declared in the header file and defined in the implementation file, +so swig doesn't need to know about the constant values when parsing +the header file. +

+

Done: Added the “constexpr “ keyword to Swig. Added testcase +cpp0x_constexpr. R11322

+

Problem: No compilers were known to support constexpr yet, so the +testcase was temporarily commented out in common.mk. +

+

Extern template [done]

+

Extern template forces the GCC compiler to not instantiate the +template in the translation unit at that time. It's a feature +specifically aimed at compilers to speed up the compilation process. +

+

Done: Added support for 'extern template class +std::vector<MyClass>;'. Added testcase cpp0x_template_explicit. +R11385 , R11386

+

Initializer lists [done]

+

Initializer list is a new type in standard library: +std::initializer_list<T>. New symbols {} are introduced for the +initializer lists. +

+

One can now use: +

+
 class A {
+ public:
+   A( std::initializer_list<int> );
+ };
+ A a1 = {1,2,3,4};

+Languages like Java, C# and Python already support direct creation of +lists natively.

+

Problem: initializer_list cannot be treated as an ordinary list. +The constructor containing initializer_list can only be accessed by +assigning the value using the {} brackets. I also don't think there +is a simple way to convert an ordinary list or a vector to the +initializer_list.

+

Done: Ignored the constructor having initializer_list as its +argument. Show warning to the user. Added testcase +cpp0x_initializer_list. R11450

+

Article: +http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1919.pdf

+

Uniform initialization [done]

+

The new C++0x standard will allow the following:

+
struct IdString {
+  std::string name;
+  int identifier;
+};
+ 
+IdString GetString() {
+  return {"SomeName", 4}; //Note the lack of explicit type.
+}

+The feature works exactly as it did now for POD types only (eg. int +a[] = {1,2,3};). The following declarations are the same in the new +C++0x:

+
IdString str1 = {„SomeName“, 4};
+IdString str2{„SomeName“, 4};

+The new way of using uniform initialization allows the following:

+
struct BasicStruct {
+ int x;
+ double y;
+};
+ 
+struct AltStruct {
+  AltStruct(int x, double y) : x_{x}, y_{y} {}
+ 
+private:
+  int x_;
+  double y_;
+};
+ 
+BasicStruct var1{5, 3.2}; // only fills the struct components
+AltStruct var2{2, 4.3};   // calls the constructor

+The new syntax is specific to C++. Java, C# and scripting languages +do not support this behaviour, but always need constructors. They +support {} brackets for declaration of arrays as C does + they add +support for creation of arrays on-the-fly (what c++0x introduced with +this feature and more).

+

Done: Added syntax for {} member initialization in class +constructor. Added testcase cpp0x_uniform_initialization. R11413

+

Type inference [partially done]

+

A new keyword 'auto' is introduced in C++0x:

+
auto a1 = 100;
+auto a2 = myFunc();

+The type of a1 and a2 is automatically determined according to the +initialization value during the semantic phase of the compiler.

+

Another macro 'decltype()' is introduced. The macro takes the +concrete object as an argument and returns its type. User could use +this as:

+
int i = 100;
+decltype(i) j = 200; // decltype(i) = int

+Calling operators are allowed as well:

+
decltype(i+j) k = 300;

+Done: Added support for decltype() syntax. Test cases for normal +decltype members and alternate function members work fine. Currently +only syntax in form decltype(variable name) work. No support for +custom expresions eg. decltype(i+j) yet. R11525

+

TODO: William proposed to support the hidden variables as well +(ones not parsed by Swig and added to symbol table). This also allows +Swig to parse custom expressions like decltype(i+j). The idea is to +introduce a new SwigType for this.

+

Range-based for-loop [ignored]

+

This feature is always present inside the implementation block +only. +

+

Lambda functions and expressions [done]

+

C++0x introduces lambda functions defined as:

+
[](int x, int y) -> int { return x + y; }

+If the lambda function contains a single return statement only or the +function doesn't return any type, the return type '->' can be +omitted. Lambda functions are function objects.

+

The following example prints the number of items stored in a list:

+
std::vector<int> someList;
+int total = 0;
+std::for_each( someList.begin(), someList.end(), [&total](int x) {total += x} );
+std::cout << total;

+Parameters inside the [] are the visible parameters of the lambda +functions. These can be & (references), = (copies), variable name +(variable copy), &variable name (variable reference) or this +(copy of the current object).

+

Lambda functions can be stored using:

+
auto myLambdaFunc = [this]() { this->SomePrivateMemberFunction() };

+Proposal: Lambda functions are most commonly used inside the function +block to quickly define how the sort, find and similar functions +should work (the other way would be overriding a class – the Java +style). The latest GCC does not support lambda functions yet so it is +difficult to test the feature once implemented. I would implement the +syntax support for this feature, but produce no wrapper code. Lambda +functions still work inside the function block though.

+

Article: +http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2550.pdf

+

Done: Added syntax support for the lambda functions. Added +testcase cpp0x_lambda_functions.i. R11491, R11492

+

Alternate function syntax [done]

+

The problem with decltype() is that the parameters need to be +defined before the decltype. The following syntax is not valid, +because lhs and rhs hasn't been defined at the time of decltype:

+
template< typename LHS, typename RHS> 
+  decltype(lhs+rhs) AddingFunc(const LHS &lhs, const RHS &rhs) {return lhs + rhs;} //Not legal C++0x

+The solution C++0x offers is the combination of the 'auto' keyword +before and '-> rettype' after the function declaration:

+
template< typename LHS, typename RHS> 
+  auto AddingFunc(const LHS &lhs, const RHS &rhs) -> decltype(lhs+rhs) {return lhs + rhs;}

+The new syntax only makes the job for the C++ compilers easier when +parsing such functions. The new syntax can be used for ordinary +functions as well:

+
struct SomeStruct {
+  auto FuncName(int x, int y) -> int;
+};
+ 
+auto SomeStruct::FuncName(int x, int y) -> int {
+  return x + y;
+}

+Done: Added support for the 'auto' return type. Added support for the +'-> type' after the funtion declaration. Added testcases +cpp0x_alternate_function_syntax.i and +cpp0x_alternate_function_syntax_runme.py. R11414

+

Concepts, Axioms [ignored]

+

In C++ there is a common problem when you use a template in the +class which doesn't support all the operations the functions in the +class actually do on the type. Compiler errors are usually very long +and unreadable. C++0x adds support for the "concepts". The +idea is to define what operations and attributes should the template +have. In contrast to class inheritance and polimorphism, all lookups +are done in compile-time. +

+

Basic syntax (note LessThanComparable? +instead of "class" or "typename"): +

+
 template<LessThanComparable? T>
+ const T& min(const T &x, const T &y) {
+   return y < x ? y : x;
+ }

+Extended syntax (requires conditions are separated with &&, +|| or !): +

+
 template< typename T> requires LessThanComparable?<T>
+ const T& min(const T &x, const T &y) {
+   return y < x ? y : x;
+ }

+Definition of the concepts: +

+
 concept LessThanComparable?< typename T > {
+   bool operator<(T,T);
+   requires GreaterThanComparable?<T>;
+   typename value_type;
+   typename reference;
+ };

+Concept maps allow usage of a specific type: +

+
 template< typename T>
+ concept_map InputIterator?<T*> {
+   typedef T value_type ;
+   typedef T& reference ;
+   typedef T* pointer ;
+   typedef std::ptrdiff_t difference_type ;
+ };

+Concept maps can act as mini-types, with function definitions and +other constructs commonly associated with classes: +

+
 concept Stack< typename X> {
+   typename value_type;
+   void push(X&, const value_type&);
+   void pop(X&);
+   value_type top(const X&);
+   bool empty(const X&);
+ };
+ template< typename T>
+ concept_map Stack<std::vector<T> > {
+   typedef T value_type;
+   void push(std::vector<T>& v, const T& x) { v.push_back(x); }
+   void pop(std::vector<T>& v) { v.pop_back(); }
+   T top(const std::vector<T>& v) { return v.back(); }
+   bool empty(const std::vector<T>& v) { return v.empty(); }
+ };

+Axioms are a facility pertaining to concepts supplied by C++0x to +express the semantic properties of concepts. For example, the concept +Semigroup can be defined with an axiom Associativity as: +

+
 concept Semigroup< typename Op, typename T> : CopyConstructible?<T> {
+   T operator()(Op, T, T);
+   axiom Associativity(Op op, T x, T y, T z) {
+     op(x, op(y, z)) == op(op(x, y), z);
+   }
+ };

+Axioms are more like hints to the compiler to speed-up the process of +compilation. +

+

Ignored: Concepts and axioms were removed from the C++0x standard. +

+

Object construction improvement [done]

+

This feature allows classes constructors to call other +constructors with different arguments (similar to Java and C# +behaviour). +

+

The syntax is as follows: +

+
 class SomeType {
+  int number;
+ public:
+   SomeType(int newNumber) : number(newNumber) {}
+   SomeType() : SomeType(42) {}
+ };

+Also when using the inheritance, the feature introduces inheritance +of all superclass constructors without being defined separately in +the inherited class: +

+
 class BaseClass {
+ public:
+   BaseClass(int iValue);
+ };
+ class DerivedClass: public BaseClass {
+   public:
+   using BaseClass::BaseClass; // Adds DerivedClass(int) constructor
+ };

+Swig already correctly parses and produces the correct wrapper for +the “using†keyword.

+

Done: Added testcase cpp0x_constructors.i which covers both +constructor delegation and constructor inheritance. R11532

+

Problem: Constructor delegation and constructor inheritance is not +supported by any compiler yet, so it's impossible to try and test +this feature.

+

Null pointer constant [done]

+

nullptr is part of the standard library. +

+

It's defined as typedef decltype(nullptr) nullptr_t; +

+

nullptr_t is defined in <cstddef>. +

+

As far as the C++ is compatible with 0 as the pointer value, swig +values will work for the C++. And the other way around, nullptr +behaves as the ordinary pointer (false, if empty, true, if not +empty), so it's ok for swig to compare it.

+

Done: Written a testcase cpp0x_null_pointer_constant.i and +cpp0x_null_pointer_constant_runme.py to prove the nullptr +functionality. R11484

+

Strongly typed enumerations [partially done]

+

C++0x introduces a new syntax for strongly typed enum declaration: +

+
 enum class Enumeration {
+  Val1,
+  Val2,
+  Val3 = 100,
+  Val4 /* = 101 */
+ };

+Typing if (Val4 == 101) will result in compilation error. +

+

The enum itself can now be explicitely of type int, long, unsigned +int etc.: +

+
 enum class Enum2 : unsigned int {Val1, Val2};

+And it can be forward declared as well: +

+
 enum Enum1;                   //Illegal in C++ and C++0x; no size is explicitly specified.
+ enum Enum2 : unsigned int;    //Legal in C++0x.
+ enum class Enum3;             //Legal in C++0x, because enum class declarations have a default type of "int".
+ enum class Enum4: unsigned int; //Legal C++0x.
+ enum Enum2 : unsigned short;  //Illegal in C++0x, because Enum2 was previously declared with a different type.

+Done: Added syntax 'enum class Name' and forward declarators 'enum +Name : inherited type' or 'enum class Name : inherited type' in +R11449.

+

TODO: Add semantic support for enum elements not clashing with +enum elements in other enum classes. See cpp0x_strongly_typed_enums.i +warnings.

+

Problem: Swig currently doesn't support nested classes. This +feature should be implemented using a new nested class when using +“enum class†with a single anonymous “enum {elements}†+element inside. For example:

+
class A { enum class EA { a,b,c,d }; };

+should be mapped to

+
class A { class EA { enum {a,b,c,d}; }; };

+Angle bracket [done]

+

Support for right angled brackets was implemented using the +following article as a base: +http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1757.html +

+

Done: Added support for angle brackets. Used the preferred +"Approach 1". Added a testcase named +cpp0x_template_double_brackets. R11245

+

Explicit conversion operators [done]

+

This is used when converting one type to another (eg. if +(myObject) {}, where myObject is your custom class converted to +bool). +

+

Requires both operator and function overloading which is not +supported in any target language (eg. python, php). +

+

Done: Swig already supports the keyword "explicit" for +function types as well. Added test case +cpp0x_explicit_conversion_operators. R11323

+

Template typedefs [partially done]

+

The new C++0x will allow creation of wrapper around the template. +For example, if we want to do this:

+
template< typename first, typename second, int third>
+class SomeType;
+ 
+template< typename second>
+typedef SomeType<OtherType, second, 5> TypedefName; //Illegal in C++

+This is still illegal! But we can now use the new syntax for +achieving the same effect:

+
template< typename first, typename second, int third>
+class SomeType;
+
+template< typename second>
+using TypedefName = SomeType<OtherType, second, 5>;

+Here we created a new wrapper TypedefName taking one template +argument <second> which creates a type SomeType<OtherType, +second, 5>. OtherType and 5 are predefined here and hidden from +the user – the user only uses TypedefName type.

+

The same goes for the following example:

+
typedef void (*PFD)(double);            // Old style
+using PF = void (*)(double);            // New introduced syntax

+Swig supports parsing typedefs for templates as well for example:

+
typedef List<int> intList;

+Done: Expanded support for the new 'using' syntax and template +aliasing. Added testcase cpp0x_template_typedefs. R11533

+

TODO: Make Swig aware of the newly defined typedef. The TYPEDEF +keyword is part of the storage_class rule and type+declarator (see +c_decl rule) is the right part of the definition – for example void +(*PFD)(double) cannot be transformed to void *(double) easily. To +fully support the new 'using' form, we'll probably have to change the +type, type_right rules and declarator, direct_declarator, +notso_direct_declarator etc., which is PITA.

+

Unrestricted unions [done]

+

C++ currently offers usage of unions for types with trivial +constructors only. The new C++0x standard allows usage of types with +non-trivial constructors as well:

+
 struct point {
+  point() {}
+  point(int x, int y): x_(x), y_(y) {}
+  int x_, y_;
+ };
+ union P {
+  int z;
+  double w;
+  point p;  // Illegal in C++; point has a non-trivial constructor.  However, this is legal in C++0x.
+ } p1;

+Swig already parses the given syntax.

+

Done: Added testcase cpp0x_unrestricted_unions. R11435, R11447

+

Problem: GCC doesn't support unrestricted unions yet so there is +no way to actually test, if it works.

+

Variadic templates [partially done]

+

The new C++0x offers the following syntax:

+
template<typename... Values> class tuple;

+This can be used for example:

+
class tuple<int, std::vector<int>, std::map<std::string, std::vector<int>>> someInstanceName;

+The ... is used in two cases. One is in the template header where it +marks on the left the keywords 'typename' or 'class' and a type name +on the right. The second case is usually in the function block to +decompose typename on the left of the ... . For example:

+
void printf(const char *s) {
+  while (*s) {
+    if (*s == '%' && *(++s) != '%')
+      throw std::runtime_error("invalid format string: missing arguments");
+    std::cout << *s++;
+  }
+}
+ 
+template<typename T, typename... Args>
+void printf(const char* s, T value, Args... args) { // recursive action – split previous args to value + args
+  while (*s) {
+    if (*s == '%' && *(++s) != '%') {
+      std::cout << value;
+      printf(*s ? ++s : s, args...); // call even when *s == 0 to detect extra arguments
+      return;
+    }
+    std::cout << *s++;
+  }
+  throw std::logic_error("extra arguments provided to printf");
+}

+The tricky part is that variadic templates can unpack actually +anywhere – including the class inheritance :(

+
template <typename... BaseClasses> class ClassName : public BaseClasses... {
+public:
+ 
+   ClassName (BaseClasses&&... baseClasses) : BaseClasses(baseClasses)... {}
+}

+A new extension to sizeof is also introduced with this feature. The +... after sizeof returns number of arguments:

+
template<typename ...Args> struct SomeStruct {
+  static const int size = sizeof...(Args);
+}
+// SomeStruct<Type1, Type2>::size is 2 and SomeStruct<>::size is 0

+Done: Added syntax support for 'typename' or 'class' + ... + id. +Added testcase cpp0x_variadic_templates. R11458

+

Done: Added syntax support for BaseClass + ..., type + ... + id in +parameters and baseclass + ... for intializers after constructor. +Extended Swig syntax to support sizeof...(Args). R11467

+

Done: Fixed %template to support variadic number of templates.

+

TODO: Only (if present) first variadically defined argument is +currently used in %template directive. The next ones are ignored.

+

New string literals [partially done]

+

Beside the implementation, the new C++0x Unicode and custom +delimeter constants can occur in templates in the header file. +

+

Done: Added symbols 'u', 'u8' and 'U' to mark the beginning of the +UTF string. Also added test case cpp0x_raw_string_literals. R11327

+

Done: Added R"DELIMITER[, ]DELIMITER" for a custom +delimiter for the beginning/end of the string. R11328

+

TODO: Fix the Swig's C++ preprocessor bug when parsing an odd +number of “ inside the string brackets. See +Source/Preprocessor/cpp.c.

+

User-defined literals [partially done]

+

C++ has different suffix literals. eg. 12.5f marks the number 12.5 +as float. +

+

C++0x allows user to define his own suffix for the strings always +starting with the underscore (_). eg. int a = "hello"_mySuffix; +

+

The syntax is similar to other operator overloading functions: +

+
 OutputType operator "" _mySuffix(const char * string_values);

+The null terminated const char* is the string between the "". +The _mySuffix is the name of the suffix operator. And the OutputType +is the outputType the operator returns. +

+

Other forms are: +

+
 OutputType operator "" _mySuffix(const char * string_values, size_t num_chars);
+ OutputType operator "" _mySuffix(const wchar_t * string_values, size_t num_chars);
+ OutputType operator "" _mySuffix(const char16_t * string_values, size_t num_chars);
+ OutputType operator "" _mySuffix(const char32_t * string_values, size_t num_chars);
+ OutputType operator "" _mySuffix(int value); /* cooked version - ie. atoi() of string */

+Another possibility is to use variadic templates: +

+
 template<char...> OutputType operator "" _mySuffix();
+ OutputType someVariable = "1234"_mySuffix;

+This instantiates the literal processing function as +operator""_Suffix<'1', '2', '3', '4'>. In this form, +there is no terminating null character to the string. The main +purpose to doing this is to use C++0x's constexpr keyword and the +compiler to allow the literal to be transformed entirely at compile +time, assuming OutputType is a constexpr-constructable and copyable +type, and the literal processing function is a constexpr function.

+

Article: +http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2765.pdf

+

Done: Added syntax support for userdefined literals. Added +testcase cpp0x_userdefined_literals.i. R11494

+

TODO: %rename doesn't parse operatorâ€â€ yet.

+

Thread-local storage [done] +

+

New C++0x introduces keyword "thread_local" which marks +the following variable dynamically located depending on the current +thread when using the address-of (&) operator. +

+

Syntax: +

+
 struct A {
+   thread_local int val;
+ };

+Done: Add "thread_local" keyword to Swig. Added testcase +cpp0x_thread_local. R11393

+

Defaulting/deleting of standard functions on C++ objects [done]

+

C++ automatically creates default constructor with empty +parameters, copy constructor, operator= and destructor for any class. +Sometimes user wants to explicitly remove one of them or enable them +(eg. default constructor with empty parameters doesn't work any more, +if any other constructor is defined). +

+

Words "default" and "delete" are introduced. +The syntax is similar to declaration of pure virtual function: +

+
 struct NonCopyable {
+   NonCopyable & operator=(const NonCopyable&) = delete; /* Removes operator= */
+   NonCopyable(const NonCopyable&) = delete; /* Removed copy constructor */
+   NonCopyable() = default; /* Explicitly allows the empty constructor */
+   void *operator new(std::size_t) = delete; /* Removes new NonCopyable */
+ };

+User has the ability by using keyword delete to disallow calling of +the standard functions brought by C++ itself. +

+
 struct A1 {
+   void f(int i);
+   void f(double i) = delete;  /* Don't cast double to int. Compiler returns an error */
+ };
+ struct A2 {
+   void f(int i);
+   template<class T> void f(T) = delete; /* Only accept int */
+ };

+Ignored: Swig already parses the keywords "= delete" and "= +default". These keywords are used for built-in functions (copy +constructor, operator= etc.), which are ignored by Swig anyway.

+

Done: Added testcase cpp0x_default_delete. R11535

+

Type long long int [done]

+

Type long long int is an integer type that has at least 64 useful +bits. C99 added it to its standard, but the C++ didn't adopt it until +C++0x. Most C++ compilers supported it though. +

+

Done: Swig already parses the C code including the long long type. +

+

Static assertions [done]

+

static_assert() can be used at class scope as well eg.: +

+
 template <typename T>
+ struct Check {
+  static_assert(sizeof(int) <= sizeof(T), "not big enough");
+ };

+Done: Added syntax support for "static_assert()". Added +test case cpp0x_static_assert. R11369

+

Allow sizeof to work on members of classes without an explicit +object [done]

+

C++0x allows calls of sizeof to concrete objects as well: +

+
 struct A { int member; };
+ sizeof(A::member); //Does not work with C++03. Okay with C++0x

+This kind of syntax is already supported by Swig.

+

Done: Added testcase cpp0x_sizeof_objects. R11538 +

+

Threading facilities [ignored]

+

C++0x will add the following classes to the standard library: +

+
 * std::thread
+ * std::mutex, std::recursive_mutex
+ * std::condition_variable, std::condition_variable_any
+ * std::lock_guard, std::unique_lock
+ * std::packaged_task

+Ignored: No changes to the language itself is made. +

+

Tuple types [TODO]

+

Tuple is array of various types. C++0x introduced this feature +using variadic templates. Tuple is defined as:

+
template <class ...Types> class tuple;

+Constructor is automatically generated filling the tuple elements. +get<X> function is introduced to get the Xth element in the +tuple.

+
typedef tuple< int, double, long &, const char * > test_tuple ;
+long lengthy = 12 ;
+test_tuple proof( 18, 6.5, lengthy, "Ciao!" ) ;
+lengthy = get<0>(proof) ;  // Assign to 'lengthy' the value 18.
+get<3>(proof) = " Beautiful!" ;  // Modify the tuple’s fourth element.

+Tuples can be copied to each other, if all the elements are copiable:

+
typedef tuple< int , double, string       > tuple_1 t1 ;
+typedef tuple< char, short , const char * > tuple_2 t2( 'X', 2, "Hola!" ) ;
+t1 = t2 ;  // Ok, first two elements can be converted,
+           // the third one can be constructed from a 'const char *'.

+TODO: Implement wrappers for the tuplet<> class.

+

Hash tables [TODO]

+

C++0x introduces the "unordered" version of existing +types, which in practice work faster than the linear types: +

+
 - unordered set
+ - unordered multiset
+ - unordered map
+ - unordered multimap

+Swig should use the "unordered" types exactly the same as +the original linear types.

+

Problem: Unordered types do not contain exactly same members as +ordered ones (eg. _Hashtable_iterator does not offer operator--() and +constructor with compare function which is required). So simply +aliasing unordered classes to ordered ones doesn't work.

+

TODO: Implement wrappers for unordered_ types. Initial work is +already done in Lib/std/unordered_*.i files.

+

Regular expressions [ignored]

+

Two new classes are introduced in C++0x: basic_regex and +match_results. Both are defined in regex header file. +

+

Ignored: The new feature extends the standardy library only. No +changes to Swig needed. +

+

General-purpose smart pointers [done]

+

This feature deprecates auto_ptr and adds shared_ptr, weak_ptr and +unique_ptr to the standard library. +

+

This feature only adds the smart pointers to the standard library +and doesn't effect the C++ syntax.

+

Done: Added test case which uses all three smart pointers in the +class. R11394

+

Problem: GCC standard library doesn't contain the new smart +pointers yet. +

+

Extensible random number facility [ignored]

+

This feature standardize the pseudo random number algorithm +(currently, the random number generator was dependent on the +platform/compiler). It adds functions linear_congruential, +subtract_with_carry and mersenne_twister and symbols +uniform_int_distribution, bernoulli_distribution, +geometric_distribution, poisson_distribution, binomial_distribution, +uniform_real_distribution, exponential_distribution, +normal_distribution and gamma_distribution to the standard library. +

+

Ignored: The new feature extends the standardy library only. No +changes to Swig needed. +

+

Wrapper reference [ignored]

+

This feature adds ref and cref classes to the standard library +(#include <utility>) usually used in tempalte functions. +

+

Ignored: The new feature extends the standardy library only. No +changes to Swig needed. +

+

Polymorphous wrappers for function objects [done]

+

Two features are introduced: +

+
    +
  • The function template wrapper: +

    +
+
 function<int ( int, int )> pF;
+
    +
  • and the function object: +

    +
+
 struct Test {
+   bool operator()( short x, short y );
+ };

+Swig already supports the two.

+

Done: Added a runtime testcase for function objects +cpp0x_function_objects. R11419.

+

Type traits for metaprogramming [ignored]

+

C++0x adds a new header file <type_traits> which includes +helper functions to determine the template type while initializing +the object at compile time. +

+

Swig already supports the following code: +

+
 template< int B, int N >
+ struct Pow {
+  // recursive call and recombination.
+  enum{ value = B*Pow< B, N-1 >::value };
+ };
+ template< int B > struct Pow< B, 0 >  // N == 0 condition of termination.
+ {
+  enum{ value = 1 };
+ };
+ int quartic_of_three = Pow< 3, 4 >::value ;

+Functions is_convertible, is_integral, is_integral_const etc. are +part of the new header: +

+
// First way of operating.
+template< bool B > struct algorithm {
+  template< class T1, class T2 > int do_it( T1 &, T2 & )  { /*...*/ }
+};
+// Second way of operating.
+template<> struct algorithm<true> {
+  template< class T1, class T2 > int do_it( T1, T2 )  { /*...*/ }
+};
+// Instantiating 'elaborate' will automatically instantiate the correct way to operate.
+template< class T1, class T2 > int elaborate( T1 A, T2 B ) {
+  // Use the second way only if 'T1' is an integer and if 'T2' is
+  // in floating point, otherwise use the first way.
+  return algorithm< is_integral<T1>::value && is_floating_point<T2>::value >::do_it( A, B );
+}

+Swig correctly parses the syntax for template<bool>, +template<class T> and template<>. +

+

Ignored: Swig requires explicitly defined template class +(%template directive) to export it to the target language.

+

Uniform method for computing return type of function objects +[partially done]

+

The template function is introduced: std::result_of() which +depends on decltype: +

+
template< class Obj >
+class calculus_ver2 {
+ public:
+   template< class Arg >
+   typename std::result_of<Obj(Arg)>::type operator()( Arg& a ) const { 
+     return member(a);
+   }
+ private:
+   Obj member;
+};

+Swig correctly parses the result_of class.

+

TODO: The return type (the result_of::type member) is not +calculated by Swig. This needs a much more complex semantic parser.

+

Done: Added testcase cpp0x_result_of. R11534

+ + \ No newline at end of file From fc6c84554b8ca497a9e2ee0cc40d3c8ef285b5be Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 20 Aug 2009 00:26:26 +0000 Subject: [PATCH 047/481] Grammar and formatting improvements git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11655 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Doc/Manual/Cpp0x.html | 171 +++++++++++++++++++++--------------------- 1 file changed, 86 insertions(+), 85 deletions(-) diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html index 9ec67861b..4466e6cfd 100644 --- a/Doc/Manual/Cpp0x.html +++ b/Doc/Manual/Cpp0x.html @@ -1,7 +1,7 @@ -SWIG and Python +SWIG and C++0x @@ -59,13 +59,13 @@

7.1 Introduction

-

This chapter gives you a brief overview about the Swig -implementation of the C++0x standard. This part of Swig is still a work in -progress. Initial C++0x support for Swig was written during the +

This chapter gives you a brief overview about the SWIG +implementation of the C++0x standard. This part of SWIG is still a work in +progress. Initial C++0x support for SWIG was written during the Google Summer of Code 2009 period.

-

Swig supports all the new C++ syntax changes with some limitations +

SWIG supports all the new C++ syntax changes with some minor limitations (decltype expressions, variadic templates number). Wrappers for the -new types (unordered_ types, result_of, tuples) are not supported +new STL types (unordered_ containers, result_of, tuples) are not supported yet.

7.2 Core language changes

@@ -74,7 +74,7 @@ yet.

7.2.1 Rvalue reference and move semantics

-

Swig correctly parses the new operator && the same as the reference operator &.

+

SWIG correctly parses the new operator && the same as the reference operator &.

The wrapper for the following code is correctly produced:

@@ -90,14 +90,14 @@ class MyClass {
 

7.2.2 Generalized constant expressions

-

Swig correctly parses the keyword "constexpr", but ignores its functionality. Constant functions cannot be used as constants yet.

+

SWIG correctly parses the keyword constexpr, but ignores its functionality. Constant functions cannot be used as constants.

 constexpr int myConstFunc() { return 10; }
-const int a = myConstFunc(); // reslults in error
+const int a = myConstFunc(); // results in error
 
-

User needs to use values or predefined constants when defining the new constant value:

+

Users needs to use values or predefined constants when defining the new constant value:

 #define MY_CONST 10
@@ -108,7 +108,7 @@ const int a = MY_CONST; // ok
 

7.2.3 Extern template

-

Swig correctly parses the keywords "extern template". However, the explicit template instantiation is not usable for Swig.

+

SWIG correctly parses the keywords extern template. However, the explicit template instantiation is not used by SWIG, a %template is still required.

@@ -127,8 +127,8 @@ public:
 
 
 

Constructors using the std::initializer_list class are removed -from the wrapped class, because the only way to acess such a -constructor is at the compile time using the "= {}" assignment.

+from the wrapped class, because the only way to access such a +constructor is at compile time using the "= {}" assignment.

User should add another constructor with specific arguments filling the class members manually.

@@ -142,7 +142,7 @@ public: A a1 = {1,2,3,4};
-

He should add another constructor using the std::vector for example:

+

You should add another constructor using the std::vector for example:

 class A {
@@ -153,7 +153,7 @@ public:
 A a1 = {1,2,3,4};
 
-

And call it in target language:

+

And call it from your target language, for example, in Python:

 >>> a2 = A( [1,2,3,4] )
 
@@ -161,8 +161,8 @@ A a1 = {1,2,3,4};

7.2.5 Uniform initialization

-

The curly brackets {} for memeber initialization are fully -supported by Swig:

+

The curly brackets {} for member initialization are fully +supported by SWIG:

 struct BasicStruct {
@@ -181,7 +181,7 @@ BasicStruct var1{5, 3.2}; // only fills the struct components
 AltStruct var2{2, 4.3};   // calls the constructor
 
-

Usage in the target language is the same:

+

Uniform initialization does not affect usage from the target language, for example in Python:

 >>> a = AltStruct(10, 142.15)
@@ -194,8 +194,8 @@ AltStruct var2{2, 4.3};   // calls the constructor
 

7.2.6 Type inference

-

Swig supports "decltype()" with some limitations. Single -variable is allowed, however expressions are not supported yet. For +

SWIG supports decltype() with some limitations. Single +variables are allowed, however, expressions are not supported yet. For example, the following code will work:

 int i;
@@ -208,34 +208,34 @@ int i; int j;
 decltype(i+j) k;  // syntax error
 
-

7.2.7 Range-based for-loop

+

7.2.7 Range-based for-loop

-

This feature is part of the implementation block only. Swig +

This feature is part of the implementation block only. SWIG ignores it.

7.2.8 Lambda functions and expressions

-

Swig correctly parses the Lambda functions syntax. For example:

+

SWIG correctly parses the Lambda functions syntax. For example:

 auto myLambdaFunc = [this]() { this->SomePrivateMemberFunction() };
 

The lambda functions are removed from the wrapper class for now, because of the lack of support -for closures (scope of the lambda functions) in target languages though.

+for closures (scope of the lambda functions) in the target languages.

7.2.9 Alternate function syntax

-

Swig fully supports the new definition of functions. For example:

+

SWIG fully supports the new definition of functions. For example:

 struct SomeStruct {
   int FuncName(int x, int y);
 };
 
-

can now be written as:

+

can now be written as in C++0x:

 struct SomeStruct {
@@ -247,7 +247,7 @@ auto SomeStruct::FuncName(int x, int y) -> int {
 }
 
-

The usage in the target languages remains the same:

+

The usage in the target languages remains the same, for example in Python:

 >>> a = SomeStruct()
@@ -255,7 +255,7 @@ auto SomeStruct::FuncName(int x, int y) -> int {
 15
 
-

User can also use the type inference for the return type. For example:

+

SWIG will also deal with type inference for the return type, as per the limitations described earlier. For example:

 auto square(float a, float b) -> decltype(a);
 
@@ -263,9 +263,9 @@ auto square(float a, float b) -> decltype(a);

7.2.10 Object construction improvement

-

Swig correctly parses and includes the external functions +

SWIG correctly parses and includes the external functions (constructor delegation and constructor inheritance) into the class -using the "using" keyword.

+using the using keyword.

 class BaseClass {
@@ -282,19 +282,20 @@ class DerivedClass: public BaseClass {
 

7.2.11 Null pointer constant

-

Swig correctly maps the std::nullptr constant to the null pointer +

SWIG correctly maps the std::nullptr constant to the null pointer constant in the target language.

7.2.12 Strongly typed enumerations

-

Swig parses the new "enum class" syntax and forward declarator for the enums:

+

SWIG parses the new enum class syntax and forward declarator for the enums:

 enum class MyEnum : unsigned int;
 
-

The strongly typed enumerations are treated the same as the ordinary and anonymous enums for now, -because Swig doesn't support the nested classes. For example, the following code:

+

The strongly typed enumerations are treated the same as the ordinary and anonymous enums. +This is because SWIG doesn't support nested classes. This is usually not a problem, however, +there may be some name clashes. For example, the following code:

 class Color {
@@ -313,7 +314,7 @@ class Color {
 };
 
-

should be written as a series of separated classes containing anonymous enums:

+

A workaround is to write these as a series of separated classes containing anonymous enums:

 class PrintingColors {
@@ -338,7 +339,7 @@ class AllColors {
 

7.2.13 Double angle brackets

-

Swig correctly parses the symbols >> as the closure of the +

SWIG correctly parses the symbols >> as closing the template block, if found inside it at the top level, or as the right shift operator >> otherwise.

@@ -346,8 +347,8 @@ shift operator >> otherwise.

std::vector<std::vector<int>> myIntTable;
-

User can force the bit shifting operator using the parenthesis -around the expressions. For example

+

The bit shifting operator using the parenthesis +around the expressions can be forced. For example

 template<(5>>3)>
@@ -357,7 +358,7 @@ class A {};
 

7.2.14 Explicit conversion operators

-

Swig correctly parses the keyword "explicit" both for operators and constructors. +

SWIG correctly parses the keyword explicit both for operators and constructors. For example:

@@ -385,22 +386,22 @@ public:
 

The usage of explicit constructors and operators is somehow specific to C++ when assigning the value of one object to another one of different type or translating one type to another. It requires both operator and function overloading features, -which are not supported by majority of Swig target languages. Also the constructors and operators are not particulary useful in any -Swig target languages, because all use their own faclities (eg. classes Cloneable and Comparable in Java) +which are not supported by the majority of SWIG target languages. Also the constructors and operators are not particulary useful in any +SWIG target languages, because all use their own facilities (eg. classes Cloneable and Comparable in Java) to achieve particular copy and compare behaviours.

7.2.15 Template typedefs

-

Swig currently parses the new "using name =" syntax, but +

SWIG currently parses the new using name = syntax, but ignores the definition:

 using PFD = void (*)(double); // New introduced syntax
 
-

User should still define the typedefs using the old syntax:

+

You should still define the typedefs using the old syntax:

 typedef void (*PFD)(double);  // The old style
@@ -409,7 +410,7 @@ typedef void (*PFD)(double);  // The old style
 

7.2.16 Unrestricted unions

-

Swig fully supports any type inside the union even if it does not +

SWIG fully supports any type inside a union even if it does not define the trivial constructor. For example, the wrapper for the following code is correctly produced:

@@ -430,7 +431,7 @@ union P {

7.2.17 Variadic templates

-

Swig fully supports the variadic templates syntax (inside the <> +

SWIG fully supports the variadic templates syntax (inside the <> block, variadic class inheritance and variadic constructor and initializers) with some limitations. The following code is correctly parsed:

@@ -447,19 +448,19 @@ public: const int SIZE = sizeof...(ClassName<int, int>);
-

The %template statement however, accepts only at most as the amount of -arguments defined in the original template<> block for now:

+

For now however, the %template directive only accepts at most the number of +arguments defined in the original template<> block:

 %template(MyVariant1) ClassName<>         // ok
 %template(MyVariant2) ClassName<int>      // ok
-%template(MyVariant3) ClassName<int, int> // too much arguments
+%template(MyVariant3) ClassName<int, int> // too many arguments
 

7.2.18 New string literals

-

Swig fully supports custom delimiters and unicode string +

SWIG fully supports custom delimiters and unicode string constants.

@@ -478,13 +479,13 @@ char16_t   *g = uR"XXX[to be or "not" to be [these are parenthesis], this is the
 char32_t   *h = UR"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX";
 
-

Note: Swig currently incorrectly parses the odd number of double quotes -inside the string due to Swig's C++ preprocessor.

+

Note: SWIG currently incorrectly parses the odd number of double quotes +inside the string due to SWIG's C++ preprocessor.

-

7.2.19 User-defined literals

+

7.2.19 User-defined literals

-

Swig correctly parses the new operator""_mysuffix() functions.

+

SWIG correctly parses the new operator""_mysuffix() functions.

 OutputType operator "" _mySuffix(const char * string_values, size_t num_chars);
@@ -494,13 +495,13 @@ OutputType operator "" _mySuffix(const char32_t * string_values, size_t num_char
 OutputType operator "" _mySuffix(int value);
 
-

The %rename currently doesn't parse the double quotes so the user -should rename the functions in the code using the #define preprocessor directive.

+

The %rename currently doesn't parse the double quotes. Please +rename the functions in the code using the #define preprocessor directive.

-

7.2.20 Thread-local storage

+

7.2.20 Thread-local storage

-

Swig correctly parses the "thread_local" keyword. For example, a variable +

SWIG correctly parses the thread_local keyword. For example, a variable reachable by the current thread can be defined as:

@@ -509,36 +510,36 @@ struct A {
 };
 
-

The new C++0x threading libraries are ignored because each Swig target language offers +

The new C++0x threading libraries are ignored because each SWIG target language offers its own threading facilities.

7.2.21 Defaulting/deleting of standard functions on C++ objects

-

Swig correctly parses the "= delete" and "= default" +

SWIG correctly parses the = delete and = default keywords. For example:

 struct NonCopyable {
   NonCopyable& operator=(const NonCopyable&) = delete; /* Removes operator= */
-  NonCopyable(const NonCopyable&) = delete;                /* Removed copy constructor */
-  NonCopyable() = default;                                     /* Explicitly allows the empty constructor */
-  void *operator new(std::size_t) = delete;                    /* Removes new NonCopyable */
+  NonCopyable(const NonCopyable&) = delete;            /* Removed copy constructor */
+  NonCopyable() = default;                             /* Explicitly allows the empty constructor */
+  void *operator new(std::size_t) = delete;            /* Removes new NonCopyable */
 };
 
-

This feature is somehow specific to the C++ only. The defaulting/deleting is currently ignored, because Swig +

This feature is specific to C++ only. The defaulting/deleting is currently ignored, because SWIG automatically produces wrappers for special constructors and operators specific to the target language.

7.2.22 Type long long int

-

Swig correctly parses and uses the new "long long" type already introduced in C99 some time ago.

+

SWIG correctly parses and uses the new long long type already introduced in C99 some time ago.

7.2.23 Static assertions

-

Swig correctly parses and calls the new "static_assert" function.

+

SWIG correctly parses and calls the new static_assert function.

 template <typename T>
@@ -550,7 +551,7 @@ struct Check {
 

7.2.24 Allow sizeof to work on members of classes without an explicit object

-

Swig correctly calls the sizeof() on types as well as on the +

SWIG correctly calls the sizeof() on types as well as on the objects. For example:

@@ -573,30 +574,30 @@ const int SIZE = sizeof(A::member); // does not work with C++03. Okay with C++0x
 

7.3.1 Threading facilities

-

Swig does not currently wrap or use any of the new threading -classes introduced (thread, mutex, locks, condition variable, task). The main reason is that -Swig target languages offer their own threading facilities that do not rely on the C++.

+

SWIG does not currently wrap or use any of the new threading +classes introduced (thread, mutex, locks, condition variables, task). The main reason is that +SWIG target languages offer their own threading facilities that do not rely on C++.

7.3.2 Tuple types and hash tables

-

Swig does not wrap the new tuple types and the unordered_ classes yet. Variadic support is there so the user can -include the tuple header file and is parsed without any problems.

+

SWIG does not wrap the new tuple types and the unordered_ container classes yet. Variadic template support is working so it is possible to +include the tuple header file; it is parsed without any problems.

7.3.3 Regular expressions

-

Swig does not wrap the new C++0x regular expressions classes, because the Swig target languages use their own facilities for this.

+

SWIG does not wrap the new C++0x regular expressions classes, because the SWIG target languages use their own facilities for this.

-

7.3.4 General-purpose smart pointers

+

7.3.4 General-purpose smart pointers

-

Swig does not wrap the new shared, weak and unique smart pointers, because the Swig target languages offer their own garbage collectors.

+

SWIG does not wrap the new shared, weak and unique smart pointers, because the SWIG target languages offer their own garbage collectors.

7.3.5 Extensible random number facility

-

This feature extends and standardizes the standard library only and does not effect the C++ language and Swig.

+

This feature extends and standardizes the standard library only and does not effect the C++ language and SWIG.

7.3.6 Wrapper reference

@@ -604,7 +605,7 @@ include the tuple header file and is parsed without any problems.

The new ref and cref classes are used to instantiate a parameter as a reference of a template function. For example:

-void f( int &r )  { r++ ; }
+void f( int &r )  { r++; }
  
 // Template function.
 template< class F, class P > void g( F f, P t )  { f(t); }
@@ -615,18 +616,18 @@ int main() {
                // then 'i' will not be modified.
   cout << i << endl ;  // Output -> 0
  
-  g( f, ref(i) ) ;  // 'g<void(int &r),reference_wrapper<int>>' is instanced
+  g( f, ref(i) ) ;  // 'g<void(int &r),reference_wrapper<int>>' is instantiated
                     // then 'i' will be modified.
   cout << i << endl ;  // Output -> 1
 }
 
-

The ref and cref classes are not wrapped by Swig because the Swig target languages do not support referencing.

+

The ref and cref classes are not wrapped by SWIG because the SWIG target languages do not support referencing.

7.3.7 Polymorphous wrappers for function objects

-

Swig fully supports the function template wrappers and function objects:

+

SWIG fully supports function template wrappers and function objects:

 function<int ( int, int )> pF;   // function template wrapper
@@ -639,7 +640,7 @@ struct Test {
 

7.3.8 Type traits for metaprogramming

-

The new C++ metaprogramming is useful at compile time and is aimed specifically for the C++ development:

+

The new C++ metaprogramming is useful at compile time and is aimed specifically for C++ development:

 // First way of operating.
@@ -658,13 +659,13 @@ template< class T1, class T2 > int elaborate( T1 A, T2 B ) {
 }
 
-

Swig correctly parses the template specialization, template types and values inside the <> block and the new helper functions is_convertible, is_integral, is_const etc. -However, Swig still explicitly requires concrete types when using the %template directive, so the C++ metaprogramming features are not really interesting at runtime in Swig target languages.

+

SWIG correctly parses the template specialization, template types and values inside the <> block and the new helper functions: is_convertible, is_integral, is_const etc. +However, SWIG still explicitly requires concrete types when using the %template directive, so the C++ metaprogramming features are not really of interest at runtime in the target languages.

7.3.9 Uniform method for computing return type of function objects

-

Swig does not wrap the new result_of class introduced in the <functional> header and map the result_of::type to the concrete type yet. For example:

+

SWIG does not wrap the new result_of class introduced in the <functional> header and map the result_of::type to the concrete type yet. For example:

 %inline %{
 #include <functional>
@@ -686,9 +687,9 @@ typename std::result_of<Fun(Arg)>::type test_result_impl(Fun fun, Arg arg)
 
 
 >>> test_result_impl(SQUARE, 5.0)
-<Swig Object of type 'std::result_of< Fun(Arg) >::type *' at 0x7faf99ed8a50>
+<SWIG Object of type 'std::result_of< Fun(Arg) >::type *' at 0x7faf99ed8a50>
 
-

User should use decltype() where possible for now.

+

Instead, please use decltype() where possible for now.

From 7f5326020352e7df3d953f2cafbee734a79ab815 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 6 Mar 2010 00:51:54 +0000 Subject: [PATCH 048/481] merge revisions 11872:11876 from trunk to gsoc2009-matevz branch - license changes git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11905 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- ANNOUNCE | 10 +- COPYRIGHT | 63 + Doc/Manual/Sections.html | 2 +- Examples/GIFPlot/Chicken/check.list | 3 - Examples/GIFPlot/Chicken/full/Makefile | 28 - Examples/GIFPlot/Chicken/full/README | 6 - Examples/GIFPlot/Chicken/full/cmap | Bin 768 -> 0 bytes Examples/GIFPlot/Chicken/full/gifplot.i | 26 - .../GIFPlot/Chicken/full/test-gifplot.scm | 66 - Examples/GIFPlot/Chicken/simple/Makefile | 28 - Examples/GIFPlot/Chicken/simple/README | 5 - Examples/GIFPlot/Chicken/simple/simple.i | 34 - .../GIFPlot/Chicken/simple/test-simple.scm | 29 - Examples/GIFPlot/Common-Lisp/full/cmap | Bin 768 -> 0 bytes Examples/GIFPlot/Common-Lisp/full/gifplot.i | 21 - Examples/GIFPlot/Common-Lisp/full/runme.lisp | 59 - Examples/GIFPlot/Guile/check.list | 3 - Examples/GIFPlot/Guile/full/Makefile | 28 - Examples/GIFPlot/Guile/full/README | 8 - Examples/GIFPlot/Guile/full/cmap | Bin 768 -> 0 bytes Examples/GIFPlot/Guile/full/gifplot.i | 21 - Examples/GIFPlot/Guile/full/runme.scm | 66 - Examples/GIFPlot/Guile/simple/Makefile | 28 - Examples/GIFPlot/Guile/simple/README | 11 - Examples/GIFPlot/Guile/simple/runme.scm | 30 - Examples/GIFPlot/Guile/simple/simple.i | 34 - Examples/GIFPlot/Include/gifplot.h | 333 --- Examples/GIFPlot/Interface/gifplot.i | 264 -- Examples/GIFPlot/Java/check.list | 4 - Examples/GIFPlot/Java/full/Makefile | 20 - Examples/GIFPlot/Java/full/README | 8 - Examples/GIFPlot/Java/full/cmap | Bin 768 -> 0 bytes Examples/GIFPlot/Java/full/gifplot.i | 15 - Examples/GIFPlot/Java/full/runme.java | 75 - Examples/GIFPlot/Java/shadow/Makefile | 21 - Examples/GIFPlot/Java/shadow/README | 5 - Examples/GIFPlot/Java/shadow/cmap | Bin 768 -> 0 bytes Examples/GIFPlot/Java/shadow/runme.java | 76 - Examples/GIFPlot/Java/simple/Makefile | 21 - Examples/GIFPlot/Java/simple/README | 5 - Examples/GIFPlot/Java/simple/runme.java | 41 - Examples/GIFPlot/Java/simple/simple.i | 38 - Examples/GIFPlot/Lib/Makefile.in | 22 - Examples/GIFPlot/Lib/color.c | 143 -- Examples/GIFPlot/Lib/font.c | 705 ------ Examples/GIFPlot/Lib/frame.c | 924 ------- Examples/GIFPlot/Lib/gif.c | 672 ----- Examples/GIFPlot/Lib/matrix.c | 343 --- Examples/GIFPlot/Lib/pixmap.c | 159 -- Examples/GIFPlot/Lib/plot2d.c | 445 ---- Examples/GIFPlot/Lib/plot3d.c | 2181 ----------------- Examples/GIFPlot/Makefile.in | 23 - Examples/GIFPlot/Ocaml/check.list | 3 - Examples/GIFPlot/Ocaml/full/Makefile | 33 - Examples/GIFPlot/Ocaml/full/README | 8 - Examples/GIFPlot/Ocaml/full/cmap | Bin 768 -> 0 bytes Examples/GIFPlot/Ocaml/full/gifplot.i | 15 - Examples/GIFPlot/Ocaml/full/runme.ml | 87 - Examples/GIFPlot/Ocaml/simple/Makefile | 33 - Examples/GIFPlot/Ocaml/simple/cmap | Bin 768 -> 0 bytes Examples/GIFPlot/Ocaml/simple/runme.ml | 35 - Examples/GIFPlot/Ocaml/simple/simple.i | 33 - Examples/GIFPlot/Perl5/check.list | 4 - Examples/GIFPlot/Perl5/full/Makefile | 24 - Examples/GIFPlot/Perl5/full/README | 8 - Examples/GIFPlot/Perl5/full/cmap | Bin 768 -> 0 bytes Examples/GIFPlot/Perl5/full/gifplot.i | 15 - Examples/GIFPlot/Perl5/full/runme.pl | 68 - Examples/GIFPlot/Perl5/shadow/Makefile | 25 - Examples/GIFPlot/Perl5/shadow/README | 2 - Examples/GIFPlot/Perl5/shadow/cmap | Bin 768 -> 0 bytes Examples/GIFPlot/Perl5/shadow/runme.pl | 68 - Examples/GIFPlot/Perl5/simple/Makefile | 24 - Examples/GIFPlot/Perl5/simple/README | 5 - Examples/GIFPlot/Perl5/simple/runme.pl | 28 - Examples/GIFPlot/Perl5/simple/simple.i | 38 - Examples/GIFPlot/Php/check.list | 3 - Examples/GIFPlot/Php/full/Makefile | 20 - Examples/GIFPlot/Php/full/README | 4 - Examples/GIFPlot/Php/full/cmap | Bin 768 -> 0 bytes Examples/GIFPlot/Php/full/gifplot.i | 15 - Examples/GIFPlot/Php/full/runme.php | 78 - Examples/GIFPlot/Php/shadow/Makefile | 19 - Examples/GIFPlot/Php/shadow/README | 2 - Examples/GIFPlot/Php/shadow/cmap | Bin 768 -> 0 bytes Examples/GIFPlot/Php/shadow/runme.php | 79 - Examples/GIFPlot/Php/simple/Makefile | 20 - Examples/GIFPlot/Php/simple/README | 5 - Examples/GIFPlot/Php/simple/runme.php | 32 - Examples/GIFPlot/Php/simple/simple.i | 38 - Examples/GIFPlot/Pike/check.list | 2 - Examples/GIFPlot/Pike/simple/Makefile | 24 - Examples/GIFPlot/Pike/simple/README | 5 - Examples/GIFPlot/Pike/simple/runme.pike | 30 - Examples/GIFPlot/Pike/simple/simple.i | 38 - Examples/GIFPlot/Python/check.list | 4 - Examples/GIFPlot/Python/full/Makefile | 26 - Examples/GIFPlot/Python/full/README | 8 - Examples/GIFPlot/Python/full/cmap | Bin 768 -> 0 bytes Examples/GIFPlot/Python/full/gifplot.i | 15 - Examples/GIFPlot/Python/full/runme.py | 64 - Examples/GIFPlot/Python/shadow/Makefile | 27 - Examples/GIFPlot/Python/shadow/README | 8 - Examples/GIFPlot/Python/shadow/cmap | Bin 768 -> 0 bytes Examples/GIFPlot/Python/shadow/runme.py | 62 - Examples/GIFPlot/Python/simple/Makefile | 26 - Examples/GIFPlot/Python/simple/README | 5 - Examples/GIFPlot/Python/simple/runme.py | 27 - Examples/GIFPlot/Python/simple/simple.i | 38 - Examples/GIFPlot/README | 59 - Examples/GIFPlot/Ruby/check.list | 4 - Examples/GIFPlot/Ruby/full/Makefile | 24 - Examples/GIFPlot/Ruby/full/README | 8 - Examples/GIFPlot/Ruby/full/cmap | Bin 768 -> 0 bytes Examples/GIFPlot/Ruby/full/gifplot.i | 15 - Examples/GIFPlot/Ruby/full/runme.rb | 66 - Examples/GIFPlot/Ruby/shadow/Makefile | 25 - Examples/GIFPlot/Ruby/shadow/README | 5 - Examples/GIFPlot/Ruby/shadow/cmap | Bin 768 -> 0 bytes Examples/GIFPlot/Ruby/shadow/runme.rb | 66 - Examples/GIFPlot/Ruby/simple/Makefile | 24 - Examples/GIFPlot/Ruby/simple/README | 5 - Examples/GIFPlot/Ruby/simple/runme.rb | 27 - Examples/GIFPlot/Ruby/simple/simple.i | 38 - Examples/GIFPlot/Tcl/check.list | 4 - Examples/GIFPlot/Tcl/full/Makefile | 24 - Examples/GIFPlot/Tcl/full/README | 8 - Examples/GIFPlot/Tcl/full/cmap | Bin 768 -> 0 bytes Examples/GIFPlot/Tcl/full/gifplot.i | 15 - Examples/GIFPlot/Tcl/full/runme.tcl | 67 - Examples/GIFPlot/Tcl/mandel/Makefile | 24 - Examples/GIFPlot/Tcl/mandel/README | 6 - Examples/GIFPlot/Tcl/mandel/cmap | Bin 768 -> 0 bytes Examples/GIFPlot/Tcl/mandel/display.tcl | 68 - Examples/GIFPlot/Tcl/mandel/mandel.i | 47 - Examples/GIFPlot/Tcl/mandel/mandel.tcl | 170 -- Examples/GIFPlot/Tcl/simple/Makefile | 24 - Examples/GIFPlot/Tcl/simple/README | 5 - Examples/GIFPlot/Tcl/simple/runme.tcl | 27 - Examples/GIFPlot/Tcl/simple/simple.i | 38 - Examples/chicken/zlib/Makefile | 28 - Examples/chicken/zlib/README.html | 1666 ------------- Examples/chicken/zlib/example.i | 76 - Examples/chicken/zlib/test-zlib.scm | 41 - Examples/guile/check.list | 1 - Examples/lua/lua.c | 1 - .../test-suite/csharp/li_std_map_runme.cs | 5 - Examples/test-suite/li_std_queue.i | 11 +- Examples/test-suite/li_std_set.i | 22 +- Examples/test-suite/li_std_stack.i | 11 +- .../ruby/ruby_li_std_speed_runme.rb | 3 - Examples/test-suite/ruby_li_std_speed.i | 11 +- Examples/xml/example_gif.i | 329 --- LICENSE | 109 +- LICENSE-GPL | 674 +++++ LICENSE-UNIVERSITIES | 95 + Lib/allegrocl/allegrocl.swg | 2 - Lib/allegrocl/longlongs.i | 3 - Lib/allegrocl/std_list.i | 3 - Lib/allegrocl/std_string.i | 3 - Lib/attribute.i | 3 - Lib/carrays.i | 3 - Lib/cdata.i | 3 - Lib/chicken/chicken.swg | 3 - Lib/chicken/chickenrun.swg | 4 - Lib/chicken/multi-generic.scm | 2 +- Lib/chicken/std_string.i | 3 - Lib/chicken/typemaps.i | 3 - Lib/clisp/clisp.swg | 3 - Lib/cmalloc.i | 3 - Lib/constraints.i | 3 - Lib/cpointer.i | 3 - Lib/csharp/arrays_csharp.i | 3 - Lib/csharp/csharp.swg | 3 - Lib/csharp/csharphead.swg | 3 - Lib/csharp/director.swg | 3 - Lib/csharp/enums.swg | 3 - Lib/csharp/enumsimple.swg | 3 - Lib/csharp/enumtypesafe.swg | 3 - Lib/csharp/std_except.i | 3 - Lib/csharp/std_map.i | 3 - Lib/csharp/std_pair.i | 3 - Lib/csharp/std_string.i | 3 - Lib/csharp/std_vector.i | 3 - Lib/csharp/std_wstring.i | 3 - Lib/csharp/stl.i | 3 - Lib/csharp/typemaps.i | 3 - Lib/csharp/wchar.i | 3 - Lib/cstring.i | 3 - Lib/cwstring.i | 3 - Lib/exception.i | 3 - Lib/gcj/cni.swg | 3 - Lib/guile/common.scm | 6 - Lib/guile/cplusplus.i | 3 - Lib/guile/guile.i | 3 - Lib/guile/guile_gh.swg | 3 - Lib/guile/guile_gh_run.swg | 3 - Lib/guile/guile_scm.swg | 3 - Lib/guile/guile_scm_run.swg | 3 - Lib/guile/guilemain.i | 3 - Lib/guile/interpreter.i | 3 - Lib/guile/list-vector.i | 3 - Lib/guile/pointer-in-out.i | 3 - Lib/guile/ports.i | 3 - Lib/guile/std_common.i | 3 - Lib/guile/std_map.i | 3 - Lib/guile/std_pair.i | 3 - Lib/guile/std_string.i | 3 - Lib/guile/std_vector.i | 3 - Lib/guile/stl.i | 3 - Lib/guile/typemaps.i | 3 - Lib/inttypes.i | 3 - Lib/java/arrays_java.i | 3 - Lib/java/director.swg | 3 - Lib/java/enums.swg | 3 - Lib/java/enumsimple.swg | 3 - Lib/java/enumtypesafe.swg | 3 - Lib/java/enumtypeunsafe.swg | 3 - Lib/java/java.swg | 3 - Lib/java/javahead.swg | 3 - Lib/java/std_except.i | 3 - Lib/java/std_map.i | 3 - Lib/java/std_pair.i | 3 - Lib/java/std_string.i | 3 - Lib/java/std_vector.i | 3 - Lib/java/std_wstring.i | 3 - Lib/java/stl.i | 3 - Lib/java/typemaps.i | 3 - Lib/java/various.i | 3 - Lib/lua/_std_common.i | 3 - Lib/lua/lua.swg | 3 - Lib/lua/lua_fnptr.i | 3 - Lib/lua/luarun.swg | 3 - Lib/lua/luaruntime.swg | 3 - Lib/lua/luatypemaps.swg | 3 - Lib/lua/std_except.i | 3 - Lib/lua/std_map.i | 3 - Lib/lua/std_pair.i | 3 - Lib/lua/std_string.i | 3 - Lib/lua/std_vector.i | 3 - Lib/lua/stl.i | 3 - Lib/lua/typemaps.i | 3 - Lib/lua/wchar.i | 6 +- Lib/math.i | 3 - Lib/modula3/modula3.swg | 3 - Lib/modula3/modula3head.swg | 3 - Lib/modula3/typemaps.i | 3 - Lib/mzscheme/mzrun.swg | 3 - Lib/mzscheme/mzscheme.swg | 3 - Lib/mzscheme/std_common.i | 3 - Lib/mzscheme/std_map.i | 3 - Lib/mzscheme/std_pair.i | 3 - Lib/mzscheme/std_string.i | 3 - Lib/mzscheme/std_vector.i | 3 - Lib/mzscheme/stl.i | 3 - Lib/mzscheme/typemaps.i | 3 - Lib/ocaml/cstring.i | 3 - Lib/ocaml/director.swg | 3 - Lib/ocaml/ocaml.i | 3 - Lib/ocaml/ocamldec.swg | 3 - Lib/ocaml/std_common.i | 3 - Lib/ocaml/std_deque.i | 3 - Lib/ocaml/std_list.i | 3 - Lib/ocaml/std_map.i | 3 - Lib/ocaml/std_pair.i | 3 - Lib/ocaml/std_string.i | 3 - Lib/ocaml/std_vector.i | 3 - Lib/ocaml/stl.i | 3 - Lib/ocaml/typecheck.i | 3 - Lib/ocaml/typemaps.i | 3 - Lib/octave/octcontainer.swg | 3 - Lib/octave/octiterators.swg | 3 - Lib/perl5/perlmain.i | 3 - Lib/perl5/reference.i | 3 - Lib/perl5/std_common.i | 3 - Lib/perl5/std_list.i | 3 - Lib/perl5/std_map.i | 3 - Lib/perl5/std_pair.i | 3 - Lib/perl5/std_vector.i | 3 - Lib/perl5/stl.i | 3 - Lib/perl5/typemaps.i | 3 - Lib/php/const.i | 3 - Lib/php/globalvar.i | 3 - Lib/php/php.swg | 3 - Lib/php/phpkw.swg | 3 - Lib/php/phprun.swg | 3 - Lib/php/std_common.i | 3 - Lib/php/std_map.i | 3 - Lib/php/std_pair.i | 3 - Lib/php/std_string.i | 3 - Lib/php/std_vector.i | 3 - Lib/php/stl.i | 3 - Lib/php/typemaps.i | 3 - Lib/pike/pike.swg | 3 - Lib/pike/pikerun.swg | 3 - Lib/pike/std_string.i | 3 - Lib/pointer.i | 3 - Lib/python/ccomplex.i | 3 - Lib/python/director.swg | 3 - Lib/python/embed15.i | 3 - Lib/python/file.i | 4 - Lib/python/pycontainer.swg | 3 - Lib/python/pyiterators.swg | 3 - Lib/python/pyrun.swg | 3 - Lib/python/typemaps.i | 3 - Lib/ruby/director.swg | 3 - Lib/ruby/rubyautodoc.swg | 15 +- Lib/ruby/rubycontainer.swg | 3 - Lib/ruby/rubycontainer_extended.swg | 24 +- Lib/ruby/rubyiterators.swg | 3 - Lib/ruby/rubyprimtypes.swg | 4 - Lib/ruby/rubyrun.swg | 3 - Lib/ruby/rubystdautodoc.swg | 12 +- Lib/ruby/rubytracking.swg | 3 - Lib/ruby/rubywstrings.swg | 20 +- Lib/ruby/stl.i | 3 - Lib/ruby/typemaps.i | 3 - Lib/std/_std_deque.i | 3 - Lib/std_except.i | 3 - Lib/stdint.i | 3 - Lib/stl.i | 3 - Lib/swigarch.i | 3 - Lib/swigrun.i | 3 - Lib/tcl/mactclinit.c | 93 - Lib/tcl/mactkinit.c | 3 - Lib/tcl/std_common.i | 3 - Lib/tcl/std_pair.i | 3 - Lib/tcl/std_vector.i | 3 - Lib/tcl/stl.i | 3 - Lib/tcl/tcl8.swg | 3 - Lib/tcl/tclinterp.i | 3 - Lib/tcl/tclopers.swg | 3 - Lib/tcl/tclresult.i | 3 - Lib/tcl/tclrun.swg | 3 - Lib/tcl/tclsh.i | 3 - Lib/tcl/tclwstrings.swg | 3 - Lib/tcl/typemaps.i | 3 - Lib/tcl/wish.i | 3 - Lib/typemaps/attribute.swg | 3 - Lib/typemaps/carrays.swg | 3 - Lib/typemaps/cdata.swg | 3 - Lib/typemaps/cmalloc.swg | 3 - Lib/typemaps/cpointer.swg | 3 - Lib/typemaps/cstrings.swg | 3 - Lib/typemaps/exception.swg | 3 - Lib/typemaps/ptrtypes.swg | 3 - Lib/typemaps/swigtypemaps.swg | 3 - Lib/typemaps/typemaps.swg | 3 - Lib/uffi/uffi.swg | 2 - Lib/wchar.i | 3 - Lib/windows.i | 3 - Makefile.in | 56 +- README | 57 +- Source/CParse/cparse.h | 8 +- Source/CParse/cscanner.c | 8 +- Source/CParse/parser.y | 8 +- Source/CParse/templ.c | 8 +- Source/CParse/util.c | 8 +- Source/DOH/base.c | 12 +- Source/DOH/doh.h | 14 +- Source/DOH/dohint.h | 15 +- Source/DOH/file.c | 12 +- Source/DOH/fio.c | 12 +- Source/DOH/hash.c | 12 +- Source/DOH/list.c | 12 +- Source/DOH/memory.c | 12 +- Source/DOH/string.c | 12 +- Source/DOH/void.c | 12 +- Source/Include/swigwarn.h | 10 +- Source/Modules/allegrocl.cxx | 8 +- Source/Modules/allocate.cxx | 8 +- Source/Modules/browser.cxx | 8 +- Source/Modules/cffi.cxx | 8 +- Source/Modules/chicken.cxx | 8 +- Source/Modules/clisp.cxx | 8 +- Source/Modules/contract.cxx | 8 +- Source/Modules/csharp.cxx | 8 +- Source/Modules/directors.cxx | 8 +- Source/Modules/emit.cxx | 8 +- Source/Modules/guile.cxx | 8 +- Source/Modules/java.cxx | 8 +- Source/Modules/lang.cxx | 8 +- Source/Modules/lua.cxx | 8 +- Source/Modules/main.cxx | 8 +- Source/Modules/modula3.cxx | 8 +- Source/Modules/module.cxx | 8 +- Source/Modules/mzscheme.cxx | 8 +- Source/Modules/ocaml.cxx | 8 +- Source/Modules/octave.cxx | 8 +- Source/Modules/overload.cxx | 8 +- Source/Modules/perl5.cxx | 12 +- Source/Modules/php.cxx | 8 +- Source/Modules/pike.cxx | 8 +- Source/Modules/python.cxx | 8 +- Source/Modules/r.cxx | 8 +- Source/Modules/ruby.cxx | 8 +- Source/Modules/s-exp.cxx | 8 +- Source/Modules/swigmain.cxx | 12 +- Source/Modules/swigmod.h | 8 +- Source/Modules/tcl8.cxx | 8 +- Source/Modules/typepass.cxx | 8 +- Source/Modules/uffi.cxx | 8 +- Source/Modules/utils.cxx | 8 +- Source/Modules/xml.cxx | 8 +- Source/Preprocessor/cpp.c | 8 +- Source/Preprocessor/expr.c | 8 +- Source/Preprocessor/preprocessor.h | 8 +- Source/Swig/cwrap.c | 8 +- Source/Swig/deprecate.c | 8 +- Source/Swig/error.c | 8 +- Source/Swig/fragment.c | 8 +- Source/Swig/getopt.c | 8 +- Source/Swig/include.c | 8 +- Source/Swig/misc.c | 8 +- Source/Swig/naming.c | 8 +- Source/Swig/parms.c | 8 +- Source/Swig/scanner.c | 8 +- Source/Swig/stype.c | 8 +- Source/Swig/swig.h | 8 +- Source/Swig/swigfile.h | 8 +- Source/Swig/swigopt.h | 8 +- Source/Swig/swigparm.h | 8 +- Source/Swig/swigscan.h | 8 +- Source/Swig/swigtree.h | 8 +- Source/Swig/swigwrap.h | 8 +- Source/Swig/symbol.c | 8 +- Source/Swig/tree.c | 8 +- Source/Swig/typemap.c | 8 +- Source/Swig/typeobj.c | 8 +- Source/Swig/typesys.c | 8 +- Source/Swig/wrapfunc.c | 8 +- configure.in | 4 +- 432 files changed, 1381 insertions(+), 12563 deletions(-) create mode 100644 COPYRIGHT delete mode 100644 Examples/GIFPlot/Chicken/check.list delete mode 100644 Examples/GIFPlot/Chicken/full/Makefile delete mode 100644 Examples/GIFPlot/Chicken/full/README delete mode 100644 Examples/GIFPlot/Chicken/full/cmap delete mode 100644 Examples/GIFPlot/Chicken/full/gifplot.i delete mode 100644 Examples/GIFPlot/Chicken/full/test-gifplot.scm delete mode 100644 Examples/GIFPlot/Chicken/simple/Makefile delete mode 100644 Examples/GIFPlot/Chicken/simple/README delete mode 100644 Examples/GIFPlot/Chicken/simple/simple.i delete mode 100644 Examples/GIFPlot/Chicken/simple/test-simple.scm delete mode 100644 Examples/GIFPlot/Common-Lisp/full/cmap delete mode 100644 Examples/GIFPlot/Common-Lisp/full/gifplot.i delete mode 100644 Examples/GIFPlot/Common-Lisp/full/runme.lisp delete mode 100644 Examples/GIFPlot/Guile/check.list delete mode 100644 Examples/GIFPlot/Guile/full/Makefile delete mode 100644 Examples/GIFPlot/Guile/full/README delete mode 100644 Examples/GIFPlot/Guile/full/cmap delete mode 100644 Examples/GIFPlot/Guile/full/gifplot.i delete mode 100644 Examples/GIFPlot/Guile/full/runme.scm delete mode 100644 Examples/GIFPlot/Guile/simple/Makefile delete mode 100644 Examples/GIFPlot/Guile/simple/README delete mode 100644 Examples/GIFPlot/Guile/simple/runme.scm delete mode 100644 Examples/GIFPlot/Guile/simple/simple.i delete mode 100644 Examples/GIFPlot/Include/gifplot.h delete mode 100644 Examples/GIFPlot/Interface/gifplot.i delete mode 100644 Examples/GIFPlot/Java/check.list delete mode 100644 Examples/GIFPlot/Java/full/Makefile delete mode 100644 Examples/GIFPlot/Java/full/README delete mode 100644 Examples/GIFPlot/Java/full/cmap delete mode 100644 Examples/GIFPlot/Java/full/gifplot.i delete mode 100644 Examples/GIFPlot/Java/full/runme.java delete mode 100644 Examples/GIFPlot/Java/shadow/Makefile delete mode 100644 Examples/GIFPlot/Java/shadow/README delete mode 100644 Examples/GIFPlot/Java/shadow/cmap delete mode 100644 Examples/GIFPlot/Java/shadow/runme.java delete mode 100644 Examples/GIFPlot/Java/simple/Makefile delete mode 100644 Examples/GIFPlot/Java/simple/README delete mode 100644 Examples/GIFPlot/Java/simple/runme.java delete mode 100644 Examples/GIFPlot/Java/simple/simple.i delete mode 100644 Examples/GIFPlot/Lib/Makefile.in delete mode 100644 Examples/GIFPlot/Lib/color.c delete mode 100644 Examples/GIFPlot/Lib/font.c delete mode 100644 Examples/GIFPlot/Lib/frame.c delete mode 100644 Examples/GIFPlot/Lib/gif.c delete mode 100644 Examples/GIFPlot/Lib/matrix.c delete mode 100644 Examples/GIFPlot/Lib/pixmap.c delete mode 100644 Examples/GIFPlot/Lib/plot2d.c delete mode 100644 Examples/GIFPlot/Lib/plot3d.c delete mode 100644 Examples/GIFPlot/Makefile.in delete mode 100644 Examples/GIFPlot/Ocaml/check.list delete mode 100644 Examples/GIFPlot/Ocaml/full/Makefile delete mode 100644 Examples/GIFPlot/Ocaml/full/README delete mode 100644 Examples/GIFPlot/Ocaml/full/cmap delete mode 100644 Examples/GIFPlot/Ocaml/full/gifplot.i delete mode 100644 Examples/GIFPlot/Ocaml/full/runme.ml delete mode 100644 Examples/GIFPlot/Ocaml/simple/Makefile delete mode 100644 Examples/GIFPlot/Ocaml/simple/cmap delete mode 100644 Examples/GIFPlot/Ocaml/simple/runme.ml delete mode 100644 Examples/GIFPlot/Ocaml/simple/simple.i delete mode 100644 Examples/GIFPlot/Perl5/check.list delete mode 100644 Examples/GIFPlot/Perl5/full/Makefile delete mode 100644 Examples/GIFPlot/Perl5/full/README delete mode 100644 Examples/GIFPlot/Perl5/full/cmap delete mode 100644 Examples/GIFPlot/Perl5/full/gifplot.i delete mode 100644 Examples/GIFPlot/Perl5/full/runme.pl delete mode 100644 Examples/GIFPlot/Perl5/shadow/Makefile delete mode 100644 Examples/GIFPlot/Perl5/shadow/README delete mode 100644 Examples/GIFPlot/Perl5/shadow/cmap delete mode 100644 Examples/GIFPlot/Perl5/shadow/runme.pl delete mode 100644 Examples/GIFPlot/Perl5/simple/Makefile delete mode 100644 Examples/GIFPlot/Perl5/simple/README delete mode 100644 Examples/GIFPlot/Perl5/simple/runme.pl delete mode 100644 Examples/GIFPlot/Perl5/simple/simple.i delete mode 100644 Examples/GIFPlot/Php/check.list delete mode 100644 Examples/GIFPlot/Php/full/Makefile delete mode 100644 Examples/GIFPlot/Php/full/README delete mode 100644 Examples/GIFPlot/Php/full/cmap delete mode 100644 Examples/GIFPlot/Php/full/gifplot.i delete mode 100644 Examples/GIFPlot/Php/full/runme.php delete mode 100644 Examples/GIFPlot/Php/shadow/Makefile delete mode 100644 Examples/GIFPlot/Php/shadow/README delete mode 100644 Examples/GIFPlot/Php/shadow/cmap delete mode 100644 Examples/GIFPlot/Php/shadow/runme.php delete mode 100644 Examples/GIFPlot/Php/simple/Makefile delete mode 100644 Examples/GIFPlot/Php/simple/README delete mode 100644 Examples/GIFPlot/Php/simple/runme.php delete mode 100644 Examples/GIFPlot/Php/simple/simple.i delete mode 100644 Examples/GIFPlot/Pike/check.list delete mode 100644 Examples/GIFPlot/Pike/simple/Makefile delete mode 100644 Examples/GIFPlot/Pike/simple/README delete mode 100644 Examples/GIFPlot/Pike/simple/runme.pike delete mode 100644 Examples/GIFPlot/Pike/simple/simple.i delete mode 100644 Examples/GIFPlot/Python/check.list delete mode 100644 Examples/GIFPlot/Python/full/Makefile delete mode 100644 Examples/GIFPlot/Python/full/README delete mode 100644 Examples/GIFPlot/Python/full/cmap delete mode 100644 Examples/GIFPlot/Python/full/gifplot.i delete mode 100644 Examples/GIFPlot/Python/full/runme.py delete mode 100644 Examples/GIFPlot/Python/shadow/Makefile delete mode 100644 Examples/GIFPlot/Python/shadow/README delete mode 100644 Examples/GIFPlot/Python/shadow/cmap delete mode 100644 Examples/GIFPlot/Python/shadow/runme.py delete mode 100644 Examples/GIFPlot/Python/simple/Makefile delete mode 100644 Examples/GIFPlot/Python/simple/README delete mode 100644 Examples/GIFPlot/Python/simple/runme.py delete mode 100644 Examples/GIFPlot/Python/simple/simple.i delete mode 100644 Examples/GIFPlot/README delete mode 100644 Examples/GIFPlot/Ruby/check.list delete mode 100644 Examples/GIFPlot/Ruby/full/Makefile delete mode 100644 Examples/GIFPlot/Ruby/full/README delete mode 100644 Examples/GIFPlot/Ruby/full/cmap delete mode 100644 Examples/GIFPlot/Ruby/full/gifplot.i delete mode 100644 Examples/GIFPlot/Ruby/full/runme.rb delete mode 100644 Examples/GIFPlot/Ruby/shadow/Makefile delete mode 100644 Examples/GIFPlot/Ruby/shadow/README delete mode 100644 Examples/GIFPlot/Ruby/shadow/cmap delete mode 100644 Examples/GIFPlot/Ruby/shadow/runme.rb delete mode 100644 Examples/GIFPlot/Ruby/simple/Makefile delete mode 100644 Examples/GIFPlot/Ruby/simple/README delete mode 100644 Examples/GIFPlot/Ruby/simple/runme.rb delete mode 100644 Examples/GIFPlot/Ruby/simple/simple.i delete mode 100644 Examples/GIFPlot/Tcl/check.list delete mode 100644 Examples/GIFPlot/Tcl/full/Makefile delete mode 100644 Examples/GIFPlot/Tcl/full/README delete mode 100644 Examples/GIFPlot/Tcl/full/cmap delete mode 100644 Examples/GIFPlot/Tcl/full/gifplot.i delete mode 100644 Examples/GIFPlot/Tcl/full/runme.tcl delete mode 100644 Examples/GIFPlot/Tcl/mandel/Makefile delete mode 100644 Examples/GIFPlot/Tcl/mandel/README delete mode 100644 Examples/GIFPlot/Tcl/mandel/cmap delete mode 100644 Examples/GIFPlot/Tcl/mandel/display.tcl delete mode 100644 Examples/GIFPlot/Tcl/mandel/mandel.i delete mode 100644 Examples/GIFPlot/Tcl/mandel/mandel.tcl delete mode 100644 Examples/GIFPlot/Tcl/simple/Makefile delete mode 100644 Examples/GIFPlot/Tcl/simple/README delete mode 100644 Examples/GIFPlot/Tcl/simple/runme.tcl delete mode 100644 Examples/GIFPlot/Tcl/simple/simple.i delete mode 100644 Examples/chicken/zlib/Makefile delete mode 100644 Examples/chicken/zlib/README.html delete mode 100644 Examples/chicken/zlib/example.i delete mode 100644 Examples/chicken/zlib/test-zlib.scm delete mode 100644 Examples/xml/example_gif.i create mode 100644 LICENSE-GPL create mode 100644 LICENSE-UNIVERSITIES delete mode 100644 Lib/tcl/mactclinit.c diff --git a/ANNOUNCE b/ANNOUNCE index 9ef41142a..2595f7a55 100644 --- a/ANNOUNCE +++ b/ANNOUNCE @@ -1,10 +1,10 @@ -*** ANNOUNCE: SWIG 1.3.40 (in progress) *** +*** ANNOUNCE: SWIG 2.0.0 (in progress) *** http://www.swig.org -We're pleased to announce SWIG-1.3.40, the latest installment in the -SWIG development effort. SWIG-1.3.40 includes a number of bug fixes +We're pleased to announce SWIG-2.0.0, the latest installment in the +SWIG development effort. SWIG-2.0.0 includes a number of bug fixes and enhancements. What is SWIG? @@ -24,11 +24,11 @@ Availability: ------------- The release is available for download on Sourceforge at - http://prdownloads.sourceforge.net/swig/swig-1.3.40.tar.gz + http://prdownloads.sourceforge.net/swig/swig-2.0.0.tar.gz A Windows version is also available at - http://prdownloads.sourceforge.net/swig/swigwin-1.3.40.zip + http://prdownloads.sourceforge.net/swig/swigwin-2.0.0.zip Please report problems with this release to the swig-dev mailing list, details at http://www.swig.org/mail.html. diff --git a/COPYRIGHT b/COPYRIGHT new file mode 100644 index 000000000..45f9d6b45 --- /dev/null +++ b/COPYRIGHT @@ -0,0 +1,63 @@ +SWIG Copyright and Authors +-------------------------- + +Copyright (c) 1995-2010 The SWIG Developers +Copyright (c) 2005-2006 Arizona Board of Regents (University of Arizona). +Copyright (c) 1998-2005 University of Chicago. +Copyright (c) 1995-1998 The University of Utah and the Regents of the University of California + +Portions also copyrighted by: + Network Applied Communication Laboratory, Inc + Information-technology Promotion Agency, Japan + +Active SWIG Developers: + William Fulton (wsf@fultondesigns.co.uk) (SWIG core, Java, C#, Windows, Cygwin) + Olly Betts (olly@survex.com) (PHP) + Joseph Wang (joequant@gmail.com) (R) + Xavier Delacour (xavier.delacour@gmail.com) (Octave) + +Past SWIG developers and major contributors include: + Dave Beazley (dave-swig@dabeaz.com) (SWIG core, Python, Tcl, Perl) + Henning Thielemann (swig@henning-thielemann.de) (Modula3) + Matthias Köppe (mkoeppe@mail.math.uni-magdeburg.de) (Guile, MzScheme) + Luigi Ballabio (luigi.ballabio@fastwebnet.it) (STL wrapping) + Mikel Bancroft (mikel@franz.com) (Allegro CL) + Surendra Singhi (efuzzyone@netscape.net) (CLISP, CFFI) + Marcelo Matus (mmatus@acms.arizona.edu) (SWIG core, Python, UTL[python,perl,tcl,ruby]) + Art Yerkes (ayerkes@speakeasy.net) (Ocaml) + Lyle Johnson (lyle@users.sourceforge.net) (Ruby) + Charlie Savage (cfis@interserv.com) (Ruby) + Thien-Thi Nguyen (ttn@glug.org) (build/test/misc) + Richard Palmer (richard@magicality.org) (PHP) + Sam Liddicott - Anonova Ltd (saml@liddicott.com) (PHP) + Tim Hockin - Sun Microsystems (thockin@sun.com) (PHP) + Kevin Ruland (PHP) + Shibukawa Yoshiki (Japanese Translation) + Jason Stewart (jason@openinformatics.com) (Perl5) + Loic Dachary (Perl5) + David Fletcher (Perl5) + Gary Holt (Perl5) + Masaki Fukushima (Ruby) + Scott Michel (scottm@cs.ucla.edu) (Java directors) + Tiger Feng (songyanf@cs.uchicago.edu) (SWIG core) + Mark Rose (mrose@stm.lbl.gov) (Directors) + Jonah Beckford (beckford@usermail.com) (CHICKEN) + Ahmon Dancy (dancy@franz.com) (Allegro CL) + Dirk Gerrits (Allegro CL) + Neil Cawse (C#) + Harco de Hilster (Java) + Alexey Dyachenko (dyachenko@fromru.com) (Tcl) + Bob Techentin (Tcl) + Martin Froehlich (Guile) + Marcio Luis Teixeira (Guile) + Duncan Temple Lang (R) + Miklos Vajna (PHP directors) + Mark Gossage (mark@gossage.cjb.net) (Lua) + Gonzalo Garramuno (ggarra@advancedsl.com.ar) (Ruby, Ruby's UTL) + John Lenz (Guile, MzScheme updates, Chicken module, runtime system) + +Past contributors include: + James Michael DuPont, Clark McGrew, Dustin Mitchell, Ian Cooke, Catalin Dumitrescu, Baran + Kovuk, Oleg Tolmatcev, Tal Shalif, Lluis Padro, Chris Seatory, Igor Bely, Robin Dunn + (See CHANGES and CHANGES.current for a more complete list). + diff --git a/Doc/Manual/Sections.html b/Doc/Manual/Sections.html index 789efc129..ab47ed8ee 100644 --- a/Doc/Manual/Sections.html +++ b/Doc/Manual/Sections.html @@ -6,7 +6,7 @@

SWIG-1.3 Development Documentation

-Last update : SWIG-1.3.40 (in progress) +Last update : SWIG-2.0.0 (in progress)

Sections

diff --git a/Examples/GIFPlot/Chicken/check.list b/Examples/GIFPlot/Chicken/check.list deleted file mode 100644 index e75ee586a..000000000 --- a/Examples/GIFPlot/Chicken/check.list +++ /dev/null @@ -1,3 +0,0 @@ -# see top-level Makefile.in -full -simple diff --git a/Examples/GIFPlot/Chicken/full/Makefile b/Examples/GIFPlot/Chicken/full/Makefile deleted file mode 100644 index 2ae4fd7ea..000000000 --- a/Examples/GIFPlot/Chicken/full/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../preinst-swig -INTERFACE = gifplot.i -SRCS = -CXXSRCS = -TARGET = gifplot -INCLUDE = -I. -I../../Include -SWIGOPT = -I../../Include -CFLAGS = -VARIANT = -LIBS = -L../.. -lgifplot -lm - -# comment the following two lines to build a dynamic so file -CHICKEN_MAIN = test-gifplot.scm -VARIANT = _static - -all:: $(TARGET) - -$(TARGET): $(INTERFACE) $(SRCS) - $(MAKE) -f $(TOP)/Makefile \ - SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \ - INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='$(TARGET)' \ - SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT) - -clean:: - $(MAKE) -f $(TOP)/Makefile chicken_clean - rm -f gifplot.scm image.gif - rm -f $(TARGET) diff --git a/Examples/GIFPlot/Chicken/full/README b/Examples/GIFPlot/Chicken/full/README deleted file mode 100644 index e5ddd7af1..000000000 --- a/Examples/GIFPlot/Chicken/full/README +++ /dev/null @@ -1,6 +0,0 @@ -This example runs the entire gifplot.h header file through SWIG without -any changes. The Scheme program 'test-gifplot.scm' does something a -little more interesting. You'll have to go look at the header file to -get a complete listing of the functions. - -`make' will build a static binary. Run ./gifplot to test it. diff --git a/Examples/GIFPlot/Chicken/full/cmap b/Examples/GIFPlot/Chicken/full/cmap deleted file mode 100644 index a20c331a9573dd8443380680bfe2cc428780d8a9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 768 zcmZQzpd(=A5)hSEP}Mdtvvzdz4h)M)OwTDSuW4%Uoiu&!q7`d5@7R0z#JS5i?>&C` z?#s{r^Z@9-XXO?YlTlLFHMX#G@$?UkN=VBFxv-;m^2~WlR;}N<`@pd?7q8!a^y1xT znmh34m-nxpKDd4D;+bOy_iW#^cE#d(Gbi_Tw$xXZ7G$R-M27|XxI5We80l&#%Snpx zbFrd(h8Vt}lCeu@T6xFJRlCpJeMef510DGC$^DyG&YwK8f9ICexact (round (max (min cc 239) 0))))) - (gifplot:Plot3D-solidquad p3 x y z1 (+ x dx) y z2 (+ x dx) (+ y dy) - z3 x (+ y dy) z4 - (gifplot:int->Pixel (+ c 16)))) - (y-loop (+ y dy) (+ j 1))))) - (x-loop (+ x dx) (+ i 1))))))) - -(display "Making a nice 3D plot...\n") -(drawsolid) - -(gifplot:FrameBuffer-writeGIF frame cmap "image.gif") -(display "Wrote image.gif\n") diff --git a/Examples/GIFPlot/Chicken/simple/Makefile b/Examples/GIFPlot/Chicken/simple/Makefile deleted file mode 100644 index 484e58390..000000000 --- a/Examples/GIFPlot/Chicken/simple/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../preinst-swig -INTERFACE = simple.i -SRCS = -CXXSRCS = -TARGET = simple -INCLUDE = -I. -I../../Include -SWIGOPT = -I../../Include -CFLAGS = -VARIANT = -LIBS = -L../.. -lgifplot -lm - -# comment the following two lines to build a dynamic so file -CHICKEN_MAIN = test-simple.scm -VARIANT = _static - -all:: $(TARGET) - -$(TARGET): $(INTERFACE) $(SRCS) - $(MAKE) -f $(TOP)/Makefile \ - SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \ - INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='$(TARGET)' \ - SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT) - -clean:: - $(MAKE) -f $(TOP)/Makefile chicken_clean - rm -f simple.scm image.gif - rm -f $(TARGET) diff --git a/Examples/GIFPlot/Chicken/simple/README b/Examples/GIFPlot/Chicken/simple/README deleted file mode 100644 index 3b138f381..000000000 --- a/Examples/GIFPlot/Chicken/simple/README +++ /dev/null @@ -1,5 +0,0 @@ -This is a very minimalistic example in which just a few functions -and constants from library are wrapped and used to draw some simple -shapes. - -`make' will build an exe. Run ./simple to test it. diff --git a/Examples/GIFPlot/Chicken/simple/simple.i b/Examples/GIFPlot/Chicken/simple/simple.i deleted file mode 100644 index 23ac8a856..000000000 --- a/Examples/GIFPlot/Chicken/simple/simple.i +++ /dev/null @@ -1,34 +0,0 @@ -/* This example shows a very simple interface wrapping a few - primitive declarations */ - -%module simple -%{ -#include "gifplot.h" -%} - -typedef unsigned int Pixel; - -/* Here are a few useful functions */ - -ColorMap *new_ColorMap(char *filename = 0); -void delete_ColorMap(ColorMap *cmap); - -FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height); -void delete_FrameBuffer(FrameBuffer *frame); -void FrameBuffer_clear(FrameBuffer *frame, Pixel color); -void FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -void FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -void FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color); -int FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename); - -/* And some useful constants, which we redefine (from gifplot.h) so - that SWIG sees them */ -#define BLACK 0 -#define WHITE 1 -#define RED 2 -#define GREEN 3 -#define BLUE 4 -#define YELLOW 5 -#define CYAN 6 -#define MAGENTA 7 - diff --git a/Examples/GIFPlot/Chicken/simple/test-simple.scm b/Examples/GIFPlot/Chicken/simple/test-simple.scm deleted file mode 100644 index 43250d8e9..000000000 --- a/Examples/GIFPlot/Chicken/simple/test-simple.scm +++ /dev/null @@ -1,29 +0,0 @@ -;;; Draw some simple shapes - -(declare (uses simple)) - -(display "Drawing some basic shapes\n") - -(define cmap (simple:new-ColorMap #f)) -(define f (simple:new-FrameBuffer 400 400)) - -;; Clear the picture -(simple:FrameBuffer-clear f (simple:BLACK)) - -;; Make a red box -(simple:FrameBuffer-box f 40 40 200 200 (simple:RED)) - -;; Make a blue circle -(simple:FrameBuffer-circle f 200 200 40 (simple:BLUE)) - -;; Make green line -(simple:FrameBuffer-line f 10 390 390 200 (simple:GREEN)) - -;; Write an image out to disk - -(simple:FrameBuffer-writeGIF f cmap "image.gif") -(display "Wrote image.gif\n") - -(simple:delete-FrameBuffer f) -(simple:delete-ColorMap cmap) - diff --git a/Examples/GIFPlot/Common-Lisp/full/cmap b/Examples/GIFPlot/Common-Lisp/full/cmap deleted file mode 100644 index a20c331a9573dd8443380680bfe2cc428780d8a9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 768 zcmZQzpd(=A5)hSEP}Mdtvvzdz4h)M)OwTDSuW4%Uoiu&!q7`d5@7R0z#JS5i?>&C` z?#s{r^Z@9-XXO?YlTlLFHMX#G@$?UkN=VBFxv-;m^2~WlR;}N<`@pd?7q8!a^y1xT znmh34m-nxpKDd4D;+bOy_iW#^cE#d(Gbi_Tw$xXZ7G$R-M27|XxI5We80l&#%Snpx zbFrd(h8Vt}lCeu@T6xFJRlCpJeMef510DGC$^DyG&YwK8f9IC&C` z?#s{r^Z@9-XXO?YlTlLFHMX#G@$?UkN=VBFxv-;m^2~WlR;}N<`@pd?7q8!a^y1xT znmh34m-nxpKDd4D;+bOy_iW#^cE#d(Gbi_Tw$xXZ7G$R-M27|XxI5We80l&#%Snpx zbFrd(h8Vt}lCeu@T6xFJRlCpJeMef510DGC$^DyG&YwK8f9IC -#include -#include -#include -#include -#include - -#ifndef GIFPLOT_H - -#ifdef SWIG -%nodefault; -#endif - -/* Pixel is 8-bits */ - -typedef unsigned char Pixel; -typedef float Zvalue; - -/* ------------------------------------------------------------------------ - ColorMap - - Definition and methods for colormaps - ------------------------------------------------------------------------ */ - -typedef struct ColorMap { - unsigned char *cmap; - char *name; -} ColorMap; - -extern ColorMap *new_ColorMap(char *filename); -extern void delete_ColorMap(ColorMap *c); -extern void ColorMap_default(ColorMap *c); -extern void ColorMap_assign(ColorMap *c, int index, int r, int g, int b); -extern int ColorMap_getitem(ColorMap *c, int index); -extern void ColorMap_setitem(ColorMap *c, int index, int value); -extern int ColorMap_write(ColorMap *c, char *filename); - -/* Some default colors */ - -#define BLACK 0 -#define WHITE 1 -#define RED 2 -#define GREEN 3 -#define BLUE 4 -#define YELLOW 5 -#define CYAN 6 -#define MAGENTA 7 - -/*------------------------------------------------------------------------- - FrameBuffer - - This structure defines a simple 8 bit framebuffer. - ------------------------------------------------------------------------- */ - -typedef struct FrameBuffer { - Pixel **pixels; - Zvalue **zbuffer; - unsigned int height; - unsigned int width; - int xmin; /* These are used for clipping */ - int ymin; - int xmax; - int ymax; -} FrameBuffer; - -#define ZMIN 1e+36 - -/* FrameBuffer Methods */ - -extern FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height); -extern void delete_FrameBuffer(FrameBuffer *frame); -extern int FrameBuffer_resize(FrameBuffer *frame, int width, int height); -extern void FrameBuffer_clear(FrameBuffer *frame, Pixel color); -extern void FrameBuffer_plot(FrameBuffer *frame, int x, int y, Pixel color); -extern void FrameBuffer_horizontal(FrameBuffer *frame, int xmin, int xmax, int y, Pixel color); -extern void FrameBuffer_horizontalinterp(FrameBuffer *f, int xmin, int xmax, int y, Pixel c1, Pixel c2); -extern void FrameBuffer_vertical(FrameBuffer *frame, int ymin, int ymax, int x, Pixel color); -extern void FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -extern void FrameBuffer_solidbox(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -extern void FrameBuffer_interpbox(FrameBuffer *f, int x1, int y1, int x2, int y2, Pixel c1, Pixel c2, Pixel c3, Pixel c4); -extern void FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color); -extern void FrameBuffer_solidcircle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color); -extern void FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -extern void FrameBuffer_setclip(FrameBuffer *frame, int xmin, int ymin, int xmax, int ymax); -extern void FrameBuffer_noclip(FrameBuffer *frame); -extern int FrameBuffer_makeGIF(FrameBuffer *frame, ColorMap *cmap, void *buffer, unsigned int maxsize); -extern int FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename); -extern void FrameBuffer_zresize(FrameBuffer *f, int width, int height); -extern void FrameBuffer_zclear(FrameBuffer *f); -extern void FrameBuffer_solidtriangle(FrameBuffer *f, int x1, int y1, int x2, int y2, int x3, int y3, Pixel c); -extern void FrameBuffer_interptriangle(FrameBuffer *f, int tx1, int ty1, Pixel c1, - int tx2, int ty2, Pixel c2, int tx3, int ty3, Pixel c3); - -#define HORIZONTAL 1 -#define VERTICAL 2 - -extern void FrameBuffer_drawchar(FrameBuffer *frame, int x, int y, int fgcolor, int bgcolor, char chr, int orientation); -extern void FrameBuffer_drawstring(FrameBuffer *f, int x, int y, int fgcolor, int bgcolor, char *text, int orientation); - -/* ------------------------------------------------------------------------ - PixMap - - The equivalent of "bit-maps". - ------------------------------------------------------------------------ */ - -typedef struct PixMap { - int width; - int height; - int centerx; - int centery; - int *map; -} PixMap; - -/* PIXMAP methods */ - -extern PixMap *new_PixMap(int width, int height, int centerx, int centery); -extern void delete_PixMap(PixMap *pm); -extern void PixMap_set(PixMap *pm, int x, int y, int pix); -extern void FrameBuffer_drawpixmap(FrameBuffer *f, PixMap *pm, int x, int y, int fgcolor, int bgcolor); - -#define GIFPLOT_TRANSPARENT 0 -#define GIFPLOT_FOREGROUND 1 -#define GIFPLOT_BACKGROUND 2 - -/* ------------------------------------------------------------------------ - Plot2D - - Definition and methods for 2D plots. - ------------------------------------------------------------------------ */ - -typedef struct Plot2D { - FrameBuffer *frame; /* what frame buffer are we using */ - int view_xmin; /* Minimum coordinates of view region */ - int view_ymin; - int view_xmax; /* Maximum coordinates of view region */ - int view_ymax; - double xmin; /* Minimum coordinates of plot region */ - double ymin; - double xmax; /* Maximum coordinates of plot region */ - double ymax; - int xscale; /* Type of scaling (LINEAR, LOG, etc..) */ - int yscale; - double dx; /* Private scaling parameters */ - double dy; -} Plot2D; - -/* 2D Plot methods */ - -extern Plot2D *new_Plot2D(FrameBuffer *frame,double xmin,double ymin, double xmax, double ymax); -extern void delete_Plot2D(Plot2D *p2); -extern Plot2D *Plot2D_copy(Plot2D *p2); -extern void Plot2D_clear(Plot2D *p2, Pixel c); -extern void Plot2D_setview(Plot2D *p2, int vxmin, int vymin, int vxmax, int vymax); -extern void Plot2D_setrange(Plot2D *p2, double xmin, double ymin, double xmax, double ymax); -extern void Plot2D_setscale(Plot2D *p2, int xscale, int yscale); -extern void Plot2D_plot(Plot2D *p2, double x, double y, Pixel color); -extern void Plot2D_box(Plot2D *p2, double x1, double y1, double x2, double y2, Pixel color); -extern void Plot2D_solidbox(Plot2D *p2, double x1, double y1,double x2, double y2, Pixel color); -extern void Plot2D_interpbox(Plot2D *p2, double x1, double y1, double x2, double y2, Pixel c1, Pixel c2, Pixel c3, Pixel c4); -extern void Plot2D_circle(Plot2D *p2, double x, double y, double radius, Pixel color); -extern void Plot2D_solidcircle(Plot2D *p2, double x, double y, double radius, Pixel color); -extern void Plot2D_line(Plot2D *p2, double x1, double y1, double x2, double y2, Pixel color); -extern void Plot2D_start(Plot2D *p2); -extern void Plot2D_drawpixmap(Plot2D *p2, PixMap *pm, double x, double y, Pixel color, Pixel bgcolor); -extern void Plot2D_xaxis(Plot2D *p2, double x, double y, double xtick, int ticklength, Pixel c); -extern void Plot2D_yaxis(Plot2D *p2, double x, double y, double ytick, int ticklength, Pixel c); -extern void Plot2D_triangle(Plot2D *p2, double x1, double y1, double x2, double y2, double x3, double y3, Pixel c); -extern void Plot2D_solidtriangle(Plot2D *p2, double x1, double y1, double x2, double y2, double x3, double y3, Pixel c); -extern void Plot2D_interptriangle(Plot2D *p2, double x1, double y1, Pixel c1, - double x2, double y2, Pixel c2, - double x3, double y3, Pixel c3); - -#define LINEAR 10 -#define LOG 11 - -/* ----------------------------------------------------------------------- - Matrix - - Operations on 4x4 transformation matrices and vectors. - Matrices are represented as a double array of 16 elements - ----------------------------------------------------------------------- */ - -typedef double *Matrix; -typedef struct GL_Vector { - double x; - double y; - double z; - double w; -} GL_Vector; - -extern Matrix new_Matrix(); -extern void delete_Matrix(Matrix a); -extern Matrix Matrix_copy(Matrix a); -extern void Matrix_multiply(Matrix a, Matrix b, Matrix c); -extern void Matrix_identity(Matrix a); -extern void Matrix_zero(Matrix a); -extern void Matrix_transpose(Matrix a, Matrix result); -extern void Matrix_invert(Matrix a, Matrix inva); -extern void Matrix_transform(Matrix a, GL_Vector *r, GL_Vector *t); -extern void Matrix_transform4(Matrix a, double rx, double ry, double rz, - double rw, GL_Vector *t); - -extern void Matrix_print(Matrix a); -extern void Matrix_translate(Matrix a, double tx, double ty, double tz); -extern void Matrix_rotatex(Matrix a, double deg); -extern void Matrix_rotatey(Matrix a, double deg); -extern void Matrix_rotatez(Matrix a, double deg); - -/* ----------------------------------------------------------------------- - Plot3D - - Data Structure for 3-D plots - ------------------------------------------------------------------------ */ - -typedef struct Plot3D { - FrameBuffer *frame; /* Frame buffer being used */ - int view_xmin; /* Viewing region */ - int view_ymin; - int view_xmax; - int view_ymax; - double xmin; /* Bounding box */ - double ymin; - double zmin; - double xmax; - double ymax; - double zmax; - double xcenter; /* Center point */ - double ycenter; - double zcenter; - double fovy; /* Field of view */ - double aspect; /* Aspect ratio */ - double znear; /* near "clipping" plane */ - double zfar; /* far "clipping" plane */ - Matrix center_mat; /* Matrix used for centering the model */ - Matrix model_mat; /* Model rotation matrix */ - Matrix view_mat; /* Viewing matrix */ - Matrix fullmodel_mat; /* Full model matrix. Used by sphere plot */ - Matrix trans_mat; /* Total transformation matrix */ - double lookatz; /* Where is the z-lookat point */ - double xshift; /* Used for translation and stuff */ - double yshift; - double zoom; - int width; - int height; - int pers_mode; /* Perspective mode (private) */ - double ortho_left,ortho_right,ortho_bottom,ortho_top; -} Plot3D; - -extern Plot3D *new_Plot3D(FrameBuffer *frame, double xmin, double ymin, double zmin, - double xmax, double ymax, double zmax); -extern void delete_Plot3D(Plot3D *p3); -extern Plot3D *Plot3D_copy(Plot3D *p3); -extern void Plot3D_clear(Plot3D *p3, Pixel Color); -extern void Plot3D_perspective(Plot3D *p3, double fovy, double znear, double zfar); -extern void Plot3D_ortho(Plot3D *p3, double left, double right, double top, double bottom); -extern void Plot3D_lookat(Plot3D *p3, double z); -extern void Plot3D_autoperspective(Plot3D *p3, double fovy); -extern void Plot3D_autoortho(Plot3D *p3); -extern void Plot3D_rotx(Plot3D *p3, double deg); -extern void Plot3D_roty(Plot3D *p3, double deg); -extern void Plot3D_rotz(Plot3D *p3, double deg); -extern void Plot3D_rotl(Plot3D *p3, double deg); -extern void Plot3D_rotr(Plot3D *p3, double deg); -extern void Plot3D_rotd(Plot3D *p3, double deg); -extern void Plot3D_rotu(Plot3D *p3, double deg); -extern void Plot3D_rotc(Plot3D *p3, double deg); -extern void Plot3D_zoom(Plot3D *p3, double percent); -extern void Plot3D_left(Plot3D *p3, double percent); -extern void Plot3D_right(Plot3D *p3, double percent); -extern void Plot3D_down(Plot3D *p3, double percent); -extern void Plot3D_up(Plot3D *p3, double percent); -extern void Plot3D_center(Plot3D *p3, double cx, double cy); - -extern void Plot3D_plot(Plot3D *p3, double x, double y, double z, Pixel Color); - -extern void Plot3D_setview(Plot3D *p3, int vxmin, int vymin, int vxmax, int vymax); -extern void Plot3D_start(Plot3D *p3); -extern void Plot3D_line(Plot3D *p3, double x1, double y1, double z1, - double x2, double y2, double z2, Pixel color); -extern void Plot3D_triangle(Plot3D *p3, double x1, double y1, double z1, - double x2, double y2, double z2, - double x3, double y3, double z3, Pixel color); -extern void Plot3D_solidtriangle(Plot3D *p3, double x1, double y1, double z1, - double x2, double y2, double z2, - double x3, double y3, double z3, Pixel color); - -extern void Plot3D_interptriangle(Plot3D *p3, - double x1, double y1, double z1, Pixel c1, - double x2, double y2, double z2, Pixel c2, - double x3, double y3, double z3, Pixel c3); - -extern void Plot3D_quad(Plot3D *p3, double x1, double y1, double z1, - double x2, double y2, double z2, - double x3, double y3, double z3, - double x4, double y4, double z4, - Pixel color); - -extern void Plot3D_solidquad(Plot3D *p3, double x1, double y1, double z1, - double x2, double y2, double z2, - double x3, double y3, double z3, - double x4, double y4, double z4, - Pixel color); - -extern void Plot3D_interpquad(Plot3D *p3, double x1, double y1, double z1, Pixel c1, - double x2, double y2, double z2, Pixel c2, - double x3, double y3, double z3, Pixel c3, - double x4, double y4, double z4, Pixel c4); - - -extern void Plot3D_solidsphere(Plot3D *p3, double x, double y, double z, double radius,Pixel c); - -extern void Plot3D_outlinesphere(Plot3D *p3, double x, double y, double z, double radius,Pixel c, Pixel bc); - -extern PixMap PixMap_SQUARE; -extern PixMap PixMap_TRIANGLE; -extern PixMap PixMap_CROSS; - -#endif -#define GIFPLOT_H - - - diff --git a/Examples/GIFPlot/Interface/gifplot.i b/Examples/GIFPlot/Interface/gifplot.i deleted file mode 100644 index fdf661c5e..000000000 --- a/Examples/GIFPlot/Interface/gifplot.i +++ /dev/null @@ -1,264 +0,0 @@ -// -// Graphics module -// -%module gifplot -%{ -#include "gifplot.h" -%} - -#if defined(SWIGJAVA ) || defined(SWIGPHP) - %rename(make_default) ColorMap::default(); -#endif - -%rename(__getitem__) ColorMap::getitem(int index); -%rename(__setitem__) ColorMap::setitem(int index, int value); - -/* Pixel is 8-bits */ - -typedef unsigned char Pixel; -typedef float Zvalue; - -/* ------------------------------------------------------------------------ - ColorMap - - Definition and methods for colormaps - ------------------------------------------------------------------------ */ - -typedef struct ColorMap { - char *name; - -// -// %extend adds some C methods to this structure to make it -// look like a C++ class in Python. -// These are really named things like ColorMap_default, ColorMap_assign, etc... - - %extend { - ColorMap(char *filename); - ~ColorMap(); - void default(); - void assign(int index,int r, int g, int b); - int getitem(int index); - void setitem(int index, int value); - int write(char *filename); - } -} ColorMap; - -/* Some default colors */ - -#define BLACK 0 -#define WHITE 1 -#define RED 2 -#define GREEN 3 -#define BLUE 4 -#define YELLOW 5 -#define CYAN 6 -#define MAGENTA 7 - -/*------------------------------------------------------------------------- - FrameBuffer - - This structure defines a simple 8 bit framebuffer. - ------------------------------------------------------------------------- */ - -typedef struct FrameBuffer { - unsigned int height; - unsigned int width; - int xmin; /* These are used for clipping */ - int ymin; - int xmax; - int ymax; - %extend { - FrameBuffer(unsigned int width, unsigned int height); - ~FrameBuffer(); - void resize(int width, int height); - void clear(Pixel color); - void plot(int x, int y, Pixel color); - void horizontal(int xmin, int xmax, int y, Pixel color); - void horizontalinterp(int xmin, int xmax, int y, Pixel c1, Pixel c2); - void vertical(int ymin, int ymax, int x, Pixel color); - void box(int x1, int y1, int x2, int y2, Pixel color); - void solidbox(int x1, int y1, int x2, int y2, Pixel color); - void interpbox(int x1, int y1, int x2, int y2, Pixel c1, Pixel c2, Pixel c3, Pixel c4); - void circle(int x1, int y1, int radius, Pixel color); - void solidcircle(int x1, int y1, int radius, Pixel color); - void line(int x1, int y1, int x2, int y2, Pixel color); - void setclip(int xmin, int ymin, int xmax, int ymax); - void noclip(); - int makeGIF(ColorMap *cmap, void *buffer, unsigned int maxsize); - void zresize(int width, int height); - void zclear(); - void drawchar(int x, int y, int fgcolor, int bgcolor, char chr, int orientation); - void drawstring(int x, int y, int fgcolor, int bgcolor, char *text, int orientation); - void drawpixmap(PixMap *pm, int x, int y, int fgcolor, int bgcolor); - int writeGIF(ColorMap *cmap, char *filename); - } -} FrameBuffer; - -#define HORIZONTAL 1 -#define VERTICAL 2 - -/* -------------------------------------------------------------------------- - PixMap - - The equivalent of "bit-maps". - -------------------------------------------------------------------------- */ - -/* PIXMAP methods */ - -extern PixMap *new_PixMap(int width, int height, int centerx, int centery); -extern void delete_PixMap(PixMap *pm); -extern void PixMap_set(PixMap *pm, int x, int y, int pix); - -#define GIFPLOT_TRANSPARENT 0 -#define GIFPLOT_FOREGROUND 1 -#define GIFPLOT_BACKGROUND 2 - -/* -------------------------------------------------------------------------- - Plot2D - - Definition and methods for 2D plots. - --------------------------------------------------------------------------- */ - -typedef struct Plot2D { - FrameBuffer *frame; - int view_xmin; /* Minimum coordinates of view region */ - int view_ymin; - int view_xmax; /* Maximum coordinates of view region */ - int view_ymax; - double xmin; /* Minimum coordinates of plot region */ - double ymin; - double xmax; /* Maximum coordinates of plot region */ - double ymax; - int xscale; /* Type of scaling (LINEAR, LOG, etc..) */ - int yscale; - %extend { - Plot2D(FrameBuffer *frame,double xmin,double ymin, double xmax, double ymax); - ~Plot2D(); - Plot2D *copy(); - void clear(Pixel c); - void setview(int vxmin, int vymin, int vxmax, int vymax); - void setrange(double xmin, double ymin, double xmax, double ymax); - void setscale(int xscale, int yscale); - void plot(double x, double y, Pixel color); - void box(double x1, double y1, double x2, double y2, Pixel color); - void solidbox(double x1, double y1, double x2, double y2, Pixel color); - void interpbox(double x1, double y1, double x2, double y2, Pixel c1, Pixel c2, Pixel c3, Pixel c4); - - void circle(double x, double y, double radius, Pixel color); - void solidcircle(double x, double y, double radius, Pixel color); - void line(double x1, double y1, double x2, double y2, Pixel color); - void start(); - void drawpixmap(PixMap *pm, double x, double y, Pixel color, Pixel bgcolor); - void xaxis(double x, double y, double xtick, int ticklength, Pixel color); - void yaxis(double x, double y, double ytick, int ticklength, Pixel color); - void triangle(double x1, double y1, double x2, double y2, double x3, double y3, Pixel c); - - void solidtriangle(double x1, double y1, double x2, double y2, double x3, double y3, Pixel c); - - void interptriangle(double x1, double y1, Pixel c1, - double x2, double y2, Pixel c2, - double x3, double y3, Pixel c3); - - } -} Plot2D; - -#define LINEAR 10 -#define LOG 11 - -/* ------------------------------------------------------------------------------ - Plot3D - - Data Structure for 3-D plots - ------------------------------------------------------------------------------ */ - -typedef struct Plot3D { - FrameBuffer *frame; - int view_xmin; /* Viewing region */ - int view_ymin; - int view_xmax; - int view_ymax; - double xmin; /* Bounding box */ - double ymin; - double zmin; - double xmax; - double ymax; - double zmax; - double xcenter; /* Center point */ - double ycenter; - double zcenter; - double fovy; /* Field of view */ - double aspect; /* Aspect ratio */ - double znear; /* near "clipping" plane */ - double zfar; /* far "clipping" plane */ - double lookatz; /* Where is the z-lookat point */ - double xshift; /* Used for translation and stuff */ - double yshift; - %extend { - Plot3D(FrameBuffer *frame, double xmin, double ymin, double zmin, double xmax, double ymax, double zmax); - ~Plot3D(); - Plot3D *copy(); - void clear(Pixel bgcolor); - void perspective( double fovy, double znear, double zfar); - void lookat( double z); - void autoperspective( double fovy); - void ortho(double left, double right, double bottom, double top); - void autoortho(); - void rotx( double deg); - void roty( double deg); - void rotz( double deg); - void rotl( double deg); - void rotr( double deg); - void rotd( double deg); - void rotu( double deg); - void rotc( double deg); - void zoom( double percent); - void left( double percent); - void right( double percent); - void down( double percent); - void up( double percent); - void center( double cx, double cy); - void plot( double x, double y, double z, Pixel Color); - void setview( int vxmin, int vymin, int vxmax, int vymax); - void start(); - void line( double x1, double y1, double z1, - double x2, double y2, double z2, Pixel color); - void triangle( double x1, double y1, double z1, - double x2, double y2, double z2, - double x3, double y3, double z3, Pixel color); - void solidtriangle( double x1, double y1, double z1, - double x2, double y2, double z2, - double x3, double y3, double z3, Pixel color); - void interptriangle(double x1, double y1, double z1, Pixel c1, - double x2, double y2, double z2, Pixel c2, - double x3, double y3, double z3, Pixel c3); - void quad( double x1, double y1, double z1, - double x2, double y2, double z2, - double x3, double y3, double z3, - double x4, double y4, double z4, - Pixel color); - void solidquad( double x1, double y1, double z1, - double x2, double y2, double z2, - double x3, double y3, double z3, - double x4, double y4, double z4, - Pixel color); - void interpquad( double x1, double y1, double z1, Pixel c1, - double x2, double y2, double z2, Pixel c2, - double x3, double y3, double z3, Pixel c3, - double x4, double y4, double z4, Pixel c4); - void solidsphere( double x, double y, double z, double radius,Pixel c); - void outlinesphere( double x, double y, double z, double radius,Pixel c, Pixel bc); - } -} Plot3D; - -#ifndef SWIGJAVA -/* These directives create constants of a specific type. They - do not correspond to any C variable or declared constant in the - header file */ -%constant PixMap * SQUARE = &PixMap_SQUARE; -%constant PixMap * TRIANGLE = &PixMap_TRIANGLE; -%constant PixMap * CROSS = &PixMap_CROSS; -#endif - - - - diff --git a/Examples/GIFPlot/Java/check.list b/Examples/GIFPlot/Java/check.list deleted file mode 100644 index 13de977af..000000000 --- a/Examples/GIFPlot/Java/check.list +++ /dev/null @@ -1,4 +0,0 @@ -# see top-level Makefile.in -full -shadow -simple diff --git a/Examples/GIFPlot/Java/full/Makefile b/Examples/GIFPlot/Java/full/Makefile deleted file mode 100644 index 8f167237d..000000000 --- a/Examples/GIFPlot/Java/full/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../swig -SWIGOPT = -I../../Include -noproxy -SRCS = -TARGET = gifplot -INTERFACE = gifplot.i -LIBS = -L../.. -lgifplot -INCLUDES = -I../../Include - -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java - javac *.java - -clean:: - $(MAKE) -f $(TOP)/Makefile java_clean - rm -f *.gif - -check: all diff --git a/Examples/GIFPlot/Java/full/README b/Examples/GIFPlot/Java/full/README deleted file mode 100644 index 93463ea30..000000000 --- a/Examples/GIFPlot/Java/full/README +++ /dev/null @@ -1,8 +0,0 @@ -This example runs the entire gifplot.h header file through SWIG without -any changes. The program 'runme.java' does something a little more -interesting. After doing a make, run it using 'java runme'. You'll have to go -look at the header file to get a complete listing of the functions. - -Note the differences in the runme.java files between this example and the -'full' example. This example does not use shadow classes. - diff --git a/Examples/GIFPlot/Java/full/cmap b/Examples/GIFPlot/Java/full/cmap deleted file mode 100644 index a20c331a9573dd8443380680bfe2cc428780d8a9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 768 zcmZQzpd(=A5)hSEP}Mdtvvzdz4h)M)OwTDSuW4%Uoiu&!q7`d5@7R0z#JS5i?>&C` z?#s{r^Z@9-XXO?YlTlLFHMX#G@$?UkN=VBFxv-;m^2~WlR;}N<`@pd?7q8!a^y1xT znmh34m-nxpKDd4D;+bOy_iW#^cE#d(Gbi_Tw$xXZ7G$R-M27|XxI5We80l&#%Snpx zbFrd(h8Vt}lCeu@T6xFJRlCpJeMef510DGC$^DyG&YwK8f9IC 239) c = 239; - gifplot.Plot3D_solidquad(p3,x,y,z1,x+dx,y,z2,x+dx,y+dy,z3,x,y+dy,z4,(short)(c+16)); - y = y + dy; - } - x = x + dx; - } - - gifplot.FrameBuffer_writeGIF(frame,cmap,"image.gif"); - System.out.println( "Wrote image.gif" ); - } - - // Here is the function to plot - public static double func(double x, double y) { - return 5*java.lang.Math.cos(2*java.lang.Math.sqrt(x*x+y*y))*java.lang.Math.exp(-0.3*java.lang.Math.sqrt(x*x+y*y)); - } -} diff --git a/Examples/GIFPlot/Java/shadow/Makefile b/Examples/GIFPlot/Java/shadow/Makefile deleted file mode 100644 index 8062c2700..000000000 --- a/Examples/GIFPlot/Java/shadow/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../swig -SWIGOPT = -outcurrentdir -SRCS = -TARGET = gifplot -INTERFACEDIR = ../../Interface/ -INTERFACE = gifplot.i -LIBS = -L../.. -lgifplot -INCLUDES = -I../../Include - -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' INTERFACEDIR='$(INTERFACEDIR)' java - javac *.java - -clean:: - $(MAKE) -f $(TOP)/Makefile java_clean - rm -f *.gif - -check: all diff --git a/Examples/GIFPlot/Java/shadow/README b/Examples/GIFPlot/Java/shadow/README deleted file mode 100644 index b06c5a8f1..000000000 --- a/Examples/GIFPlot/Java/shadow/README +++ /dev/null @@ -1,5 +0,0 @@ -This example uses the file in ../../Interface/gifplot.i to build -an interface with shadow classes. After doing a make, run the program runme, ie: 'java runme'. - -Note the differences in the runme.java files between this example and the -'full' example. This example uses the shadow classes. diff --git a/Examples/GIFPlot/Java/shadow/cmap b/Examples/GIFPlot/Java/shadow/cmap deleted file mode 100644 index a20c331a9573dd8443380680bfe2cc428780d8a9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 768 zcmZQzpd(=A5)hSEP}Mdtvvzdz4h)M)OwTDSuW4%Uoiu&!q7`d5@7R0z#JS5i?>&C` z?#s{r^Z@9-XXO?YlTlLFHMX#G@$?UkN=VBFxv-;m^2~WlR;}N<`@pd?7q8!a^y1xT znmh34m-nxpKDd4D;+bOy_iW#^cE#d(Gbi_Tw$xXZ7G$R-M27|XxI5We80l&#%Snpx zbFrd(h8Vt}lCeu@T6xFJRlCpJeMef510DGC$^DyG&YwK8f9IC 239) c = 239; - p3.solidquad(x,y,z1,x+dx,y,z2,x+dx,y+dy,z3,x,y+dy,z4,(short)(c+16)); - y = y + dy; - } - x = x + dx; - } - - frame.writeGIF(cmap,"image.gif"); - System.out.println( "Wrote image.gif" ); - } - - // Here is the function to plot - public static double func(double x, double y) { - return 5*java.lang.Math.cos(2*java.lang.Math.sqrt(x*x+y*y))*java.lang.Math.exp(-0.3*java.lang.Math.sqrt(x*x+y*y)); - } -} diff --git a/Examples/GIFPlot/Java/simple/Makefile b/Examples/GIFPlot/Java/simple/Makefile deleted file mode 100644 index d707fd458..000000000 --- a/Examples/GIFPlot/Java/simple/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../swig -SWIGOPT = -noproxy -SRCS = -TARGET = simple -INTERFACE = simple.i -LIBS = -L../.. -lgifplot -INCLUDES = -I../../Include - -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java - javac *.java - - -clean:: - $(MAKE) -f $(TOP)/Makefile java_clean - rm -f *.gif - -check: all diff --git a/Examples/GIFPlot/Java/simple/README b/Examples/GIFPlot/Java/simple/README deleted file mode 100644 index 13ff49611..000000000 --- a/Examples/GIFPlot/Java/simple/README +++ /dev/null @@ -1,5 +0,0 @@ -This is a very minimalistic example in which just a few functions -and constants from library are wrapped and used to draw some simple -shapes. After doing a make, run the java program, ie 'java runme'. - - diff --git a/Examples/GIFPlot/Java/simple/runme.java b/Examples/GIFPlot/Java/simple/runme.java deleted file mode 100644 index 2d8d2bb48..000000000 --- a/Examples/GIFPlot/Java/simple/runme.java +++ /dev/null @@ -1,41 +0,0 @@ - -public class runme { - - static { - try { - System.loadLibrary("simple"); - } 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[]) { - - // Draw some simple shapes - System.out.println( "Drawing some basic shapes" ); - - SWIGTYPE_p_ColorMap cmap = simple.new_ColorMap(null); - SWIGTYPE_p_FrameBuffer f = simple.new_FrameBuffer(400,400); - - // Clear the picture - simple.FrameBuffer_clear(f,(short)simple.BLACK); - - // Make a red box - simple.FrameBuffer_box(f,40,40,200,200,(short)simple.RED); - - // Make a blue circle - simple.FrameBuffer_circle(f,200,200,40,(short)simple.BLUE); - - // Make green line - simple.FrameBuffer_line(f,10,390,390,200, (short)simple.GREEN); - - // Write an image out to disk - - simple.FrameBuffer_writeGIF(f,cmap,"image.gif"); - System.out.println( "Wrote image.gif" ); - - simple.delete_FrameBuffer(f); - simple.delete_ColorMap(cmap); - } -} diff --git a/Examples/GIFPlot/Java/simple/simple.i b/Examples/GIFPlot/Java/simple/simple.i deleted file mode 100644 index 457bc4c09..000000000 --- a/Examples/GIFPlot/Java/simple/simple.i +++ /dev/null @@ -1,38 +0,0 @@ -/* This example shows a very simple interface wrapping a few - primitive declarations */ - -%module simple -%{ -#include "gifplot.h" -%} - -typedef unsigned char Pixel; - -/* Here are a few useful functions */ - -ColorMap *new_ColorMap(char *filename = 0); -void delete_ColorMap(ColorMap *cmap); - -FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height); -void delete_FrameBuffer(FrameBuffer *frame); -void FrameBuffer_clear(FrameBuffer *frame, Pixel color); -void FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -void FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -void FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color); -int FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename); - -/* And some useful constants */ - -#define BLACK 0 -#define WHITE 1 -#define RED 2 -#define GREEN 3 -#define BLUE 4 -#define YELLOW 5 -#define CYAN 6 -#define MAGENTA 7 - - - - - diff --git a/Examples/GIFPlot/Lib/Makefile.in b/Examples/GIFPlot/Lib/Makefile.in deleted file mode 100644 index 9db828eb2..000000000 --- a/Examples/GIFPlot/Lib/Makefile.in +++ /dev/null @@ -1,22 +0,0 @@ -CC = @CC@ -CCSHARED= @CCSHARED@ -INCLUDES= -I../Include -CFLAGS = -O -SRCS = frame.c color.c plot2d.c plot3d.c font.c pixmap.c matrix.c gif.c -OBJS = $(SRCS:.c=.@OBJEXT@) -AR = @AR@ -RANLIB = @RANLIB@ -TARGET = ../libgifplot.a - -.c.@OBJEXT@: - $(CC) $(CCSHARED) $(INCLUDES) $(CFLAGS) -c -o $*.@OBJEXT@ $< - -all: $(OBJS) - @rm -f ../libgifplot.a - $(AR) cr $(TARGET) $(OBJS) - $(RANLIB) $(TARGET) - -clean: - rm -f *.@OBJEXT@ *~ $(TARGET) - -check: all diff --git a/Examples/GIFPlot/Lib/color.c b/Examples/GIFPlot/Lib/color.c deleted file mode 100644 index 7d79baca9..000000000 --- a/Examples/GIFPlot/Lib/color.c +++ /dev/null @@ -1,143 +0,0 @@ -/* ----------------------------------------------------------------------------- - * color.c - * - * Colormaps - * - * Author(s) : David Beazley (beazley@cs.uchicago.edu) - * Copyright (C) 1995-1996 - * - * See the file LICENSE for information on usage and redistribution. - * ----------------------------------------------------------------------------- */ - -#define COLORMAP -#include "gifplot.h" -#include - -/* ------------------------------------------------------------------------ - ColorMap *new_ColorMap(char *filename) - - Read a colormap from a file. - ------------------------------------------------------------------------ */ - -ColorMap *new_ColorMap(char *filename) { - ColorMap *c; - FILE *cm; - void ColorMap_default(ColorMap *); - - if (!filename) { - c = (ColorMap *) malloc(sizeof(ColorMap)); - c->cmap = (unsigned char *) malloc(768*sizeof(char)); - c->name = 0; - ColorMap_default(c); - return c; - } - if (strlen(filename) == 0) { - c = (ColorMap *) malloc(sizeof(ColorMap)); - c->cmap = (unsigned char *) malloc(768*sizeof(char)); - ColorMap_default(c); - return c; - } - if ((cm = fopen(filename,"rb")) == NULL) { - return (ColorMap *) 0; - } - c = (ColorMap *) malloc(sizeof(ColorMap)); - c->cmap = (unsigned char *) malloc(768*sizeof(char)); - if (fread(c->cmap, 768, 1, cm) != 1) { - free((char *)c->cmap); - free((char *)c); - fclose(cm); - return (ColorMap *) 0; - } - fclose(cm); - c->name = (char *) malloc(strlen(filename)+1); - strcpy(c->name, filename); - ColorMap_default(c); - return c; -} - -/* -------------------------------------------------------------------------- - delete_ColorMap(ColorMap *cm) - - Destroy a ColorMap - -------------------------------------------------------------------------- */ - -void delete_ColorMap(ColorMap *cm) { - if (cm) { - free((char *)cm->cmap); - if (cm->name) - free((char *)cm->name); - free((char *)cm); - } -} - -/* -------------------------------------------------------------------------- - ColorMap_default(ColorMap *cm) - - This function fills in default values for the first 8 entries of the - colormap. These are *fixed* values---used internally. - -------------------------------------------------------------------------- */ - -void ColorMap_default(ColorMap *cm) { - unsigned char *r,*g,*b; - if (cm) { - r = cm->cmap; - g = cm->cmap+256; - b = cm->cmap+512; - - r[0] = 0; g[0] = 0; b[0] = 0; /* BLACK */ - r[1] = 255; g[1] = 255; b[1] = 255; /* WHITE */ - r[2] = 255; g[2] = 0; b[2] = 0; /* RED */ - r[3] = 0; g[3] = 255; b[3] = 0; /* GREEN */ - r[4] = 0; g[4] = 0; b[4] = 255; /* BLUE */ - r[5] = 255; g[5] = 255; b[5] = 0; /* YELLOW */ - r[6] = 0; g[6] = 255; b[6] = 255; /* CYAN */ - r[7] = 255; g[7] = 0; b[7] = 255; /* MAGENTA */ - } -} - -void ColorMap_assign(ColorMap *cm, int index, int r, int g, int b) { - unsigned char *rb,*gb,*bb; - - rb = cm->cmap; - gb = cm->cmap+256; - bb = cm->cmap+512; - - rb[index] = r; - gb[index] = g; - bb[index] = b; -} - -int ColorMap_getitem(ColorMap *cm, int index) { - if ((index < 0) && (index >= 768)) return -1; - return cm->cmap[index]; -} - -void ColorMap_setitem(ColorMap *cm, int index, int value) { - if ((index < 0) && (index >= 768)) return; - cm->cmap[index]=value; -} - -/* -------------------------------------------------------------------- - ColorMap_write(ColorMap *cm, char *filename) - - Write out a colormap to disk. - -------------------------------------------------------------------- */ - -int ColorMap_write(ColorMap *cm, char *filename) { - - FILE *f; - if (!cm) return -1; - if (!filename) return -1; - if (strlen(filename) == 0) return -1; - - f = fopen(filename,"w"); - - if (fwrite(cm->cmap,768,1,f) != 1) { - fclose(f); - return -1; - } - fclose(f); - return 0; -} - -#undef COLORMAP diff --git a/Examples/GIFPlot/Lib/font.c b/Examples/GIFPlot/Lib/font.c deleted file mode 100644 index b30ee9b14..000000000 --- a/Examples/GIFPlot/Lib/font.c +++ /dev/null @@ -1,705 +0,0 @@ -/* ----------------------------------------------------------------------------- - * font.c - * - * Some basic fonts. - * - * Author(s) : David Beazley (beazley@cs.uchicago.edu) - * Copyright (C) 1995-1996 - * - * See the file LICENSE for information on usage and redistribution. - * ----------------------------------------------------------------------------- */ - -#define FONT -#include "gifplot.h" - -static char Char_A[80] = "\ -...x....\ -...x....\ -..x.x...\ -..x.x...\ -.x...x..\ -.xxxxx..\ -x.....x.\ -x.....x.\ -x.....x.\ -........"; - -static char Char_B[80] = "\ -xxxxxx..\ -x.....x.\ -x.....x.\ -x.....x.\ -xxxxxx..\ -x.....x.\ -x.....x.\ -x.....x.\ -xxxxxx..\ -........"; - -static char Char_C[80] = "\ -..xxxx..\ -.x....x.\ -x.......\ -x.......\ -x.......\ -x.......\ -x.......\ -.x....x.\ -..xxxx..\ -........"; - -static char Char_D[80] = "\ -xxxxx...\ -x....x..\ -x.....x.\ -x.....x.\ -x.....x.\ -x.....x.\ -x.....x.\ -x....x..\ -xxxxx...\ -........"; -static char Char_E[80] = "\ -xxxxxxx.\ -x.......\ -x.......\ -x.......\ -xxxxx...\ -x.......\ -x.......\ -x.......\ -xxxxxxx.\ -........"; -static char Char_F[80] = "\ -xxxxxxx.\ -x.......\ -x.......\ -x.......\ -xxxxx...\ -x.......\ -x.......\ -x.......\ -x.......\ -........"; -static char Char_G[80] = "\ -.xxxxx..\ -x.....x.\ -x.......\ -x.......\ -x...xxx.\ -x.....x.\ -x.....x.\ -x.....x.\ -.xxxxx..\ -........"; -static char Char_H[80] = "\ -x.....x.\ -x.....x.\ -x.....x.\ -x.....x.\ -xxxxxxx.\ -x.....x.\ -x.....x.\ -x.....x.\ -x.....x.\ -........"; -static char Char_I[80] = "\ -xxxxxxx.\ -...x....\ -...x....\ -...x....\ -...x....\ -...x....\ -...x....\ -...x....\ -xxxxxxx.\ -........"; -static char Char_J[80] = "\ -......x.\ -......x.\ -......x.\ -......x.\ -......x.\ -......x.\ -x.....x.\ -.x...x..\ -..xxx...\ -........"; -static char Char_K[80] = "\ -x.....x.\ -x....x..\ -x...x...\ -x..x....\ -xxx.....\ -x..x....\ -x...x...\ -x....x..\ -x.....x.\ -........"; -static char Char_L[80] = "\ -x.......\ -x.......\ -x.......\ -x.......\ -x.......\ -x.......\ -x.......\ -x.......\ -xxxxxxx.\ -........"; -static char Char_M[80] = "\ -x.....x.\ -xx...xx.\ -xx...xx.\ -x.x.x.x.\ -x.x.x.x.\ -x..x..x.\ -x..x..x.\ -x.....x.\ -x.....x.\ -........"; -static char Char_N[80] = "\ -x.....x.\ -xx....x.\ -x.x...x.\ -x.x...x.\ -x..x..x.\ -x...x.x.\ -x...x.x.\ -x....xx.\ -x.....x.\ -........"; -static char Char_O[80] = "\ -.xxxxx..\ -x.....x.\ -x.....x.\ -x.....x.\ -x.....x.\ -x.....x.\ -x.....x.\ -x.....x.\ -.xxxxx..\ -........"; -static char Char_P[80] = "\ -xxxxxx..\ -x.....x.\ -x.....x.\ -x.....x.\ -xxxxxx..\ -x.......\ -x.......\ -x.......\ -x.......\ -........"; -static char Char_Q[80] = "\ -.xxxxx..\ -x.....x.\ -x.....x.\ -x.....x.\ -x.....x.\ -x.....x.\ -x...x.x.\ -x....x..\ -.xxxx.x.\ -........"; -static char Char_R[80] = "\ -xxxxxx..\ -x.....x.\ -x.....x.\ -x.....x.\ -xxxxxx..\ -x..x....\ -x...x...\ -x....x..\ -x.....x.\ -........"; -static char Char_S[80] = "\ -.xxxxx..\ -x.....x.\ -x.......\ -x.......\ -.xxxxx..\ -......x.\ -......x.\ -x.....x.\ -.xxxxx..\ -........"; -static char Char_T[80] = "\ -xxxxxxx.\ -...x....\ -...x....\ -...x....\ -...x....\ -...x....\ -...x....\ -...x....\ -...x....\ -........"; -static char Char_U[80] = "\ -x.....x.\ -x.....x.\ -x.....x.\ -x.....x.\ -x.....x.\ -x.....x.\ -x.....x.\ -x.....x.\ -.xxxxx..\ -........"; -static char Char_V[80] = "\ -x.....x.\ -x.....x.\ -.x...x..\ -.x...x..\ -..x.x...\ -..x.x...\ -...x....\ -...x....\ -...x....\ -........"; -static char Char_W[80] = "\ -x.....x.\ -x.....x.\ -x.....x.\ -x.....x.\ -x.....x.\ -x..x..x.\ -x..x..x.\ -x.x.x.x.\ -.x...x..\ -........"; -static char Char_X[80] = "\ -x.....x.\ -x.....x.\ -.x...x..\ -..x.x...\ -...x....\ -..x.x...\ -.x...x..\ -x.....x.\ -x.....x.\ -........"; -static char Char_Y[80] = "\ -x.....x.\ -x.....x.\ -.x...x..\ -..x.x...\ -...x....\ -...x....\ -...x....\ -...x....\ -...x....\ -........"; -static char Char_Z[80] = "\ -xxxxxxx.\ -......x.\ -.....x..\ -....x...\ -...x....\ -..x.....\ -.x......\ -x.......\ -xxxxxxx.\ -........"; -static char Char_0[80] = "\ -.xxxxx..\ -x....xx.\ -x...x.x.\ -x..x..x.\ -x..x..x.\ -x.x...x.\ -x.x...x.\ -xx....x.\ -.xxxxx..\ -........"; -static char Char_1[80] = "\ -...x....\ -..xx....\ -...x....\ -...x....\ -...x....\ -...x....\ -...x....\ -...x....\ -..xxx...\ -........"; -static char Char_2[80] = "\ -..xxxx..\ -.x....x.\ -x.....x.\ -.....x..\ -....x...\ -...x....\ -..x.....\ -.x......\ -xxxxxxx.\ -........"; -static char Char_3[80] = "\ -.xxxxx..\ -x.....x.\ -......x.\ -......x.\ -...xxx..\ -......x.\ -......x.\ -x.....x.\ -.xxxxx..\ -........"; -static char Char_4[80] = "\ -....xx..\ -...x.x..\ -..x..x..\ -.x...x..\ -xxxxxxx.\ -.....x..\ -.....x..\ -.....x..\ -.....x..\ -........"; -static char Char_5[80] = "\ -xxxxxxx.\ -x.......\ -x.......\ -x.......\ -xxxxxx..\ -......x.\ -......x.\ -x.....x.\ -.xxxxx..\ -........"; -static char Char_6[80] = "\ -....xxx.\ -..xx....\ -.x......\ -x.......\ -x.xxx...\ -xx...x..\ -x.....x.\ -.x...x..\ -..xxx...\ -........"; -static char Char_7[80] = "\ -xxxxxxx.\ -x.....x.\ -.....x..\ -....x...\ -...x....\ -..x.....\ -.x......\ -x.......\ -x.......\ -........"; -static char Char_8[80] = "\ -.xxxxx..\ -x.....x.\ -x.....x.\ -x.....x.\ -.xxxxx..\ -x.....x.\ -x.....x.\ -x.....x.\ -.xxxxx..\ -........"; -static char Char_9[80] = "\ -..xxxx..\ -.x....x.\ -x.....x.\ -x....xx.\ -.xxxx.x.\ -......x.\ -......x.\ -....xx..\ -.xxx....\ -........"; -static char Char_MINUS[80] = "\ -........\ -........\ -........\ -........\ -.xxxxxx.\ -........\ -........\ -........\ -........\ -........"; -static char Char_PLUS[80] = "\ -........\ -........\ -...x....\ -...x....\ -.xxxxx..\ -...x....\ -...x....\ -........\ -........\ -........"; -static char Char_EQUAL[80] = "\ -........\ -........\ -........\ -.xxxxx..\ -........\ -.xxxxx..\ -........\ -........\ -........\ -........"; -static char Char_LPAREN[80] = "\ -....x...\ -...x....\ -..x.....\ -.x......\ -.x......\ -.x......\ -..x.....\ -...x....\ -....x...\ -........"; -static char Char_RPAREN[80] = "\ -...x....\ -....x...\ -.....x..\ -......x.\ -......x.\ -......x.\ -.....x..\ -....x...\ -...x....\ -........"; -static char Char_QUOTE[80] = "\ -..x.x...\ -..x.x...\ -........\ -........\ -........\ -........\ -........\ -........\ -........\ -........"; -static char Char_COLON[80] = "\ -........\ -........\ -...xx...\ -...xx...\ -........\ -...xx...\ -...xx...\ -........\ -........\ -........"; -static char Char_PERIOD[80] = "\ -........\ -........\ -........\ -........\ -........\ -........\ -........\ -...xx...\ -...xx...\ -........"; -static char Char_COMMA[80] = "\ -........\ -........\ -........\ -........\ -........\ -........\ -...xx...\ -...xx...\ -....x...\ -...x...."; - -static char Char_SLASH[80] = "\ -........\ -......x.\ -.....x..\ -....x...\ -...x....\ -..x.....\ -.x......\ -x.......\ -........\ -........"; - -static char Char_SPACE[80] = "\ -........\ -........\ -........\ -........\ -........\ -........\ -........\ -........\ -........\ -........"; - -static char *GP_Font[128]; -static int InitGP_Font = 0; - -static void initGP_Fonts(void) { - - int i; - for (i = 0; i < 128; i++) - GP_Font[i] = (char *) 0; - - GP_Font['A'] = GP_Font['a'] = Char_A; - GP_Font['B'] = GP_Font['b'] = Char_B; - GP_Font['C'] = GP_Font['c'] = Char_C; - GP_Font['D'] = GP_Font['d'] = Char_D; - GP_Font['E'] = GP_Font['e'] = Char_E; - GP_Font['F'] = GP_Font['f'] = Char_F; - GP_Font['G'] = GP_Font['g'] = Char_G; - GP_Font['H'] = GP_Font['h'] = Char_H; - GP_Font['I'] = GP_Font['i'] = Char_I; - GP_Font['J'] = GP_Font['j'] = Char_J; - GP_Font['K'] = GP_Font['k'] = Char_K; - GP_Font['L'] = GP_Font['l'] = Char_L; - GP_Font['M'] = GP_Font['m'] = Char_M; - GP_Font['N'] = GP_Font['n'] = Char_N; - GP_Font['O'] = GP_Font['o'] = Char_O; - GP_Font['P'] = GP_Font['p'] = Char_P; - GP_Font['Q'] = GP_Font['q'] = Char_Q; - GP_Font['R'] = GP_Font['r'] = Char_R; - GP_Font['S'] = GP_Font['s'] = Char_S; - GP_Font['T'] = GP_Font['t'] = Char_T; - GP_Font['U'] = GP_Font['u'] = Char_U; - GP_Font['V'] = GP_Font['v'] = Char_V; - GP_Font['W'] = GP_Font['w'] = Char_W; - GP_Font['X'] = GP_Font['x'] = Char_X; - GP_Font['Y'] = GP_Font['y'] = Char_Y; - GP_Font['Z'] = GP_Font['z'] = Char_Z; - GP_Font['0'] = Char_0; - GP_Font['1'] = Char_1; - GP_Font['2'] = Char_2; - GP_Font['3'] = Char_3; - GP_Font['4'] = Char_4; - GP_Font['5'] = Char_5; - GP_Font['6'] = Char_6; - GP_Font['7'] = Char_7; - GP_Font['8'] = Char_8; - GP_Font['9'] = Char_9; - GP_Font['.'] = Char_PERIOD; - GP_Font[','] = Char_COMMA; - GP_Font['='] = Char_EQUAL; - GP_Font['-'] = Char_MINUS; - GP_Font['+'] = Char_PLUS; - GP_Font['\"'] = Char_QUOTE; - GP_Font['('] = Char_LPAREN; - GP_Font[')'] = Char_RPAREN; - GP_Font[':'] = Char_COLON; - GP_Font['/'] = Char_SLASH; - GP_Font[' '] = Char_SPACE; - InitGP_Font = 1; -} - -/* ----------------------------------------------------------------------- - void FrameBuffer_drawchar(FrameBuffer *f, int x, int y, Pixel fgcolor, Pixel bgcolor, char chr, int orientation) - - Draws a character at location x, y with given color and orientation parameters. - Orientation can either be HORIZONTAL or VERTICAL - ----------------------------------------------------------------------- */ -void FrameBuffer_drawchar(FrameBuffer *f, int x, int y, int fgcolor, - int bgcolor, char chr, int orientation) { - - Pixel c, bc,*p,*p1; - char *ch; - int i,j; - int xpixels,ypixels; - - if (!InitGP_Font) initGP_Fonts(); - - c = (Pixel) fgcolor; - bc = (Pixel) bgcolor; - xpixels = f->width; - ypixels = f->height; - - if (orientation == HORIZONTAL) { - if ((x < f->xmin) || (x > f->xmax-8) || - (y < f->ymin) || (y > f->ymax-10)) return; - - ch = GP_Font[(int) chr]; - if (!ch) return; - p = &f->pixels[y+9][x]; - for (i = 0; i < 10; i++) { - p1 = p; - for (j = 0; j< 8; j++) { - if (*(ch++) == 'x') *p= c; - else if (bgcolor >= 0) - *p = bc; - p++; - } - p = (p1 - xpixels); - } - } else { - if ((x < f->xmin+10) || (x >= f->xmax) || - (y < f->ymin) || (y > f->ymax-8)) return; - - ch = GP_Font[(int) chr]; - if (!ch) return; - p = &f->pixels[y][x-9]; - for (i = 0; i < 10; i++) { - p1 = p; - for (j = 0; j< 8; j++) { - if (*(ch++) == 'x') *p= c; - else if (bgcolor >= 0) - *p = bc; - p+=xpixels; - } - p = p1 + 1; - } - } -} - -/* ---------------------------------------------------------------------- - void FrameBuffer_drawstring(FrameBuffer *f, int x, int y, int fgcolor, - int bgcolor, char *text, int orientation) - - Draws an ASCII string on the framebuffer. Can be oriented either horizontally - or vertically. - ---------------------------------------------------------------------- */ - -void FrameBuffer_drawstring(FrameBuffer *f, int x, int y, int fgcolor, int bgcolor, char *text, int orientation) { - - char *c; - int x1, y1; - int xpixels, ypixels; - - x1 = x; - y1 = y; - xpixels = f->width; - ypixels = f->height; - c = text; - while (*c) { - if (*c == '\n') { - if (orientation == HORIZONTAL) { - x1 = x; y1= y1- 10*xpixels; - } else { - y1 = y; x1= x1 + 10*ypixels; - } - } else { - FrameBuffer_drawchar(f, x1,y1,fgcolor, bgcolor,*c, orientation); - if (orientation == HORIZONTAL) { - x1+=8; - if (x1 >= (xpixels-8)) { - x1 = x; y1= y1- 10;} - if (y1 < 0) return; - } else { - y1 += 8; - if (y1 >= (ypixels-8)) { - y1 = y; x1 = x1 + 10;} - if (x1 > (xpixels-10)) return; - } - } - c++; - } -} - - - - - - - - diff --git a/Examples/GIFPlot/Lib/frame.c b/Examples/GIFPlot/Lib/frame.c deleted file mode 100644 index e006f0daf..000000000 --- a/Examples/GIFPlot/Lib/frame.c +++ /dev/null @@ -1,924 +0,0 @@ -/* ----------------------------------------------------------------------------- - * frame.c - * - * Frame buffer management - * - * Author(s) : David Beazley (beazley@cs.uchicago.edu) - * Copyright (C) 1995-1996 - * - * See the file LICENSE for information on usage and redistribution. - * ----------------------------------------------------------------------------- */ - -#define FRAME -#include "gifplot.h" -#include - -/* ------------------------------------------------------------------------ - FrameBuffer *new_FrameBuffer(int width, int height) - - Creates a new framebuffer for storing data. - ------------------------------------------------------------------------ */ - -FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height) { - - FrameBuffer *f; - int FrameBuffer_resize(FrameBuffer *f, int width, int height); - - /* Create a new frame buffer */ - - f = (FrameBuffer *) malloc(sizeof(FrameBuffer)); - f->pixels = (Pixel **) 0; - f->zbuffer = (Zvalue **) 0; - /* Set its size */ - - if (FrameBuffer_resize(f, width, height) == -1) { - free((char *) f); - return (FrameBuffer *) 0; - } - - f->xmin = 0; - f->ymin = 0; - f->xmax = width; - f->ymax = height; - return f; -} - -/* ------------------------------------------------------------------------ - void delete_FrameBuffer(FrameBuffer *f) - - Destroys the given framebuffer - ------------------------------------------------------------------------ */ - -void delete_FrameBuffer(FrameBuffer *f) { - - if (f) { - if (f->pixels) { - free((char *) f->pixels[0]); - free((char *) f->pixels); - } - if (f->zbuffer) { - free((char *) f->zbuffer[0]); - free((char *) f->zbuffer); - } - free((char *)f); - } -} - -/* ------------------------------------------------------------------------ - int *FrameBuffer_resize(FrameBuffer *f, int width, int height) - - Resize the given framebuffer. Returns 0 on success, -1 on failure. - ------------------------------------------------------------------------ */ - -int FrameBuffer_resize(FrameBuffer *f, int width, int height) { - int i; - if ((f) && (width > 0) && (height > 0)) { - if (f->pixels) { - free((char *)f->pixels[0]); - free((char *)f->pixels); - } - f->pixels = (Pixel **) malloc (height*sizeof(Pixel *)); - if (!f->pixels) return -1; - f->pixels[0] = (Pixel *) malloc(height*width*sizeof(Pixel)); - if (!f->pixels[0]) { - free((char *)f->pixels); - return -1; - } - for (i = 0; i < height; i++) - f->pixels[i] = f->pixels[0] + i*width; - f->width = width; - f->height = height; - if (f->zbuffer) { - FrameBuffer_zresize(f,width,height); - } - return 0; - } else { - return -1; - } -} - -/* ------------------------------------------------------------------------ - void FrameBuffer_clear(FrameBuffer *f, Pixel color) - - Clears the current FrameBuffer - ------------------------------------------------------------------------ */ - -void FrameBuffer_clear(FrameBuffer *f, Pixel color) { - Pixel *p; - unsigned int i; - p = &f->pixels[0][0]; - - for (i = 0; i < f->width*f->height; i++, p++) - *p = color; -} - -/* ------------------------------------------------------------------------ - void FrameBuffer_plot(FrameBuffer *f, int x1, int y1, Pixel color) - - Plots a point and does a bounds check. - ------------------------------------------------------------------------ */ - -void FrameBuffer_plot(FrameBuffer *f, int x1, int y1, Pixel color) { - - if ((x1 < f->xmin) || (x1 >= f->xmax) || (y1 < f->ymin) || (y1 >= f->ymax)) - return; - f->pixels[y1][x1] = color; - -} - -/* ------------------------------------------------------------------------ - FrameBuffer_horizontal(Framebuffer *f, int xmin, int xmax, int y, Pixel color) - - Draw a horizontal line (clipped) - ------------------------------------------------------------------------ */ - -void FrameBuffer_horizontal(FrameBuffer *f, int xmin, int xmax, int y, Pixel color) { - - Pixel *p; - int i; - - if ((y < f->ymin) || (y >= f->ymax)) return; - if (xmin < f->xmin) xmin = f->xmin; - if (xmax >= f->xmax) xmax = f->xmax - 1; - - p = &f->pixels[y][xmin]; - for (i = xmin; i <= xmax; i++, p++) - *p = color; - -} - -/* ------------------------------------------------------------------------ - FrameBuffer_horizontalinterp(Framebuffer *f, int xmin, int xmax, int y, - Pixel c1, Pixel c2) - - Draw a horizontal line (clipped) with color interpolation. - ------------------------------------------------------------------------ */ - -void FrameBuffer_horizontalinterp(FrameBuffer *f, int xmin, int xmax, int y, - Pixel c1, Pixel c2) { - - Pixel *p; - int i; - double mc; - int x1; - if ((y < f->ymin) || (y >= f->ymax)) return; - - x1 = xmin; - if (xmin < f->xmin) xmin = f->xmin; - if (xmax >= f->xmax) xmax = f->xmax - 1; - if (xmax < f->xmin) return; - if (xmin >= f->xmax) return; - - if (xmin != xmax) - mc = (double)(c2 - c1)/(double) (xmax - xmin); - else - mc = 0.0; - - p = &f->pixels[y][xmin]; - for (i = xmin; i <= xmax; i++, p++) - *p = (Pixel) (mc*(i-x1) + c1); - -} - - -/* ------------------------------------------------------------------------ - FrameBuffer_vertical(Framebuffer *f, int xmin, int xmax, int y, Pixel color) - - Draw a Vertical line (clipped) - ------------------------------------------------------------------------ */ - -void FrameBuffer_vertical(FrameBuffer *f, int ymin, int ymax, int x, Pixel color) { - - Pixel *p; - int i; - - if ((x < f->xmin) || (x >= f->xmax)) return; - if (ymax < f->ymin) return; - if (ymin > f->ymax) return; - if (ymin < f->ymin) ymin = f->ymin; - if (ymax >= f->ymax) ymax = f->ymax - 1; - - p = &f->pixels[ymin][x]; - for (i = 0; i <= (ymax - ymin); i++, p+=f->width) - *p = color; - -} - -/* ------------------------------------------------------------------------ - void FrameBuffer_box(FrameBuffer *f, int x1, int y1, int x2, int y2, Pixel color) - - Makes an outline box. - ------------------------------------------------------------------------ */ - -void FrameBuffer_box(FrameBuffer *f, int x1, int y1, int x2, int y2, Pixel color) { - - int xt, yt; - - /* Make sure points are in correct order */ - - if (x2 < x1) { - xt = x2; - x2 = x1; - x1 = xt; - } - if (y2 < y1) { - yt = y2; - y2 = y1; - y1 = yt; - } - - /* Draw lower edge */ - - FrameBuffer_horizontal(f,x1,x2,y1,color); - - /* Draw upper edge */ - - FrameBuffer_horizontal(f,x1,x2,y2,color); - - /* Draw left side */ - - FrameBuffer_vertical(f,y1,y2,x1,color); - - /* Draw right side */ - - FrameBuffer_vertical(f,y1,y2,x2,color); - -} - -/* ------------------------------------------------------------------------ - void FrameBuffer_solidbox(FrameBuffer *f, int x1, int y1, int x2, int y2, Pixel color) - - Makes an solid box. - ------------------------------------------------------------------------ */ - -void FrameBuffer_solidbox(FrameBuffer *f, int x1, int y1, int x2, int y2, Pixel color) { - - int xt, yt; - - /* Make sure points are in correct order */ - - if (x2 < x1) { - xt = x2; - x2 = x1; - x1 = xt; - } - if (y2 < y1) { - yt = y2; - y2 = y1; - y1 = yt; - } - - /* Now perform some clipping */ - - if (y1 < f->ymin) y1 = f->ymin; - if (y2 >= f->ymax) y2 = f->ymax - 1; - - /* Fill it in using horizontal lines */ - - for (yt = y1; yt <= y2; yt++) - FrameBuffer_horizontal(f,x1,x2,yt,color); - -} - -/* ------------------------------------------------------------------------ - void FrameBuffer_interpbox(FrameBuffer *f, int x1, int y1, int x2, int y2 - Pixel c1, Pixel c2, Pixel c3, Pixel c4) - - Makes a box with interpolated color. Colors are assigned as follows : - (x1,y1) = c1 - (x1,y2) = c2 - (x2,y1) = c3 - (x2,y2) = c4 - ------------------------------------------------------------------------ */ - -void FrameBuffer_interpbox(FrameBuffer *f, int x1, int y1, int x2, int y2, - Pixel c1, Pixel c2, Pixel c3, Pixel c4) { - - int xt, yt; - Pixel ct; - double mc1,mc2; - int ystart; - /* Make sure points are in correct order */ - - if (x2 < x1) { - xt = x2; - x2 = x1; - x1 = xt; - ct = c1; - c1 = c3; - c3 = ct; - ct = c2; - c2 = c4; - c4 = ct; - } - if (y2 < y1) { - yt = y2; - y2 = y1; - y1 = yt; - ct = c1; - c1 = c2; - c2 = ct; - ct = c3; - c3 = c4; - c4 = ct; - } - - /* Now perform some clipping */ - - ystart = y1; - mc1 = (double) (c2 - c1)/(double) (y2 - y1); - mc2 = (double) (c4 - c3)/(double) (y2 - y1); - if (y1 < f->ymin) y1 = f->ymin; - if (y2 >= f->ymax) y2 = f->ymax - 1; - - /* Fill it in using horizontal lines */ - - for (yt = y1; yt <= y2; yt++) - FrameBuffer_horizontalinterp(f,x1,x2,yt,(Pixel) ((mc1*(yt - ystart)) + c1), - (Pixel) ((mc2*(yt-ystart))+c3)); - -} - -/* --------------------------------------------------------------------------- - FrameBuffer_line(FrameBuffer *f, int x1, int y1, int x2, int y2, color) - - Draws a line on the framebuffer using the Bresenham line algorithm. The - line is clipped to fit within the current view window. - ---------------------------------------------------------------------------- */ - -void FrameBuffer_line(FrameBuffer *f, int x1, int y1, int x2, int y2, Pixel c) { - - int dx,dy,dxneg,dyneg, inc1,inc2,di; - int x, y, xpixels, ypixels, xt, yt; - Pixel *p; - double m; - int end1 = 0, end2 = 0; - - /* Need to figure out where in the heck this line is */ - - dx = x2 - x1; - dy = y2 - y1; - - if (dx == 0) { - /* Draw a Vertical Line */ - if (y1 < y2) - FrameBuffer_vertical(f,y1,y2,x1,c); - else - FrameBuffer_vertical(f,y2,y1,x1,c); - return; - } - if (dy == 0) { - /* Draw a Horizontal Line */ - if (x1 < x2) - FrameBuffer_horizontal(f,x1,x2,y1,c); - else - FrameBuffer_horizontal(f,x2,x1,y1,c); - return; - } - - /* Figure out where in the heck these lines are using the - Cohen-Sutherland Line Clipping Scheme. */ - - end1 = ((x1 - f->xmin) < 0) | - (((f->xmax- 1 - x1) < 0) << 1) | - (((y1 - f->ymin) < 0) << 2) | - (((f->ymax-1 - y1) < 0) << 3); - - end2 = ((x2 - f->xmin) < 0) | - (((f->xmax-1 - x2) < 0) << 1) | - (((y2 - f->ymin) < 0) << 2) | - (((f->ymax-1 - y2) < 0) << 3); - - if (end1 & end2) return; /* Nope : Not visible */ - - /* Make sure points have a favorable orientation */ - - if (x1 > x2) { - xt = x1; - x1 = x2; - x2 = xt; - yt = y1; - y1 = y2; - y2 = yt; - } - - /* Clip against the boundaries */ - m = (y2 - y1)/(double) (x2-x1); - if (x1 < f->xmin) { - y1 = (int) ((f->xmin - x1)*m + y1); - x1 = (int) f->xmin; - } - if (x2 >= f->xmax) { - y2 = (int) ((f->xmax -1 -x1)*m + y1); - x2 = (int) (f->xmax - 1); - } - - if (y1 > y2) { - xt = x1; - x1 = x2; - x2 = xt; - yt = y1; - y1 = y2; - y2 = yt; - } - - m = 1/m; - if (y1 < f->ymin) { - x1 = (int) ((f->ymin - y1)*m + x1); - y1 = (int) f->ymin; - } - if (y2 >= f->ymax) { - x2 = (int) ((f->ymax-1-y1)*m + x1); - y2 = (int) (f->ymax-1); - } - - if ((x1 < f->xmin) || (x1 >= f->xmax) || (y1 < f->ymin) || (y1 >= f->ymax) || - (x2 < f->xmin) || (x2 >= f->xmax) || (y2 < f->ymin) || (y2 >= f->ymax)) return; - - dx = x2 - x1; - dy = y2 - y1; - xpixels = f->width; - ypixels = f->height; - - dxneg = (dx < 0) ? 1 : 0; - dyneg = (dy < 0) ? 1 : 0; - - dx = abs(dx); - dy = abs(dy); - if (dx >= dy) { - /* Slope between -1 and 1. */ - if (dxneg) { - x = x1; - y = y1; - x1 = x2; - y1 = y2; - x2 = x; - y2 = y; - dyneg = !dyneg; - } - inc1 = 2*dy; - inc2 = 2*(dy-dx); - di = 2*dy-dx; - - /* Draw a line using x as independent variable */ - - p = &f->pixels[y1][x1]; - x = x1; - while (x <= x2) { - *(p++) = c; - if (di < 0) { - di = di + inc1; - } else { - if (dyneg) { - p = p - xpixels; - di = di + inc2; - } else { - p = p + xpixels; - di = di + inc2; - } - } - x++; - } - } else { - /* Slope < -1 or > 1 */ - if (dyneg) { - x = x1; - y = y1; - x1 = x2; - y1 = y2; - x2 = x; - y2 = y; - dxneg = !dxneg; - } - inc1 = 2*dx; - inc2 = 2*(dx-dy); - di = 2*dx-dy; - - /* Draw a line using y as independent variable */ - - p = &f->pixels[y1][x1]; - y = y1; - while (y <= y2) { - *p = c; - p = p + xpixels; - if (di < 0) { - di = di + inc1; - } else { - if (dxneg) { - p = p - 1; - di = di + inc2; - } else { - p = p + 1; - di = di + inc2; - } - } - y++; - } - } -} - - -/* ------------------------------------------------------------------------- - FrameBuffer_circle(FrameBuffer f, int xc, int yc, int radius, Pixel c) - - Create an outline circle - ------------------------------------------------------------------------- */ - -#define plot_circle(x,y,c) \ - if ((x >= xmin) && (x < xmax) && \ - (y >= ymin) && (y < ymax)) \ - pixels[y][x] = c; - -void FrameBuffer_circle(FrameBuffer *f, int xc, int yc, int radius, Pixel c) { - - int xpixels, ypixels, x, y, p; - int xmin, ymin, xmax, ymax; - Pixel **pixels; - - if (radius <= 0) return; - xpixels = f->width; - ypixels = f->height; - pixels = f->pixels; - xmin = f->xmin; - ymin = f->ymin; - xmax = f->xmax; - ymax = f->ymax; - x = 0; - y = radius; - p = 3-2*radius; - while (x <= y) { - plot_circle(xc+x,yc+y,c); - plot_circle(xc-x,yc+y,c); - plot_circle(xc+x,yc-y,c); - plot_circle(xc-x,yc-y,c); - plot_circle(xc+y,yc+x,c); - plot_circle(xc-y,yc+x,c); - plot_circle(xc+y,yc-x,c); - plot_circle(xc-y,yc-x,c); - if (p < 0) p = p + 4*x + 6; - else { - p = p + 4*(x-y) + 10; - y = y -1; - } - x++; - } -} - - -/* ------------------------------------------------------------------------- - FrameBuffer_solidcircle(FrameBuffer f, int xc, int yc, int radius, Pixel c) - - Create an filled circle - ------------------------------------------------------------------------- */ - - -#define fill_circle(x,y,c) \ - x1 = xc - x; \ - x2 = xc + x; \ - FrameBuffer_horizontal(f,x1,x2,y,c); - -void FrameBuffer_solidcircle(FrameBuffer *f, int xc, int yc, int radius, Pixel c) { - - int xpixels, ypixels, x, y, p; - int x1,x2; - int xmin, ymin, xmax, ymax; - Pixel **pixels; - - if (radius <= 0) return; - xpixels = f->width; - ypixels = f->height; - pixels = f->pixels; - xmin = f->xmin; - ymin = f->ymin; - xmax = f->xmax; - ymax = f->ymax; - x = 0; - y = radius; - p = 3-2*radius; - while (x <= y) { - fill_circle(x,yc+y,c); - fill_circle(x,yc-y,c); - fill_circle(y,yc+x,c); - fill_circle(y,yc-x,c); - if (p < 0) p = p + 4*x + 6; - else { - p = p + 4*(x-y) + 10; - y = y -1; - } - x++; - } -} - -/* ------------------------------------------------------------------------ - void FrameBuffer_setclip(f,xmin,ymin,xmax,ymax) - - Set clipping region for plotting - ------------------------------------------------------------------------ */ - -void FrameBuffer_setclip(FrameBuffer *f, int xmin, int ymin, int xmax, int ymax) { - - if (xmin >= xmax) return; - if (ymin >= ymax) return; - - if (xmin < 0) xmin = 0; - if (ymin < 0) ymin = 0; - if (xmax > (int) f->width) xmax = f->width; - if (ymax > (int) f->height) ymax = f->height; - - f->xmin = xmin; - f->ymin = ymin; - f->xmax = xmax; - f->ymax = ymax; -} - -/* ------------------------------------------------------------------------ - void FrameBuffer_noclip(f) - - Disable clipping region - ------------------------------------------------------------------------ */ - -void FrameBuffer_noclip(FrameBuffer *f) { - f->xmin = 0; - f->ymin = 0; - f->xmax = f->width; - f->ymax = f->height; -} - - -/* ------------------------------------------------------------------------ - FrameBuffer_zresize(FrameBuffer *f, int width, int height) - - This function resizes the framebuffer's zbuffer. If none exist, it - creates a new one. - ------------------------------------------------------------------------ */ - -void FrameBuffer_zresize(FrameBuffer *f, int width, int height) { - int i; - - if (f->zbuffer) { - free((char *)f->zbuffer[0]); - free((char *)f->zbuffer); - } - f->zbuffer = (Zvalue **) malloc(height*sizeof(Zvalue *)); - f->zbuffer[0] = (Zvalue *) malloc(height*width*sizeof(Zvalue)); - for (i = 0; i < height; i++) - f->zbuffer[i] = f->zbuffer[0]+i*width; -} - -/* ------------------------------------------------------------------------ - FrameBuffer_zclear(FrameBuffer *f) - - Clears the z-buffer for a particular frame. Sets all of the z-values to - ZMIN. - ------------------------------------------------------------------------- */ - -void FrameBuffer_zclear(FrameBuffer *f) { - unsigned int i,j; - if (f) { - if (f->zbuffer) { - for (i = 0; i < f->width; i++) - for (j = 0; j < f->height; j++) - f->zbuffer[j][i] = ZMIN; - } - } -} - - - -/* ------------------------------------------------------------------------- - FrameBuffer_solidtriangle(FrameBuffer *f, int tx1, int ty2, - int tx2, int ty2, - int tx3, int ty3, Pixel color) - - This function draws a 2D filled triangle. - - General idea : - 1. Transform the three points into screen coordinates - 2. Order three points vertically on screen. - 3. Check for degenerate cases (where 3 points are colinear). - 4. Fill in the resulting triangle using horizontal lines. - -------------------------------------------------------------------------- */ - -void FrameBuffer_solidtriangle(FrameBuffer *f, int tx1, int ty1, - int tx2, int ty2, - int tx3, int ty3, Pixel color) { - int tempx, tempy; - double m1,m2,m3; - int y; - int ix1, ix2; - - /* Figure out which point has the greatest "y" value */ - - if (ty2 > ty1) { /* Swap points 1 and 2 if 2 is higher */ - tempx = tx1; - tempy = ty1; - tx1 = tx2; - ty1 = ty2; - tx2 = tempx; - ty2 = tempy; - } - if (ty3 > ty1) { /* Swap points 1 and 3 if 3 is higher */ - tempx = tx1; - tempy = ty1; - tx1 = tx3; - ty1 = ty3; - tx3 = tempx; - ty3 = tempy; - } - if (ty3 > ty2) { /* Swap points 2 and 3 if 3 is higher */ - tempx = tx2; - tempy = ty2; - tx2 = tx3; - ty2 = ty3; - tx3 = tempx; - ty3 = tempy; - } - - /* Points are now order so that t_1 is the highest point, t_2 is the - middle point, and t_3 is the lowest point */ - - /* Check for degenerate cases here */ - - if ((ty1 == ty2) && (ty2 == ty3)) { - - /* Points are aligned horizontally. Handle as a special case */ - /* Just draw three lines using the outline color */ - - FrameBuffer_line(f,tx1,ty1,tx2,ty2,color); - FrameBuffer_line(f,tx1,ty1,tx3,ty3,color); - FrameBuffer_line(f,tx2,ty2,tx3,ty3,color); - - } else { - - if (ty2 < ty1) { - /* First process line segments between (x1,y1)-(x2,y2) - And between (x1,y1),(x3,y3) */ - - m1 = (double) (tx2 - tx1)/(double) (ty2 - ty1); - m2 = (double) (tx3 - tx1)/(double) (ty3 - ty1); - - y = ty1; - while (y >= ty2) { - /* Calculate x values from slope */ - ix1 = (int) (m1*(y-ty1)+0.5) + tx1; - ix2 = (int) (m2*(y-ty1)+0.5) + tx1; - if (ix1 > ix2) - FrameBuffer_horizontal(f,ix2,ix1,y,color); - else - FrameBuffer_horizontal(f,ix1,ix2,y,color); - y--; - } - } - if (ty3 < ty2) { - /* Draw lower half of the triangle */ - m2 = (double) (tx3 - tx1)/(double) (ty3 - ty1); - m3 = (double) (tx3 - tx2)/(double)(ty3 - ty2); - y = ty2; - while (y >= ty3) { - ix1 = (int) (m3*(y-ty2)+0.5)+tx2; - ix2 = (int) (m2*(y-ty1)+0.5)+tx1; - if (ix1 > ix2) - FrameBuffer_horizontal(f,ix2,ix1,y,color); - else - FrameBuffer_horizontal(f,ix1,ix2,y,color); - y--; - } - } - } -} - -/* ------------------------------------------------------------------------- - FrameBuffer_interptriangle(FrameBuffer *f, - int tx1, int ty2, Pixel c1, - int tx2, int ty2, Pixel c2, - int tx3, int ty3, Pixel c3) - - This function draws a filled triangle with color - interpolation. - - General idea : - 1. Transform the three points into screen coordinates - 2. Order three points vertically on screen. - 3. Check for degenerate cases (where 3 points are colinear). - 4. Fill in the resulting triangle using horizontal lines. - 5. Colors are interpolated between end points - -------------------------------------------------------------------------- */ - -void FrameBuffer_interptriangle(FrameBuffer *f, - int tx1, int ty1, Pixel c1, - int tx2, int ty2, Pixel c2, - int tx3, int ty3, Pixel c3) { - int tempx, tempy; - double m1,m2,m3; - double mc1,mc2,mc3; - Pixel ic1,ic2,tempc; - int y; - int ix1, ix2; - - /* Figure out which point has the greatest "y" value */ - - if (ty2 > ty1) { /* Swap points 1 and 2 if 2 is higher */ - tempx = tx1; - tempy = ty1; - tempc = c1; - tx1 = tx2; - ty1 = ty2; - c1 = c2; - tx2 = tempx; - ty2 = tempy; - c2 = tempc; - } - if (ty3 > ty1) { /* Swap points 1 and 3 if 3 is higher */ - tempx = tx1; - tempy = ty1; - tempc = c1; - tx1 = tx3; - ty1 = ty3; - c1 = c3; - tx3 = tempx; - ty3 = tempy; - c3 = tempc; - } - if (ty3 > ty2) { /* Swap points 2 and 3 if 3 is higher */ - tempx = tx2; - tempy = ty2; - tempc = c2; - tx2 = tx3; - ty2 = ty3; - c2 = c3; - tx3 = tempx; - ty3 = tempy; - c3 = tempc; - } - - /* Points are now order so that t_1 is the highest point, t_2 is the - middle point, and t_3 is the lowest point */ - - /* Check for degenerate cases here */ - - if ((ty1 == ty2) && (ty2 == ty3)) { - - /* Points are aligned horizontally. Handle as a special case */ - /* Just draw three lines using the outline color */ - - if (tx2 > tx1) - FrameBuffer_horizontalinterp(f,tx1,tx2,ty1,c1,c2); - else - FrameBuffer_horizontalinterp(f,tx2,tx1,ty1,c2,c1); - if (tx3 > tx1) - FrameBuffer_horizontalinterp(f,tx1,tx3,ty1,c1,c3); - else - FrameBuffer_horizontalinterp(f,tx3,tx1,ty1,c3,c1); - if (tx3 > tx2) - FrameBuffer_horizontalinterp(f,tx2,tx3,ty2,c2,c3); - else - FrameBuffer_horizontalinterp(f,tx3,tx2,ty2,c3,c2); - - } else { - - /* First process line segments between (x1,y1)-(x2,y2) - And between (x1,y1),(x3,y3) */ - - if (ty2 < ty1) { - m1 = (double) (tx2 - tx1)/(double) (ty2 - ty1); - m2 = (double) (tx3 - tx1)/(double) (ty3 - ty1); - mc1 = (c2 - c1)/(double) (ty2 - ty1); - mc2 = (c3 - c1)/(double) (ty3 - ty1); - - y = ty1; - while (y >= ty2) { - /* Calculate x values from slope */ - ix1 = (int) (m1*(y-ty1)+0.5) + tx1; - ix2 = (int) (m2*(y-ty1)+0.5) + tx1; - ic1 = (int) (mc1*(y-ty1) + c1); - ic2 = (int) (mc2*(y-ty1) + c1); - if (ix1 > ix2) - FrameBuffer_horizontalinterp(f,ix2,ix1,y,ic2,ic1); - else - FrameBuffer_horizontalinterp(f,ix1,ix2,y,ic1,ic2); - y--; - } - } - if (ty3 < ty2) { - /* Draw lower half of the triangle */ - m2 = (double) (tx3 - tx1)/(double) (ty3 - ty1); - mc2 = (c3 - c1)/(double) (ty3 - ty1); - m3 = (double) (tx3 - tx2)/(double)(ty3 - ty2); - mc3 = (c3 - c2)/(double) (ty3 - ty2); - y = ty2; - while (y >= ty3) { - ix1 = (int) (m3*(y-ty2)+0.5)+tx2; - ix2 = (int) (m2*(y-ty1)+0.5)+tx1; - ic1 = (int) (mc3*(y-ty2)+c2); - ic2 = (int) (mc2*(y-ty1)+c1); - if (ix1 > ix2) - FrameBuffer_horizontalinterp(f,ix2,ix1,y,ic2,ic1); - else - FrameBuffer_horizontalinterp(f,ix1,ix2,y,ic1,ic2); - y--; - } - } - } -} - - diff --git a/Examples/GIFPlot/Lib/gif.c b/Examples/GIFPlot/Lib/gif.c deleted file mode 100644 index 7953e5ce9..000000000 --- a/Examples/GIFPlot/Lib/gif.c +++ /dev/null @@ -1,672 +0,0 @@ - -/********************************************************************** - * GIFPlot 0.0 - * - * Dave Beazley - * - * Department of Computer Science Theoretical Division (T-11) - * University of Utah Los Alamos National Laboratory - * Salt Lake City, Utah 84112 Los Alamos, New Mexico 87545 - * beazley@cs.utah.edu beazley@lanl.gov - * - * Copyright (c) 1996 - * The Regents of the University of California and the University of Utah - * All Rights Reserved - * - * Permission is hereby granted, without written agreement and without - * license or royalty fees, to use, copy, modify, and distribute this - * software and its documentation for any purpose, provided that - * (1) The above copyright notice and the following two paragraphs - * appear in all copies of the source code and (2) redistributions - * including binaries reproduces these notices in the supporting - * documentation. Substantial modifications to this software may be - * copyrighted by their authors and need not follow the licensing terms - * described here, provided that the new terms are clearly indicated in - * all files where they apply. - * - * IN NO EVENT SHALL THE AUTHOR, THE UNIVERSITY OF CALIFORNIA, THE - * UNIVERSITY OF UTAH OR DISTRIBUTORS OF THIS SOFTWARE BE LIABLE TO ANY - * PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL - * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, - * EVEN IF THE AUTHORS OR ANY OF THE ABOVE PARTIES HAVE BEEN ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - * - * THE AUTHOR, THE UNIVERSITY OF CALIFORNIA, AND THE UNIVERSITY OF UTAH - * SPECIFICALLY DISCLAIM ANY WARRANTIES,INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND - * THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, - * SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. - * - **************************************************************************/ - -/******************************************************************* - * Creates a GIF format file. - * - * Dave Beazley (T-11) - * August 11, 1995 - * - * Rather than writing directly to files, this module fills out - * output buffer. - * - * Note : To save memory, this routine uses approximately 50K of the - * output buffer as temporary storage (for hash tables and compression codes). - * The remainder of the output buffer is used to store the final image. - * This feature allows GIF images to be created with no additional - * memory overhead. - * - * -- Revision History - * $Log$ - * Revision 1.2 2003/09/01 16:23:31 beazley - * Restored the 'mojo'. - * - * Revision 1.2 1996/09/25 22:39:30 dmb - * Fixed prototypes and use of void pointers for compatibility with the Cray T3D - * - * Revision 1.1 1996/09/10 17:44:00 dmb - * Initial revision - * - * Revision 1.2 1995/08/31 14:46:07 beazley - * Minor changes to support comments and a few bug fixes. - * - * - ******************************************************************/ - - -/* - * xvgifwr.c - handles writing of GIF files. based on flgife.c and - * flgifc.c from the FBM Library, by Michael Maudlin - * - * Contains: - * WriteGIF(fp, pic, ptype, w, h, rmap, gmap, bmap, numcols, colorstyle, - * comment) - * - * Note: slightly brain-damaged, in that it'll only write non-interlaced - * GIF files (in the interests of speed, or something) - * - */ - - - -/***************************************************************** - * Portions of this code Copyright (C) 1989 by Michael Mauldin. - * Permission is granted to use this file in whole or in - * part for any purpose, educational, recreational or commercial, - * provided that this copyright notice is retained unchanged. - * This software is available to all free of charge by anonymous - * FTP and in the UUNET archives. - * - * - * Authors: Michael Mauldin (mlm@cs.cmu.edu) - * David Rowley (mgardi@watdcsu.waterloo.edu) - * - * Based on: compress.c - File compression ala IEEE Computer, June 1984. - * - * Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas) - * Jim McKie (decvax!mcvax!jim) - * Steve Davies (decvax!vax135!petsd!peora!srd) - * Ken Turkowski (decvax!decwrl!turtlevax!ken) - * James A. Woods (decvax!ihnp4!ames!jaw) - * Joe Orost (decvax!vax135!petsd!joe) - *****************************************************************/ - -#include "gifplot.h" -#include -typedef long int count_int; -typedef unsigned char byte; - -static int gif_error; -static unsigned char *op; -static int Width, Height; -static int curx, cury; -static int Interlace; - -static void putgifword(int); -static void compress(int, byte **, int); -static void output_GIF(int); -static void cl_block(void); -static void cl_hash(count_int); -static void char_init(void); -static void char_out(int); -static void flush_char(void); -static void *OutBuffer; -static int OutBufSize; -static FrameBuffer *GIF_frame; - -static unsigned char pc2nc[256],r1[256],g1[256],b1[256]; - -/*************************************************************/ -int FrameBuffer_makeGIF(FrameBuffer *f, ColorMap *c, void *outbuffer, unsigned int outbufsize) -{ - int RWidth, RHeight; - int LeftOfs, TopOfs; - int ColorMapSize, InitCodeSize, Background, BitsPerPixel; - int i,j,nc; - char *rmap, *gmap, *bmap; - char *cmap; - int count; - - Interlace = 0; - Background = 0; - OutBuffer = outbuffer; - OutBufSize = outbufsize; - GIF_frame = f; - cmap = (char *) c->cmap; - - op = (unsigned char *) outbuffer; - gif_error = 0; - for (i=0; i<256; i++) { pc2nc[i] = r1[i] = g1[i] = b1[i] = 0; } - - /* compute number of unique colors */ - nc = 0; - rmap = &cmap[0]; - gmap = &cmap[256]; - bmap = &cmap[512]; - - for (i=0; i<256; i++) { - /* see if color #i is already used */ - for (j=0; j= nc) break; - - BitsPerPixel = i; - - ColorMapSize = 1 << BitsPerPixel; - - RWidth = Width = f->width; - RHeight = Height = f->height; - LeftOfs = TopOfs = 0; - - if (BitsPerPixel <= 1) InitCodeSize = 2; - else InitCodeSize = BitsPerPixel; - - curx = 0; - cury = f->height - 1; - - strcpy((char *) op,"GIF89a"); /* Put in GIF magic number */ - op+=6; - putgifword(RWidth); /* screen descriptor */ - putgifword(RHeight); - - i = 0x80; /* Yes, there is a color map */ - i |= (8-1)<<4; /* OR in the color resolution (hardwired 8) */ - i |= (BitsPerPixel - 1); /* OR in the # of bits per pixel */ - *(op++) = i; - *(op++) = Background; /* background color */ - *(op++) = 0; - for (i=0; ipixels, f->width*f->height); - - *(op++) = 0; - *(op++) = ';'; - - count = (op - (unsigned char *) OutBuffer); - if (gif_error) return -1; - else return count; -} - -/******************************/ -static void putgifword(w) -int w; -{ - /* writes a 16-bit integer in GIF order (LSB first) */ - *(op++) = w & 0xff; - *(op++) = (w>>8)&0xff; -} - -/***********************************************************************/ - - -static unsigned long cur_accum = 0; -static int cur_bits = 0; - - - - -#define GP_BITS 12 /* BITS was already defined on some systems */ - -#define HSIZE 5003 /* 80% occupancy */ - -typedef unsigned char char_type; - -static int n_bits; /* number of bits/code */ -static int maxbits = GP_BITS; /* user settable max # bits/code */ -static int maxcode; /* maximum code, given n_bits */ -static int maxmaxcode = 1 << GP_BITS; /* NEVER generate this */ - -#define MAXCODE(n_bits) ( (1 << (n_bits)) - 1) - -static count_int *htab; -static unsigned short *codetab; -static int GIFOutBufSize; - -/* static count_int htab [HSIZE]; -static unsigned short codetab [HSIZE]; */ - -#define HashTabOf(i) htab[i] -#define CodeTabOf(i) codetab[i] - -static int hsize = HSIZE; /* for dynamic table sizing */ - -/* - * To save much memory, we overlay the table used by compress() with those - * used by decompress(). The tab_prefix table is the same size and type - * as the codetab. The tab_suffix table needs 2**BITS characters. We - * get this from the beginning of htab. The output stack uses the rest - * of htab, and contains characters. There is plenty of room for any - * possible stack (stack used to be 8000 characters). - */ - -#define tab_prefixof(i) CodeTabOf(i) -#define tab_suffixof(i) ((char_type *)(htab))[i] -#define de_stack ((char_type *)&tab_suffixof(1<= GIF_frame->width) { - curx = 0; - cury--; - } - len--; - - hshift = 0; - for ( fcode = (long) hsize; fcode < 65536L; fcode *= 2L ) - hshift++; - hshift = 8 - hshift; /* set hash code range bound */ - - hsize_reg = hsize; - cl_hash( (count_int) hsize_reg); /* clear hash table */ - - output_GIF(ClearCode); - while (len) { - c = pc2nc[data[cury][curx]]; - curx++; - if (curx >= GIF_frame->width) { - curx = 0; - cury--; - } - len--; - - fcode = (long) ( ( (long) c << maxbits) + ent); - i = (((int) c << hshift) ^ ent); /* xor hashing */ - - if ( HashTabOf (i) == fcode ) { - ent = CodeTabOf (i); - continue; - } - - if ( (long)HashTabOf (i) < 0 ) /* empty slot */ - goto nomatch; - - disp = hsize_reg - i; /* secondary hash (after G. Knott) */ - if ( i == 0 ) - disp = 1; - -probe: - if ( (i -= disp) < 0 ) - i += hsize_reg; - - if ( HashTabOf (i) == fcode ) { - ent = CodeTabOf (i); - continue; - } - - if ( (long)HashTabOf (i) >= 0 ) - goto probe; - -nomatch: - output_GIF(ent); - out_count++; - ent = c; - - if ( free_ent < maxmaxcode ) { - CodeTabOf (i) = free_ent++; /* code -> hashtable */ - HashTabOf (i) = fcode; - } - else - cl_block(); - - } - /* Put out the final code */ - output_GIF(ent); - output_GIF(EOFCode); -} - - -/***************************************************************** - * TAG( output_GIF ) - * - * Output the given code. - * Inputs: - * code: A n_bits-bit integer. If == -1, then EOF. This assumes - * that n_bits =< (long)wordsize - 1. - * Outputs: - * Outputs code to the file. - * Assumptions: - * Chars are 8 bits long. - * Algorithm: - * Maintain a BITS character long buffer (so that 8 codes will - * fit in it exactly). Use the VAX insv instruction to insert each - * code in turn. When the buffer fills up empty it and start over. - */ - -static -unsigned long masks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, - 0x001F, 0x003F, 0x007F, 0x00FF, - 0x01FF, 0x03FF, 0x07FF, 0x0FFF, - 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; - -static void output_GIF(code) -int code; -{ - cur_accum &= masks[cur_bits]; - - if (cur_bits > 0) - cur_accum |= ((long)code << cur_bits); - else - cur_accum = code; - - cur_bits += n_bits; - - while( cur_bits >= 8 ) { - char_out( (int) (cur_accum & 0xff) ); - cur_accum >>= 8; - cur_bits -= 8; - } - - /* - * If the next entry is going to be too big for the code size, - * then increase it, if possible. - */ - - if (free_ent > maxcode || clear_flg) { - - if( clear_flg ) { - maxcode = MAXCODE (n_bits = g_init_bits); - clear_flg = 0; - } - else { - n_bits++; - if ( n_bits == maxbits ) - maxcode = maxmaxcode; - else - maxcode = MAXCODE(n_bits); - } - } - - if( code == EOFCode ) { - /* At EOF, write the rest of the buffer */ - while( cur_bits > 0 ) { - char_out( (int)(cur_accum & 0xff) ); - cur_accum >>= 8; - cur_bits -= 8; - } - - flush_char(); - } -} - - -/********************************/ -static void cl_block () /* table clear for block compress */ -{ - /* Clear out the hash table */ - - cl_hash ( (count_int) hsize ); - free_ent = ClearCode + 2; - clear_flg = 1; - - output_GIF(ClearCode); -} - - -/********************************/ -static void cl_hash(hsize) /* reset code table */ -register count_int hsize; -{ - register count_int *htab_p = htab+hsize; - register long i; - register long m1 = -1; - - i = hsize - 16; - do { /* might use Sys V memset(3) here */ - *(htab_p-16) = m1; - *(htab_p-15) = m1; - *(htab_p-14) = m1; - *(htab_p-13) = m1; - *(htab_p-12) = m1; - *(htab_p-11) = m1; - *(htab_p-10) = m1; - *(htab_p-9) = m1; - *(htab_p-8) = m1; - *(htab_p-7) = m1; - *(htab_p-6) = m1; - *(htab_p-5) = m1; - *(htab_p-4) = m1; - *(htab_p-3) = m1; - *(htab_p-2) = m1; - *(htab_p-1) = m1; - htab_p -= 16; - } while ((i -= 16) >= 0); - - for ( i += 16; i > 0; i-- ) - *--htab_p = m1; -} - - -/****************************************************************************** - * - * GIF Specific routines - * - ******************************************************************************/ - -/* - * Number of characters so far in this 'packet' - */ -static int a_count; - -/* - * Set up the 'byte output' routine - */ -static void char_init() -{ - a_count = 0; -} - -/* - * Define the storage for the packet accumulator - */ -static char accum[ 256 ]; - -/* - * Add a character to the end of the current packet, and if it is 254 - * characters, flush the packet to disk. - */ -static void char_out(c) -int c; -{ - accum[ a_count++ ] = c; - if( a_count >= 254 ) - flush_char(); -} - -/* - * Flush the packet to disk, and reset the accumulator - */ -static void flush_char() -{ - if (gif_error) return; - if( a_count > 0 ) { - *(op++) = a_count; - memcpy(op,accum,a_count); - op+=a_count; - a_count = 0; - - if (op > (unsigned char *) ((char *) OutBuffer + (GIFOutBufSize - 2048))) { - gif_error = 1; - } - } -} - - -/* ---------------------------------------------------------------------- - int FrameBuffer_writeGIF(char *filename) - - Write a GIF file to filename - ----------------------------------------------------------------------- */ - -int FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename) { - - FILE *file; - void *buffer; - int nbytes; - int bufsize; - - file = fopen(filename,"wb"); - if (file == NULL) return -1; - - bufsize = (f->width*f->height*3)/2; - buffer = (void *) malloc(bufsize); - nbytes = FrameBuffer_makeGIF(f,c,buffer,bufsize); - if (nbytes == -1) { - free(buffer); - fclose(file); - return -1; - } - if (fwrite(buffer,nbytes,1,file) != 1) { - free(buffer); - fclose(file); - return -1; - } - fclose(file); - free(buffer); - return 0; -} - - - - - diff --git a/Examples/GIFPlot/Lib/matrix.c b/Examples/GIFPlot/Lib/matrix.c deleted file mode 100644 index ef0cf3aab..000000000 --- a/Examples/GIFPlot/Lib/matrix.c +++ /dev/null @@ -1,343 +0,0 @@ -/* ----------------------------------------------------------------------------- - * matrix.c - * - * Some 4x4 matrix operations - * - * Author(s) : David Beazley (beazley@cs.uchicago.edu) - * Copyright (C) 1995-1996 - * - * See the file LICENSE for information on usage and redistribution. - * ----------------------------------------------------------------------------- */ - -#define MATRIX -#include "gifplot.h" -#include - -/* ------------------------------------------------------------------------ - Matrix new_Matrix() - - Create a new 4x4 matrix. - ------------------------------------------------------------------------ */ -Matrix -new_Matrix() { - Matrix m; - m = (Matrix) malloc(16*sizeof(double)); - return m; -} - -/* ------------------------------------------------------------------------ - delete_Matrix(Matrix *m); - - Destroy a matrix - ------------------------------------------------------------------------ */ - -void -delete_Matrix(Matrix m) { - if (m) - free((char *) m); -} - -/* ------------------------------------------------------------------------ - Matrix Matrix_copy(Matrix a) - - Makes a copy of matrix a and returns it. - ------------------------------------------------------------------------ */ - -Matrix Matrix_copy(Matrix a) { - int i; - Matrix r = 0; - if (a) { - r = new_Matrix(); - if (r) { - for (i = 0; i < 16; i++) - r[i] = a[i]; - } - } - return r; -} - -/* ------------------------------------------------------------------------ - Matrix_multiply(Matrix a, Matrix b, Matrix c) - - Multiplies a*b = c - c may be one of the source matrices - ------------------------------------------------------------------------ */ -void -Matrix_multiply(Matrix a, Matrix b, Matrix c) { - double temp[16]; - int i,j,k; - - for (i =0; i < 4; i++) - for (j = 0; j < 4; j++) { - temp[i*4+j] = 0.0; - for (k = 0; k < 4; k++) - temp[i*4+j] += a[i*4+k]*b[k*4+j]; - } - for (i = 0; i < 16; i++) - c[i] = temp[i]; -} - -/* ------------------------------------------------------------------------ - Matrix_identity(Matrix a) - - Puts an identity matrix in matrix a - ------------------------------------------------------------------------ */ - -void -Matrix_identity(Matrix a) { - int i; - for (i = 0; i < 16; i++) a[i] = 0; - a[0] = 1; - a[5] = 1; - a[10] = 1; - a[15] = 1; -} - -/* ------------------------------------------------------------------------ - Matrix_zero(Matrix a) - - Puts a zero matrix in matrix a - ------------------------------------------------------------------------ */ -void -Matrix_zero(Matrix a) { - int i; - for (i = 0; i < 16; i++) a[i] = 0; -} - -/* ------------------------------------------------------------------------ - Matrix_transpose(Matrix a, Matrix result) - - Transposes matrix a and puts it in result. - ------------------------------------------------------------------------ */ -void -Matrix_transpose(Matrix a, Matrix result) { - double temp[16]; - int i,j; - - for (i = 0; i < 4; i++) - for (j = 0; j < 4; j++) - temp[4*i+j] = a[4*j+i]; - - for (i = 0; i < 16; i++) - result[i] = temp[i]; -} - - -/* ------------------------------------------------------------------------ - Matrix_gauss(Matrix a, Matrix b) - - Solves ax=b for x, using Gaussian elimination. Destroys a. - Really only used for calculating inverses of 4x4 transformation - matrices. - ------------------------------------------------------------------------ */ - -void Matrix_gauss(Matrix a, Matrix b) { - int ipiv[4], indxr[4], indxc[4]; - int i,j,k,l,ll; - int irow=0, icol=0; - double big, pivinv; - double dum; - for (j = 0; j < 4; j++) - ipiv[j] = 0; - for (i = 0; i < 4; i++) { - big = 0; - for (j = 0; j < 4; j++) { - if (ipiv[j] != 1) { - for (k = 0; k < 4; k++) { - if (ipiv[k] == 0) { - if (fabs(a[4*j+k]) >= big) { - big = fabs(a[4*j+k]); - irow = j; - icol = k; - } - } else if (ipiv[k] > 1) - return; /* Singular matrix */ - } - } - } - ipiv[icol] = ipiv[icol]+1; - if (irow != icol) { - for (l = 0; l < 4; l++) { - dum = a[4*irow+l]; - a[4*irow+l] = a[4*icol+l]; - a[4*icol+l] = dum; - } - for (l = 0; l < 4; l++) { - dum = b[4*irow+l]; - b[4*irow+l] = b[4*icol+l]; - b[4*icol+l] = dum; - } - } - indxr[i] = irow; - indxc[i] = icol; - if (a[4*icol+icol] == 0) return; - pivinv = 1.0/a[4*icol+icol]; - a[4*icol+icol] = 1.0; - for (l = 0; l < 4; l++) - a[4*icol+l] = a[4*icol+l]*pivinv; - for (l = 0; l < 4; l++) - b[4*icol+l] = b[4*icol+l]*pivinv; - for (ll = 0; ll < 4; ll++) { - if (ll != icol) { - dum = a[4*ll+icol]; - a[4*ll+icol] = 0; - for (l = 0; l < 4; l++) - a[4*ll+l] = a[4*ll+l] - a[4*icol+l]*dum; - for (l = 0; l < 4; l++) - b[4*ll+l] = b[4*ll+l] - b[4*icol+l]*dum; - } - } - } - for (l = 3; l >= 0; l--) { - if (indxr[l] != indxc[l]) { - for (k = 0; k < 4; k++) { - dum = a[4*k+indxr[l]]; - a[4*k+indxr[l]] = a[4*k+indxc[l]]; - a[4*k+indxc[l]] = dum; - } - } - } -} - -/* ------------------------------------------------------------------------ - Matrix_invert(Matrix a, Matrix inva) - - Inverts Matrix a and places the result in inva. - Relies on the Gaussian Elimination code above. (See Numerical recipes). - ------------------------------------------------------------------------ */ -void -Matrix_invert(Matrix a, Matrix inva) { - - double temp[16]; - int i; - - for (i = 0; i < 16; i++) - temp[i] = a[i]; - Matrix_identity(inva); - Matrix_gauss(temp,inva); -} - -/* ------------------------------------------------------------------------ - Matrix_transform(Matrix a, GL_Vector *r, GL_Vector *t) - - Transform a vector. a*r ----> t - ------------------------------------------------------------------------ */ - -void Matrix_transform(Matrix a, GL_Vector *r, GL_Vector *t) { - - double rx, ry, rz, rw; - - rx = r->x; - ry = r->y; - rz = r->z; - rw = r->w; - t->x = a[0]*rx + a[1]*ry + a[2]*rz + a[3]*rw; - t->y = a[4]*rx + a[5]*ry + a[6]*rz + a[7]*rw; - t->z = a[8]*rx + a[9]*ry + a[10]*rz + a[11]*rw; - t->w = a[12]*rx + a[13]*ry + a[14]*rz + a[15]*rw; -} - -/* ------------------------------------------------------------------------ - Matrix_transform4(Matrix a, double x, double y, double z, double w, GL_Vector *t) - - Transform a vector from a point specified as 4 doubles - ------------------------------------------------------------------------ */ - -void Matrix_transform4(Matrix a, double rx, double ry, double rz, double rw, - GL_Vector *t) { - - t->x = a[0]*rx + a[1]*ry + a[2]*rz + a[3]*rw; - t->y = a[4]*rx + a[5]*ry + a[6]*rz + a[7]*rw; - t->z = a[8]*rx + a[9]*ry + a[10]*rz + a[11]*rw; - t->w = a[12]*rx + a[13]*ry + a[14]*rz + a[15]*rw; -} - -/* --------------------------------------------------------------------- - Matrix_translate(Matrix a, double tx, double ty, double tz) - - Put a translation matrix in Matrix a - ---------------------------------------------------------------------- */ - -void Matrix_translate(Matrix a, double tx, double ty, double tz) { - Matrix_identity(a); - a[3] = tx; - a[7] = ty; - a[11] = tz; - a[15] = 1; -} - -/* ----------------------------------------------------------------------- - Matrix_rotatex(Matrix a, double deg) - - Produce an x-rotation matrix for given angle in degrees. - ----------------------------------------------------------------------- */ -void -Matrix_rotatex(Matrix a, double deg) { - double r; - - r = 3.1415926*deg/180.0; - Matrix_zero(a); - a[0] = 1.0; - a[5] = cos(r); - a[6] = -sin(r); - a[9] = sin(r); - a[10] = cos(r); - a[15] = 1.0; -} - -/* ----------------------------------------------------------------------- - Matrix_rotatey(Matrix a, double deg) - - Produce an y-rotation matrix for given angle in degrees. - ----------------------------------------------------------------------- */ -void -Matrix_rotatey(Matrix a, double deg) { - double r; - - r = 3.1415926*deg/180.0; - Matrix_zero(a); - a[0] = cos(r); - a[2] = sin(r); - a[5] = 1.0; - a[8] = -sin(r); - a[10] = cos(r); - a[15] = 1; - -} -/* ----------------------------------------------------------------------- - Matrix_RotateZ(Matrix a, double deg) - - Produce an z-rotation matrix for given angle in degrees. - ----------------------------------------------------------------------- */ -void -Matrix_rotatez(Matrix a, double deg) { - double r; - - r = 3.1415926*deg/180.0; - Matrix_zero(a); - a[0] = cos(r); - a[1] = -sin(r); - a[4] = sin(r); - a[5] = cos(r); - a[10] = 1.0; - a[15] = 1.0; -} - - -/* A debugging routine */ - -void Matrix_set(Matrix a, int i, int j, double val) { - a[4*j+i] = val; -} - -void Matrix_print(Matrix a) { - int i,j; - for (i = 0; i < 4; i++) { - for (j = 0; j < 4; j++) { - fprintf(stdout,"%10f ",a[4*i+j]); - } - fprintf(stdout,"\n"); - } - fprintf(stdout,"\n"); -} - diff --git a/Examples/GIFPlot/Lib/pixmap.c b/Examples/GIFPlot/Lib/pixmap.c deleted file mode 100644 index a55cf041f..000000000 --- a/Examples/GIFPlot/Lib/pixmap.c +++ /dev/null @@ -1,159 +0,0 @@ -/* ----------------------------------------------------------------------------- - * pixmap.c - * - * Pixel maps (i.e., bitmaps) - * - * Author(s) : David Beazley (beazley@cs.uchicago.edu) - * Copyright (C) 1995-1996 - * - * See the file LICENSE for information on usage and redistribution. - * ----------------------------------------------------------------------------- */ - -#define PIXMAP -#include "gifplot.h" - -/* ----------------------------------------------------------------------- - PixMap *new_PixMap(int width, int height, int centerx, int centery) - - Create a new pixmap of given size - ----------------------------------------------------------------------- */ -PixMap *new_PixMap(int width, int height, int centerx, int centery) { - PixMap *pm; - if ((width > 0) && (height > 0)) { - pm = (PixMap *) malloc(sizeof(PixMap)); - pm->width = width; - pm->height = height; - pm->centerx = centerx; - pm->centery = centery; - pm->map = (int *) malloc(height*width*sizeof(int)); - return pm; - } - return (PixMap *) 0; -} - -/* -------------------------------------------------------------------------- - void delete_PixMap(PixMap *pm) - - Destroy a pixmap - -------------------------------------------------------------------------- */ - -void delete_PixMap(PixMap *pm) { - if (pm) { - free((char *) pm->map); - free((char *) pm); - } -} - -/* --------------------------------------------------------------------------- - void PixMap_set(PixMap *pm, int x, int y, int pix) - - Set a pixel in the bitmap - --------------------------------------------------------------------------- */ -void -PixMap_set(PixMap *pm, int x, int y, int pix) { - if ((x < 0) || (x>=pm->width)) return; - if ((y < 0) || (y>=pm->height)) return; - - pm->map[pm->width*y + x] = pix; -} - -/* ----------------------------------------------------------------------------- - void FrameBuffer_drawpixmap(FrameBuffer *f, PixMap *pm, int x, int y, int fgcolor, int bgcolor) - - Draw a pixmap onto the framebuffer. This is somewhat optimized for speed. - ------------------------------------------------------------------------------ */ - -void -FrameBuffer_drawpixmap(FrameBuffer *f, PixMap *pm, int x, int y, int fgcolor, int bgcolor) { - - int startx, starty; /* Starting location on framebuffer */ - int startpixx = 0, startpixy = 0; /* Starting location in pixmap */ - int endx, endy; /* Ending location on framebuffer */ - int i,j, px, py; - int c; - - startx = x - pm->centerx; - starty = y + pm->centery; - endx = startx + pm->width; - endy = starty - pm->height; - - /* Figure out if we need to clip */ - - if (startx < f->xmin) { - startpixx = f->xmin - startx; - startx = f->xmin; - } - if (starty >= f->ymax) { - startpixy = starty - f->ymax; - starty = f->ymax-1; - } - if (endx >= f->xmax) { - endx = f->xmax-1; - } - if (endy < f->ymin) { - endy = f->ymin; - } - py = startpixy; - for (j = starty; j >= endy; j--) { - px = startpixx; - for (i = startx; i < endx; i++) { - c = pm->map[py*pm->width + px]; - switch (c) { - case GIFPLOT_FOREGROUND: - f->pixels[j][i] = fgcolor; - break; - case GIFPLOT_BACKGROUND: - f->pixels[j][i] = bgcolor; - break; - default: - break; - } - px++; - } - py++; - } -} - -/************************************************************************** - * Some common PixMaps (for plotting) - * - **************************************************************************/ - -int _SQUARE_MAP[] = { - 0,1,1,1,1,1,1,1, - 0,1,1,1,1,1,1,1, - 0,1,1,1,1,1,1,1, - 0,1,1,1,1,1,1,1, - 0,1,1,1,1,1,1,1, - 0,1,1,1,1,1,1,1, - 0,1,1,1,1,1,1,1, - 0,0,0,0,0,0,0,0 }; - -PixMap PixMap_SQUARE = { 8,8,4,4, _SQUARE_MAP}; - -int _TRIANGLE_MAP[] = { - 0,0,0,1,0,0,0,0, - 0,0,0,1,0,0,0,0, - 0,0,1,1,1,0,0,0, - 0,0,1,1,1,0,0,0, - 0,1,1,1,1,1,0,0, - 0,1,1,1,1,1,0,0, - 1,1,1,1,1,1,1,0, - 0,0,0,0,0,0,0,0 }; - -PixMap PixMap_TRIANGLE = { 8,8,4,4,_TRIANGLE_MAP}; - -int _CROSS_MAP[] = { - 0,0,0,1,0,0,0,0, - 0,0,0,1,0,0,0,0, - 0,0,0,1,0,0,0,0, - 1,1,1,1,1,1,1,0, - 0,0,0,1,0,0,0,0, - 0,0,0,1,0,0,0,0, - 0,0,0,1,0,0,0,0, - 0,0,0,0,0,0,0,0 }; - -PixMap PixMap_CROSS = { 8,8,4,4,_CROSS_MAP}; - - - diff --git a/Examples/GIFPlot/Lib/plot2d.c b/Examples/GIFPlot/Lib/plot2d.c deleted file mode 100644 index e78107bf1..000000000 --- a/Examples/GIFPlot/Lib/plot2d.c +++ /dev/null @@ -1,445 +0,0 @@ -/* ----------------------------------------------------------------------------- - * plot2d.c - * - * 2-Dimensional plotting - * - * Author(s) : David Beazley (beazley@cs.uchicago.edu) - * Copyright (C) 1995-1996 - * - * See the file LICENSE for information on usage and redistribution. - * ----------------------------------------------------------------------------- */ - -#define PLOT2D - -#include "gifplot.h" - -/* ------------------------------------------------------------------------ - Plot2D *new_Plot2D(FrameBuffer *frame, xmin, ymin, xmax, ymax) - - Create a new 2D plot with given minimum and maximum coordinates. - ------------------------------------------------------------------------ */ -Plot2D *new_Plot2D(FrameBuffer *frame,double xmin,double ymin,double xmax,double ymax) { - Plot2D *p2; - if (frame) { - if (xmax <= xmin) return (Plot2D *) 0; - if (ymax <= ymin) return (Plot2D *) 0; - p2 = (Plot2D *) malloc(sizeof(Plot2D)); - p2->frame = frame; - p2->xmin = xmin; - p2->ymin = ymin; - p2->xmax = xmax; - p2->ymax = ymax; - p2->view_xmin = 0; - p2->view_xmax = frame->width; - p2->view_ymin = 0; - p2->view_ymax = frame->height; - p2->xscale = LINEAR; - p2->yscale = LINEAR; - p2->dx = (p2->view_xmax - p2->view_xmin)/(p2->xmax - p2->xmin); - p2->dy = (p2->view_ymax - p2->view_ymin)/(p2->ymax - p2->ymin); - return p2; - } - return (Plot2D *) 0; -} - -/* ---------------------------------------------------------------------------- - delete_Plot2D(Plot2D *p2) - - Delete a 2D plot - ---------------------------------------------------------------------------- */ -void -delete_Plot2D(Plot2D *p2) { - if (p2) - free((char *) p2); -} - -/* ----------------------------------------------------------------------------- - Plot2D *Plot2D_copy(Plot2D *p2) - - Makes a copy of the Plot2D data structure. - ----------------------------------------------------------------------------- */ - -Plot2D *Plot2D_copy(Plot2D *p2) { - Plot2D *c2; - if (p2) { - c2 = (Plot2D *) malloc(sizeof(Plot2D)); - if (c2) { - c2->frame = p2->frame; - c2->view_xmin = p2->view_xmin; - c2->view_ymin = p2->view_ymin; - c2->view_xmax = p2->view_xmax; - c2->view_ymax = p2->view_ymax; - c2->xmin = p2->xmin; - c2->ymin = p2->ymin; - c2->xmax = p2->xmax; - c2->ymax = p2->ymax; - c2->xscale = p2->xscale; - c2->yscale = p2->yscale; - c2->dx = p2->dx; - c2->dy = p2->dy; - } - return c2; - } else { - return (Plot2D *) 0; - } -} - -/* ----------------------------------------------------------------------------- - Plot2D_clear(Plot2D *p2, Pixel c) - - Clear the region assigned to this plot to the given color. - -------------------------------------------------------------------------- */ - -void Plot2D_clear(Plot2D *p2, Pixel c) { - int i,j; - for (i = p2->view_xmin; i < p2->view_xmax; i++) - for (j = p2->view_ymin; j < p2->view_ymax; j++) { - p2->frame->pixels[j][i] = c; - } -} - -/* ------------------------------------------------------------------------------ - Plot2D_setview - - Sets the plot region on the framebuffer - ------------------------------------------------------------------------------ */ - -void -Plot2D_setview(Plot2D *p2, int vxmin, int vymin, int vxmax, int vymax) { - if (p2) { - p2->view_xmin = vxmin; - p2->view_ymin = vymin; - p2->view_xmax = vxmax; - p2->view_ymax = vymax; - p2->dx = (p2->view_xmax - p2->view_xmin)/(p2->xmax - p2->xmin); - p2->dy = (p2->view_ymax - p2->view_ymin)/(p2->ymax - p2->ymin); - FrameBuffer_setclip(p2->frame,vxmin,vymin,vxmax,vymax); - } -} - -/* ------------------------------------------------------------------------------- - Plot2D_setrange(Plot2D *p2, double xmin, double ymin, double xmax, double ymax) - - Sets the plotting range. - ------------------------------------------------------------------------------- */ - -void -Plot2D_setrange(Plot2D *p2, double xmin, double ymin, double xmax, double ymax) { - if (p2) { - p2->xmin = xmin; - p2->ymin = ymin; - p2->xmax = xmax; - p2->ymax = ymax; - p2->dx = (p2->view_xmax - p2->view_xmin)/(p2->xmax - p2->xmin); - p2->dy = (p2->view_ymax - p2->view_ymin)/(p2->ymax - p2->ymin); - } -} - -/* ------------------------------------------------------------------------------- - Plot2D_setscale(Plot2D *p2, int xscale, int yscale) - - Sets the plotting scaling method - ------------------------------------------------------------------------------- */ - -void -Plot2D_setscale(Plot2D *p2, int xscale, int yscale) { - if (p2) { - p2->xscale = xscale; - p2->yscale = yscale; - } -} - -/* ---------------------------------------------------------------------------- - Plot2D_transform(Plot2D *p2, double x, double y, int *px, int *py) - - Transforms x,y into screen coordinates px and py. Result is returned - in px and py. Rounds to the nearest pixel instead of truncating. - ----------------------------------------------------------------------------- */ - -void -Plot2D_transform(Plot2D *p2, double x, double y, int *px, int *py) { - if (p2) { - *px = p2->view_xmin + (int) (p2->dx*(x-p2->xmin) + 0.5); - *py = p2->view_ymin + (int) (p2->dy*(y-p2->ymin) + 0.5); - } -} - -/* ------------------------------------------------------------------------------- - Plot2D_plot(Plot2D *p2, double x, double y, Pixel color) - - Plot a 2D Point of a given color - ------------------------------------------------------------------------------- */ -void -Plot2D_plot(Plot2D *p2, double x, double y, Pixel color) { - int px, py; - - Plot2D_transform(p2,x,y,&px,&py); - FrameBuffer_plot(p2->frame, px, py, color); -} - -/* ------------------------------------------------------------------------------- - Plot2D_box(Plot2D *p2, double x1, double y1, double x2, double y2, Pixel Color) - - Plot an outline box on the 2D plot - ------------------------------------------------------------------------------- */ -void -Plot2D_box(Plot2D *p2, double x1, double y1,double x2, double y2, Pixel color) { - int ix1, ix2,iy1, iy2; - - Plot2D_transform(p2,x1,y1,&ix1,&iy1); - Plot2D_transform(p2,x2,y2,&ix2,&iy2); - FrameBuffer_box(p2->frame,ix1,iy1,ix2,iy2,color); -} - -/* ------------------------------------------------------------------------------- - Plot2D_solidbox(Plot2D *p2, double x1, double y1, double x2, double y2, Pixel Color) - - Plot a solid box box on the 2D plot - ------------------------------------------------------------------------------- */ -void -Plot2D_solidbox(Plot2D *p2, double x1, double y1,double x2, double y2, Pixel color) { - int ix1, ix2,iy1, iy2; - - Plot2D_transform(p2,x1,y1,&ix1,&iy1); - Plot2D_transform(p2,x2,y2,&ix2,&iy2); - FrameBuffer_solidbox(p2->frame,ix1,iy1,ix2,iy2,color); -} - -/* ------------------------------------------------------------------------------- - Plot2D_interpbox(Plot2D *p2, double x1, double y1, double x2, double y2, - Pixel c1, Pixel c2, Pixel c3, Pixel c4) - - Plot a color-interpolated box on the 2D plot - ------------------------------------------------------------------------------- */ -void -Plot2D_interpbox(Plot2D *p2, double x1, double y1,double x2, double y2, - Pixel c1, Pixel c2, Pixel c3, Pixel c4) { - int ix1, ix2,iy1, iy2; - - Plot2D_transform(p2,x1,y1,&ix1,&iy1); - Plot2D_transform(p2,x2,y2,&ix2,&iy2); - FrameBuffer_interpbox(p2->frame,ix1,iy1,ix2,iy2,c1,c2,c3,c4); -} - -/* ------------------------------------------------------------------------------- - Plot2D_circle(Plot2D *p2, double x, double y, double radius, Pixel color) - - Make an outline circle on the 2D plot. - ------------------------------------------------------------------------------- */ -void -Plot2D_circle(Plot2D *p2, double x, double y, double radius, Pixel color) { - int ix, iy, ir; - - Plot2D_transform(p2,x,y,&ix,&iy); - ir = p2->dx * radius; /* This is really incorrect. Will need ellipse */ - if (ir > 1) - FrameBuffer_circle(p2->frame,ix,iy,ir,color); - else - FrameBuffer_plot(p2->frame,ix,iy,color); - -} - -/* ------------------------------------------------------------------------------- - Plot2D_solidcircle(Plot2D *p2, double x, double y, double radius, Pixel color) - - Make an solid circle on the 2D plot. - ------------------------------------------------------------------------------- */ -void -Plot2D_solidcircle(Plot2D *p2, double x, double y, double radius, Pixel color) { - int ix, iy, ir; - - Plot2D_transform(p2,x,y,&ix,&iy); - ir = p2->dx * radius; /* This is really incorrect. Will need ellipse */ - if (ir > 1) - FrameBuffer_solidcircle(p2->frame,ix,iy,ir,color); - else - FrameBuffer_plot(p2->frame,ix,iy,color); -} - -/* ------------------------------------------------------------------------------- - Plot2D_line(Plot2D *p2, double x1, double y1, double x2, double y2, Pixel color) - - Draw a line - ------------------------------------------------------------------------------- */ - -void -Plot2D_line(Plot2D *p2, double x1, double y1, double x2, double y2, Pixel color) { - int ix1, ix2, iy1, iy2; - - Plot2D_transform(p2,x1,y1,&ix1,&iy1); - Plot2D_transform(p2,x2,y2,&ix2,&iy2); - FrameBuffer_line(p2->frame,ix1,iy1,ix2,iy2,color); -} - - - -/* ------------------------------------------------------------------------------- - Plot2D_start(Plot2D *p2) - - This should be called before starting to make a 2D plot. It will change - the viewport coordinates for the framebuffer and do other stuff. - ------------------------------------------------------------------------------- */ - -void Plot2D_start(Plot2D *p2) { - if (p2) { - FrameBuffer_setclip(p2->frame, p2->view_xmin,p2->view_ymin,p2->view_xmax, p2->view_ymax); - p2->dx = (p2->view_xmax - p2->view_xmin)/(p2->xmax - p2->xmin); - p2->dy = (p2->view_ymax - p2->view_ymin)/(p2->ymax - p2->ymin); - } -} - -/* -------------------------------------------------------------------------- - void Plot2D_drawpixmap(Plot2D *p2, PixMap *pm, double x, double y, Pixel color, Pixel bgcolor) - - Draw a pixel map at the given coordinates. (Used for putting symbols on 2D - plots). - -------------------------------------------------------------------------- */ -void -Plot2D_drawpixmap(Plot2D *p2, PixMap *pm, double x, double y, Pixel color, Pixel bgcolor) { - int ix, iy; - - Plot2D_transform(p2,x,y,&ix,&iy); - FrameBuffer_drawpixmap(p2->frame,pm,ix,iy,color,bgcolor); -} - -/* ---------------------------------------------------------------------------- - void Plot2D_xaxis(Plot2D *p2, double x, double y, double xtick, int ticklength, Pixel color) - - Draw an X axis bar at location x,y with ticks spaced every xtick units. - Ticks are spaced starting at "x" - ----------------------------------------------------------------------------- */ - -void Plot2D_xaxis(Plot2D *p2, double x, double y, double xtick, int ticklength, Pixel color) { - int ix, iy,iy2; - double xt; - - /* Draw a line fox the axis */ - - Plot2D_line(p2,p2->xmin,y,p2->xmax,y,color); - xt = x; - while (xt >= p2->xmin) { - Plot2D_transform(p2,xt,y,&ix,&iy); - iy2 = iy+ticklength; - iy = iy-ticklength; - FrameBuffer_line(p2->frame,ix,iy,ix,iy2,color); - xt = xt - xtick; - } - xt = x + xtick; - while (xt < p2->xmax) { - Plot2D_transform(p2,xt,y,&ix,&iy); - iy2 = iy+ticklength; - iy = iy-ticklength; - FrameBuffer_line(p2->frame,ix,iy,ix,iy2,color); - xt = xt + xtick; - } -} - - -/* ---------------------------------------------------------------------------- - void Plot2D_yaxis(Plot2D *p2, double x, double y, double ytick, int ticklength, Pixel c) - - Draw an Y axis bar at location x,y with ticks spaced every xtick units. - Ticks are spaced starting at "y" - ----------------------------------------------------------------------------- */ - -void Plot2D_yaxis(Plot2D *p2, double x, double y, double ytick, int ticklength, Pixel color) { - int ix, iy, ix2; - double yt; - - /* Draw a line fox the axis */ - - Plot2D_line(p2,x,p2->ymin,x,p2->ymax,color); - yt = y; - while (yt >= p2->ymin) { - Plot2D_transform(p2,x,yt,&ix,&iy); - ix2 = ix+ticklength; - ix = ix-ticklength; - FrameBuffer_line(p2->frame,ix,iy,ix2,iy,color); - yt = yt - ytick; - } - yt = y + ytick; - while (yt < p2->ymax) { - Plot2D_transform(p2,x,yt,&ix,&iy); - ix2 = ix+ticklength; - ix = ix-ticklength; - FrameBuffer_line(p2->frame,ix,iy,ix2,iy,color); - yt = yt + ytick; - } -} - - -/* ------------------------------------------------------------------------- - Plot2D_triangle(Plot2D *p2, double x1, double y1, - double x2, double y2, - double x3, double y3, - Pixel fillcolor) - - This function draws a 2D outline triangle. - -------------------------------------------------------------------------- */ - -void Plot2D_triangle(Plot2D *p2, double x1, double y1, - double x2, double y2, - double x3, double y3, Pixel color) { - - Plot2D_line(p2,x1,y1,x2,y2,color); - Plot2D_line(p2,x2,y2,x3,y3,color); - Plot2D_line(p2,x3,y3,x1,y1,color); - -} - - -/* ------------------------------------------------------------------------- - Plot2D_solidtriangle(Plot2D *p2, double x1, double y1, - double x2, double y2, - double x3, double y3, - Pixel color) - - This function draws a 2D filled triangle. Can be used to - draw other primitives such as quadralaterals, etc... - - -------------------------------------------------------------------------- */ - -void Plot2D_solidtriangle(Plot2D *p2, double x1, double y1, - - double x2, double y2, - double x3, double y3, Pixel color) { - - int tx1, tx2, tx3, ty1, ty2, ty3; - - /* Transform the three points into screen coordinates */ - - Plot2D_transform(p2,x1,y1,&tx1,&ty1); - Plot2D_transform(p2,x2,y2,&tx2,&ty2); - Plot2D_transform(p2,x3,y3,&tx3,&ty3); - - FrameBuffer_solidtriangle(p2->frame,tx1,ty1,tx2,ty2,tx3,ty3,color); - -} - -/* ------------------------------------------------------------------------- - Plot2D_interptriangle(Plot2D *p2, double x1, double y1, Pixel c1, - double x2, double y2, Pixel c2, - double x3, double y3, Pixel c3); - - This function draws a 2D filled triangle with color interpolation. - Can be used to draw other primitives such as quadralaterals, etc... - -------------------------------------------------------------------------- */ - -void Plot2D_interptriangle(Plot2D *p2, double x1, double y1, Pixel c1, - double x2, double y2, Pixel c2, - double x3, double y3, Pixel c3) { - - int tx1, tx2, tx3, ty1, ty2, ty3; - - /* Transform the three points into screen coordinates */ - - Plot2D_transform(p2,x1,y1,&tx1,&ty1); - Plot2D_transform(p2,x2,y2,&tx2,&ty2); - Plot2D_transform(p2,x3,y3,&tx3,&ty3); - - FrameBuffer_interptriangle(p2->frame,tx1,ty1,c1,tx2,ty2,c2,tx3,ty3,c3); - -} - - - diff --git a/Examples/GIFPlot/Lib/plot3d.c b/Examples/GIFPlot/Lib/plot3d.c deleted file mode 100644 index 387e420e2..000000000 --- a/Examples/GIFPlot/Lib/plot3d.c +++ /dev/null @@ -1,2181 +0,0 @@ -/* ----------------------------------------------------------------------------- - * plot3d.c - * - * Three-dimensional plotting. - * - * Author(s) : David Beazley (beazley@cs.uchicago.edu) - * Copyright (C) 1995-1996 - * - * See the file LICENSE for information on usage and redistribution. - * ----------------------------------------------------------------------------- */ - -#define PLOT3D -#include "gifplot.h" -#include -#include - -#define ORTHO 1 -#define PERSPECTIVE 2 -/* ------------------------------------------------------------------------ - Plot3D *new_Plot3D(FrameBuffer *f, double xmin, double ymin, double zmin, - double xmax, double ymax, double zmax) - - Creates a new 3D plot. Min and max coordinates are primarily used to - pick some default parameters. Returns NULL on failure - ------------------------------------------------------------------------- */ - -Plot3D *new_Plot3D(FrameBuffer *f, double xmin, double ymin, double zmin, - double xmax, double ymax, double zmax) { - - Plot3D *p3; - void Plot3D_maketransform(Plot3D *p3); - - /* Check to make sure the framebuffer and min/max parameters are valid */ - - if (!f) return (Plot3D *) 0; - if ((xmin > xmax) || (ymin > ymax) || (zmin > zmax)) return (Plot3D *) 0; - - p3 = (Plot3D *) malloc(sizeof(Plot3D)); - p3->frame = f; - p3->xmin = xmin; - p3->ymin = ymin; - p3->zmin = zmin; - p3->xmax = xmax; - p3->ymax = ymax; - p3->zmax = zmax; - - /* Set view region to the entire size of the framebuffer */ - - p3->view_xmin = 0; - p3->view_ymin = 0; - p3->view_xmax = f->width; - p3->view_ymax = f->height; - p3->width = f->width; - p3->height = f->height; - - /* Calculate a center point based off the min and max coordinates given */ - - p3->xcenter = (xmax - xmin)/2.0 + xmin; - p3->ycenter = (ymax - ymin)/2.0 + ymin; - p3->zcenter = (zmax - zmin)/2.0 + zmin; - - /* Calculate the aspect ratio of the viewing region */ - - p3->aspect = (double) f->width/(double) f->height; - - /* Set default view parameters */ - p3->xshift = 1.0; - p3->yshift = 1.0; - p3->zoom = 0.5; - p3->fovy = 40.0; /* 40 degree field of view */ - - /* Create matrices */ - - p3->model_mat = new_Matrix(); - p3->view_mat = new_Matrix(); - p3->center_mat = new_Matrix(); - p3->fullmodel_mat = new_Matrix(); - p3->trans_mat = new_Matrix(); - p3->pers_mode = ORTHO; - - FrameBuffer_zresize(p3->frame,p3->width, p3->height); - Matrix_identity(p3->view_mat); - Matrix_identity(p3->model_mat); - Matrix_translate(p3->center_mat, -p3->xcenter,-p3->ycenter,-p3->zcenter); - Plot3D_maketransform(p3); - return p3; -} - -/* --------------------------------------------------------------------- - delete_Plot3D(Plot3D *p3) - - Deletes a 3D plot - --------------------------------------------------------------------- */ - -void delete_Plot3D(Plot3D *p3) { - if (p3) { - delete_Matrix(p3->view_mat); - delete_Matrix(p3->model_mat); - delete_Matrix(p3->trans_mat); - free((char *) p3); - } -} - -/* --------------------------------------------------------------------- - Plot3D *Plot3D_copy(Plot3D *p3) - - This makes a copy of the 3D plot structure and returns a pointer to it. - --------------------------------------------------------------------- */ - -Plot3D *Plot3D_copy(Plot3D *p3) { - Plot3D *c3; - if (p3) { - c3 = (Plot3D *) malloc(sizeof(Plot3D)); - if (c3) { - c3->frame = p3->frame; - c3->view_xmin = p3->view_xmin; - c3->view_ymin = p3->view_ymin; - c3->view_xmax = p3->view_xmax; - c3->view_ymax = p3->view_ymax; - c3->xmin = p3->xmin; - c3->ymin = p3->ymin; - c3->zmin = p3->zmin; - c3->xmax = p3->xmax; - c3->ymax = p3->ymax; - c3->zmax = p3->zmax; - c3->xcenter = p3->xcenter; - c3->ycenter = p3->ycenter; - c3->zcenter = p3->zcenter; - c3->fovy = p3->fovy; - c3->aspect = p3->aspect; - c3->znear = p3->znear; - c3->zfar = p3->zfar; - c3->center_mat = Matrix_copy(p3->center_mat); - c3->model_mat = Matrix_copy(p3->model_mat); - c3->view_mat = Matrix_copy(p3->view_mat); - c3->fullmodel_mat = Matrix_copy(p3->fullmodel_mat); - c3->trans_mat = Matrix_copy(p3->trans_mat); - c3->lookatz = p3->lookatz; - c3->xshift = p3->xshift; - c3->yshift = p3->yshift; - c3->zoom = p3->zoom; - c3->width = p3->width; - c3->height = p3->height; - c3->pers_mode = p3->pers_mode; - } - return c3; - } else { - return (Plot3D *) 0; - } -} - -/* ---------------------------------------------------------------------- - Plot3D_clear(Plot3D *p3, Pixel bgcolor) - - Clear the pixel and zbuffer only for the view region of this image. - ---------------------------------------------------------------------- */ -void -Plot3D_clear(Plot3D *p3, Pixel bgcolor) { - int i,j; - - for (i = p3->view_xmin; i < p3->view_xmax; i++) - for (j = p3->view_ymin; j < p3->view_ymax; j++) { - p3->frame->pixels[j][i] = bgcolor; - p3->frame->zbuffer[j][i] = ZMIN; - } -} - -/* --------------------------------------------------------------------- - Plot3D_maketransform(Plot3D *p3) - - This function builds the total 3D transformation matrix from a - collection of components. - - Trans = View * Rotation * Center - - Where View is the viewing transformation matrix, Rotation is the - model rotation matrix, Center is the translation matrix used to - center the Model at the origin. - --------------------------------------------------------------------- */ - -void -Plot3D_maketransform(Plot3D *p3) { - - Matrix_multiply(p3->model_mat,p3->center_mat, p3->fullmodel_mat); - Matrix_multiply(p3->view_mat,p3->fullmodel_mat, p3->trans_mat); -} - -/* --------------------------------------------------------------------- - Plot3D_perspective(Plot3D *p3, double fovy, double znear, double zfar) - - Sets up the perspective viewing transformation. Assumes "lookat" - has already been called. - --------------------------------------------------------------------- */ - -void -Plot3D_perspective(Plot3D *p3, double fovy, double znear, double zfar) { - double theta; - double mat[16]; - - p3->fovy = fovy; - p3->znear = znear; - p3->zfar = zfar; - - theta = 3.1415926*fovy/180.0; - - Matrix_identity(mat); - mat[0] = cos(theta/2.0)/(sin(theta/2.0)*p3->aspect); - mat[5] = cos(theta/2.0)/(sin(theta/2.0)); - mat[10] = -(zfar + znear)/(zfar-znear); - mat[14] = -1.0; - mat[11] = -(2*zfar*znear)/(zfar - znear); - mat[15] = 0.0; - - /* Update the view transformation matrix */ - - Matrix_multiply(mat,p3->view_mat,p3->view_mat); - - /* Update the global transformation matrix */ - - Plot3D_maketransform(p3); - p3->pers_mode = PERSPECTIVE; - -} - -/* --------------------------------------------------------------------- - Plot3D_lookat(Plot3D *p3, double z) - - A greatly simplified version of (lookat). Specifies the position - of the viewpoint. (can be used for moving image in or out). - - Destroys the current viewing transformation matrix, so it will have - to be recalculated. - --------------------------------------------------------------------- */ - -void -Plot3D_lookat(Plot3D *p3, double z) { - if (p3) { - Matrix_translate(p3->view_mat, 0,0,-z); - p3->lookatz = z; - Plot3D_maketransform(p3); - } -} - -/* ------------------------------------------------------------------------- - Plot3D_autoperspective(Plot3D *p3, double fovy) - - Automatically figures out a semi-decent viewpoint given the - min,max parameters currently set for this image - ------------------------------------------------------------------------- */ - -void -Plot3D_autoperspective(Plot3D *p3, double fovy) { - - /* Make a perspective transformation matrix for this system */ - - double zfar; - double znear; - double d, dmax; - double cx,cy,cz; - double xmin,xmax,ymin,ymax,zmin,zmax; - - xmin = p3->xmin; - ymin = p3->ymin; - zmin = p3->zmin; - xmax = p3->xmax; - ymax = p3->ymax; - zmax = p3->zmax; - cx = p3->xcenter; - cy = p3->ycenter; - cz = p3->zcenter; - - /* Calculate longest point from center point */ - - dmax = (xmin-cx)*(xmin-cx) + (ymin-cy)*(ymin-cy) + (zmin-cz)*(zmin-cz); - d = (xmax-cx)*(xmax-cx) + (ymin-cy)*(ymin-cy) + (zmin-cz)*(zmin-cz); - if (d > dmax) dmax = d; - d = (xmin-cx)*(xmin-cx) + (ymax-cy)*(ymax-cy) + (zmin-cz)*(zmin-cz); - if (d > dmax) dmax = d; - d = (xmax-cx)*(xmax-cx) + (ymax-cy)*(ymax-cy) + (zmin-cz)*(zmin-cz); - if (d > dmax) dmax = d; - d = (xmin-cx)*(xmin-cx) + (ymin-cy)*(ymin-cy) + (zmax-cz)*(zmax-cz); - if (d > dmax) dmax = d; - d = (xmax-cx)*(xmax-cx) + (ymin-cy)*(ymin-cy) + (zmax-cz)*(zmax-cz); - if (d > dmax) dmax = d; - d = (xmin-cx)*(xmin-cx) + (ymax-cy)*(ymax-cy) + (zmax-cz)*(zmax-cz); - if (d > dmax) dmax = d; - d = (xmax-cx)*(xmax-cx) + (ymax-cy)*(ymax-cy) + (zmax-cz)*(zmax-cz); - if (d > dmax) dmax = d; - - dmax = sqrt(dmax); - d = p3->lookatz; - - znear = d - dmax; - zfar = znear+1.5*dmax; - Plot3D_perspective(p3, fovy,znear,zfar); - -} - - -/* --------------------------------------------------------------------- - Plot3D_ortho(Plot3D *p3, double left, double right, double bottom, double top) - - Sets up an orthographic viewing transformation. - --------------------------------------------------------------------- */ - -void -Plot3D_ortho(Plot3D *p3, double left, double right, double bottom, double top) { - - - Matrix_identity(p3->view_mat); - p3->view_mat[0] = (2.0/(right - left))/p3->aspect; - p3->view_mat[5] = 2.0/(top - bottom); - p3->view_mat[10] = -1; - p3->view_mat[15] = 1.0; - p3->view_mat[3] = -(right+left)/(right-left); - p3->view_mat[7] = -(top+bottom)/(top-bottom); - - /* Update the global transformation matrix */ - - Plot3D_maketransform(p3); - p3->pers_mode = ORTHO; - p3->ortho_left = left; - p3->ortho_right = right; - p3->ortho_bottom = bottom; - p3->ortho_top = top; - -} - -/* --------------------------------------------------------------------- - Plot3D_autoortho(Plot3D *p3) - - Automatically pick an orthographic projection that's probably - pretty good. - --------------------------------------------------------------------- */ - -void -Plot3D_autoortho(Plot3D *p3) { - - /* Make a perspective transformation matrix for this system */ - - double d, dmax; - double cx,cy,cz; - double xmin,xmax,ymin,ymax,zmin,zmax; - - xmin = p3->xmin; - ymin = p3->ymin; - zmin = p3->zmin; - xmax = p3->xmax; - ymax = p3->ymax; - zmax = p3->zmax; - cx = p3->xcenter; - cy = p3->ycenter; - cz = p3->zcenter; - - /* Calculate longest point from center point */ - - dmax = (xmin-cx)*(xmin-cx) + (ymin-cy)*(ymin-cy) + (zmin-cz)*(zmin-cz); - d = (xmax-cx)*(xmax-cx) + (ymin-cy)*(ymin-cy) + (zmin-cz)*(zmin-cz); - if (d > dmax) dmax = d; - d = (xmin-cx)*(xmin-cx) + (ymax-cy)*(ymax-cy) + (zmin-cz)*(zmin-cz); - if (d > dmax) dmax = d; - d = (xmax-cx)*(xmax-cx) + (ymax-cy)*(ymax-cy) + (zmin-cz)*(zmin-cz); - if (d > dmax) dmax = d; - d = (xmin-cx)*(xmin-cx) + (ymin-cy)*(ymin-cy) + (zmax-cz)*(zmax-cz); - if (d > dmax) dmax = d; - d = (xmax-cx)*(xmax-cx) + (ymin-cy)*(ymin-cy) + (zmax-cz)*(zmax-cz); - if (d > dmax) dmax = d; - d = (xmin-cx)*(xmin-cx) + (ymax-cy)*(ymax-cy) + (zmax-cz)*(zmax-cz); - if (d > dmax) dmax = d; - d = (xmax-cx)*(xmax-cx) + (ymax-cy)*(ymax-cy) + (zmax-cz)*(zmax-cz); - if (d > dmax) dmax = d; - - dmax = sqrt(dmax); - - Plot3D_ortho(p3,-dmax,dmax,-dmax,dmax); - -} - - - -/* ------------------------------------------------------------------------- - Plot3D_setview(Plot3D *p3, int vxmin, int vymin, int vxmax, int vymax) - - Sets the viewport for this 3D graph. Will recalculate all of the - local viewing transformation matrices accordingly. - ------------------------------------------------------------------------- */ -void -Plot3D_setview(Plot3D *p3, int vxmin, int vymin, int vxmax, int vymax) { - if (p3) { - if ((vxmin > vxmax) || (vymin >vymax)) return; - p3->view_xmin = vxmin; - p3->view_ymin = vymin; - p3->view_xmax = vxmax; - p3->view_ymax = vymax; - p3->width = (vxmax - vxmin); - p3->height = (vymax - vymin); - p3->aspect = (double) p3->width/(double) p3->height; - - /* Fix up the viewing transformation matrix */ - - if (p3->pers_mode == PERSPECTIVE) { - Plot3D_lookat(p3,p3->lookatz); - Plot3D_perspective(p3,p3->fovy,p3->znear,p3->zfar); - } else { - Plot3D_ortho(p3,p3->ortho_left,p3->ortho_right,p3->ortho_bottom, p3->ortho_top); - } - FrameBuffer_setclip(p3->frame,vxmin,vymin,vxmax,vymax); - } -} - -/* --------------------------------------------------------------------------- - Plot2D_start(Plot2D *p3) - - Set up viewing region and other parameters for this image. - --------------------------------------------------------------------------- */ - -void -Plot3D_start(Plot3D *p3) { - if (p3) - FrameBuffer_setclip(p3->frame, p3->view_xmin,p3->view_ymin,p3->view_xmax, p3->view_ymax); - -} - -/* ------------------------------------------------------------------------- - Plot3D_plot(Plot3D *p3, double x, double y, double z, Pixel Color) - - Plot a 3D point - ------------------------------------------------------------------------- */ - -void -Plot3D_plot(Plot3D *p3, double x, double y, double z, Pixel color) { - - GL_Vector t; - int ix, iy; - double invw; - FrameBuffer *f; - - /* Perform a transformation */ - - Matrix_transform4(p3->trans_mat,x,y,z,1,&t); - - /* Scale the coordinates into unit cube */ - - invw = 1.0/t.w; - t.x = t.x *invw; - t.y = t.y *invw; - t.z = t.z *invw; -#ifdef GL_DEBUG - fprintf(stdout,"t.x = %g, t.y = %g, t.z = %g\n", t.x,t.y,t.z); -#endif - /* Calculate the x and y coordinates */ - - ix = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5); - iy = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5); - - if ((ix >= 0) && (ix < p3->width) && - (iy >= 0) && (ix < p3->height)) { - ix += p3->view_xmin; - iy += p3->view_ymin; - f = p3->frame; - if (t.z <= f->zbuffer[iy][ix]) { - f->pixels[iy][ix] = color; - f->zbuffer[iy][ix] = t.z; - } - } -} - -/* ---------------------------------------------------------------------- - Plot3D_rotx(Plot3D *p3, double deg) - - Rotate the model around its x axis. - ---------------------------------------------------------------------- */ - -void -Plot3D_rotx(Plot3D *p3, double deg) { - double temp[16]; - - Matrix_rotatex(temp,deg); /* Construct a x rotation matrix */ - Matrix_multiply(p3->model_mat,temp,p3->model_mat); - Plot3D_maketransform(p3); - -} - -/* ---------------------------------------------------------------------- - Plot3D_roty(Plot3D *p3, double deg) - - Rotate the model around its y axis. - ---------------------------------------------------------------------- */ - -void -Plot3D_roty(Plot3D *p3, double deg) { - double temp[16]; - - Matrix_rotatey(temp,deg); /* Construct a y rotation matrix */ - Matrix_multiply(p3->model_mat,temp,p3->model_mat); - Plot3D_maketransform(p3); - -} - -/* ---------------------------------------------------------------------- - Plot3D_rotz(Plot3D *p3, double deg) - - Rotate the model around its z axis. - ---------------------------------------------------------------------- */ - -void -Plot3D_rotz(Plot3D *p3, double deg) { - double temp[16]; - - Matrix_rotatez(temp,deg); /* Construct a z rotation matrix */ - Matrix_multiply(p3->model_mat,temp,p3->model_mat); - Plot3D_maketransform(p3); - -} - - -/* ---------------------------------------------------------------------- - Plot3D_rotd(Plot3D *p3, double deg) - - Rotate the model down - ---------------------------------------------------------------------- */ - -void -Plot3D_rotd(Plot3D *p3, double deg) { - double temp[16]; - - Matrix_rotatex(temp,deg); /* Construct a x rotation matrix */ - Matrix_multiply(temp, p3->model_mat,p3->model_mat); - Plot3D_maketransform(p3); - -} - - -/* ---------------------------------------------------------------------- - Plot3D_rotu(Plot3D *p3, double deg) - - Rotate the model up - ---------------------------------------------------------------------- */ - -void -Plot3D_rotu(Plot3D *p3, double deg) { - double temp[16]; - - Matrix_rotatex(temp,-deg); /* Construct a x rotation matrix */ - Matrix_multiply(temp,p3->model_mat,p3->model_mat); - Plot3D_maketransform(p3); - -} - - -/* ---------------------------------------------------------------------- - Plot3D_rotr(Plot3D *p3, double deg) - - Rotate the model down - ---------------------------------------------------------------------- */ - -void -Plot3D_rotr(Plot3D *p3, double deg) { - double temp[16]; - - Matrix_rotatey(temp,deg); /* Construct a y rotation matrix */ - Matrix_multiply(temp, p3->model_mat,p3->model_mat); - Plot3D_maketransform(p3); - -} - - -/* ---------------------------------------------------------------------- - Plot3D_rotl(Plot3D *p3, double deg) - - Rotate the model left - ---------------------------------------------------------------------- */ - -void -Plot3D_rotl(Plot3D *p3, double deg) { - double temp[16]; - - Matrix_rotatey(temp,-deg); /* Construct a y rotation matrix */ - Matrix_multiply(temp,p3->model_mat,p3->model_mat); - Plot3D_maketransform(p3); - -} - - -/* ---------------------------------------------------------------------- - Plot3D_rotc(Plot3D *p3, double deg) - - Rotate the model around center point - ---------------------------------------------------------------------- */ - -void -Plot3D_rotc(Plot3D *p3, double deg) { - double temp[16]; - - Matrix_rotatez(temp,-deg); /* Construct a z rotation matrix */ - Matrix_multiply(temp,p3->model_mat,p3->model_mat); - Plot3D_maketransform(p3); -} - -/* ------------------------------------------------------------------------- - Plot3D_zoom(Plot3D *p3, double percent) - - Zooms in or out the current image. percent defines a percentage of - zoom. - - Zooming is actually done by adjusting the perspective field of view - instead of scaling the model or moving in the viewpoint. This - seems to work the best. - ------------------------------------------------------------------------- */ - -void -Plot3D_zoom(Plot3D *p3, double percent) { - - double scale; - double dx; - if (percent <= 0) return; - scale = percent/100.0; - - dx = (1.0/scale - 1.0)/(2*p3->zoom); /* Don't even ask where this came from */ - p3->xshift += dx; - p3->yshift += dx; - p3->zoom = p3->zoom*scale; - -#ifdef OLD - p3->fovy = p3->fovy*scale; - if (p3->fovy > 170.0) p3->fovy = 170.0; - if (p3->fovy == 0) p3->fovy = 0.0001; - Plot3D_lookat(p3,p3->lookatz); - Plot3D_perspective(p3,p3->fovy,p3->znear,p3->zfar); -#endif -} - -/* -------------------------------------------------------------------------- - Plot3D_left(Plot3D *p3, double s) - - Shifts the image to the left by s units. This is a little funky. - - s is scaled so that s = 100 equals one full screen. - -------------------------------------------------------------------------- */ -void -Plot3D_left(Plot3D *p3, double s) { - p3->xshift -= (s/100.0)/p3->zoom; -} - -/* -------------------------------------------------------------------------- - Plot3D_right(Plot3D *p3, double s) - - Shifts the image to the right by s units. - - s is scaled so that s = 100 equals one full screen. - -------------------------------------------------------------------------- */ -void -Plot3D_right(Plot3D *p3, double s) { - p3->xshift += (s/100.0)/p3->zoom; -} - -/* -------------------------------------------------------------------------- - Plot3D_up(Plot3D *p3, double s) - - Shifts the image up left by s units. - - s is scaled so that s = 100 equals one full screen. - -------------------------------------------------------------------------- */ -void -Plot3D_up(Plot3D *p3, double s) { - p3->yshift += (s/100.0)/p3->zoom; -} - -/* -------------------------------------------------------------------------- - Plot3D_down(Plot3D *p3, double s) - - Shifts the image down by s units. - - s is scaled so that s = 100 equals one full screen. - -------------------------------------------------------------------------- */ -void -Plot3D_down(Plot3D *p3, double s) { - p3->yshift -= (s/100.0)/p3->zoom; -} - -/* ------------------------------------------------------------------------- - Plot3D_center(Plot3D *p3, double cx, double cy) - - Centers the image on a point in the range (0,0) - (100,100) - ------------------------------------------------------------------------- */ -void -Plot3D_center(Plot3D *p3, double cx, double cy) { - Plot3D_left(p3,cx-50); - Plot3D_down(p3,cy-50); -} - - - -/*************************************************************************** - * 3d Primitives * - ***************************************************************************/ - -/* ------------------------------------------------------------------------- - Plot3D_horizontal(Plot3D *p3, int xmin, int xmax, int y, double z1, double z2, Pixel color) - - Draws a "Horizontal" line on the framebuffer between two screen coordinates, - but also supplies z-values and zbuffering. This function probably isn't - too useful by itself, but will be used by a number of other primitives. - -------------------------------------------------------------------------- */ - -void Plot3D_horizontal(Plot3D *p3, int xmin, int xmax, int y, Zvalue z1, Zvalue z2, Pixel color) { - Pixel *p; - FrameBuffer *f; - int i; - Zvalue *zbuf,z,mz; - int startx, endx; - - f = p3->frame; - if ((y < f->ymin) || (y >= f->ymax)) return; - if (xmin > f->xmax) return; - if (xmin < f->xmin) startx = f->xmin; - else startx = xmin; - if (xmax < f->xmin) return; - if (xmax >= f->xmax) endx = f->xmax - 1; - else endx = xmax; - - /* Calculate z slope */ - - if (xmax != xmin) { - mz = (Zvalue) ((double) (z2 - z1)/(double) (xmax - xmin)); - } else { - mz = 0; - } - - /* Draw it */ - - p = &f->pixels[y][startx]; - zbuf = &f->zbuffer[y][startx]; - z = (Zvalue) (mz*(startx-xmin) + z1); - for (i = startx; i <= endx; i++, p++, zbuf++,z+=mz) { - if (z <= *zbuf) { - *p = color; - *zbuf = z; - } - } -} - - -/* ------------------------------------------------------------------------- - Plot3D_vertical(Plot3D *p3, int ymin, int ymax, int x, double z1, double z2, Pixel color) - - Draws a "Vertical" line on the framebuffer between two screen coordinates, - but also supplies z-values and zbuffering. This function probably isn't - too useful by itself, but will be used by a number of other primitives. - -------------------------------------------------------------------------- */ - -void Plot3D_vertical(Plot3D *p3, int ymin, int ymax, int x, Zvalue z1, Zvalue z2, Pixel color) { - Pixel *p; - FrameBuffer *f; - int i; - Zvalue *zbuf,z,mz; - int starty, endy; - - f = p3->frame; - if ((x < f->xmin) || (x >= f->xmax)) return; - if (ymin >= f->ymax) return; - if (ymin < f->ymin) starty = f->ymin; - else starty = ymin; - if (ymax < f->ymin) return; - if (ymax >= f->ymax) endy = f->ymax - 1; - else endy = ymax; - - /* Calculate z slope */ - - mz = (double) (z2 - z1)/(double) (ymax - ymin); - - /* Draw it */ - - p = &f->pixels[starty][x]; - zbuf = &f->zbuffer[starty][x]; - for (i = starty; i <= endy; i++, p+=f->width, zbuf+=f->width) { - z = (Zvalue) (mz*(i-ymin) + z1); - if (z <= *zbuf) { - *p = color; - *zbuf = z; - } - } -} - -/* ------------------------------------------------------------------------------- - Plot3D_linetransform(Plot3D *p3, int x1, int y1, Zvalue z1, - int x2, int y2, Zvalue z2, Pixel c) - - Draw a 3D line between points that have already been transformed into - 3D space. - - Uses a Bresenham line algorithm, but with linear interpolation between - Zvalues. - ------------------------------------------------------------------------------- */ - -void -Plot3D_linetransform(Plot3D *p3, int x1, int y1, Zvalue z1, int x2, int y2, Zvalue z2, Pixel c) { - - int orig_x1, orig_y1, orig_x2,orig_y2; - Zvalue zt; - - /* Bresenham line drawing parameters */ - FrameBuffer *f; - int dx,dy,dxneg,dyneg, inc1,inc2,di; - int x, y, xpixels, ypixels, xt, yt; - Pixel *p; - double m; - int end1 = 0, end2 = 0; - Zvalue *zbuf,mz,z; - - f = p3->frame; - - /* Need to figure out where in the heck this line is */ - - dx = x2 - x1; - dy = y2 - y1; - - if ((dx == 0) && (dy == 0)) { - if ((x1 < f->xmin) || (x1 >= f->xmax) || - (y1 < f->ymin) || (y1 >= f->ymax)) return; - if (z1 <= f->zbuffer[y1][x1]) { - f->pixels[y1][x1] = c; - } - return; - } - if (dx == 0) { - /* Draw a Vertical Line */ - if (y1 < y2) - Plot3D_vertical(p3,y1,y2,x1,z1,z2,c); - else - Plot3D_vertical(p3,y2,y1,x1,z2,z1,c); - return; - } - if (dy == 0) { - /* Draw a Horizontal Line */ - if (x1 < x2) - Plot3D_horizontal(p3,x1,x2,y1,z1,z2,c); - else - Plot3D_horizontal(p3,x2,x1,y1,z2,z1,c); - return; - } - - /* Figure out where in the heck these lines are using the - Cohen-Sutherland Line Clipping Scheme. */ - - end1 = ((x1 - f->xmin) < 0) | - (((f->xmax- 1 - x1) < 0) << 1) | - (((y1 - f->ymin) < 0) << 2) | - (((f->ymax-1 - y1) < 0) << 3); - - end2 = ((x2 - f->xmin) < 0) | - (((f->xmax-1 - x2) < 0) << 1) | - (((y2 - f->ymin) < 0) << 2) | - (((f->ymax-1 - y2) < 0) << 3); - - if (end1 & end2) return; /* Nope : Not visible */ - - /* Make sure points have a favorable orientation */ - - if (x1 > x2) { - xt = x1; - x1 = x2; - x2 = xt; - yt = y1; - y1 = y2; - y2 = yt; - zt = z1; - z1 = z2; - z2 = zt; - } - - /* Save original points before we clip them off */ - orig_x1 = x1; - orig_y1 = y1; - orig_x2 = x2; - orig_y2 = y2; - - /* Clip against the boundaries */ - m = (y2 - y1)/(double) (x2-x1); - if (x1 < f->xmin) { - y1 = (f->xmin - x1)*m + y1; - x1 = f->xmin; - } - if (x2 >= f->xmax) { - y2 = (f->xmax -1 -x1)*m + y1; - x2 = f->xmax - 1; - } - - if (y1 > y2) { - xt = x1; - x1 = x2; - x2 = xt; - yt = y1; - y1 = y2; - y2 = yt; - zt = z1; - z1 = z2; - z2 = zt; - - /* Swap original points */ - - xt = orig_x1; - orig_x1 = orig_x2; - orig_x2 = xt; - yt = orig_y1; - orig_y1 = orig_y2; - orig_y2 = yt; - } - - m = 1/m; - if (y1 < f->ymin) { - x1 = (f->ymin - y1)*m + x1; - y1 = f->ymin; - } - if (y2 >= f->ymax) { - x2 = (f->ymax-1-y1)*m + x1; - y2 = f->ymax-1; - } - - if ((x1 < f->xmin) || (x1 >= f->xmax) || (y1 < f->ymin) || (y1 >= f->ymax) || - (x2 < f->xmin) || (x2 >= f->xmax) || (y2 < f->ymin) || (y2 >= f->ymax)) return; - - dx = x2 - x1; - dy = y2 - y1; - xpixels = f->width; - ypixels = f->height; - - dxneg = (dx < 0) ? 1 : 0; - dyneg = (dy < 0) ? 1 : 0; - - dx = abs(dx); - dy = abs(dy); - if (dx >= dy) { - /* Slope between -1 and 1. */ - mz = (z2 - z1)/(orig_x2 - orig_x1); /* Z interpolation slope */ - if (dxneg) { - x = x1; - y = y1; - x1 = x2; - y1 = y2; - x2 = x; - y2 = y; - dyneg = !dyneg; - } - inc1 = 2*dy; - inc2 = 2*(dy-dx); - di = 2*dy-dx; - - /* Draw a line using x as independent variable */ - - p = &f->pixels[y1][x1]; - zbuf = &f->zbuffer[y1][x1]; - x = x1; - while (x <= x2) { - /* Do a z-buffer check */ - z = mz*(x-orig_x1)+z1; - if (z <= *zbuf){ - *p = c; - *zbuf = z; - } - p++; - zbuf++; - if (di < 0) { - di = di + inc1; - } else { - if (dyneg) { - p = p - xpixels; - zbuf = zbuf - xpixels; - di = di + inc2; - } else { - p = p + xpixels; - zbuf = zbuf + xpixels; - di = di + inc2; - } - } - x++; - } - } else { - /* Slope < -1 or > 1 */ - mz = (z2 - z1)/(double) (orig_y2 - orig_y1); - if (dyneg) { - x = x1; - y = y1; - x1 = x2; - y1 = y2; - x2 = x; - y2 = y; - dxneg = !dxneg; - } - inc1 = 2*dx; - inc2 = 2*(dx-dy); - di = 2*dx-dy; - - /* Draw a line using y as independent variable */ - - p = &f->pixels[y1][x1]; - zbuf = &f->zbuffer[y1][x1]; - y = y1; - while (y <= y2) { - /* Do a z-buffer check */ - z = mz*(y-orig_y1)+z1; - if (z <= *zbuf) { - *p = c; - *zbuf = z; - } - p = p + xpixels; - zbuf = zbuf + xpixels; - if (di < 0) { - di = di + inc1; - } else { - if (dxneg) { - p = p - 1; - zbuf = zbuf - 1; - di = di + inc2; - } else { - p = p + 1; - zbuf = zbuf + 1; - di = di + inc2; - } - } - y++; - } - } -} - -/* --------------------------------------------------------------------------- - Plot3D_line(Plot3D *p3, double x1, double y1, double z1, double x2, double y2, double z2,int color) - - Draws a line in 3D space. This is done as follows (for lack of a better - method). - - 1. The points (x1,y1,z1) and (x2,y2,z2) are transformed into screen coordinates - 2. We draw the line using a modified Bresenham line algorithm. - 3. Zbuffer values are linearly interpolated between the two points. - ---------------------------------------------------------------------------- */ - -void -Plot3D_line(Plot3D *p3, double fx1, double fy1, double fz1, double fx2, double fy2, - double fz2, Pixel c) { - - /* 3D Transformation parameters */ - GL_Vector t; - double invw; - int x1,y1,x2,y2; - Zvalue z1,z2; - - /* Transform the two points into screen coordinates */ - - Matrix_transform4(p3->trans_mat,fx1,fy1,fz1,1,&t); /* Point 1 */ - invw = 1.0/t.w; - t.x = t.x *invw; - t.y = t.y *invw; - t.z = t.z *invw; - x1 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - y1 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - z1 = t.z; - - Matrix_transform4(p3->trans_mat,fx2,fy2,fz2,1,&t); /* Point 2 */ - invw = 1.0/t.w; - t.x = t.x *invw; - t.y = t.y *invw; - t.z = t.z *invw; - x2 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - y2 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - z2 = t.z; - Plot3D_linetransform(p3,x1,y1,z1,x2,y2,z2,c); -} - - -/* ------------------------------------------------------------------------- - Plot3D_triangle(Plot3D *p3, double x1, double y1, double z1, - double x2, double y2, double z2, - double x3, double y3, double z3, - Pixel fillcolor) - - This function draws a 3D z-buffered outline triangle. - -------------------------------------------------------------------------- */ - -void Plot3D_triangle(Plot3D *p3, double x1, double y1, double z1, - double x2, double y2, double z2, - double x3, double y3, double z3, Pixel color) { - - int tx1, tx2, tx3, ty1, ty2, ty3; - Zvalue tz1, tz2, tz3; - GL_Vector t; - double invw; - - /* Transform the three points into screen coordinates */ - - Matrix_transform4(p3->trans_mat,x1,y1,z1,1,&t); /* Point 1 */ - invw = 1.0/t.w; - t.x = t.x *invw; - t.y = t.y *invw; - t.z = t.z *invw; - tx1 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - ty1 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - tz1 = (Zvalue) t.z; - - Matrix_transform4(p3->trans_mat,x2,y2,z2,1,&t); /* Point 2 */ - invw = 1.0/t.w; - t.x = t.x *invw; - t.y = t.y *invw; - t.z = t.z *invw; - tx2 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - ty2 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - tz2 = (Zvalue) t.z; - - Matrix_transform4(p3->trans_mat,x3,y3,z3,1,&t); /* Point 3 */ - invw = 1.0/t.w; - t.x = t.x *invw; - t.y = t.y *invw; - t.z = t.z *invw; - tx3 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - ty3 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - tz3 = (Zvalue) t.z; - - - Plot3D_linetransform(p3,tx1,ty1,tz1,tx2,ty2,tz2,color); - Plot3D_linetransform(p3,tx1,ty1,tz1,tx3,ty3,tz3,color); - Plot3D_linetransform(p3,tx2,ty2,tz2,tx3,ty3,tz3,color); -} - - -/* ------------------------------------------------------------------------- - Plot3D_solidtriangletransform(Plot3D *p3, int tx1, int ty2, Zvalue tz1, - int tx2, int ty2, Zvalue tz2, - int tx3, int ty3, Zvalue tz3, Pixel color) - - This function draws a 3D z-buffered filled triangle. Assumes three - points have already been transformed into screen coordinates. - - General idea : - 1. Transform the three points into screen coordinates - 2. Order three points vertically on screen. - 3. Check for degenerate cases (where 3 points are colinear). - 4. Fill in the resulting triangle using horizontal lines. - -------------------------------------------------------------------------- */ - -void Plot3D_solidtriangletransform(Plot3D *p3, int tx1, int ty1, Zvalue tz1, - int tx2, int ty2, Zvalue tz2, - int tx3, int ty3, Zvalue tz3, Pixel color) { - int tempx, tempy; - Zvalue tempz; - double m1,m2,m3, mz1, mz2, mz3; - int y; - int ix1, ix2; - Zvalue zz1, zz2; - FrameBuffer *f; - register double fy1,fy2; - register Zvalue fz1,fz2; - - f = p3->frame; - - /* Check for degenerate cases here */ - - if ((ty1 == ty2) && (ty2 == ty3)) { - if (tx2 < tx1) { /* Swap points 1 and 2 if 2 is higher */ - tempx = tx1; - tempz = tz1; - tx1 = tx2; - tz1 = tz2; - tx2 = tempx; - tz2 = tempz; - } - if (tx3 < tx1) { /* Swap points 1 and 3 if 3 is higher */ - tempx = tx1; - tempz = tz1; - tx1 = tx3; - tz1 = tz3; - tx3 = tempx; - tz3 = tempz; - } - if (tx3 < tx2) { /* Swap points 2 and 3 if 3 is higher */ - tempx = tx2; - tempz = tz2; - tx2 = tx3; - tz2 = tz3; - tx3 = tempx; - tz3 = tempz; - } - - /* Points are aligned horizontally. Handle as a special case */ - /* Just draw three lines using the outline color */ - - Plot3D_horizontal(p3,tx1,tx2,ty1,tz1,tz3,color); - - /* Plot3D_linetransform(p3,tx1,ty1,tz1,tx2,ty2,tz2,color); - Plot3D_linetransform(p3,tx1,ty1,tz1,tx3,ty3,tz3,color); - Plot3D_linetransform(p3,tx2,ty2,tz2,tx3,ty3,tz3,color); - */ - - return; - } - - /* Figure out which point has the greatest "y" value */ - - if (ty2 > ty1) { /* Swap points 1 and 2 if 2 is higher */ - tempx = tx1; - tempy = ty1; - tempz = tz1; - tx1 = tx2; - ty1 = ty2; - tz1 = tz2; - tx2 = tempx; - ty2 = tempy; - tz2 = tempz; - } - if (ty3 > ty1) { /* Swap points 1 and 3 if 3 is higher */ - tempx = tx1; - tempy = ty1; - tempz = tz1; - tx1 = tx3; - ty1 = ty3; - tz1 = tz3; - tx3 = tempx; - ty3 = tempy; - tz3 = tempz; - } - if (ty3 > ty2) { /* Swap points 2 and 3 if 3 is higher */ - tempx = tx2; - tempy = ty2; - tempz = tz2; - tx2 = tx3; - ty2 = ty3; - tz2 = tz3; - tx3 = tempx; - ty3 = tempy; - tz3 = tempz; - } - - /* Points are now order so that t_1 is the highest point, t_2 is the - middle point, and t_3 is the lowest point */ - - if (ty2 < ty1) { - /* First process line segments between (x1,y1)-(x2,y2) - And between (x1,y1),(x3,y3) */ - - m1 = (double) (tx2 - tx1)/(double) (ty2 - ty1); - m2 = (double) (tx3 - tx1)/(double) (ty3 - ty1); - mz1 = (tz2 - tz1)/(double) (ty2 - ty1); - mz2 = (tz3 - tz1)/(double) (ty3 - ty1); - - y = ty1; - fy1 = m1*(y-ty1)+0.5 + tx1; - fy2 = m2*(y-ty1)+0.5 + tx1; - fz1 = mz1*(y-ty1) + tz1; - fz2 = mz2*(y-ty1) + tz1; - while (y >= ty2) { - /* Replace with bresenham scheme */ - /* Calculate x values from slope */ - ix1 = (int) fy1; - ix2 = (int) fy2; - zz1 = fz1; - zz2 = fz2; - fy1-= m1; - fy2-= m2; - fz1-= mz1; - fz2-= mz2; - if (ix1 > ix2) - Plot3D_horizontal(p3,ix2,ix1,y,zz2,zz1,color); - else - Plot3D_horizontal(p3,ix1,ix2,y,zz1,zz2,color); - y--; - } - } - if (ty3 < ty2) { - /* Draw lower half of the triangle */ - m2 = (double) (tx3 - tx1)/(double) (ty3 - ty1); - m3 = (double) (tx3 - tx2)/(double)(ty3 - ty2); - mz2 = (tz3 - tz1)/(double) (ty3 - ty1); - mz3 = (tz3 - tz2)/(double) (ty3 - ty2); - y = ty2; - while (y >= ty3) { - ix1 = (int) (m3*(y-ty2)+0.5)+tx2; - ix2 = (int) (m2*(y-ty1)+0.5)+tx1; - zz1 = mz3*(y-ty2)+tz2; - zz2 = mz2*(y-ty1)+tz1; - if (ix1 > ix2) - Plot3D_horizontal(p3,ix2,ix1,y,zz2,zz1,color); - else - Plot3D_horizontal(p3,ix1,ix2,y,zz1,zz2,color); - y--; - } - } -} - -/* ------------------------------------------------------------------------- - Plot3D_solidtriangle(Plot3D *p3, double x1, double y1, double z1, - double x2, double y2, double z2, - double x3, double y3, double z3, - Pixel color) - - This function draws a 3D z-buffered filled triangle. Can be used to - draw other primitives such as quadralaterals, etc... - - This function simply transforms the given points and calls - Plot3D_SolidTriangleTransform(). - -------------------------------------------------------------------------- */ - -void Plot3D_solidtriangle(Plot3D *p3, double x1, double y1, double z1, - double x2, double y2, double z2, - double x3, double y3, double z3, Pixel color) { - - int tx1, tx2, tx3, ty1, ty2, ty3; - Zvalue tz1, tz2, tz3; - GL_Vector t; - double invw; - Matrix a; - register double xshift, yshift, zoom, width, height, view_xmin, view_ymin; - - a = p3->trans_mat; - xshift = p3->xshift; - yshift = p3->yshift; - zoom = p3->zoom; - height = p3->height; - width = p3->width; - view_xmin = p3->view_xmin; - view_ymin = p3->view_ymin; - - /* Transform the three points into screen coordinates */ - - t.w = a[12]*x1 + a[13]*y1 + a[14]*z1 + a[15]; - invw = 1.0/t.w; - t.x = (a[0]*x1 + a[1]*y1 + a[2]*z1 + a[3])*invw; - t.y = (a[4]*x1 + a[5]*y1 + a[6]*z1 + a[7])*invw; - t.z = (a[8]*x1 + a[9]*y1 + a[10]*z1 + a[11])*invw; - - tx1 = (int) ((t.x +xshift)*zoom*width + 0.5) + view_xmin; - ty1 = (int) ((t.y +yshift)*zoom*height + 0.5) + view_ymin; - tz1 = (Zvalue) t.z; - - - t.w = a[12]*x2 + a[13]*y2 + a[14]*z2 + a[15]; - invw = 1.0/t.w; - t.x = (a[0]*x2 + a[1]*y2 + a[2]*z2 + a[3])*invw; - t.y = (a[4]*x2 + a[5]*y2 + a[6]*z2 + a[7])*invw; - t.z = (a[8]*x2 + a[9]*y2 + a[10]*z2 + a[11])*invw; - tx2 = (int) ((t.x +xshift)*zoom*width + 0.5) + view_xmin; - ty2 = (int) ((t.y +yshift)*zoom*height + 0.5) + view_ymin; - tz2 = (Zvalue) t.z; - - t.w = a[12]*x3 + a[13]*y3 + a[14]*z3 + a[15]; - invw = 1.0/t.w; - t.x = (a[0]*x3 + a[1]*y3 + a[2]*z3 + a[3])*invw; - t.y = (a[4]*x3 + a[5]*y3 + a[6]*z3 + a[7])*invw; - t.z = (a[8]*x3 + a[9]*y3 + a[10]*z3 + a[11])*invw; - tx3 = (int) ((t.x +xshift)*zoom*width + 0.5) + view_xmin; - ty3 = (int) ((t.y +yshift)*zoom*height + 0.5) + view_ymin; - tz3 = (Zvalue) t.z; - - Plot3D_solidtriangletransform(p3,tx1,ty1,tz1,tx2,ty2,tz2,tx3,ty3,tz3,color); - -} - - -/* ------------------------------------------------------------------------- - Plot3D_horizontalinterp(Plot3D *p3, int xmin, int xmax, int y, - double z1, double z2, Pixel c1, Pixel c2) - - Draws a "Horizontal" line on the framebuffer between two screen coordinates, - but also supplies z-values and zbuffering. Performs a color interpolation - between c1 and c2. This is primarily used by the SolidTriangleInterp() - function to give the illusion of smooth surfaces. - -------------------------------------------------------------------------- */ - -void Plot3D_horizontalinterp(Plot3D *p3, int xmin, int xmax, int y, - Zvalue z1, Zvalue z2, Pixel c1, Pixel c2) { - Pixel *p; - FrameBuffer *f; - int i; - Zvalue *zbuf,z,mz; - double mc; - int startx, endx; - double invdx; - - f = p3->frame; - if ((y < f->ymin) || (y >= f->ymax)) return; - if (xmin >= f->xmax) return; - if (xmin < f->xmin) startx = f->xmin; - else startx = xmin; - if (xmax < f->xmin) return; - if (xmax >= f->xmax) endx = f->xmax - 1; - else endx = xmax; - - /* Calculate z slope */ - if (xmax != xmin) { - invdx = 1.0/(double) (xmax-xmin); - } else { - invdx = 0; - } - - mz = (Zvalue) (z2 - z1)*invdx; - - /* Calculate c slope */ - - mc = (double) (c2 - c1)*invdx; - - /* Draw it */ - - p = &f->pixels[y][startx]; - zbuf = &f->zbuffer[y][startx]; - for (i = startx; i <= endx; i++, p++, zbuf++) { - z = (Zvalue) (mz*(i-xmin) + z1); - if (z <= *zbuf) { - *p = (Pixel) (mc*(i-xmin)+c1); - *zbuf = z; - } - } -} - -/* ------------------------------------------------------------------------- - Plot3D_interptriangletransform(Plot3D *p3, - int tx1, int ty2, Zvalue tz1, Pixel c1, - int tx2, int ty2, Zvalue tz2, Pixel c2, - int tx3, int ty3, Zvalue tz3, Pixel c3) - - This function draws a 3D z-buffered filled triangle with color - interpolation. Assumes three points have already been transformed - into screen coordinates. - - General idea : - 1. Transform the three points into screen coordinates - 2. Order three points vertically on screen. - 3. Check for degenerate cases (where 3 points are colinear). - 4. Fill in the resulting triangle using horizontal lines. - 5. Colors are interpolated between end points - -------------------------------------------------------------------------- */ - -void Plot3D_interptriangletransform(Plot3D *p3, - int tx1, int ty1, Zvalue tz1, Pixel c1, - int tx2, int ty2, Zvalue tz2, Pixel c2, - int tx3, int ty3, Zvalue tz3, Pixel c3) { - int tempx, tempy; - Zvalue tempz; - double m1,m2,m3, mz1, mz2, mz3; - double mc1,mc2,mc3; - Pixel ic1,ic2,tempc; - int y; - int ix1, ix2; - Zvalue zz1, zz2; - FrameBuffer *f; - - f = p3->frame; - - /* Figure out which point has the greatest "y" value */ - - if (ty2 > ty1) { /* Swap points 1 and 2 if 2 is higher */ - tempx = tx1; - tempy = ty1; - tempz = tz1; - tempc = c1; - tx1 = tx2; - ty1 = ty2; - tz1 = tz2; - c1 = c2; - tx2 = tempx; - ty2 = tempy; - tz2 = tempz; - c2 = tempc; - } - if (ty3 > ty1) { /* Swap points 1 and 3 if 3 is higher */ - tempx = tx1; - tempy = ty1; - tempz = tz1; - tempc = c1; - tx1 = tx3; - ty1 = ty3; - tz1 = tz3; - c1 = c3; - tx3 = tempx; - ty3 = tempy; - tz3 = tempz; - c3 = tempc; - } - if (ty3 > ty2) { /* Swap points 2 and 3 if 3 is higher */ - tempx = tx2; - tempy = ty2; - tempz = tz2; - tempc = c2; - tx2 = tx3; - ty2 = ty3; - tz2 = tz3; - c2 = c3; - tx3 = tempx; - ty3 = tempy; - tz3 = tempz; - c3 = tempc; - } - - /* Points are now order so that t_1 is the highest point, t_2 is the - middle point, and t_3 is the lowest point */ - - /* Check for degenerate cases here */ - - if ((ty1 == ty2) && (ty2 == ty3)) { - - /* Points are aligned horizontally. Handle as a special case */ - /* Just draw three lines using the outline color */ - - if (tx2 > tx1) - Plot3D_horizontalinterp(p3,tx1,tx2,ty1,tz1,tz2,c1,c2); - else - Plot3D_horizontalinterp(p3,tx2,tx1,ty1,tz2,tz1,c2,c1); - if (tx3 > tx1) - Plot3D_horizontalinterp(p3,tx1,tx3,ty1,tz1,tz3,c1,c3); - else - Plot3D_horizontalinterp(p3,tx3,tx1,ty1,tz3,tz1,c3,c1); - if (tx3 > tx2) - Plot3D_horizontalinterp(p3,tx2,tx3,ty2,tz2,tz3,c2,c3); - else - Plot3D_horizontalinterp(p3,tx3,tx2,ty2,tz3,tz2,c3,c2); - - } else { - - /* First process line segments between (x1,y1)-(x2,y2) - And between (x1,y1),(x3,y3) */ - - if (ty2 < ty1) { - m1 = (double) (tx2 - tx1)/(double) (ty2 - ty1); - m2 = (double) (tx3 - tx1)/(double) (ty3 - ty1); - mz1 = (tz2 - tz1)/(double) (ty2 - ty1); - mz2 = (tz3 - tz1)/(double) (ty3 - ty1); - mc1 = (c2 - c1)/(double) (ty2 - ty1); - mc2 = (c3 - c1)/(double) (ty3 - ty1); - - y = ty1; - while (y >= ty2) { - /* Calculate x values from slope */ - ix1 = (int) (m1*(y-ty1)+0.5) + tx1; - ix2 = (int) (m2*(y-ty1)+0.5) + tx1; - zz1 = mz1*(y-ty1) + tz1; - zz2 = mz2*(y-ty1) + tz1; - ic1 = mc1*(y-ty1) + c1; - ic2 = mc2*(y-ty1) + c1; - if (ix1 > ix2) - Plot3D_horizontalinterp(p3,ix2,ix1,y,zz2,zz1,ic2,ic1); - else - Plot3D_horizontalinterp(p3,ix1,ix2,y,zz1,zz2,ic1,ic2); - y--; - } - } - if (ty3 < ty2) { - /* Draw lower half of the triangle */ - m2 = (double) (tx3 - tx1)/(double) (ty3 - ty1); - mz2 = (tz3 - tz1)/(double) (ty3 - ty1); - mc2 = (c3 - c1)/(double) (ty3 - ty1); - m3 = (double) (tx3 - tx2)/(double)(ty3 - ty2); - mz3 = (tz3 - tz2)/(double) (ty3 - ty2); - mc3 = (c3 - c2)/(double) (ty3 - ty2); - y = ty2; - while (y >= ty3) { - ix1 = (int) (m3*(y-ty2)+0.5)+tx2; - ix2 = (int) (m2*(y-ty1)+0.5)+tx1; - zz1 = mz3*(y-ty2)+tz2; - zz2 = mz2*(y-ty1)+tz1; - ic1 = mc3*(y-ty2)+c2; - ic2 = mc2*(y-ty1)+c1; - if (ix1 > ix2) - Plot3D_horizontalinterp(p3,ix2,ix1,y,zz2,zz1,ic2,ic1); - else - Plot3D_horizontalinterp(p3,ix1,ix2,y,zz1,zz2,ic1,ic2); - y--; - } - } - } -} - -/* ------------------------------------------------------------------------- - Plot3D_interptriangle(Plot3D *p3, - double x1, double y1, double z1, Pixel c1, - double x2, double y2, double z2, Pixel c2, - double x3, double y3, double z3, Pixel c3) - - This function draws a 3D z-buffered filled triangle with color - interpolation. - - This function simply transforms the given points and calls - Plot3D_InterpTriangleTransform(). - -------------------------------------------------------------------------- */ - -void Plot3D_interptriangle(Plot3D *p3, - double x1, double y1, double z1, Pixel c1, - double x2, double y2, double z2, Pixel c2, - double x3, double y3, double z3, Pixel c3) { - - int tx1, tx2, tx3, ty1, ty2, ty3; - Zvalue tz1, tz2, tz3; - GL_Vector t; - double invw; - - /* Transform the three points into screen coordinates */ - - Matrix_transform4(p3->trans_mat,x1,y1,z1,1,&t); /* Point 1 */ - invw = 1.0/t.w; - t.x = t.x *invw; - t.y = t.y *invw; - t.z = t.z *invw; - tx1 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - ty1 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - tz1 = (Zvalue) t.z; - - Matrix_transform4(p3->trans_mat,x2,y2,z2,1,&t); /* Point 2 */ - invw = 1.0/t.w; - t.x = t.x *invw; - t.y = t.y *invw; - t.z = t.z *invw; - tx2 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - ty2 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - tz2 = (Zvalue) t.z; - - Matrix_transform4(p3->trans_mat,x3,y3,z3,1,&t); /* Point 3 */ - invw = 1.0/t.w; - t.x = t.x *invw; - t.y = t.y *invw; - t.z = t.z *invw; - tx3 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - ty3 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - tz3 = (Zvalue) t.z; - - Plot3D_interptriangletransform(p3,tx1,ty1,tz1,c1,tx2,ty2,tz2,c2,tx3,ty3,tz3,c3); -} - -/* ------------------------------------------------------------------------- - Plot3D_quad(Plot3D *p3, double x1, double y1, double z1, - double x2, double y2, double z2, - double x3, double y3, double z3, - double x4, double y4, double z4, - Pixel fillcolor) - - This function draws a 3D outlined Quadralateral. Used primarily for - drawing meshes and other things. - - Plotting is done in the following order : - (x1,y1,z1) --> (x2,y2,z2) - (x2,y2,z2) --> (x3,y3,z3) - (x3,y3,z3) --> (x4,y4,z4) - (x4,y4,z4) --> (x1,y1,z1) - -------------------------------------------------------------------------- */ - -void Plot3D_quad(Plot3D *p3, double x1, double y1, double z1, - double x2, double y2, double z2, - double x3, double y3, double z3, - double x4, double y4, double z4, - Pixel color) { - - int tx1, tx2, tx3, tx4, ty1, ty2, ty3, ty4; - Zvalue tz1, tz2, tz3, tz4; - GL_Vector t; - double invw; - - /* Transform the three points into screen coordinates */ - - Matrix_transform4(p3->trans_mat,x1,y1,z1,1,&t); /* Point 1 */ - invw = 1.0/t.w; - t.x = t.x *invw; - t.y = t.y *invw; - t.z = t.z *invw; - tx1 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - ty1 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - tz1 = (Zvalue) t.z; - - Matrix_transform4(p3->trans_mat,x2,y2,z2,1,&t); /* Point 2 */ - invw = 1.0/t.w; - t.x = t.x *invw; - t.y = t.y *invw; - t.z = t.z *invw; - tx2 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - ty2 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - tz2 = (Zvalue) t.z; - - Matrix_transform4(p3->trans_mat,x3,y3,z3,1,&t); /* Point 3 */ - invw = 1.0/t.w; - t.x = t.x *invw; - t.y = t.y *invw; - t.z = t.z *invw; - tx3 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - ty3 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - tz3 = (Zvalue) t.z; - - Matrix_transform4(p3->trans_mat,x4,y4,z4,1,&t); /* Point 3 */ - invw = 1.0/t.w; - t.x = t.x *invw; - t.y = t.y *invw; - t.z = t.z *invw; - tx4 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - ty4 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - tz4 = (Zvalue) t.z; - - Plot3D_linetransform(p3,tx1,ty1,tz1,tx2,ty2,tz2,color); - Plot3D_linetransform(p3,tx2,ty2,tz2,tx3,ty3,tz3,color); - Plot3D_linetransform(p3,tx3,ty3,tz3,tx4,ty4,tz4,color); - Plot3D_linetransform(p3,tx4,ty4,tz4,tx1,ty1,tz1,color); - -} - - -/* ------------------------------------------------------------------------- - Plot3D_solidquad(Plot3D *p3, double x1, double y1, double z1, - double x2, double y2, double z2, - double x3, double y3, double z3, - double x4, double y4, double z4, - Pixel fillcolor) - - This function draws a 3D solid Quadralateral. Uses the function - Plot3D_SolidTriangleTransform() to fill in the region. - - Plotting is done in the following order : - (x1,y1,z1) --> (x2,y2,z2) - (x2,y2,z2) --> (x3,y3,z3) - (x3,y3,z3) --> (x4,y4,z4) - (x4,y4,z4) --> (x1,y1,z1) - -------------------------------------------------------------------------- */ - -void Plot3D_solidquad(Plot3D *p3, double x1, double y1, double z1, - double x2, double y2, double z2, - double x3, double y3, double z3, - double x4, double y4, double z4, - Pixel color) { - - int tx1, tx2, tx3, tx4, ty1, ty2, ty3, ty4; - Zvalue tz1, tz2, tz3, tz4; - GL_Vector t; - double invw; - - /* Transform the three points into screen coordinates */ - - Matrix_transform4(p3->trans_mat,x1,y1,z1,1,&t); /* Point 1 */ - invw = 1.0/t.w; - t.x = t.x *invw; - t.y = t.y *invw; - t.z = t.z *invw; - tx1 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - ty1 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - tz1 = (Zvalue) t.z; - - Matrix_transform4(p3->trans_mat,x2,y2,z2,1,&t); /* Point 2 */ - invw = 1.0/t.w; - t.x = t.x *invw; - t.y = t.y *invw; - t.z = t.z *invw; - tx2 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - ty2 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - tz2 = (Zvalue) t.z; - - Matrix_transform4(p3->trans_mat,x3,y3,z3,1,&t); /* Point 3 */ - invw = 1.0/t.w; - t.x = t.x *invw; - t.y = t.y *invw; - t.z = t.z *invw; - tx3 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - ty3 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - tz3 = (Zvalue) t.z; - - Matrix_transform4(p3->trans_mat,x4,y4,z4,1,&t); /* Point 3 */ - invw = 1.0/t.w; - t.x = t.x *invw; - t.y = t.y *invw; - t.z = t.z *invw; - tx4 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - ty4 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - tz4 = (Zvalue) t.z; - - Plot3D_solidtriangletransform(p3,tx1,ty1,tz1,tx2,ty2,tz2,tx3,ty3,tz3,color); - Plot3D_solidtriangletransform(p3,tx1,ty1,tz1,tx4,ty4,tz4,tx3,ty3,tz3,color); -} - -/* ------------------------------------------------------------------------- - Plot3D_interpquad(Plot3D *p3, double x1, double y1, double z1, Pixel c1, - double x2, double y2, double z2, Pixel c2, - double x3, double y3, double z3, Pixel c3, - double x4, double y4, double z4, Pixel c4) - - This function draws a 3D color-interpolated Quadralateral. Uses the function - Plot3D_InterpTriangleTransform() to fill in the region. - - Plotting is done in the following order : - (x1,y1,z1) --> (x2,y2,z2) - (x2,y2,z2) --> (x3,y3,z3) - (x3,y3,z3) --> (x4,y4,z4) - (x4,y4,z4) --> (x1,y1,z1) - -------------------------------------------------------------------------- */ - -void Plot3D_interpquad(Plot3D *p3, double x1, double y1, double z1, Pixel c1, - double x2, double y2, double z2, Pixel c2, - double x3, double y3, double z3, Pixel c3, - double x4, double y4, double z4, Pixel c4) { - - - int tx1, tx2, tx3, tx4, ty1, ty2, ty3, ty4; - Zvalue tz1, tz2, tz3, tz4; - GL_Vector t; - double invw; - - /* Transform the three points into screen coordinates */ - - Matrix_transform4(p3->trans_mat,x1,y1,z1,1,&t); /* Point 1 */ - invw = 1.0/t.w; - t.x = t.x *invw; - t.y = t.y *invw; - t.z = t.z *invw; - tx1 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - ty1 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - tz1 = (Zvalue) t.z; - - Matrix_transform4(p3->trans_mat,x2,y2,z2,1,&t); /* Point 2 */ - invw = 1.0/t.w; - t.x = t.x *invw; - t.y = t.y *invw; - t.z = t.z *invw; - tx2 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - ty2 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - tz2 = (Zvalue) t.z; - - Matrix_transform4(p3->trans_mat,x3,y3,z3,1,&t); /* Point 3 */ - invw = 1.0/t.w; - t.x = t.x *invw; - t.y = t.y *invw; - t.z = t.z *invw; - tx3 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - ty3 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - tz3 = (Zvalue) t.z; - - Matrix_transform4(p3->trans_mat,x4,y4,z4,1,&t); /* Point 3 */ - invw = 1.0/t.w; - t.x = t.x *invw; - t.y = t.y *invw; - t.z = t.z *invw; - tx4 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - ty4 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - tz4 = (Zvalue) t.z; - - Plot3D_interptriangletransform(p3,tx1,ty1,tz1,c1,tx2,ty2,tz2,c2,tx3,ty3,tz3,c3); - Plot3D_interptriangletransform(p3,tx1,ty1,tz1,c1,tx4,ty4,tz4,c4,tx3,ty3,tz3,c3); - -} - -/* -------------------------------------------------------------------------- - Plot3D_solidsphere(Plot3 *p3, double x, double y, double z, double radius, - Pixel c) - - Makes a 3D sphere at x,y,z with given radius and color. - - Basic strategy : - 1. Transform point to screen coordinates - 2. Figure out what the radius is in screen coordinates - 3. Use bresenham algorithm for large spheres - 4. Use bitmaps for small spheres - -------------------------------------------------------------------------- */ - -/* This is used to fill in spheres */ -static int s_xmin; -static int s_ymin; -static int s_xmax; -static int s_ymax; -static Pixel **s_pixels; -static Zvalue **s_zbuffer; - -void Plot3D_spherehorizontal(int xmin, int xmax, int y, Zvalue z, Pixel color) { - int i; - int startx, endx; - Pixel *p; - Zvalue *zbuf; - - if ((y < s_ymin) || (y >= s_ymax)) return; - if (xmin < s_xmin) startx = s_xmin; - else startx = xmin; - if (xmax >= s_xmax) endx = s_xmax - 1; - else endx = xmax; - - /* Draw it */ - - p = &s_pixels[y][xmin]; - zbuf = &s_zbuffer[y][xmin]; - for (i = startx; i <= endx; i++, p++, zbuf++) { - if (z <= *zbuf) { - *p = color; - *zbuf = z; - } - } -} - -void Plot3D_solidsphere(Plot3D *p3, double x, double y, double z, double radius, - Pixel c) { - - GL_Vector t,r; - double rad; - int tx,ty, irad; - Zvalue tz; - double invw; - int ix, iy, ix1,ix2,p; - FrameBuffer *f; - - /* First transform the point into model coordinates */ - - Matrix_transform4(p3->fullmodel_mat,x,y,z,1,&t); - - /* Now transform two points in order to find proper sphere radius */ - - Matrix_transform4(p3->view_mat,t.x+radius,t.y,t.z,t.w,&r); /* transform radius */ - Matrix_transform4(p3->view_mat,t.x,t.y,t.z,t.w,&t); - - invw = 1.0/t.w; - t.x = t.x*invw; - t.y = t.y*invw; - t.z = t.z*invw; - invw = 1.0/r.w; - r.x = r.x*invw; - r.y = r.y*invw; - r.z = r.z*invw; - invw = 1.0/r.w; - - rad = fabs(t.x - r.x); - - /* Transform everything into screen coordinates */ - - tx = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - ty = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - tz = (Zvalue) t.z; - irad = (int) (p3->zoom*(rad*p3->width + 0.5)); - - /* This is only a temporary solution (maybe). */ - -#define fill_zcircle(x,y,c) \ - ix1 = tx - x; \ - ix2 = tx + x; \ - if (ix1 < s_xmin) ix1 = s_xmin; \ - if (ix2 >= s_xmax) ix2 = s_xmax; \ - Plot3D_spherehorizontal(ix1,ix2,y,tz,c); - - f = p3->frame; - s_xmin = f->xmin; - s_ymin = f->ymin; - s_xmax = f->xmax; - s_ymax = f->ymax; - s_pixels = f->pixels; - s_zbuffer = f->zbuffer; - if (irad <= 1) { - /* Plot a single pixel */ - if ((tx >= f->xmin) && (tx < f->xmax)) { - if ((ty >= f->ymin) && (ty ymax)) { - if (tz <= f->zbuffer[ty][tx]) { - f->pixels[ty][tx] = c; - f->zbuffer[ty][tx] = tz; - } - } - } - return; - } - ix = 0; - iy = irad; - p = 3-2*irad; - while (ix <= iy) { - fill_zcircle(ix,ty+iy,c); - fill_zcircle(ix,ty-iy,c); - fill_zcircle(iy,ty+ix,c); - fill_zcircle(iy,ty-ix,c); - if (p < 0) p = p + 4*ix + 6; - else { - p = p + 4*(ix-iy) + 10; - iy = iy -1; - } - ix++; - } -} - - -/* -------------------------------------------------------------------- - Plot3D_outlinesphere(Plot3D *p3, double x, double y, double z, - double radius, Pixel color, Pixel bc) - - Draws an outlined sphere. - -------------------------------------------------------------------- */ - -void Plot3D_outlinesphere(Plot3D *p3, double x, double y, double z, - double radius, Pixel c, Pixel bc) -{ - GL_Vector t,r; - double rad; - int tx,ty, irad; - Zvalue tz; - double invw; - int ix, iy, ix1,ix2,p; - - FrameBuffer *f; - - /* First transform the point into model coordinates */ - - Matrix_transform4(p3->fullmodel_mat,x,y,z,1,&t); - - /* Now transform two points in order to find proper sphere radius */ - - Matrix_transform4(p3->view_mat,t.x+radius,t.y,t.z,t.w,&r); /* transform radius */ - Matrix_transform4(p3->view_mat,t.x,t.y,t.z,t.w,&t); - - invw = 1.0/t.w; - t.x = t.x*invw; - t.y = t.y*invw; - t.z = t.z*invw; - invw = 1.0/r.w; - r.x = r.x*invw; - r.y = r.y*invw; - r.z = r.z*invw; - invw = 1.0/r.w; - - rad = fabs(t.x - r.x); - - /* Transform everything into screen coordinates */ - - tx = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; - ty = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin; - tz = (Zvalue) t.z; - irad = (int) (p3->zoom*(rad*p3->width + 0.5)); - - /* This is only a temporary solution (maybe). */ -#define plot_zcircle(x,y,c) \ - if ((x >= s_xmin) && (x < s_xmax) && \ - (y >= s_ymin) && (y < s_ymax)) {\ - if (tz <= s_zbuffer[y][x]) { \ - s_pixels[y][x] = c; \ - s_zbuffer[y][x] = tz; } \ - } - - f = p3->frame; - s_xmin = f->xmin; - s_ymin = f->ymin; - s_xmax = f->xmax; - s_ymax = f->ymax; - s_pixels = f->pixels; - s_zbuffer = f->zbuffer; - - if (irad <= 1) { - /* Plot a single pixel */ - if ((tx >= f->xmin) && (tx < f->xmax)) { - if ((ty >= f->ymin) && (ty ymax)) { - if (tz <= f->zbuffer[ty][tx]) { - f->pixels[ty][tx] = c; - f->zbuffer[ty][tx] = tz; - } - } - } - return; - } - ix = 0; - iy = irad; - p = 3-2*irad; - while (ix <= iy) { - fill_zcircle(ix,ty+iy,c); - fill_zcircle(ix,ty-iy,c); - fill_zcircle(iy,ty+ix,c); - fill_zcircle(iy,ty-ix,c); - - plot_zcircle(tx+ix,ty+iy,bc); - plot_zcircle(tx-ix,ty+iy,bc); - plot_zcircle(tx+ix,ty-iy,bc); - plot_zcircle(tx-ix,ty-iy,bc); - plot_zcircle(tx+iy,ty+ix,bc); - plot_zcircle(tx-iy,ty+ix,bc); - plot_zcircle(tx+iy,ty-ix,bc); - plot_zcircle(tx-iy,ty-ix,bc); - if (p < 0) p = p + 4*ix + 6; - else { - p = p + 4*(ix-iy) + 10; - iy = iy -1; - } - ix++; - } -} - -/* QUAD Test - Test out quad functions for graphing */ - -double zf(double x, double y) { - return cos(sqrt(x*x + y*y)*10.0)/(sqrt(x*x+y*y)+1); -} - -void Quad_Test(Plot3D *p3, int npoints) { - int i,j; - double dx; - double x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4,za; - int c; - dx = 2.0/npoints; - - - for (i = 0; i < npoints; i++) - for (j = 0; j < npoints; j++) { - x1 = i*dx + -1.0; - y1 = j*dx + -1.0; - x2 = x1 + dx; - x3 = x1 + dx; - x4 = x1; - y2 = y1; - y3 = y1 + dx; - y4 = y1 + dx; - z1 = zf(x1,y1); - z2 = zf(x2,y2); - z3 = zf(x3,y3); - z4 = zf(x4,y4); - za = 0.25*(z1+z2+z3+z4); - c = 16+((za + 1)*120); - if (c > 254) c = 254; - Plot3D_quad(p3,x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4,(Pixel) c); - } -} - - -void Quad_SolidTest(Plot3D *p3, int npoints) { - int i,j; - double dx; - double x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4,za; - int c; - dx = 2.0/npoints; - - - for (i = 0; i < npoints; i++) - for (j = 0; j < npoints; j++) { - x1 = i*dx + -1.0; - y1 = j*dx + -1.0; - x2 = x1 + dx; - x3 = x1 + dx; - x4 = x1; - y2 = y1; - y3 = y1 + dx; - y4 = y1 + dx; - z1 = zf(x1,y1); - z2 = zf(x2,y2); - z3 = zf(x3,y3); - z4 = zf(x4,y4); - za = 0.25*(z1+z2+z3+z4); - c = 16+((za + 1)*120); - if (c > 254) c = 254; - Plot3D_solidquad(p3,x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4,(Pixel) c); - } -} - - - -void Quad_InterpTest(Plot3D *p3, int npoints) { - int i,j; - double dx; - double x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4; - int c1,c2,c3,c4; - dx = 2.0/npoints; - - - for (i = 0; i < npoints; i++) - for (j = 0; j < npoints; j++) { - x1 = i*dx + -1.0; - y1 = j*dx + -1.0; - x2 = x1 + dx; - x3 = x1 + dx; - x4 = x1; - y2 = y1; - y3 = y1 + dx; - y4 = y1 + dx; - z1 = zf(x1,y1); - z2 = zf(x2,y2); - z3 = zf(x3,y3); - z4 = zf(x4,y4); - c1 = 16+((z1 + 1)*120); - c2 = 16+((z2 + 1)*120); - c3 = 16+((z3 + 1)*120); - c4 = 16+((z4 + 1)*120); - if (c1 > 254) c1 = 254; - if (c2 > 254) c2 = 254; - if (c3 > 254) c3 = 254; - if (c4 > 254) c4 = 254; - Plot3D_interpquad(p3,x1,y1,z1,(Pixel) c1,x2,y2,z2,(Pixel) c2,x3,y3,z3,(Pixel) c3,x4,y4,z4,(Pixel) c4); - } -} - - - - - - - - - - - - diff --git a/Examples/GIFPlot/Makefile.in b/Examples/GIFPlot/Makefile.in deleted file mode 100644 index 4e51360c8..000000000 --- a/Examples/GIFPlot/Makefile.in +++ /dev/null @@ -1,23 +0,0 @@ -prefix = @prefix@ -exec_prefix = @exec_prefix@ -RANLIB = @RANLIB@ -OPT = - -INSTALL = ../install-sh -c -INSTALL_DATA = ${INSTALL} -m 644 -SHELL = /bin/sh - -all: - cd Lib && $(MAKE) OPT="$(OPT)" - -install: - $(INSTALL_DATA) Include/gifplot.h $(prefix)/include/gifplot.h - $(INSTALL_DATA) libgifplot.a $(exec_prefix)/lib/libgifplot.a - $(RANLIB) $(exec_prefix)/lib/libgifplot.a - -clean:: - rm -f *.@OBJEXT@ *~ libgifplot.a *_wrap* *_man* - cd Lib && $(MAKE) clean - rm -f config.log config.status config.cache - -check: all diff --git a/Examples/GIFPlot/Ocaml/check.list b/Examples/GIFPlot/Ocaml/check.list deleted file mode 100644 index e75ee586a..000000000 --- a/Examples/GIFPlot/Ocaml/check.list +++ /dev/null @@ -1,3 +0,0 @@ -# see top-level Makefile.in -full -simple diff --git a/Examples/GIFPlot/Ocaml/full/Makefile b/Examples/GIFPlot/Ocaml/full/Makefile deleted file mode 100644 index 4f35c43f9..000000000 --- a/Examples/GIFPlot/Ocaml/full/Makefile +++ /dev/null @@ -1,33 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../swig -SWIGOPT = -I../../Include -SRCS = -TARGET = gifcaml -INTERFACE = gifplot.i -LIBS = -L../.. -lgifplot -lm -INCLUDES = -I../../Include -MLFILE = gifplot.ml -IOBJS = runme.cmo -PROGFILE = runme.ml - -all:: static - -static:: - $(MAKE) -f $(TOP)/Makefile TOP='$(TOP)' \ - IOBJS='$(IOBJS)' PROGFILE='$(PROGFILE)' \ - SRCS='$(SRCS)' SWIG='$(SWIG)' MLFILE='$(MLFILE)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ocaml_static - -dynamic:: - $(MAKE) -f $(TOP)/Makefile TOP='$(TOP)' \ - IOBJS='$(IOBJS)' PROGFILE='$(PROGFILE)' \ - SRCS='$(SRCS)' SWIG='$(SWIG)' MLFILE='$(MLFILE)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ocaml_dynamic - -clean:: - $(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean - rm -f *.gif - -check: all diff --git a/Examples/GIFPlot/Ocaml/full/README b/Examples/GIFPlot/Ocaml/full/README deleted file mode 100644 index 4a2b400b5..000000000 --- a/Examples/GIFPlot/Ocaml/full/README +++ /dev/null @@ -1,8 +0,0 @@ -This example runs the entire gifplot.h header file through SWIG without -any changes. The ocaml program 'runme.ml' does something a little more -interesting. You'll have to go look at the header file to get a complete -listing of the functions. - - - - diff --git a/Examples/GIFPlot/Ocaml/full/cmap b/Examples/GIFPlot/Ocaml/full/cmap deleted file mode 100644 index a20c331a9573dd8443380680bfe2cc428780d8a9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 768 zcmZQzpd(=A5)hSEP}Mdtvvzdz4h)M)OwTDSuW4%Uoiu&!q7`d5@7R0z#JS5i?>&C` z?#s{r^Z@9-XXO?YlTlLFHMX#G@$?UkN=VBFxv-;m^2~WlR;}N<`@pd?7q8!a^y1xT znmh34m-nxpKDd4D;+bOy_iW#^cE#d(Gbi_Tw$xXZ7G$R-M27|XxI5We80l&#%Snpx zbFrd(h8Vt}lCeu@T6xFJRlCpJeMef510DGC$^DyG&YwK8f9IC C_float x) - [ x ; y ; z1 ; - (x +. dx) ; y ; z2 ; - (x +. dx) ; (y +. dy) ; z3 ; - x ; (y +. dx) ; z4 ; - (float_of_int (c + 16)) ]))) ; - y_loop (y +. dy) (j + 1) - end in - begin - y_loop ymin 0 ; - x_loop (x +. dx) (i + 1) - end - end in - x_loop xmin 0 - end - -let _ = print_endline "Making a nice 3D plot..." -let _ = drawsolid () - -let _ = _FrameBuffer_writeGIF (C_list [ frame ; cmap ; C_string "image.gif" ]) -let _ = print_endline "Write image.gif" diff --git a/Examples/GIFPlot/Ocaml/simple/Makefile b/Examples/GIFPlot/Ocaml/simple/Makefile deleted file mode 100644 index 50492efc7..000000000 --- a/Examples/GIFPlot/Ocaml/simple/Makefile +++ /dev/null @@ -1,33 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../swig -SWIGOPT = -I../../Include -SRCS = -TARGET = gifsimple -INTERFACE = simple.i -LIBS = -L../.. -lgifplot -lm -INCLUDES = -I../../Include -MLFILE = simple.ml -IOBJS = simple_wrap.o simple.cmo runme.cmo -PROGFILE = runme.ml - -all:: static - -static:: - $(MAKE) -f $(TOP)/Makefile TOP='$(TOP)' \ - IOBJS='$(IOBJS)' PROGFILE='$(PROGFILE)' \ - SRCS='$(SRCS)' SWIG='$(SWIG)' MLFILE='$(MLFILE)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ocaml_static - -dynamic:: - $(MAKE) -f $(TOP)/Makefile TOP='$(TOP)' \ - IOBJS='$(IOBJS)' PROGFILE='$(PROGFILE)' \ - SRCS='$(SRCS)' SWIG='$(SWIG)' MLFILE='$(MLFILE)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ocaml_static - -clean:: - $(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean - rm -f *.gif - -check: all diff --git a/Examples/GIFPlot/Ocaml/simple/cmap b/Examples/GIFPlot/Ocaml/simple/cmap deleted file mode 100644 index a20c331a9573dd8443380680bfe2cc428780d8a9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 768 zcmZQzpd(=A5)hSEP}Mdtvvzdz4h)M)OwTDSuW4%Uoiu&!q7`d5@7R0z#JS5i?>&C` z?#s{r^Z@9-XXO?YlTlLFHMX#G@$?UkN=VBFxv-;m^2~WlR;}N<`@pd?7q8!a^y1xT znmh34m-nxpKDd4D;+bOy_iW#^cE#d(Gbi_Tw$xXZ7G$R-M27|XxI5We80l&#%Snpx zbFrd(h8Vt}lCeu@T6xFJRlCpJeMef510DGC$^DyG&YwK8f9IC&C` z?#s{r^Z@9-XXO?YlTlLFHMX#G@$?UkN=VBFxv-;m^2~WlR;}N<`@pd?7q8!a^y1xT znmh34m-nxpKDd4D;+bOy_iW#^cE#d(Gbi_Tw$xXZ7G$R-M27|XxI5We80l&#%Snpx zbFrd(h8Vt}lCeu@T6xFJRlCpJeMef510DGC$^DyG&YwK8f9IC 239) { $c = 239; } - Plot3D_solidquad($p3,$x,$y,$z1,$x+$dx,$y,$z2,$x+$dx,$y+$dy,$z3,$x,$y+$dy,$z4,$c+16); - $y = $y + $dy; - } - $x = $x + $dx; - } -} - -print "Making a nice 3D plot...\n"; -drawsolid(); - -FrameBuffer_writeGIF($frame,$cmap,"image.gif"); -print "Wrote image.gif\n"; - diff --git a/Examples/GIFPlot/Perl5/shadow/Makefile b/Examples/GIFPlot/Perl5/shadow/Makefile deleted file mode 100644 index c39eac52c..000000000 --- a/Examples/GIFPlot/Perl5/shadow/Makefile +++ /dev/null @@ -1,25 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../swig -SWIGOPT = -outcurrentdir -SRCS = -TARGET = gifplot -INTERFACEDIR = ../../Interface/ -INTERFACE = gifplot.i -LIBS = -L../.. -lgifplot -lm -INCLUDES = -I../../Include - -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' INTERFACEDIR='$(INTERFACEDIR)' perl5 - -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='myperl' INTERFACE='$(INTERFACE)' INTERFACEDIR='$(INTERFACEDIR)' perl5_static - -clean:: - $(MAKE) -f $(TOP)/Makefile perl5_clean - rm -f *.gif - -check: all diff --git a/Examples/GIFPlot/Perl5/shadow/README b/Examples/GIFPlot/Perl5/shadow/README deleted file mode 100644 index ab12e344e..000000000 --- a/Examples/GIFPlot/Perl5/shadow/README +++ /dev/null @@ -1,2 +0,0 @@ -This example use the file in ../../Interface/gifplot.i to build -an interface with shadow classes. Run the script 'runme.pl'. diff --git a/Examples/GIFPlot/Perl5/shadow/cmap b/Examples/GIFPlot/Perl5/shadow/cmap deleted file mode 100644 index a20c331a9573dd8443380680bfe2cc428780d8a9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 768 zcmZQzpd(=A5)hSEP}Mdtvvzdz4h)M)OwTDSuW4%Uoiu&!q7`d5@7R0z#JS5i?>&C` z?#s{r^Z@9-XXO?YlTlLFHMX#G@$?UkN=VBFxv-;m^2~WlR;}N<`@pd?7q8!a^y1xT znmh34m-nxpKDd4D;+bOy_iW#^cE#d(Gbi_Tw$xXZ7G$R-M27|XxI5We80l&#%Snpx zbFrd(h8Vt}lCeu@T6xFJRlCpJeMef510DGC$^DyG&YwK8f9ICclear($BLACK); - -$p3 = new gifplot::Plot3D($frame,$xmin,$ymin,$zmin,$xmax,$ymax,$zmax); -$p3->lookat(2*($zmax-$zmin)); -$p3->autoperspective(40); -$p3->rotu(60); -$p3->rotr(30); -$p3->rotd(10); - -sub drawsolid { - $p3->clear($BLACK); - $p3->start(); - my $dx = 1.0*($xmax-$xmin)/$nxpoints; - my $dy = 1.0*($ymax-$ymin)/$nypoints; - my $cscale = 240.0/($zmax-$zmin); - my $x = $xmin; - for ($i = 0; $i < $nxpoints; $i++) { - my $y = $ymin; - for ($j = 0; $j < $nypoints; $j++) { - my $z1 = func($x,$y); - my $z2 = func($x+$dx,$y); - my $z3 = func($x+$dx,$y+$dy); - my $z4 = func($x,$y+$dy); - my $c1 = $cscale*($z1-$zmin); - my $c2 = $cscale*($z2-$zmin); - my $c3 = $cscale*($z3-$zmin); - my $c4 = $cscale*($z4-$zmin); - my $c = ($c1+$c2+$c3+$c4)/4; - if ($c < 0) { $c = 0; } - if ($c > 239) { $c = 239; } - $p3->solidquad($x,$y,$z1,$x+$dx,$y,$z2,$x+$dx,$y+$dy,$z3,$x,$y+$dy,$z4,$c+16); - $y = $y + $dy; - } - $x = $x + $dx; - } -} - -print "Making a nice 3D plot...\n"; -drawsolid(); - -$frame->writeGIF($cmap,"image.gif"); -print "Wrote image.gif\n"; - diff --git a/Examples/GIFPlot/Perl5/simple/Makefile b/Examples/GIFPlot/Perl5/simple/Makefile deleted file mode 100644 index 36a8fa938..000000000 --- a/Examples/GIFPlot/Perl5/simple/Makefile +++ /dev/null @@ -1,24 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../swig -SWIGOPT = -SRCS = -TARGET = simple -INTERFACE = simple.i -LIBS = -L../.. -lgifplot -INCLUDES = -I../../Include - -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5 - -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_static - -clean:: - $(MAKE) -f $(TOP)/Makefile perl5_clean - rm -f *.gif - -check: all diff --git a/Examples/GIFPlot/Perl5/simple/README b/Examples/GIFPlot/Perl5/simple/README deleted file mode 100644 index c2c799a70..000000000 --- a/Examples/GIFPlot/Perl5/simple/README +++ /dev/null @@ -1,5 +0,0 @@ -This is a very minimalistic example in which just a few functions -and constants from library are wrapped and used to draw some simple -shapes. The script 'runme.pl' runs the example. - - diff --git a/Examples/GIFPlot/Perl5/simple/runme.pl b/Examples/GIFPlot/Perl5/simple/runme.pl deleted file mode 100644 index f28255e7c..000000000 --- a/Examples/GIFPlot/Perl5/simple/runme.pl +++ /dev/null @@ -1,28 +0,0 @@ -# Draw some simple shapes -print "Drawing some basic shapes\n"; - -use simple; - -$cmap = simple::new_ColorMap(); -$f = simple::new_FrameBuffer(400,400); - -# Clear the picture -simple::FrameBuffer_clear($f,$simple::BLACK); - -# Make a red box -simple::FrameBuffer_box($f,40,40,200,200,$simple::RED); - -# Make a blue circle -simple::FrameBuffer_circle($f,200,200,40,$simple::BLUE); - -# Make green line -simple::FrameBuffer_line($f,10,390,390,200, $simple::GREEN); - -# Write an image out to disk - -simple::FrameBuffer_writeGIF($f,$cmap,"image.gif"); -print "Wrote image.gif\n"; - -simple::delete_FrameBuffer($f); -simple::delete_ColorMap($cmap); - diff --git a/Examples/GIFPlot/Perl5/simple/simple.i b/Examples/GIFPlot/Perl5/simple/simple.i deleted file mode 100644 index 457bc4c09..000000000 --- a/Examples/GIFPlot/Perl5/simple/simple.i +++ /dev/null @@ -1,38 +0,0 @@ -/* This example shows a very simple interface wrapping a few - primitive declarations */ - -%module simple -%{ -#include "gifplot.h" -%} - -typedef unsigned char Pixel; - -/* Here are a few useful functions */ - -ColorMap *new_ColorMap(char *filename = 0); -void delete_ColorMap(ColorMap *cmap); - -FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height); -void delete_FrameBuffer(FrameBuffer *frame); -void FrameBuffer_clear(FrameBuffer *frame, Pixel color); -void FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -void FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -void FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color); -int FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename); - -/* And some useful constants */ - -#define BLACK 0 -#define WHITE 1 -#define RED 2 -#define GREEN 3 -#define BLUE 4 -#define YELLOW 5 -#define CYAN 6 -#define MAGENTA 7 - - - - - diff --git a/Examples/GIFPlot/Php/check.list b/Examples/GIFPlot/Php/check.list deleted file mode 100644 index e75ee586a..000000000 --- a/Examples/GIFPlot/Php/check.list +++ /dev/null @@ -1,3 +0,0 @@ -# see top-level Makefile.in -full -simple diff --git a/Examples/GIFPlot/Php/full/Makefile b/Examples/GIFPlot/Php/full/Makefile deleted file mode 100644 index e33e7a730..000000000 --- a/Examples/GIFPlot/Php/full/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../swig -SWIGOPT = -I../../Include -noproxy -SRCS = -TARGET = php_gifplot -INTERFACE = gifplot.i -LIBS = -L../.. -lgifplot -lm -INCLUDES = -I../../Include - -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' php - -clean:: - $(MAKE) -f $(TOP)/Makefile php_clean - rm -f *.gif - rm -f php_gifplot.h - -check: all diff --git a/Examples/GIFPlot/Php/full/README b/Examples/GIFPlot/Php/full/README deleted file mode 100644 index f8d38d9af..000000000 --- a/Examples/GIFPlot/Php/full/README +++ /dev/null @@ -1,4 +0,0 @@ -This example runs the entire gifplot.h header file through SWIG without -any changes. The script 'runme.php3' does something a little more -interesting. You'll have to go look at the header file to get a complete -listing of the functions. diff --git a/Examples/GIFPlot/Php/full/cmap b/Examples/GIFPlot/Php/full/cmap deleted file mode 100644 index a20c331a9573dd8443380680bfe2cc428780d8a9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 768 zcmZQzpd(=A5)hSEP}Mdtvvzdz4h)M)OwTDSuW4%Uoiu&!q7`d5@7R0z#JS5i?>&C` z?#s{r^Z@9-XXO?YlTlLFHMX#G@$?UkN=VBFxv-;m^2~WlR;}N<`@pd?7q8!a^y1xT znmh34m-nxpKDd4D;+bOy_iW#^cE#d(Gbi_Tw$xXZ7G$R-M27|XxI5We80l&#%Snpx zbFrd(h8Vt}lCeu@T6xFJRlCpJeMef510DGC$^DyG&YwK8f9IC 239) { $c = 239; } - Plot3D_solidquad($p3, $x,$y,$z1,$x+$dx,$y,$z2,$x+$dx,$y+$dy,$z3,$x,$y+$dy,$z4,$c+16); - $y = $y + $dy; - } - $x = $x + $dx; - } -} - -print "Making a nice 3D plot...\n"; -drawsolid(); - -FrameBuffer_writeGIF($frame, $cmap,"image.gif"); -print "Wrote image.gif\n"; - -?> diff --git a/Examples/GIFPlot/Php/shadow/Makefile b/Examples/GIFPlot/Php/shadow/Makefile deleted file mode 100644 index df8ee30c0..000000000 --- a/Examples/GIFPlot/Php/shadow/Makefile +++ /dev/null @@ -1,19 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../swig -SWIGOPT = -I../../Interface -SRCS = -TARGET = php_gifplot -INTERFACE = gifplot.i -LIBS = -L../.. -lgifplot -lm -INCLUDES = -I../../Include - -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' php - -clean:: - $(MAKE) -f $(TOP)/Makefile php_clean - rm -f *.gif - -check: all diff --git a/Examples/GIFPlot/Php/shadow/README b/Examples/GIFPlot/Php/shadow/README deleted file mode 100644 index 3e91f7d59..000000000 --- a/Examples/GIFPlot/Php/shadow/README +++ /dev/null @@ -1,2 +0,0 @@ -This example use the file in ../../Interface/gifplot.i to build -an interface with shadow classes. Run the script 'runme.php3'. diff --git a/Examples/GIFPlot/Php/shadow/cmap b/Examples/GIFPlot/Php/shadow/cmap deleted file mode 100644 index a20c331a9573dd8443380680bfe2cc428780d8a9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 768 zcmZQzpd(=A5)hSEP}Mdtvvzdz4h)M)OwTDSuW4%Uoiu&!q7`d5@7R0z#JS5i?>&C` z?#s{r^Z@9-XXO?YlTlLFHMX#G@$?UkN=VBFxv-;m^2~WlR;}N<`@pd?7q8!a^y1xT znmh34m-nxpKDd4D;+bOy_iW#^cE#d(Gbi_Tw$xXZ7G$R-M27|XxI5We80l&#%Snpx zbFrd(h8Vt}lCeu@T6xFJRlCpJeMef510DGC$^DyG&YwK8f9ICclear(BLACK); - - -$p3 = new Plot3D($frame,$xmin,$ymin,$zmin,$xmax,$ymax,$zmax); -$p3->lookat(2*($zmax-$zmin)); -$p3->autoperspective(40); -$p3->rotu(60); -$p3->rotr(30); -$p3->rotd(10); - -function drawsolid() { - global $xmax; - global $xmin; - global $ymax; - global $ymin; - global $zmin; - global $zmax; - global $nxpoints; - global $nypoints; - global $p3; - - $p3->clear(BLACK); - $p3->start(); - $dx = 1.0*($xmax-$xmin)/$nxpoints; - $dy = 1.0*($ymax-$ymin)/$nypoints; - $cscale = 240.0/($zmax-$zmin); - $x = $xmin; - for ($i = 0; $i < $nxpoints; $i++) { - $y = $ymin; - for ($j = 0; $j < $nypoints; $j++) { - $z1 = func($x,$y); - $z2 = func($x+$dx,$y); - $z3 = func($x+$dx,$y+$dy); - $z4 = func($x,$y+$dy); - $c1 = $cscale*($z1-$zmin); - $c2 = $cscale*($z2-$zmin); - $c3 = $cscale*($z3-$zmin); - $c4 = $cscale*($z4-$zmin); - $c = ($c1+$c2+$c3+$c4)/4; - if ($c < 0) { $c = 0; } - if ($c > 239) { $c = 239; } - $p3->solidquad($x,$y,$z1,$x+$dx,$y,$z2,$x+$dx,$y+$dy,$z3,$x,$y+$dy,$z4,$c+16); - $y = $y + $dy; - } - $x = $x + $dx; - } -} - -print "Making a nice 3D plot...\n"; -drawsolid(); - -$frame->writeGIF($cmap,"image.gif"); -print "Wrote image.gif\n"; - -?> diff --git a/Examples/GIFPlot/Php/simple/Makefile b/Examples/GIFPlot/Php/simple/Makefile deleted file mode 100644 index e60b641fa..000000000 --- a/Examples/GIFPlot/Php/simple/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../swig -SWIGOPT = -noproxy -SRCS = -TARGET = php_simple -INTERFACE = simple.i -LIBS = -L../.. -lgifplot -INCLUDES = -I../../Include - -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' php - -clean:: - $(MAKE) -f $(TOP)/Makefile php_clean - rm -f *.gif - rm -f php_simple.h - -check: all diff --git a/Examples/GIFPlot/Php/simple/README b/Examples/GIFPlot/Php/simple/README deleted file mode 100644 index c2c799a70..000000000 --- a/Examples/GIFPlot/Php/simple/README +++ /dev/null @@ -1,5 +0,0 @@ -This is a very minimalistic example in which just a few functions -and constants from library are wrapped and used to draw some simple -shapes. The script 'runme.pl' runs the example. - - diff --git a/Examples/GIFPlot/Php/simple/runme.php b/Examples/GIFPlot/Php/simple/runme.php deleted file mode 100644 index cf21a0927..000000000 --- a/Examples/GIFPlot/Php/simple/runme.php +++ /dev/null @@ -1,32 +0,0 @@ - - diff --git a/Examples/GIFPlot/Php/simple/simple.i b/Examples/GIFPlot/Php/simple/simple.i deleted file mode 100644 index 457bc4c09..000000000 --- a/Examples/GIFPlot/Php/simple/simple.i +++ /dev/null @@ -1,38 +0,0 @@ -/* This example shows a very simple interface wrapping a few - primitive declarations */ - -%module simple -%{ -#include "gifplot.h" -%} - -typedef unsigned char Pixel; - -/* Here are a few useful functions */ - -ColorMap *new_ColorMap(char *filename = 0); -void delete_ColorMap(ColorMap *cmap); - -FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height); -void delete_FrameBuffer(FrameBuffer *frame); -void FrameBuffer_clear(FrameBuffer *frame, Pixel color); -void FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -void FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -void FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color); -int FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename); - -/* And some useful constants */ - -#define BLACK 0 -#define WHITE 1 -#define RED 2 -#define GREEN 3 -#define BLUE 4 -#define YELLOW 5 -#define CYAN 6 -#define MAGENTA 7 - - - - - diff --git a/Examples/GIFPlot/Pike/check.list b/Examples/GIFPlot/Pike/check.list deleted file mode 100644 index d38998cab..000000000 --- a/Examples/GIFPlot/Pike/check.list +++ /dev/null @@ -1,2 +0,0 @@ -# see top-level Makefile.in -simple diff --git a/Examples/GIFPlot/Pike/simple/Makefile b/Examples/GIFPlot/Pike/simple/Makefile deleted file mode 100644 index d339e0333..000000000 --- a/Examples/GIFPlot/Pike/simple/Makefile +++ /dev/null @@ -1,24 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../swig -SWIGOPT = -SRCS = -TARGET = simple -INTERFACE = simple.i -LIBS = -L../.. -lgifplot -INCLUDES = -I../../Include - -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike - -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='mypike' INTERFACE='$(INTERFACE)' pike_static - -clean:: - $(MAKE) -f $(TOP)/Makefile pike_clean - rm -f *.gif - -check: all diff --git a/Examples/GIFPlot/Pike/simple/README b/Examples/GIFPlot/Pike/simple/README deleted file mode 100644 index 177b3633b..000000000 --- a/Examples/GIFPlot/Pike/simple/README +++ /dev/null @@ -1,5 +0,0 @@ -This is a very minimalistic example in which just a few functions -and constants from library are wrapped and used to draw some simple -shapes. The script 'runme.pike' runs the example. - - diff --git a/Examples/GIFPlot/Pike/simple/runme.pike b/Examples/GIFPlot/Pike/simple/runme.pike deleted file mode 100644 index 0e70235f1..000000000 --- a/Examples/GIFPlot/Pike/simple/runme.pike +++ /dev/null @@ -1,30 +0,0 @@ -int main() -{ - // Draw some simple shapes - write("Drawing some basic shapes\n"); - - .simple.ColorMap cmap = .simple.new_ColorMap(); - .simple.FrameBuffer f = .simple.new_FrameBuffer(400, 400); - - // Clear the picture - .simple.FrameBuffer_clear(f, .simple.BLACK); - - // Make a red box - .simple.FrameBuffer_box(f, 40, 40, 200, 200, .simple.RED); - - // Make a blue circle - .simple.FrameBuffer_circle(f, 200, 200, 40, .simple.BLUE); - - // Make green line - .simple.FrameBuffer_line(f, 10, 390, 390, 200, .simple.GREEN); - - // Write an image out to disk - .simple.FrameBuffer_writeGIF(f, cmap, "image.gif"); - write("Wrote image.gif\n"); - - .simple.delete_FrameBuffer(f); - .simple.delete_ColorMap(cmap); - - return 0; -} - diff --git a/Examples/GIFPlot/Pike/simple/simple.i b/Examples/GIFPlot/Pike/simple/simple.i deleted file mode 100644 index 457bc4c09..000000000 --- a/Examples/GIFPlot/Pike/simple/simple.i +++ /dev/null @@ -1,38 +0,0 @@ -/* This example shows a very simple interface wrapping a few - primitive declarations */ - -%module simple -%{ -#include "gifplot.h" -%} - -typedef unsigned char Pixel; - -/* Here are a few useful functions */ - -ColorMap *new_ColorMap(char *filename = 0); -void delete_ColorMap(ColorMap *cmap); - -FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height); -void delete_FrameBuffer(FrameBuffer *frame); -void FrameBuffer_clear(FrameBuffer *frame, Pixel color); -void FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -void FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -void FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color); -int FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename); - -/* And some useful constants */ - -#define BLACK 0 -#define WHITE 1 -#define RED 2 -#define GREEN 3 -#define BLUE 4 -#define YELLOW 5 -#define CYAN 6 -#define MAGENTA 7 - - - - - diff --git a/Examples/GIFPlot/Python/check.list b/Examples/GIFPlot/Python/check.list deleted file mode 100644 index 13de977af..000000000 --- a/Examples/GIFPlot/Python/check.list +++ /dev/null @@ -1,4 +0,0 @@ -# see top-level Makefile.in -full -shadow -simple diff --git a/Examples/GIFPlot/Python/full/Makefile b/Examples/GIFPlot/Python/full/Makefile deleted file mode 100644 index 83a7c864b..000000000 --- a/Examples/GIFPlot/Python/full/Makefile +++ /dev/null @@ -1,26 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../preinst-swig -SWIGOPT = -I../../Include -SRCS = -TARGET = gifplot -INTERFACE = gifplot.i -LIBS = -L../.. -lgifplot -INCLUDES = -I../../Include - -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python - -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='mypython' INTERFACE='$(INTERFACE)' python_static - -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - rm -f *.gif - -check: all - $(MAKE) -f $(TOP)/Makefile python_run diff --git a/Examples/GIFPlot/Python/full/README b/Examples/GIFPlot/Python/full/README deleted file mode 100644 index 52971e40a..000000000 --- a/Examples/GIFPlot/Python/full/README +++ /dev/null @@ -1,8 +0,0 @@ -This example runs the entire gifplot.h header file through SWIG without -any changes. The script 'runme.py' does something a little more -interesting. You'll have to go look at the header file to get a complete -listing of the functions. - - - - diff --git a/Examples/GIFPlot/Python/full/cmap b/Examples/GIFPlot/Python/full/cmap deleted file mode 100644 index a20c331a9573dd8443380680bfe2cc428780d8a9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 768 zcmZQzpd(=A5)hSEP}Mdtvvzdz4h)M)OwTDSuW4%Uoiu&!q7`d5@7R0z#JS5i?>&C` z?#s{r^Z@9-XXO?YlTlLFHMX#G@$?UkN=VBFxv-;m^2~WlR;}N<`@pd?7q8!a^y1xT znmh34m-nxpKDd4D;+bOy_iW#^cE#d(Gbi_Tw$xXZ7G$R-M27|XxI5We80l&#%Snpx zbFrd(h8Vt}lCeu@T6xFJRlCpJeMef510DGC$^DyG&YwK8f9IC 239 : c = 239 - Plot3D_solidquad(p3,x,y,z1,x+dx,y,z2,x+dx,y+dy,z3,x,y+dy,z4,c+16) - y = y + dy - x = x + dx - -print "Making a nice 3D plot..." -drawsolid() - -FrameBuffer_writeGIF(frame,cmap,"image.gif") -print "Wrote image.gif" - diff --git a/Examples/GIFPlot/Python/shadow/Makefile b/Examples/GIFPlot/Python/shadow/Makefile deleted file mode 100644 index 3ae9a9897..000000000 --- a/Examples/GIFPlot/Python/shadow/Makefile +++ /dev/null @@ -1,27 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../preinst-swig -SWIGOPT = -outcurrentdir -SRCS = -TARGET = gifplot -INTERFACEDIR = ../../Interface/ -INTERFACE = gifplot.i -LIBS = -L../.. -lgifplot -INCLUDES = -I../../Include - -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' INTERFACEDIR='$(INTERFACEDIR)' python - -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='mypython' INTERFACE='$(INTERFACE)' INTERFACEDIR='$(INTERFACEDIR)' python_static - -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - rm -f *.gif - -check: all - $(MAKE) -f $(TOP)/Makefile python_run diff --git a/Examples/GIFPlot/Python/shadow/README b/Examples/GIFPlot/Python/shadow/README deleted file mode 100644 index aa761e240..000000000 --- a/Examples/GIFPlot/Python/shadow/README +++ /dev/null @@ -1,8 +0,0 @@ -This example illustrates Python shadow classes. Take a look at -the file GIFPlot/Interface/gifplot.i - - - - - - diff --git a/Examples/GIFPlot/Python/shadow/cmap b/Examples/GIFPlot/Python/shadow/cmap deleted file mode 100644 index a20c331a9573dd8443380680bfe2cc428780d8a9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 768 zcmZQzpd(=A5)hSEP}Mdtvvzdz4h)M)OwTDSuW4%Uoiu&!q7`d5@7R0z#JS5i?>&C` z?#s{r^Z@9-XXO?YlTlLFHMX#G@$?UkN=VBFxv-;m^2~WlR;}N<`@pd?7q8!a^y1xT znmh34m-nxpKDd4D;+bOy_iW#^cE#d(Gbi_Tw$xXZ7G$R-M27|XxI5We80l&#%Snpx zbFrd(h8Vt}lCeu@T6xFJRlCpJeMef510DGC$^DyG&YwK8f9IC 239 : c = 239 - p3.solidquad(x,y,z1,x+dx,y,z2,x+dx,y+dy,z3,x,y+dy,z4,c+16) - y = y + dy - x = x + dx - -print "Making a nice 3D plot..." -drawsolid() - -frame.writeGIF(cmap,"image.gif") -print "Wrote image.gif" - diff --git a/Examples/GIFPlot/Python/simple/Makefile b/Examples/GIFPlot/Python/simple/Makefile deleted file mode 100644 index 9fc9a6c72..000000000 --- a/Examples/GIFPlot/Python/simple/Makefile +++ /dev/null @@ -1,26 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../preinst-swig -SWIGOPT = -SRCS = -TARGET = simple -INTERFACE = simple.i -LIBS = -L../.. -lgifplot -INCLUDES = -I../../Include - -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python - -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='mypython' INTERFACE='$(INTERFACE)' python_static - -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - rm -f *.gif - -check: all - $(MAKE) -f $(TOP)/Makefile python_run diff --git a/Examples/GIFPlot/Python/simple/README b/Examples/GIFPlot/Python/simple/README deleted file mode 100644 index 22152c665..000000000 --- a/Examples/GIFPlot/Python/simple/README +++ /dev/null @@ -1,5 +0,0 @@ -This is a very minimalistic example in which just a few functions -and constants from library are wrapped and used to draw some simple -shapes. The script 'runme.py' runs the example. - - diff --git a/Examples/GIFPlot/Python/simple/runme.py b/Examples/GIFPlot/Python/simple/runme.py deleted file mode 100644 index dade67767..000000000 --- a/Examples/GIFPlot/Python/simple/runme.py +++ /dev/null @@ -1,27 +0,0 @@ -# Draw some simple shapes -print "Drawing some basic shapes" -import simple - -cmap = simple.new_ColorMap() -f = simple.new_FrameBuffer(400,400) - -# Clear the picture -simple.FrameBuffer_clear(f,simple.BLACK) - -# Make a red box -simple.FrameBuffer_box(f,40,40,200,200,simple.RED) - -# Make a blue circle -simple.FrameBuffer_circle(f,200,200,40,simple.BLUE) - -# Make green line -simple.FrameBuffer_line(f,10,390,390,200, simple.GREEN) - -# Write an image out to disk - -simple.FrameBuffer_writeGIF(f,cmap,"image.gif") -print "Wrote image.gif" - -simple.delete_FrameBuffer(f) -simple.delete_ColorMap(cmap) - diff --git a/Examples/GIFPlot/Python/simple/simple.i b/Examples/GIFPlot/Python/simple/simple.i deleted file mode 100644 index 457bc4c09..000000000 --- a/Examples/GIFPlot/Python/simple/simple.i +++ /dev/null @@ -1,38 +0,0 @@ -/* This example shows a very simple interface wrapping a few - primitive declarations */ - -%module simple -%{ -#include "gifplot.h" -%} - -typedef unsigned char Pixel; - -/* Here are a few useful functions */ - -ColorMap *new_ColorMap(char *filename = 0); -void delete_ColorMap(ColorMap *cmap); - -FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height); -void delete_FrameBuffer(FrameBuffer *frame); -void FrameBuffer_clear(FrameBuffer *frame, Pixel color); -void FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -void FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -void FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color); -int FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename); - -/* And some useful constants */ - -#define BLACK 0 -#define WHITE 1 -#define RED 2 -#define GREEN 3 -#define BLUE 4 -#define YELLOW 5 -#define CYAN 6 -#define MAGENTA 7 - - - - - diff --git a/Examples/GIFPlot/README b/Examples/GIFPlot/README deleted file mode 100644 index ac1025a42..000000000 --- a/Examples/GIFPlot/README +++ /dev/null @@ -1,59 +0,0 @@ -GIFPlot -======= - -To illustrate various SWIG features, the following examples involve -building an interface to a small, but somewhat useful graphics library -for creating 2D and 3D images in the form of GIF files. The Perl, -Python, Tcl, Java, Ruby etc. directories contain various examples specific to -those languages. - -This library was originally developed as part of the SPaSM molecular -dynamics project at Los Alamos National Laboratory. However, due to -patent enforcement issues related to LZW encoding and a general lack -of time on the part of the author, the library was never officially -released. On the plus side, a number of people have found it to be a -useful easter egg within the SWIG distribution :-). - - -DUE TO PATENT RESTRICTIONS ON THE LZW COMPRESSION ALGORITHM, THIS -LIBRARY ONLY PRODUCES UNCOMPRESSED GIF FILES. SO THERE. - - -Building the Library -==================== - -In order to run the examples, it is first necessary to build the GIFPlot -C library. To do this, simply run make: - - make - -Running the Examples -==================== - -Once the library has been built, go to your chosen language directory, -that is, Perl, Python, Tcl, Java, Ruby etc. Each example should have a -README file with a description. - -Each example can be compiled using the makefile in each example directory. This -makefile uses the top level makefile in the "Examples" directory of the distribution. -If the example doesn't compile, you will need to adjust the settings in this file. - -Documentation -============= - -Read the source Luke. The examples should be pretty much self-explanatory. -The header file Include/gifplot.h contains the full API. - -The original documentation for the library can be found online at: - - http://www.dabeaz.com/gifplot/index.html - - -Let me know what you think! -=========================== -If you found this example to be useful, confusing, or otherwise, I would like to know -about it. Suggestions for improvement are welcome. - --- Dave (dave@dabeaz.com) - - diff --git a/Examples/GIFPlot/Ruby/check.list b/Examples/GIFPlot/Ruby/check.list deleted file mode 100644 index 13de977af..000000000 --- a/Examples/GIFPlot/Ruby/check.list +++ /dev/null @@ -1,4 +0,0 @@ -# see top-level Makefile.in -full -shadow -simple diff --git a/Examples/GIFPlot/Ruby/full/Makefile b/Examples/GIFPlot/Ruby/full/Makefile deleted file mode 100644 index 5af8bc832..000000000 --- a/Examples/GIFPlot/Ruby/full/Makefile +++ /dev/null @@ -1,24 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../swig -SWIGOPT = -I../../Include -SRCS = -TARGET = gifplot -INTERFACE = gifplot.i -LIBS = -L../.. -lgifplot -INCLUDES = -I../../Include - -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby - -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static - -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - rm -f *.gif - -check: all diff --git a/Examples/GIFPlot/Ruby/full/README b/Examples/GIFPlot/Ruby/full/README deleted file mode 100644 index 22af6cb06..000000000 --- a/Examples/GIFPlot/Ruby/full/README +++ /dev/null @@ -1,8 +0,0 @@ -This example runs the entire gifplot.h header file through SWIG without -any changes. The script 'runme.rb' does something a little more -interesting. You'll have to go look at the header file to get a complete -listing of the functions. - - - - diff --git a/Examples/GIFPlot/Ruby/full/cmap b/Examples/GIFPlot/Ruby/full/cmap deleted file mode 100644 index a20c331a9573dd8443380680bfe2cc428780d8a9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 768 zcmZQzpd(=A5)hSEP}Mdtvvzdz4h)M)OwTDSuW4%Uoiu&!q7`d5@7R0z#JS5i?>&C` z?#s{r^Z@9-XXO?YlTlLFHMX#G@$?UkN=VBFxv-;m^2~WlR;}N<`@pd?7q8!a^y1xT znmh34m-nxpKDd4D;+bOy_iW#^cE#d(Gbi_Tw$xXZ7G$R-M27|XxI5We80l&#%Snpx zbFrd(h8Vt}lCeu@T6xFJRlCpJeMef510DGC$^DyG&YwK8f9IC 239 - Plot3D_solidquad(P3,x,y,z1,x+dx,y,z2,x+dx,y+dy,z3,x,y+dy,z4,c+16) - y = y + dy - end - x = x + dx - end -end - -puts "Making a nice 3D plot..." -drawsolid() - -FrameBuffer_writeGIF(frame,cmap,"image.gif") -puts "Wrote image.gif" diff --git a/Examples/GIFPlot/Ruby/shadow/Makefile b/Examples/GIFPlot/Ruby/shadow/Makefile deleted file mode 100644 index 8cbea2a57..000000000 --- a/Examples/GIFPlot/Ruby/shadow/Makefile +++ /dev/null @@ -1,25 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../swig -SWIGOPT = -outcurrentdir -SRCS = -TARGET = gifplot -INTERFACEDIR = ../../Interface/ -INTERFACE = gifplot.i -LIBS = -L../.. -lgifplot -INCLUDES = -I../../Include - -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' INTERFACEDIR='$(INTERFACEDIR)' ruby - -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='myruby' INTERFACE='$(INTERFACE)' INTERFACEDIR='$(INTERFACEDIR)' ruby_static - -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - rm -f *.gif - -check: all diff --git a/Examples/GIFPlot/Ruby/shadow/README b/Examples/GIFPlot/Ruby/shadow/README deleted file mode 100644 index 7a33e137f..000000000 --- a/Examples/GIFPlot/Ruby/shadow/README +++ /dev/null @@ -1,5 +0,0 @@ -This example illustrates Ruby shadow classes. Take a look at -the file GIFPlot/Interface/gifplot.i - -Actually Ruby module of SWIG needs no shadow class. But this example -is named "shadow" in order to be consistent with other languages. diff --git a/Examples/GIFPlot/Ruby/shadow/cmap b/Examples/GIFPlot/Ruby/shadow/cmap deleted file mode 100644 index a20c331a9573dd8443380680bfe2cc428780d8a9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 768 zcmZQzpd(=A5)hSEP}Mdtvvzdz4h)M)OwTDSuW4%Uoiu&!q7`d5@7R0z#JS5i?>&C` z?#s{r^Z@9-XXO?YlTlLFHMX#G@$?UkN=VBFxv-;m^2~WlR;}N<`@pd?7q8!a^y1xT znmh34m-nxpKDd4D;+bOy_iW#^cE#d(Gbi_Tw$xXZ7G$R-M27|XxI5We80l&#%Snpx zbFrd(h8Vt}lCeu@T6xFJRlCpJeMef510DGC$^DyG&YwK8f9IC 239 - P3.solidquad(x,y,z1,x+dx,y,z2,x+dx,y+dy,z3,x,y+dy,z4,c+16) - y = y + dy - end - x = x + dx - end -end - -puts "Making a nice 3D plot..." -drawsolid() - -frame.writeGIF(cmap,"image.gif") -puts "Wrote image.gif" - diff --git a/Examples/GIFPlot/Ruby/simple/Makefile b/Examples/GIFPlot/Ruby/simple/Makefile deleted file mode 100644 index f7ca1a7d8..000000000 --- a/Examples/GIFPlot/Ruby/simple/Makefile +++ /dev/null @@ -1,24 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../swig -SWIGOPT = -SRCS = -TARGET = simple -INTERFACE = simple.i -LIBS = -L../.. -lgifplot -INCLUDES = -I../../Include - -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby - -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static - -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - rm -f *.gif - -check: all diff --git a/Examples/GIFPlot/Ruby/simple/README b/Examples/GIFPlot/Ruby/simple/README deleted file mode 100644 index 9b51038bf..000000000 --- a/Examples/GIFPlot/Ruby/simple/README +++ /dev/null @@ -1,5 +0,0 @@ -This is a very minimalistic example in which just a few functions -and constants from library are wrapped and used to draw some simple -shapes. The script 'runme.rb' runs the example. - - diff --git a/Examples/GIFPlot/Ruby/simple/runme.rb b/Examples/GIFPlot/Ruby/simple/runme.rb deleted file mode 100644 index e8bf5a40f..000000000 --- a/Examples/GIFPlot/Ruby/simple/runme.rb +++ /dev/null @@ -1,27 +0,0 @@ -# Draw some simple shapes -puts "Drawing some basic shapes" -require 'simple' - -cmap = Simple.new_ColorMap() -f = Simple.new_FrameBuffer(400,400) - -# Clear the picture -Simple.FrameBuffer_clear(f,Simple::BLACK) - -# Make a red box -Simple.FrameBuffer_box(f,40,40,200,200,Simple::RED) - -# Make a blue circle -Simple.FrameBuffer_circle(f,200,200,40,Simple::BLUE) - -# Make green line -Simple.FrameBuffer_line(f,10,390,390,200, Simple::GREEN) - -# Write an image out to disk - -Simple.FrameBuffer_writeGIF(f,cmap,"image.gif") -puts "Wrote image.gif" - -Simple.delete_FrameBuffer(f) -Simple.delete_ColorMap(cmap) - diff --git a/Examples/GIFPlot/Ruby/simple/simple.i b/Examples/GIFPlot/Ruby/simple/simple.i deleted file mode 100644 index 457bc4c09..000000000 --- a/Examples/GIFPlot/Ruby/simple/simple.i +++ /dev/null @@ -1,38 +0,0 @@ -/* This example shows a very simple interface wrapping a few - primitive declarations */ - -%module simple -%{ -#include "gifplot.h" -%} - -typedef unsigned char Pixel; - -/* Here are a few useful functions */ - -ColorMap *new_ColorMap(char *filename = 0); -void delete_ColorMap(ColorMap *cmap); - -FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height); -void delete_FrameBuffer(FrameBuffer *frame); -void FrameBuffer_clear(FrameBuffer *frame, Pixel color); -void FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -void FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -void FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color); -int FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename); - -/* And some useful constants */ - -#define BLACK 0 -#define WHITE 1 -#define RED 2 -#define GREEN 3 -#define BLUE 4 -#define YELLOW 5 -#define CYAN 6 -#define MAGENTA 7 - - - - - diff --git a/Examples/GIFPlot/Tcl/check.list b/Examples/GIFPlot/Tcl/check.list deleted file mode 100644 index 2b6e3d28a..000000000 --- a/Examples/GIFPlot/Tcl/check.list +++ /dev/null @@ -1,4 +0,0 @@ -# see top-level Makefile.in -full -mandel -simple diff --git a/Examples/GIFPlot/Tcl/full/Makefile b/Examples/GIFPlot/Tcl/full/Makefile deleted file mode 100644 index 0c016e364..000000000 --- a/Examples/GIFPlot/Tcl/full/Makefile +++ /dev/null @@ -1,24 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../swig -SWIGOPT = -I../../Include -SRCS = -TARGET = gifplot -INTERFACE = gifplot.i -LIBS = -L../.. -lgifplot -INCLUDES = -I../../Include - -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tcl - -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='mytclsh' INTERFACE='$(INTERFACE)' tclsh - -clean:: - $(MAKE) -f $(TOP)/Makefile tcl_clean - rm -f *.gif - -check: all diff --git a/Examples/GIFPlot/Tcl/full/README b/Examples/GIFPlot/Tcl/full/README deleted file mode 100644 index bdba4e8b0..000000000 --- a/Examples/GIFPlot/Tcl/full/README +++ /dev/null @@ -1,8 +0,0 @@ -This example runs the entire gifplot.h header file through SWIG without -any changes. The script 'runme.tcl' does something a little more -interesting. You'll have to go look at the header file to get a complete -listing of the functions. - - - - diff --git a/Examples/GIFPlot/Tcl/full/cmap b/Examples/GIFPlot/Tcl/full/cmap deleted file mode 100644 index a20c331a9573dd8443380680bfe2cc428780d8a9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 768 zcmZQzpd(=A5)hSEP}Mdtvvzdz4h)M)OwTDSuW4%Uoiu&!q7`d5@7R0z#JS5i?>&C` z?#s{r^Z@9-XXO?YlTlLFHMX#G@$?UkN=VBFxv-;m^2~WlR;}N<`@pd?7q8!a^y1xT znmh34m-nxpKDd4D;+bOy_iW#^cE#d(Gbi_Tw$xXZ7G$R-M27|XxI5We80l&#%Snpx zbFrd(h8Vt}lCeu@T6xFJRlCpJeMef510DGC$^DyG&YwK8f9IC 239} { set c 239 } - Plot3D_solidquad $p3 $x $y $z1 [expr {$x+$dx}] $y $z2 [expr {$x+$dx}] [expr {$y+$dy}] $z3 $x [expr {$y+$dy}] $z4 [expr {$c+16}] - set y [expr {$y + $dy}] - } - set x [expr {$x + $dx}] - } -} - -puts "Making a nice 3D plot..." -drawsolid - -FrameBuffer_writeGIF $frame $cmap "image.gif" -puts "Wrote image.gif" - diff --git a/Examples/GIFPlot/Tcl/mandel/Makefile b/Examples/GIFPlot/Tcl/mandel/Makefile deleted file mode 100644 index 9280d7bb2..000000000 --- a/Examples/GIFPlot/Tcl/mandel/Makefile +++ /dev/null @@ -1,24 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../swig -SWIGOPT = -I../../Interface -SRCS = -TARGET = gifplot -INTERFACE = mandel.i -LIBS = -L../.. -lgifplot -INCLUDES = -I../../Include - -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tcl - -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='mywish' INTERFACE='$(INTERFACE)' wish - -clean:: - $(MAKE) -f $(TOP)/Makefile tcl_clean - rm -f *.gif - -check: all diff --git a/Examples/GIFPlot/Tcl/mandel/README b/Examples/GIFPlot/Tcl/mandel/README deleted file mode 100644 index a533d09b8..000000000 --- a/Examples/GIFPlot/Tcl/mandel/README +++ /dev/null @@ -1,6 +0,0 @@ -Kill lots of time exploring the Mandelbrot set. This example uses -the full SWIG interface file located in ../../Interface. To run -the program, type 'wish mandel.tcl'. - - - diff --git a/Examples/GIFPlot/Tcl/mandel/cmap b/Examples/GIFPlot/Tcl/mandel/cmap deleted file mode 100644 index a20c331a9573dd8443380680bfe2cc428780d8a9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 768 zcmZQzpd(=A5)hSEP}Mdtvvzdz4h)M)OwTDSuW4%Uoiu&!q7`d5@7R0z#JS5i?>&C` z?#s{r^Z@9-XXO?YlTlLFHMX#G@$?UkN=VBFxv-;m^2~WlR;}N<`@pd?7q8!a^y1xT znmh34m-nxpKDd4D;+bOy_iW#^cE#d(Gbi_Tw$xXZ7G$R-M27|XxI5We80l&#%Snpx zbFrd(h8Vt}lCeu@T6xFJRlCpJeMef510DGC$^DyG&YwK8f9IC {BoxBegin %W %x %y} - bind $c {BoxDrag %W %x %y} - bind $c "BoxFinish %W %x %y $p2 $mxmin $mymin $mxmax $mymax $func" -} - -proc BoxBegin {w x y} { - global box - set box(anchor) [list $x $y] - catch {unset box(last)} -} - -proc BoxDrag { w x y} { - global box - catch {$w delete $box(last)} - set box(last) [eval {$w create rect} $box(anchor) {$x $y -tag box -outline white}] -} - -proc BoxFinish {w x y p2 mxmin mymin mxmax mymax func } { - global box - set start $box(anchor) - set x1 [lrange $start 0 0] - set y1 [lrange $start 1 1] - catch {$w delete $box(last)} -# Call the handler function - $func $p2 $mxmin $mymin $mxmax $mymax $x1 $y1 $x $y -} - -proc display_image {filename p2 handler} { - global __imageno __images - set i [image create photo -file $filename] - set tl .image$__imageno - toplevel $tl - frame $tl.img - frame $tl.button - - set width [image width $i] - set height [image height $i] - canvas $tl.img.c -width [expr {$width+0}] -height [expr {$height+0}] - pack $tl.img.c - $tl.img.c create image 0 0 -image $i -anchor nw - label $tl.button.label -text $filename - pack $tl.button.label -side left - button $tl.button.dismiss -text "Dismiss" -command "dismiss $tl $i" -width 10 - pack $tl.button.dismiss -side right - pack $tl.img $tl.button -side top -fill x - BoxInit $tl.img.c $p2 [$p2 cget -xmin] [$p2 cget -ymin] [$p2 cget -xmax] [$p2 cget -ymax] $handler - bind $tl "dismiss $tl $i" - bind $tl "dismiss $tl $i" - - # Bind some actions to the canvas - - incr __imageno 1 -} - -proc test {} { - puts "hello" -} - diff --git a/Examples/GIFPlot/Tcl/mandel/mandel.i b/Examples/GIFPlot/Tcl/mandel/mandel.i deleted file mode 100644 index 0b19f4727..000000000 --- a/Examples/GIFPlot/Tcl/mandel/mandel.i +++ /dev/null @@ -1,47 +0,0 @@ -// Special module to run the mandlebrot set -%module gifplot -%include gifplot.i - -%inline %{ - -void mandel(Plot2D *p2, int tol) { - double scalingx; - double scalingy; - double zr,zi,ztr,zti,cr,ci; - double cscale; - int i,j,n; - FrameBuffer *f; - - f = p2->frame; - scalingx = (p2->xmax-p2->xmin)/f->width; - scalingy = (p2->ymax-p2->ymin)/f->height; - - cscale = 239.0/tol; - printf("working...\n"); - for (i = 0; i < f->width; i++) { - for (j = 0; j < f->height; j++) { - zr = scalingx*i + p2->xmin; - zi = scalingy*j + p2->ymin; - cr = zr; - ci = zi; - n = 0; - while (n < tol) { - ztr = zr*zr-zi*zi + cr; - zti = 2*zr*zi + ci; - zr = ztr; - zi = zti; - if (ztr*ztr + zti*zti > 20) break; - n = n + 1; - } - - if (n >= tol) FrameBuffer_plot(f,i,j,BLACK); - else FrameBuffer_plot(f,i,j,16+(int) (n*cscale)); - } - if ((i % 10) == 0) printf("%d\n",i); - } - -} - -%} - - diff --git a/Examples/GIFPlot/Tcl/mandel/mandel.tcl b/Examples/GIFPlot/Tcl/mandel/mandel.tcl deleted file mode 100644 index 3e1600bc1..000000000 --- a/Examples/GIFPlot/Tcl/mandel/mandel.tcl +++ /dev/null @@ -1,170 +0,0 @@ -catch { load ./gifplot[info sharedlibextension] } -source display.tcl -set tcl_precision 17 -set f [FrameBuffer -args 400 400] -set cmap [ColorMap -args cmap] -set p2 [Plot2D -args $f -3 -2 1 2] - -set xmin -3 -set xmax 1 -set ymin -2.0 -set ymax 2.0 -set tolerance 240 -set filename mandel.gif - -# Make a plot from the above parms - -proc make_plot {} { - global p2 cmap tolerance - global xmin ymin xmax ymax filename - $p2 setrange $xmin $ymin $xmax $ymax - $p2 start - . config -cursor watch - update - mandel $p2 $tolerance - . config -cursor arrow - [$p2 cget -frame] writeGIF $cmap $filename - display_image $filename $p2 set_zoom -} - - -# Take some screen coordinates and set global min and max values - -proc set_zoom {p2 mxmin mymin mxmax mymax x1 y1 x2 y2} { - global xmin ymin xmax ymax - - set frame [$p2 cget -frame] - set width [$frame cget -width] - set height [$frame cget -height] - - if {$x1 < 0} {set x1 0} - if {$x1 > ($width)} {set x1 $width} - if {$x2 < 0} {set x2 0} - if {$x2 > ($width)} {set x2 $width} - if {$x1 < $x2} {set ixmin $x1; set ixmax $x2} {set ixmin $x2; set ixmax $x1} - - if {$y1 < 0} {set y1 0} - if {$y1 > ($height)} {set y1 $height} - if {$y2 < 0} {set y2 0} - if {$y2 > ($height)} {set y2 $height} - if {$y1 < $y2} {set iymin $y1; set iymax $y2} {set iymin $y2; set iymax $y1} - - # Now determine new min and max values based on screen location - - set xmin [expr {$mxmin + ($mxmax-$mxmin)*($ixmin)/($width)}] - set xmax [expr {$mxmin + ($mxmax-$mxmin)*($ixmax)/($width)}] - set ymin [expr {$mymin + ($mymax-$mymin)*(($height)-($iymax))/($height)}] - set ymax [expr {$mymin + ($mymax-$mymin)*(($height)-($iymin))/($height)}] - - catch {make_plot} -} - -# Box drag constrained to a square -proc BoxDrag { w x y} { - global box - catch {$w delete $box(last)} - set x1 [lrange $box(anchor) 0 0] - set y1 [lrange $box(anchor) 1 1] - set dx [expr {$x - $x1}] - set dy [expr {$y - $y1}] - if {abs($dy) > abs($dx)} {set dx $dy} - set newx [expr {$x1 + $dx}] - set newy [expr {$y1 + $dx}] - set box(last) [eval {$w create rect} $box(anchor) {$newx $newy -tag box -outline white}] -} - - -proc BoxFinish {w x y p2 mxmin mymin mxmax mymax func } { - global box - set start $box(anchor) - set x1 [lrange $box(anchor) 0 0] - set y1 [lrange $box(anchor) 1 1] - set dx [expr {$x - $x1}] - set dy [expr {$y - $y1}] - if {($dx == 0) || ($dy == 0)} { - catch {$w delete $box(last)} - return - } - if {abs($dy) > abs($dx)} {set dx $dy} - set newx [expr {$x1 + $dx}] - set newy [expr {$y1 + $dx}] - $w config -cursor watch - update -# Call the handler function - $func $p2 $mxmin $mymin $mxmax $mymax $x1 $y1 $newx $newy - catch {$w delete $box(last)} - $w config -cursor arrow -} - - -# Create a few frames - -wm title . Mandelbrot -frame .title -relief groove -borderwidth 1 -label .title.name -text "Mandelbrot Set" -button .title.quit -text "Quit" -command "exit" -button .title.about -text "About" -command "about" -pack .title.name -side left -pack .title.quit .title.about -side right - -frame .func -relief groove -borderwidth 1 - -frame .func.xrange -label .func.xrange.xrlabel -text "X range" -width 12 -entry .func.xrange.xmin -textvar xmin -width 8 -label .func.xrange.xtolabel -text "to" -entry .func.xrange.xmax -textvar xmax -width 8 -pack .func.xrange.xrlabel .func.xrange.xmin .func.xrange.xtolabel .func.xrange.xmax -side left - -frame .func.yrange -label .func.yrange.yrlabel -text "Y range" -width 12 -entry .func.yrange.ymin -textvar ymin -width 8 -label .func.yrange.ytolabel -text "to" -entry .func.yrange.ymax -textvar ymax -width 8 -pack .func.yrange.yrlabel .func.yrange.ymin .func.yrange.ytolabel .func.yrange.ymax -side left - -frame .func.npoints -label .func.npoints.label -text "Tolerance " -width 12 -entry .func.npoints.npoints -textvar tolerance -width 8 -scale .func.npoints.scale -from 0 -to 2500 -variable tolerance -orient horizontal -showvalue false \ - -sliderlength 13 -bigincrement 10 -resolution 10 -pack .func.npoints.label .func.npoints.npoints .func.npoints.scale -side left - -pack .func.xrange .func.yrange .func.npoints -side top -fill x - -# Filename dialog - -frame .save -relief groove -borderwidth 1 - -frame .save.file -label .save.file.label -text "Save as" -width 12 -entry .save.file.filename -textvar filename -width 20 -pack .save.file.label .save.file.filename -side left -pack .save.file -side left -fill x -button .save.go -text "Plot" -command "make_plot" -pack .save.go -side right - -bind .save.file.filename {make_plot} - -pack .title .func .save -side top -fill both - -proc about { } { - toplevel .about -width 350 - - message .about.m -text "\ -Mandelbrot Set\n\n\ -Copyright (c) 1997\n\ -Dave Beazley\n\ -University of Utah\n\n\ -Creates a plot of the Mandelbrot set. Any displayed image can be zoomed by clicking and \ -dragging. Although the main calculation is written in C, it may take awhile for each \ -image to be calculated (be patient). Image quality can be improved at the expense of speed \ -by increasing the tolerance value.\n" - -button .about.okay -text "Ok" -command {destroy .about} - -pack .about.m .about.okay -side top -focus .about.okay -} - -make_plot diff --git a/Examples/GIFPlot/Tcl/simple/Makefile b/Examples/GIFPlot/Tcl/simple/Makefile deleted file mode 100644 index 752d79c10..000000000 --- a/Examples/GIFPlot/Tcl/simple/Makefile +++ /dev/null @@ -1,24 +0,0 @@ -TOP = ../../.. -SWIG = $(TOP)/../swig -SWIGOPT = -SRCS = -TARGET = simple -INTERFACE = simple.i -LIBS = -L../.. -lgifplot -INCLUDES = -I../../Include - -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tcl - -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \ - TARGET='mytclsh' INTERFACE='$(INTERFACE)' tclsh - -clean:: - $(MAKE) -f $(TOP)/Makefile tcl_clean - rm -f *.gif - -check: all diff --git a/Examples/GIFPlot/Tcl/simple/README b/Examples/GIFPlot/Tcl/simple/README deleted file mode 100644 index d6b291c92..000000000 --- a/Examples/GIFPlot/Tcl/simple/README +++ /dev/null @@ -1,5 +0,0 @@ -This is a very minimalistic example in which just a few functions -and constants from library are wrapped and used to draw some simple -shapes. The script 'runme.tcl' runs the example. - - diff --git a/Examples/GIFPlot/Tcl/simple/runme.tcl b/Examples/GIFPlot/Tcl/simple/runme.tcl deleted file mode 100644 index e3f41266c..000000000 --- a/Examples/GIFPlot/Tcl/simple/runme.tcl +++ /dev/null @@ -1,27 +0,0 @@ -# Draw some simple shapes -puts "Drawing some basic shapes" - -catch { load ./simple[info sharedlibextension] simple} - -set cmap [new_ColorMap] -set f [new_FrameBuffer 400 400] - -# Clear the picture -FrameBuffer_clear $f $BLACK - -# Make a red box -FrameBuffer_box $f 40 40 200 200 $RED - -# Make a blue circle -FrameBuffer_circle $f 200 200 40 $BLUE - -# Make green line -FrameBuffer_line $f 10 390 390 200 $GREEN - -# Write an image out to disk -FrameBuffer_writeGIF $f $cmap image.gif -puts "Wrote image.gif" - -delete_FrameBuffer $f -delete_ColorMap $cmap - diff --git a/Examples/GIFPlot/Tcl/simple/simple.i b/Examples/GIFPlot/Tcl/simple/simple.i deleted file mode 100644 index 457bc4c09..000000000 --- a/Examples/GIFPlot/Tcl/simple/simple.i +++ /dev/null @@ -1,38 +0,0 @@ -/* This example shows a very simple interface wrapping a few - primitive declarations */ - -%module simple -%{ -#include "gifplot.h" -%} - -typedef unsigned char Pixel; - -/* Here are a few useful functions */ - -ColorMap *new_ColorMap(char *filename = 0); -void delete_ColorMap(ColorMap *cmap); - -FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height); -void delete_FrameBuffer(FrameBuffer *frame); -void FrameBuffer_clear(FrameBuffer *frame, Pixel color); -void FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -void FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -void FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color); -int FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename); - -/* And some useful constants */ - -#define BLACK 0 -#define WHITE 1 -#define RED 2 -#define GREEN 3 -#define BLUE 4 -#define YELLOW 5 -#define CYAN 6 -#define MAGENTA 7 - - - - - diff --git a/Examples/chicken/zlib/Makefile b/Examples/chicken/zlib/Makefile deleted file mode 100644 index 720701444..000000000 --- a/Examples/chicken/zlib/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -INTERFACE = example.i -SRCS = -CXXSRCS = -TARGET = zlib -INCLUDE = -SWIGOPT = -I/usr/include -CFLAGS = -VARIANT = -LIBS = -lz -VARIANT = _direct - -all:: $(TARGET) - -$(TARGET): $(INTERFACE) $(SRCS) - $(MAKE) -f $(TOP)/Makefile \ - SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' \ - INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='$(TARGET)' \ - SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT) - -clean:: - $(MAKE) -f $(TOP)/Makefile chicken_clean - rm -f example.scm - rm -f $(TARGET) - -check:: - csi test-zlib.scm diff --git a/Examples/chicken/zlib/README.html b/Examples/chicken/zlib/README.html deleted file mode 100644 index b082a310c..000000000 --- a/Examples/chicken/zlib/README.html +++ /dev/null @@ -1,1666 +0,0 @@ - - - - zlib - Chicken - SWIG example - - -

zlib - Chicken - SWIG

- -

Table of Contents

- Building the example
- zlib.h
- How the zlib wrapper was developed
- -

Building the example

- - zlib must be installed for this example to work.
- - Just type make to build this example.
- - If zlib is not installed in /usr/lib and /usr/include, then do - something similar to the following: - -
-
make SWIGOPT="-I/usr/local/include" LIBS="-L/usr/local/lib -lz"
-
- -

zlib.h

-
-
-001: /* zlib.h -- interface of the 'zlib' general purpose compression library
-002:   version 1.1.4, March 11th, 2002
-003: 
-004:   Copyright (C) 1995-2002 Jean-loup Gailly and Mark Adler
-005: 
-006:   This software is provided 'as-is', without any express or implied
-007:   warranty.  In no event will the authors be held liable for any damages
-008:   arising from the use of this software.
-009: 
-010:   Permission is granted to anyone to use this software for any purpose,
-011:   including commercial applications, and to alter it and redistribute it
-012:   freely, subject to the following restrictions:
-013: 
-014:   1. The origin of this software must not be misrepresented; you must not
-015:      claim that you wrote the original software. If you use this software
-016:      in a product, an acknowledgment in the product documentation would be
-017:      appreciated but is not required.
-018:   2. Altered source versions must be plainly marked as such, and must not be
-019:      misrepresented as being the original software.
-020:   3. This notice may not be removed or altered from any source distribution.
-021: 
-022:   Jean-loup Gailly        Mark Adler
-023:   jloup@gzip.org          madler@alumni.caltech.edu
-024: 
-025: 
-026:   The data format used by the zlib library is described by RFCs (Request for
-027:   Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt
-028:   (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
-029: */
-030: 
-031: #ifndef _ZLIB_H
-032: #define _ZLIB_H
-033: 
-034: #include "zconf.h"
-035: 
-036: #ifdef __cplusplus
-037: extern "C" {
-038: #endif
-039: 
-040: #define ZLIB_VERSION "1.1.4"
-041: 
-042: /* 
-043:      The 'zlib' compression library provides in-memory compression and
-044:   decompression functions, including integrity checks of the uncompressed
-045:   data.  This version of the library supports only one compression method
-046:   (deflation) but other algorithms will be added later and will have the same
-047:   stream interface.
-048: 
-049:      Compression can be done in a single step if the buffers are large
-050:   enough (for example if an input file is mmap'ed), or can be done by
-051:   repeated calls of the compression function.  In the latter case, the
-052:   application must provide more input and/or consume the output
-053:   (providing more output space) before each call.
-054: 
-055:      The library also supports reading and writing files in gzip (.gz) format
-056:   with an interface similar to that of stdio.
-057: 
-058:      The library does not install any signal handler. The decoder checks
-059:   the consistency of the compressed data, so the library should never
-060:   crash even in case of corrupted input.
-061: */
-062: 
-063: typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
-064: typedef void   (*free_func)  OF((voidpf opaque, voidpf address));
-065: 
-066: struct internal_state;
-067: 
-068: typedef struct z_stream_s {
-069:     Bytef    *next_in;  /* next input byte */
-070:     uInt     avail_in;  /* number of bytes available at next_in */
-071:     uLong    total_in;  /* total nb of input bytes read so far */
-072: 
-073:     Bytef    *next_out; /* next output byte should be put there */
-074:     uInt     avail_out; /* remaining free space at next_out */
-075:     uLong    total_out; /* total nb of bytes output so far */
-076: 
-077:     char     *msg;      /* last error message, NULL if no error */
-078:     struct internal_state FAR *state; /* not visible by applications */
-079: 
-080:     alloc_func zalloc;  /* used to allocate the internal state */
-081:     free_func  zfree;   /* used to free the internal state */
-082:     voidpf     opaque;  /* private data object passed to zalloc and zfree */
-083: 
-084:     int     data_type;  /* best guess about the data type: ascii or binary */
-085:     uLong   adler;      /* adler32 value of the uncompressed data */
-086:     uLong   reserved;   /* reserved for future use */
-087: } z_stream;
-088: 
-089: typedef z_stream FAR *z_streamp;
-090: 
-091: /*
-092:    The application must update next_in and avail_in when avail_in has
-093:    dropped to zero. It must update next_out and avail_out when avail_out
-094:    has dropped to zero. The application must initialize zalloc, zfree and
-095:    opaque before calling the init function. All other fields are set by the
-096:    compression library and must not be updated by the application.
-097: 
-098:    The opaque value provided by the application will be passed as the first
-099:    parameter for calls of zalloc and zfree. This can be useful for custom
-100:    memory management. The compression library attaches no meaning to the
-101:    opaque value.
-102: 
-103:    zalloc must return Z_NULL if there is not enough memory for the object.
-104:    If zlib is used in a multi-threaded application, zalloc and zfree must be
-105:    thread safe.
-106: 
-107:    On 16-bit systems, the functions zalloc and zfree must be able to allocate
-108:    exactly 65536 bytes, but will not be required to allocate more than this
-109:    if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
-110:    pointers returned by zalloc for objects of exactly 65536 bytes *must*
-111:    have their offset normalized to zero. The default allocation function
-112:    provided by this library ensures this (see zutil.c). To reduce memory
-113:    requirements and avoid any allocation of 64K objects, at the expense of
-114:    compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
-115: 
-116:    The fields total_in and total_out can be used for statistics or
-117:    progress reports. After compression, total_in holds the total size of
-118:    the uncompressed data and may be saved for use in the decompressor
-119:    (particularly if the decompressor wants to decompress everything in
-120:    a single step).
-121: */
-122: 
-123:                         /* constants */
-124: 
-125: #define Z_NO_FLUSH      0
-126: #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
-127: #define Z_SYNC_FLUSH    2
-128: #define Z_FULL_FLUSH    3
-129: #define Z_FINISH        4
-130: /* Allowed flush values; see deflate() below for details */
-131: 
-132: #define Z_OK            0
-133: #define Z_STREAM_END    1
-134: #define Z_NEED_DICT     2
-135: #define Z_ERRNO        (-1)
-136: #define Z_STREAM_ERROR (-2)
-137: #define Z_DATA_ERROR   (-3)
-138: #define Z_MEM_ERROR    (-4)
-139: #define Z_BUF_ERROR    (-5)
-140: #define Z_VERSION_ERROR (-6)
-141: /* Return codes for the compression/decompression functions. Negative
-142:  * values are errors, positive values are used for special but normal events.
-143:  */
-144: 
-145: #define Z_NO_COMPRESSION         0
-146: #define Z_BEST_SPEED             1
-147: #define Z_BEST_COMPRESSION       9
-148: #define Z_DEFAULT_COMPRESSION  (-1)
-149: /* compression levels */
-150: 
-151: #define Z_FILTERED            1
-152: #define Z_HUFFMAN_ONLY        2
-153: #define Z_DEFAULT_STRATEGY    0
-154: /* compression strategy; see deflateInit2() below for details */
-155: 
-156: #define Z_BINARY   0
-157: #define Z_ASCII    1
-158: #define Z_UNKNOWN  2
-159: /* Possible values of the data_type field */
-160: 
-161: #define Z_DEFLATED   8
-162: /* The deflate compression method (the only one supported in this version) */
-163: 
-164: #define Z_NULL  0  /* for initializing zalloc, zfree, opaque */
-165: 
-166: #define zlib_version zlibVersion()
-167: /* for compatibility with versions < 1.0.2 */
-168: 
-169:                         /* basic functions */
-170: 
-171: ZEXTERN const char * ZEXPORT zlibVersion OF((void));
-172: /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
-173:    If the first character differs, the library code actually used is
-174:    not compatible with the zlib.h header file used by the application.
-175:    This check is automatically made by deflateInit and inflateInit.
-176:  */
-177: 
-178: /* 
-179: ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
-180: 
-181:      Initializes the internal stream state for compression. The fields
-182:    zalloc, zfree and opaque must be initialized before by the caller.
-183:    If zalloc and zfree are set to Z_NULL, deflateInit updates them to
-184:    use default allocation functions.
-185: 
-186:      The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
-187:    1 gives best speed, 9 gives best compression, 0 gives no compression at
-188:    all (the input data is simply copied a block at a time).
-189:    Z_DEFAULT_COMPRESSION requests a default compromise between speed and
-190:    compression (currently equivalent to level 6).
-191: 
-192:      deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
-193:    enough memory, Z_STREAM_ERROR if level is not a valid compression level,
-194:    Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
-195:    with the version assumed by the caller (ZLIB_VERSION).
-196:    msg is set to null if there is no error message.  deflateInit does not
-197:    perform any compression: this will be done by deflate().
-198: */
-199: 
-200: 
-201: ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
-202: /*
-203:     deflate compresses as much data as possible, and stops when the input
-204:   buffer becomes empty or the output buffer becomes full. It may introduce some
-205:   output latency (reading input without producing any output) except when
-206:   forced to flush.
-207: 
-208:     The detailed semantics are as follows. deflate performs one or both of the
-209:   following actions:
-210: 
-211:   - Compress more input starting at next_in and update next_in and avail_in
-212:     accordingly. If not all input can be processed (because there is not
-213:     enough room in the output buffer), next_in and avail_in are updated and
-214:     processing will resume at this point for the next call of deflate().
-215: 
-216:   - Provide more output starting at next_out and update next_out and avail_out
-217:     accordingly. This action is forced if the parameter flush is non zero.
-218:     Forcing flush frequently degrades the compression ratio, so this parameter
-219:     should be set only when necessary (in interactive applications).
-220:     Some output may be provided even if flush is not set.
-221: 
-222:   Before the call of deflate(), the application should ensure that at least
-223:   one of the actions is possible, by providing more input and/or consuming
-224:   more output, and updating avail_in or avail_out accordingly; avail_out
-225:   should never be zero before the call. The application can consume the
-226:   compressed output when it wants, for example when the output buffer is full
-227:   (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
-228:   and with zero avail_out, it must be called again after making room in the
-229:   output buffer because there might be more output pending.
-230: 
-231:     If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
-232:   flushed to the output buffer and the output is aligned on a byte boundary, so
-233:   that the decompressor can get all input data available so far. (In particular
-234:   avail_in is zero after the call if enough output space has been provided
-235:   before the call.)  Flushing may degrade compression for some compression
-236:   algorithms and so it should be used only when necessary.
-237: 
-238:     If flush is set to Z_FULL_FLUSH, all output is flushed as with
-239:   Z_SYNC_FLUSH, and the compression state is reset so that decompression can
-240:   restart from this point if previous compressed data has been damaged or if
-241:   random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
-242:   the compression.
-243: 
-244:     If deflate returns with avail_out == 0, this function must be called again
-245:   with the same value of the flush parameter and more output space (updated
-246:   avail_out), until the flush is complete (deflate returns with non-zero
-247:   avail_out).
-248: 
-249:     If the parameter flush is set to Z_FINISH, pending input is processed,
-250:   pending output is flushed and deflate returns with Z_STREAM_END if there
-251:   was enough output space; if deflate returns with Z_OK, this function must be
-252:   called again with Z_FINISH and more output space (updated avail_out) but no
-253:   more input data, until it returns with Z_STREAM_END or an error. After
-254:   deflate has returned Z_STREAM_END, the only possible operations on the
-255:   stream are deflateReset or deflateEnd.
-256:   
-257:     Z_FINISH can be used immediately after deflateInit if all the compression
-258:   is to be done in a single step. In this case, avail_out must be at least
-259:   0.1% larger than avail_in plus 12 bytes.  If deflate does not return
-260:   Z_STREAM_END, then it must be called again as described above.
-261: 
-262:     deflate() sets strm->adler to the adler32 checksum of all input read
-263:   so far (that is, total_in bytes).
-264: 
-265:     deflate() may update data_type if it can make a good guess about
-266:   the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered
-267:   binary. This field is only for information purposes and does not affect
-268:   the compression algorithm in any manner.
-269: 
-270:     deflate() returns Z_OK if some progress has been made (more input
-271:   processed or more output produced), Z_STREAM_END if all input has been
-272:   consumed and all output has been produced (only when flush is set to
-273:   Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
-274:   if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
-275:   (for example avail_in or avail_out was zero).
-276: */
-277: 
-278: 
-279: ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
-280: /*
-281:      All dynamically allocated data structures for this stream are freed.
-282:    This function discards any unprocessed input and does not flush any
-283:    pending output.
-284: 
-285:      deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
-286:    stream state was inconsistent, Z_DATA_ERROR if the stream was freed
-287:    prematurely (some input or output was discarded). In the error case,
-288:    msg may be set but then points to a static string (which must not be
-289:    deallocated).
-290: */
-291: 
-292: 
-293: /* 
-294: ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
-295: 
-296:      Initializes the internal stream state for decompression. The fields
-297:    next_in, avail_in, zalloc, zfree and opaque must be initialized before by
-298:    the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
-299:    value depends on the compression method), inflateInit determines the
-300:    compression method from the zlib header and allocates all data structures
-301:    accordingly; otherwise the allocation will be deferred to the first call of
-302:    inflate.  If zalloc and zfree are set to Z_NULL, inflateInit updates them to
-303:    use default allocation functions.
-304: 
-305:      inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
-306:    memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
-307:    version assumed by the caller.  msg is set to null if there is no error
-308:    message. inflateInit does not perform any decompression apart from reading
-309:    the zlib header if present: this will be done by inflate().  (So next_in and
-310:    avail_in may be modified, but next_out and avail_out are unchanged.)
-311: */
-312: 
-313: 
-314: ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
-315: /*
-316:     inflate decompresses as much data as possible, and stops when the input
-317:   buffer becomes empty or the output buffer becomes full. It may some
-318:   introduce some output latency (reading input without producing any output)
-319:   except when forced to flush.
-320: 
-321:   The detailed semantics are as follows. inflate performs one or both of the
-322:   following actions:
-323: 
-324:   - Decompress more input starting at next_in and update next_in and avail_in
-325:     accordingly. If not all input can be processed (because there is not
-326:     enough room in the output buffer), next_in is updated and processing
-327:     will resume at this point for the next call of inflate().
-328: 
-329:   - Provide more output starting at next_out and update next_out and avail_out
-330:     accordingly.  inflate() provides as much output as possible, until there
-331:     is no more input data or no more space in the output buffer (see below
-332:     about the flush parameter).
-333: 
-334:   Before the call of inflate(), the application should ensure that at least
-335:   one of the actions is possible, by providing more input and/or consuming
-336:   more output, and updating the next_* and avail_* values accordingly.
-337:   The application can consume the uncompressed output when it wants, for
-338:   example when the output buffer is full (avail_out == 0), or after each
-339:   call of inflate(). If inflate returns Z_OK and with zero avail_out, it
-340:   must be called again after making room in the output buffer because there
-341:   might be more output pending.
-342: 
-343:     If the parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much
-344:   output as possible to the output buffer. The flushing behavior of inflate is
-345:   not specified for values of the flush parameter other than Z_SYNC_FLUSH
-346:   and Z_FINISH, but the current implementation actually flushes as much output
-347:   as possible anyway.
-348: 
-349:     inflate() should normally be called until it returns Z_STREAM_END or an
-350:   error. However if all decompression is to be performed in a single step
-351:   (a single call of inflate), the parameter flush should be set to
-352:   Z_FINISH. In this case all pending input is processed and all pending
-353:   output is flushed; avail_out must be large enough to hold all the
-354:   uncompressed data. (The size of the uncompressed data may have been saved
-355:   by the compressor for this purpose.) The next operation on this stream must
-356:   be inflateEnd to deallocate the decompression state. The use of Z_FINISH
-357:   is never required, but can be used to inform inflate that a faster routine
-358:   may be used for the single inflate() call.
-359: 
-360:      If a preset dictionary is needed at this point (see inflateSetDictionary
-361:   below), inflate sets strm-adler to the adler32 checksum of the
-362:   dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise 
-363:   it sets strm->adler to the adler32 checksum of all output produced
-364:   so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or
-365:   an error code as described below. At the end of the stream, inflate()
-366:   checks that its computed adler32 checksum is equal to that saved by the
-367:   compressor and returns Z_STREAM_END only if the checksum is correct.
-368: 
-369:     inflate() returns Z_OK if some progress has been made (more input processed
-370:   or more output produced), Z_STREAM_END if the end of the compressed data has
-371:   been reached and all uncompressed output has been produced, Z_NEED_DICT if a
-372:   preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
-373:   corrupted (input stream not conforming to the zlib format or incorrect
-374:   adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent
-375:   (for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not
-376:   enough memory, Z_BUF_ERROR if no progress is possible or if there was not
-377:   enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR
-378:   case, the application may then call inflateSync to look for a good
-379:   compression block.
-380: */
-381: 
-382: 
-383: ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
-384: /*
-385:      All dynamically allocated data structures for this stream are freed.
-386:    This function discards any unprocessed input and does not flush any
-387:    pending output.
-388: 
-389:      inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
-390:    was inconsistent. In the error case, msg may be set but then points to a
-391:    static string (which must not be deallocated).
-392: */
-393: 
-394:                         /* Advanced functions */
-395: 
-396: /*
-397:     The following functions are needed only in some special applications.
-398: */
-399: 
-400: /*   
-401: ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
-402:                                      int  level,
-403:                                      int  method,
-404:                                      int  windowBits,
-405:                                      int  memLevel,
-406:                                      int  strategy));
-407: 
-408:      This is another version of deflateInit with more compression options. The
-409:    fields next_in, zalloc, zfree and opaque must be initialized before by
-410:    the caller.
-411: 
-412:      The method parameter is the compression method. It must be Z_DEFLATED in
-413:    this version of the library.
-414: 
-415:      The windowBits parameter is the base two logarithm of the window size
-416:    (the size of the history buffer).  It should be in the range 8..15 for this
-417:    version of the library. Larger values of this parameter result in better
-418:    compression at the expense of memory usage. The default value is 15 if
-419:    deflateInit is used instead.
-420: 
-421:      The memLevel parameter specifies how much memory should be allocated
-422:    for the internal compression state. memLevel=1 uses minimum memory but
-423:    is slow and reduces compression ratio; memLevel=9 uses maximum memory
-424:    for optimal speed. The default value is 8. See zconf.h for total memory
-425:    usage as a function of windowBits and memLevel.
-426: 
-427:      The strategy parameter is used to tune the compression algorithm. Use the
-428:    value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
-429:    filter (or predictor), or Z_HUFFMAN_ONLY to force Huffman encoding only (no
-430:    string match).  Filtered data consists mostly of small values with a
-431:    somewhat random distribution. In this case, the compression algorithm is
-432:    tuned to compress them better. The effect of Z_FILTERED is to force more
-433:    Huffman coding and less string matching; it is somewhat intermediate
-434:    between Z_DEFAULT and Z_HUFFMAN_ONLY. The strategy parameter only affects
-435:    the compression ratio but not the correctness of the compressed output even
-436:    if it is not set appropriately.
-437: 
-438:       deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
-439:    memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
-440:    method). msg is set to null if there is no error message.  deflateInit2 does
-441:    not perform any compression: this will be done by deflate().
-442: */
-443:                             
-444: ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
-445:                                              const Bytef *dictionary,
-446:                                              uInt  dictLength));
-447: /*
-448:      Initializes the compression dictionary from the given byte sequence
-449:    without producing any compressed output. This function must be called
-450:    immediately after deflateInit, deflateInit2 or deflateReset, before any
-451:    call of deflate. The compressor and decompressor must use exactly the same
-452:    dictionary (see inflateSetDictionary).
-453: 
-454:      The dictionary should consist of strings (byte sequences) that are likely
-455:    to be encountered later in the data to be compressed, with the most commonly
-456:    used strings preferably put towards the end of the dictionary. Using a
-457:    dictionary is most useful when the data to be compressed is short and can be
-458:    predicted with good accuracy; the data can then be compressed better than
-459:    with the default empty dictionary.
-460: 
-461:      Depending on the size of the compression data structures selected by
-462:    deflateInit or deflateInit2, a part of the dictionary may in effect be
-463:    discarded, for example if the dictionary is larger than the window size in
-464:    deflate or deflate2. Thus the strings most likely to be useful should be
-465:    put at the end of the dictionary, not at the front.
-466: 
-467:      Upon return of this function, strm->adler is set to the Adler32 value
-468:    of the dictionary; the decompressor may later use this value to determine
-469:    which dictionary has been used by the compressor. (The Adler32 value
-470:    applies to the whole dictionary even if only a subset of the dictionary is
-471:    actually used by the compressor.)
-472: 
-473:      deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
-474:    parameter is invalid (such as NULL dictionary) or the stream state is
-475:    inconsistent (for example if deflate has already been called for this stream
-476:    or if the compression method is bsort). deflateSetDictionary does not
-477:    perform any compression: this will be done by deflate().
-478: */
-479: 
-480: ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
-481:                                     z_streamp source));
-482: /*
-483:      Sets the destination stream as a complete copy of the source stream.
-484: 
-485:      This function can be useful when several compression strategies will be
-486:    tried, for example when there are several ways of pre-processing the input
-487:    data with a filter. The streams that will be discarded should then be freed
-488:    by calling deflateEnd.  Note that deflateCopy duplicates the internal
-489:    compression state which can be quite large, so this strategy is slow and
-490:    can consume lots of memory.
-491: 
-492:      deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
-493:    enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
-494:    (such as zalloc being NULL). msg is left unchanged in both source and
-495:    destination.
-496: */
-497: 
-498: ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
-499: /*
-500:      This function is equivalent to deflateEnd followed by deflateInit,
-501:    but does not free and reallocate all the internal compression state.
-502:    The stream will keep the same compression level and any other attributes
-503:    that may have been set by deflateInit2.
-504: 
-505:       deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
-506:    stream state was inconsistent (such as zalloc or state being NULL).
-507: */
-508: 
-509: ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
-510: 				      int level,
-511: 				      int strategy));
-512: /*
-513:      Dynamically update the compression level and compression strategy.  The
-514:    interpretation of level and strategy is as in deflateInit2.  This can be
-515:    used to switch between compression and straight copy of the input data, or
-516:    to switch to a different kind of input data requiring a different
-517:    strategy. If the compression level is changed, the input available so far
-518:    is compressed with the old level (and may be flushed); the new level will
-519:    take effect only at the next call of deflate().
-520: 
-521:      Before the call of deflateParams, the stream state must be set as for
-522:    a call of deflate(), since the currently available input may have to
-523:    be compressed and flushed. In particular, strm->avail_out must be non-zero.
-524: 
-525:      deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
-526:    stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
-527:    if strm->avail_out was zero.
-528: */
-529: 
-530: /*   
-531: ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
-532:                                      int  windowBits));
-533: 
-534:      This is another version of inflateInit with an extra parameter. The
-535:    fields next_in, avail_in, zalloc, zfree and opaque must be initialized
-536:    before by the caller.
-537: 
-538:      The windowBits parameter is the base two logarithm of the maximum window
-539:    size (the size of the history buffer).  It should be in the range 8..15 for
-540:    this version of the library. The default value is 15 if inflateInit is used
-541:    instead. If a compressed stream with a larger window size is given as
-542:    input, inflate() will return with the error code Z_DATA_ERROR instead of
-543:    trying to allocate a larger window.
-544: 
-545:       inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
-546:    memory, Z_STREAM_ERROR if a parameter is invalid (such as a negative
-547:    memLevel). msg is set to null if there is no error message.  inflateInit2
-548:    does not perform any decompression apart from reading the zlib header if
-549:    present: this will be done by inflate(). (So next_in and avail_in may be
-550:    modified, but next_out and avail_out are unchanged.)
-551: */
-552: 
-553: ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
-554:                                              const Bytef *dictionary,
-555:                                              uInt  dictLength));
-556: /*
-557:      Initializes the decompression dictionary from the given uncompressed byte
-558:    sequence. This function must be called immediately after a call of inflate
-559:    if this call returned Z_NEED_DICT. The dictionary chosen by the compressor
-560:    can be determined from the Adler32 value returned by this call of
-561:    inflate. The compressor and decompressor must use exactly the same
-562:    dictionary (see deflateSetDictionary).
-563: 
-564:      inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
-565:    parameter is invalid (such as NULL dictionary) or the stream state is
-566:    inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
-567:    expected one (incorrect Adler32 value). inflateSetDictionary does not
-568:    perform any decompression: this will be done by subsequent calls of
-569:    inflate().
-570: */
-571: 
-572: ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
-573: /* 
-574:     Skips invalid compressed data until a full flush point (see above the
-575:   description of deflate with Z_FULL_FLUSH) can be found, or until all
-576:   available input is skipped. No output is provided.
-577: 
-578:     inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
-579:   if no more input was provided, Z_DATA_ERROR if no flush point has been found,
-580:   or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
-581:   case, the application may save the current current value of total_in which
-582:   indicates where valid compressed data was found. In the error case, the
-583:   application may repeatedly call inflateSync, providing more input each time,
-584:   until success or end of the input data.
-585: */
-586: 
-587: ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
-588: /*
-589:      This function is equivalent to inflateEnd followed by inflateInit,
-590:    but does not free and reallocate all the internal decompression state.
-591:    The stream will keep attributes that may have been set by inflateInit2.
-592: 
-593:       inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
-594:    stream state was inconsistent (such as zalloc or state being NULL).
-595: */
-596: 
-597: 
-598:                         /* utility functions */
-599: 
-600: /*
-601:      The following utility functions are implemented on top of the
-602:    basic stream-oriented functions. To simplify the interface, some
-603:    default options are assumed (compression level and memory usage,
-604:    standard memory allocation functions). The source code of these
-605:    utility functions can easily be modified if you need special options.
-606: */
-607: 
-608: ZEXTERN int ZEXPORT compress OF((Bytef *dest,   uLongf *destLen,
-609:                                  const Bytef *source, uLong sourceLen));
-610: /*
-611:      Compresses the source buffer into the destination buffer.  sourceLen is
-612:    the byte length of the source buffer. Upon entry, destLen is the total
-613:    size of the destination buffer, which must be at least 0.1% larger than
-614:    sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the
-615:    compressed buffer.
-616:      This function can be used to compress a whole file at once if the
-617:    input file is mmap'ed.
-618:      compress returns Z_OK if success, Z_MEM_ERROR if there was not
-619:    enough memory, Z_BUF_ERROR if there was not enough room in the output
-620:    buffer.
-621: */
-622: 
-623: ZEXTERN int ZEXPORT compress2 OF((Bytef *dest,   uLongf *destLen,
-624:                                   const Bytef *source, uLong sourceLen,
-625:                                   int level));
-626: /*
-627:      Compresses the source buffer into the destination buffer. The level
-628:    parameter has the same meaning as in deflateInit.  sourceLen is the byte
-629:    length of the source buffer. Upon entry, destLen is the total size of the
-630:    destination buffer, which must be at least 0.1% larger than sourceLen plus
-631:    12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
-632: 
-633:      compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
-634:    memory, Z_BUF_ERROR if there was not enough room in the output buffer,
-635:    Z_STREAM_ERROR if the level parameter is invalid.
-636: */
-637: 
-638: ZEXTERN int ZEXPORT uncompress OF((Bytef *dest,   uLongf *destLen,
-639:                                    const Bytef *source, uLong sourceLen));
-640: /*
-641:      Decompresses the source buffer into the destination buffer.  sourceLen is
-642:    the byte length of the source buffer. Upon entry, destLen is the total
-643:    size of the destination buffer, which must be large enough to hold the
-644:    entire uncompressed data. (The size of the uncompressed data must have
-645:    been saved previously by the compressor and transmitted to the decompressor
-646:    by some mechanism outside the scope of this compression library.)
-647:    Upon exit, destLen is the actual size of the compressed buffer.
-648:      This function can be used to decompress a whole file at once if the
-649:    input file is mmap'ed.
-650: 
-651:      uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
-652:    enough memory, Z_BUF_ERROR if there was not enough room in the output
-653:    buffer, or Z_DATA_ERROR if the input data was corrupted.
-654: */
-655: 
-656: 
-657: typedef voidp gzFile;
-658: 
-659: ZEXTERN gzFile ZEXPORT gzopen  OF((const char *path, const char *mode));
-660: /*
-661:      Opens a gzip (.gz) file for reading or writing. The mode parameter
-662:    is as in fopen ("rb" or "wb") but can also include a compression level
-663:    ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
-664:    Huffman only compression as in "wb1h". (See the description
-665:    of deflateInit2 for more information about the strategy parameter.)
-666: 
-667:      gzopen can be used to read a file which is not in gzip format; in this
-668:    case gzread will directly read from the file without decompression.
-669: 
-670:      gzopen returns NULL if the file could not be opened or if there was
-671:    insufficient memory to allocate the (de)compression state; errno
-672:    can be checked to distinguish the two cases (if errno is zero, the
-673:    zlib error is Z_MEM_ERROR).  */
-674: 
-675: ZEXTERN gzFile ZEXPORT gzdopen  OF((int fd, const char *mode));
-676: /*
-677:      gzdopen() associates a gzFile with the file descriptor fd.  File
-678:    descriptors are obtained from calls like open, dup, creat, pipe or
-679:    fileno (in the file has been previously opened with fopen).
-680:    The mode parameter is as in gzopen.
-681:      The next call of gzclose on the returned gzFile will also close the
-682:    file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
-683:    descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
-684:      gzdopen returns NULL if there was insufficient memory to allocate
-685:    the (de)compression state.
-686: */
-687: 
-688: ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
-689: /*
-690:      Dynamically update the compression level or strategy. See the description
-691:    of deflateInit2 for the meaning of these parameters.
-692:      gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
-693:    opened for writing.
-694: */
-695: 
-696: ZEXTERN int ZEXPORT    gzread  OF((gzFile file, voidp buf, unsigned len));
-697: /*
-698:      Reads the given number of uncompressed bytes from the compressed file.
-699:    If the input file was not in gzip format, gzread copies the given number
-700:    of bytes into the buffer.
-701:      gzread returns the number of uncompressed bytes actually read (0 for
-702:    end of file, -1 for error). */
-703: 
-704: ZEXTERN int ZEXPORT    gzwrite OF((gzFile file, 
-705: 				   const voidp buf, unsigned len));
-706: /*
-707:      Writes the given number of uncompressed bytes into the compressed file.
-708:    gzwrite returns the number of uncompressed bytes actually written
-709:    (0 in case of error).
-710: */
-711: 
-712: ZEXTERN int ZEXPORTVA   gzprintf OF((gzFile file, const char *format, ...));
-713: /*
-714:      Converts, formats, and writes the args to the compressed file under
-715:    control of the format string, as in fprintf. gzprintf returns the number of
-716:    uncompressed bytes actually written (0 in case of error).
-717: */
-718: 
-719: ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
-720: /*
-721:       Writes the given null-terminated string to the compressed file, excluding
-722:    the terminating null character.
-723:       gzputs returns the number of characters written, or -1 in case of error.
-724: */
-725: 
-726: ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
-727: /*
-728:       Reads bytes from the compressed file until len-1 characters are read, or
-729:    a newline character is read and transferred to buf, or an end-of-file
-730:    condition is encountered.  The string is then terminated with a null
-731:    character.
-732:       gzgets returns buf, or Z_NULL in case of error.
-733: */
-734: 
-735: ZEXTERN int ZEXPORT    gzputc OF((gzFile file, int c));
-736: /*
-737:       Writes c, converted to an unsigned char, into the compressed file.
-738:    gzputc returns the value that was written, or -1 in case of error.
-739: */
-740: 
-741: ZEXTERN int ZEXPORT    gzgetc OF((gzFile file));
-742: /*
-743:       Reads one byte from the compressed file. gzgetc returns this byte
-744:    or -1 in case of end of file or error.
-745: */
-746: 
-747: ZEXTERN int ZEXPORT    gzflush OF((gzFile file, int flush));
-748: /*
-749:      Flushes all pending output into the compressed file. The parameter
-750:    flush is as in the deflate() function. The return value is the zlib
-751:    error number (see function gzerror below). gzflush returns Z_OK if
-752:    the flush parameter is Z_FINISH and all output could be flushed.
-753:      gzflush should be called only when strictly necessary because it can
-754:    degrade compression.
-755: */
-756: 
-757: ZEXTERN z_off_t ZEXPORT    gzseek OF((gzFile file,
-758: 				      z_off_t offset, int whence));
-759: /* 
-760:       Sets the starting position for the next gzread or gzwrite on the
-761:    given compressed file. The offset represents a number of bytes in the
-762:    uncompressed data stream. The whence parameter is defined as in lseek(2);
-763:    the value SEEK_END is not supported.
-764:      If the file is opened for reading, this function is emulated but can be
-765:    extremely slow. If the file is opened for writing, only forward seeks are
-766:    supported; gzseek then compresses a sequence of zeroes up to the new
-767:    starting position.
-768: 
-769:       gzseek returns the resulting offset location as measured in bytes from
-770:    the beginning of the uncompressed stream, or -1 in case of error, in
-771:    particular if the file is opened for writing and the new starting position
-772:    would be before the current position.
-773: */
-774: 
-775: ZEXTERN int ZEXPORT    gzrewind OF((gzFile file));
-776: /*
-777:      Rewinds the given file. This function is supported only for reading.
-778: 
-779:    gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
-780: */
-781: 
-782: ZEXTERN z_off_t ZEXPORT    gztell OF((gzFile file));
-783: /*
-784:      Returns the starting position for the next gzread or gzwrite on the
-785:    given compressed file. This position represents a number of bytes in the
-786:    uncompressed data stream.
-787: 
-788:    gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
-789: */
-790: 
-791: ZEXTERN int ZEXPORT gzeof OF((gzFile file));
-792: /*
-793:      Returns 1 when EOF has previously been detected reading the given
-794:    input stream, otherwise zero.
-795: */
-796: 
-797: ZEXTERN int ZEXPORT    gzclose OF((gzFile file));
-798: /*
-799:      Flushes all pending output if necessary, closes the compressed file
-800:    and deallocates all the (de)compression state. The return value is the zlib
-801:    error number (see function gzerror below).
-802: */
-803: 
-804: ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
-805: /*
-806:      Returns the error message for the last error which occurred on the
-807:    given compressed file. errnum is set to zlib error number. If an
-808:    error occurred in the file system and not in the compression library,
-809:    errnum is set to Z_ERRNO and the application may consult errno
-810:    to get the exact error code.
-811: */
-812: 
-813:                         /* checksum functions */
-814: 
-815: /*
-816:      These functions are not related to compression but are exported
-817:    anyway because they might be useful in applications using the
-818:    compression library.
-819: */
-820: 
-821: ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
-822: 
-823: /*
-824:      Update a running Adler-32 checksum with the bytes buf[0..len-1] and
-825:    return the updated checksum. If buf is NULL, this function returns
-826:    the required initial value for the checksum.
-827:    An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
-828:    much faster. Usage example:
-829: 
-830:      uLong adler = adler32(0L, Z_NULL, 0);
-831: 
-832:      while (read_buffer(buffer, length) != EOF) {
-833:        adler = adler32(adler, buffer, length);
-834:      }
-835:      if (adler != original_adler) error();
-836: */
-837: 
-838: ZEXTERN uLong ZEXPORT crc32   OF((uLong crc, const Bytef *buf, uInt len));
-839: /*
-840:      Update a running crc with the bytes buf[0..len-1] and return the updated
-841:    crc. If buf is NULL, this function returns the required initial value
-842:    for the crc. Pre- and post-conditioning (one's complement) is performed
-843:    within this function so it shouldn't be done by the application.
-844:    Usage example:
-845: 
-846:      uLong crc = crc32(0L, Z_NULL, 0);
-847: 
-848:      while (read_buffer(buffer, length) != EOF) {
-849:        crc = crc32(crc, buffer, length);
-850:      }
-851:      if (crc != original_crc) error();
-852: */
-853: 
-854: 
-855:                         /* various hacks, don't look :) */
-856: 
-857: /* deflateInit and inflateInit are macros to allow checking the zlib version
-858:  * and the compiler's view of z_stream:
-859:  */
-860: ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
-861:                                      const char *version, int stream_size));
-862: ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
-863:                                      const char *version, int stream_size));
-864: ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int  level, int  method,
-865:                                       int windowBits, int memLevel,
-866:                                       int strategy, const char *version,
-867:                                       int stream_size));
-868: ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int  windowBits,
-869:                                       const char *version, int stream_size));
-870: #define deflateInit(strm, level) \
-871:         deflateInit_((strm), (level),       ZLIB_VERSION, sizeof(z_stream))
-872: #define inflateInit(strm) \
-873:         inflateInit_((strm),                ZLIB_VERSION, sizeof(z_stream))
-874: #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
-875:         deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
-876:                       (strategy),           ZLIB_VERSION, sizeof(z_stream))
-877: #define inflateInit2(strm, windowBits) \
-878:         inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
-879: 
-880: 
-881: #if !defined(_Z_UTIL_H) && !defined(NO_DUMMY_DECL)
-882:     struct internal_state {int dummy;}; /* hack for buggy compilers */
-883: #endif
-884: 
-885: ZEXTERN const char   * ZEXPORT zError           OF((int err));
-886: ZEXTERN int            ZEXPORT inflateSyncPoint OF((z_streamp z));
-887: ZEXTERN const uLongf * ZEXPORT get_crc_table    OF((void));
-888: 
-889: #ifdef __cplusplus
-890: }
-891: #endif
-892: 
-893: #endif /* _ZLIB_H */
-      
-
- -

How the zlib wrapper was developed

- -

Attempt #1

-
-
-/* File : example.i */
-%module example
-%{
-/* Put headers and other declarations here */
-#include "zlib.h"
-%}
-
-%include typemaps.i
-
-%include "zlib.h"
-      
-
- - The result is: - -
-
-% swig -chicken -I/usr/include example.i
-/usr/include/zlib.h:63: Syntax error in input.
-/usr/include/zlib.h:78: Syntax error in input.
-/usr/include/zlib.h:80: Syntax error in input.
-      
-
- - The first problem we see is that the macro OF(...) is - not defined. - -

Attempt #2

- - We make sure to include zconf.h so that SWIG can see the - definition of OF(...). We try again. - -
-
-/* File : example.i */
-%module example
-%{
-/* Put headers and other declarations here */
-#include "zlib.h"
-%}
-
-%include typemaps.i
-
-%include "zconf.h"
-%include "zlib.h"
-      
-
- - The result is: - -
-
-% swig -chicken -I/usr/include example.i
-      
-
- - This seems to work! But we should take a peek inside the generated - example_wrap.c to see what the names of the Scheme - procedures will be. - -
-
-% grep C_intern example_wrap.c
-  C_word err = C_intern2 (&a, errorhook);
-    sym = C_intern (&a, 21, "example:max-mem-level");
-    sym = C_intern (&a, 17, "example:max-wbits");
-    sym = C_intern (&a, 16, "example:seek-set");
-    sym = C_intern (&a, 16, "example:seek-cur");
-    sym = C_intern (&a, 16, "example:seek-end");
-    sym = C_intern (&a, 20, "example:zlib-version");
-    sym = C_intern (&a, 28, "example:z-stream-next-in-set");
-    sym = C_intern (&a, 28, "example:z-stream-next-in-get");
-    sym = C_intern (&a, 29, "example:z-stream-avail-in-set");
-    sym = C_intern (&a, 29, "example:z-stream-avail-in-get");
-    sym = C_intern (&a, 29, "example:z-stream-total-in-set");
-    sym = C_intern (&a, 29, "example:z-stream-total-in-get");
-    sym = C_intern (&a, 29, "example:z-stream-next-out-set");
-    sym = C_intern (&a, 29, "example:z-stream-next-out-get");
-    sym = C_intern (&a, 30, "example:z-stream-avail-out-set");
-    sym = C_intern (&a, 30, "example:z-stream-avail-out-get");
-    sym = C_intern (&a, 30, "example:z-stream-total-out-set");
-    sym = C_intern (&a, 30, "example:z-stream-total-out-get");
-    sym = C_intern (&a, 24, "example:z-stream-msg-set");
-    sym = C_intern (&a, 24, "example:z-stream-msg-get");
-    sym = C_intern (&a, 26, "example:z-stream-state-set");
-    sym = C_intern (&a, 26, "example:z-stream-state-get");
-    sym = C_intern (&a, 27, "example:z-stream-zalloc-set");
-    sym = C_intern (&a, 27, "example:z-stream-zalloc-get");
-    sym = C_intern (&a, 26, "example:z-stream-zfree-set");
-    sym = C_intern (&a, 26, "example:z-stream-zfree-get");
-    sym = C_intern (&a, 27, "example:z-stream-opaque-set");
-    sym = C_intern (&a, 27, "example:z-stream-opaque-get");
-    sym = C_intern (&a, 30, "example:z-stream-data-type-set");
-    sym = C_intern (&a, 30, "example:z-stream-data-type-get");
-    sym = C_intern (&a, 26, "example:z-stream-adler-set");
-    sym = C_intern (&a, 26, "example:z-stream-adler-get");
-    sym = C_intern (&a, 29, "example:z-stream-reserved-set");
-    sym = C_intern (&a, 29, "example:z-stream-reserved-get");
-    sym = C_intern (&a, 20, "example:new-z-stream");
-    sym = C_intern (&a, 23, "example:delete-z-stream");
-    sym = C_intern (&a, 18, "example:z-no-flush");
-    sym = C_intern (&a, 23, "example:z-partial-flush");
-    sym = C_intern (&a, 20, "example:z-sync-flush");
-    sym = C_intern (&a, 20, "example:z-full-flush");
-    sym = C_intern (&a, 16, "example:z-finish");
-    sym = C_intern (&a, 12, "example:z-ok");
-    sym = C_intern (&a, 20, "example:z-stream-end");
-    sym = C_intern (&a, 19, "example:z-need-dict");
-    sym = C_intern (&a, 15, "example:z-errno");
-    sym = C_intern (&a, 22, "example:z-stream-error");
-    sym = C_intern (&a, 20, "example:z-data-error");
-    sym = C_intern (&a, 19, "example:z-mem-error");
-    sym = C_intern (&a, 19, "example:z-buf-error");
-    sym = C_intern (&a, 23, "example:z-version-error");
-    sym = C_intern (&a, 24, "example:z-no-compression");
-    sym = C_intern (&a, 20, "example:z-best-speed");
-    sym = C_intern (&a, 26, "example:z-best-compression");
-    sym = C_intern (&a, 29, "example:z-default-compression");
-    sym = C_intern (&a, 18, "example:z-filtered");
-    sym = C_intern (&a, 22, "example:z-huffman-only");
-    sym = C_intern (&a, 26, "example:z-default-strategy");
-    sym = C_intern (&a, 16, "example:z-binary");
-    sym = C_intern (&a, 15, "example:z-ascii");
-    sym = C_intern (&a, 17, "example:z-unknown");
-    sym = C_intern (&a, 18, "example:z-deflated");
-    sym = C_intern (&a, 14, "example:z-null");
-    sym = C_intern (&a, 19, "example:zlibversion");
-    sym = C_intern (&a, 15, "example:deflate");
-    sym = C_intern (&a, 18, "example:deflateend");
-    sym = C_intern (&a, 15, "example:inflate");
-    sym = C_intern (&a, 18, "example:inflateend");
-    sym = C_intern (&a, 28, "example:deflatesetdictionary");
-    sym = C_intern (&a, 19, "example:deflatecopy");
-    sym = C_intern (&a, 20, "example:deflatereset");
-    sym = C_intern (&a, 21, "example:deflateparams");
-    sym = C_intern (&a, 28, "example:inflatesetdictionary");
-    sym = C_intern (&a, 19, "example:inflatesync");
-    sym = C_intern (&a, 20, "example:inflatereset");
-    sym = C_intern (&a, 16, "example:compress");
-    sym = C_intern (&a, 17, "example:compress2");
-    sym = C_intern (&a, 18, "example:uncompress");
-    sym = C_intern (&a, 14, "example:gzopen");
-    sym = C_intern (&a, 15, "example:gzdopen");
-    sym = C_intern (&a, 19, "example:gzsetparams");
-    sym = C_intern (&a, 14, "example:gzread");
-    sym = C_intern (&a, 15, "example:gzwrite");
-    sym = C_intern (&a, 16, "example:gzprintf");
-    sym = C_intern (&a, 14, "example:gzputs");
-    sym = C_intern (&a, 14, "example:gzgets");
-    sym = C_intern (&a, 14, "example:gzputc");
-    sym = C_intern (&a, 14, "example:gzgetc");
-    sym = C_intern (&a, 15, "example:gzflush");
-    sym = C_intern (&a, 14, "example:gzseek");
-    sym = C_intern (&a, 16, "example:gzrewind");
-    sym = C_intern (&a, 14, "example:gztell");
-    sym = C_intern (&a, 13, "example:gzeof");
-    sym = C_intern (&a, 15, "example:gzclose");
-    sym = C_intern (&a, 15, "example:gzerror");
-    sym = C_intern (&a, 15, "example:adler32");
-    sym = C_intern (&a, 13, "example:crc32");
-    sym = C_intern (&a, 20, "example:deflateinit-");
-    sym = C_intern (&a, 20, "example:inflateinit-");
-    sym = C_intern (&a, 21, "example:deflateinit2-");
-    sym = C_intern (&a, 21, "example:inflateinit2-");
-    sym = C_intern (&a, 32, "example:internal-state-dummy-set");
-    sym = C_intern (&a, 32, "example:internal-state-dummy-get");
-    sym = C_intern (&a, 26, "example:new-internal-state");
-    sym = C_intern (&a, 29, "example:delete-internal-state");
-    sym = C_intern (&a, 14, "example:zerror");
-    sym = C_intern (&a, 24, "example:inflatesyncpoint");
-    sym = C_intern (&a, 21, "example:get-crc-table");
-      
-
- - In fact, we want the Scheme procedure names to begin with - zlib instead of example. For - example:zlib-version, we want - zlib-version. And we want dashes when the case - switches to/from upper/lowercase; ex. the function - deflateEnd() should be the Scheme procedure - zlib-deflate-end. - -

Attempt #3

- - We make sure to add -prefix zlib -mixed to the - swig command line, and we rename - ZLIB_VERSION to VERSION. We try again. - -
-
-/* File : example.i */
-%module example
-%{
-/* Put headers and other declarations here */
-#include "zlib.h"
-%}
-
-%include typemaps.i
-
-%rename(VERSION) ZLIB_VERSION;
-
-%include "zconf.h"
-%include "zlib.h"
-      
-
- - The result is: - -
-
-% swig -chicken -prefix zlib -mixed -I/usr/include example.i
-% grep C_intern example_wrap.c
-  C_word err = C_intern2 (&a, errorhook);
-    sym = C_intern (&a, 18, "zlib:max-mem-level");
-    sym = C_intern (&a, 14, "zlib:max-wbits");
-    sym = C_intern (&a, 13, "zlib:seek-set");
-    sym = C_intern (&a, 13, "zlib:seek-cur");
-    sym = C_intern (&a, 13, "zlib:seek-end");
-    sym = C_intern (&a, 12, "zlib:version");
-    sym = C_intern (&a, 25, "zlib:z-stream-next-in-set");
-    sym = C_intern (&a, 25, "zlib:z-stream-next-in-get");
-    sym = C_intern (&a, 26, "zlib:z-stream-avail-in-set");
-    sym = C_intern (&a, 26, "zlib:z-stream-avail-in-get");
-    sym = C_intern (&a, 26, "zlib:z-stream-total-in-set");
-    sym = C_intern (&a, 26, "zlib:z-stream-total-in-get");
-    sym = C_intern (&a, 26, "zlib:z-stream-next-out-set");
-    sym = C_intern (&a, 26, "zlib:z-stream-next-out-get");
-    sym = C_intern (&a, 27, "zlib:z-stream-avail-out-set");
-    sym = C_intern (&a, 27, "zlib:z-stream-avail-out-get");
-    sym = C_intern (&a, 27, "zlib:z-stream-total-out-set");
-    sym = C_intern (&a, 27, "zlib:z-stream-total-out-get");
-    sym = C_intern (&a, 21, "zlib:z-stream-msg-set");
-    sym = C_intern (&a, 21, "zlib:z-stream-msg-get");
-    sym = C_intern (&a, 23, "zlib:z-stream-state-set");
-    sym = C_intern (&a, 23, "zlib:z-stream-state-get");
-    sym = C_intern (&a, 24, "zlib:z-stream-zalloc-set");
-    sym = C_intern (&a, 24, "zlib:z-stream-zalloc-get");
-    sym = C_intern (&a, 23, "zlib:z-stream-zfree-set");
-    sym = C_intern (&a, 23, "zlib:z-stream-zfree-get");
-    sym = C_intern (&a, 24, "zlib:z-stream-opaque-set");
-    sym = C_intern (&a, 24, "zlib:z-stream-opaque-get");
-    sym = C_intern (&a, 27, "zlib:z-stream-data-type-set");
-    sym = C_intern (&a, 27, "zlib:z-stream-data-type-get");
-    sym = C_intern (&a, 23, "zlib:z-stream-adler-set");
-    sym = C_intern (&a, 23, "zlib:z-stream-adler-get");
-    sym = C_intern (&a, 26, "zlib:z-stream-reserved-set");
-    sym = C_intern (&a, 26, "zlib:z-stream-reserved-get");
-    sym = C_intern (&a, 17, "zlib:new-z-stream");
-    sym = C_intern (&a, 20, "zlib:delete-z-stream");
-    sym = C_intern (&a, 15, "zlib:z-no-flush");
-    sym = C_intern (&a, 20, "zlib:z-partial-flush");
-    sym = C_intern (&a, 17, "zlib:z-sync-flush");
-    sym = C_intern (&a, 17, "zlib:z-full-flush");
-    sym = C_intern (&a, 13, "zlib:z-finish");
-    sym = C_intern (&a, 9, "zlib:z-ok");
-    sym = C_intern (&a, 17, "zlib:z-stream-end");
-    sym = C_intern (&a, 16, "zlib:z-need-dict");
-    sym = C_intern (&a, 12, "zlib:z-errno");
-    sym = C_intern (&a, 19, "zlib:z-stream-error");
-    sym = C_intern (&a, 17, "zlib:z-data-error");
-    sym = C_intern (&a, 16, "zlib:z-mem-error");
-    sym = C_intern (&a, 16, "zlib:z-buf-error");
-    sym = C_intern (&a, 20, "zlib:z-version-error");
-    sym = C_intern (&a, 21, "zlib:z-no-compression");
-    sym = C_intern (&a, 17, "zlib:z-best-speed");
-    sym = C_intern (&a, 23, "zlib:z-best-compression");
-    sym = C_intern (&a, 26, "zlib:z-default-compression");
-    sym = C_intern (&a, 15, "zlib:z-filtered");
-    sym = C_intern (&a, 19, "zlib:z-huffman-only");
-    sym = C_intern (&a, 23, "zlib:z-default-strategy");
-    sym = C_intern (&a, 13, "zlib:z-binary");
-    sym = C_intern (&a, 12, "zlib:z-ascii");
-    sym = C_intern (&a, 14, "zlib:z-unknown");
-    sym = C_intern (&a, 15, "zlib:z-deflated");
-    sym = C_intern (&a, 11, "zlib:z-null");
-    sym = C_intern (&a, 17, "zlib:zlib-version");
-    sym = C_intern (&a, 12, "zlib:deflate");
-    sym = C_intern (&a, 16, "zlib:deflate-end");
-    sym = C_intern (&a, 12, "zlib:inflate");
-    sym = C_intern (&a, 16, "zlib:inflate-end");
-    sym = C_intern (&a, 27, "zlib:deflate-set-dictionary");
-    sym = C_intern (&a, 17, "zlib:deflate-copy");
-    sym = C_intern (&a, 18, "zlib:deflate-reset");
-    sym = C_intern (&a, 19, "zlib:deflate-params");
-    sym = C_intern (&a, 27, "zlib:inflate-set-dictionary");
-    sym = C_intern (&a, 17, "zlib:inflate-sync");
-    sym = C_intern (&a, 18, "zlib:inflate-reset");
-    sym = C_intern (&a, 13, "zlib:compress");
-    sym = C_intern (&a, 14, "zlib:compress2");
-    sym = C_intern (&a, 15, "zlib:uncompress");
-    sym = C_intern (&a, 11, "zlib:gzopen");
-    sym = C_intern (&a, 12, "zlib:gzdopen");
-    sym = C_intern (&a, 16, "zlib:gzsetparams");
-    sym = C_intern (&a, 11, "zlib:gzread");
-    sym = C_intern (&a, 12, "zlib:gzwrite");
-    sym = C_intern (&a, 13, "zlib:gzprintf");
-    sym = C_intern (&a, 11, "zlib:gzputs");
-    sym = C_intern (&a, 11, "zlib:gzgets");
-    sym = C_intern (&a, 11, "zlib:gzputc");
-    sym = C_intern (&a, 11, "zlib:gzgetc");
-    sym = C_intern (&a, 12, "zlib:gzflush");
-    sym = C_intern (&a, 11, "zlib:gzseek");
-    sym = C_intern (&a, 13, "zlib:gzrewind");
-    sym = C_intern (&a, 11, "zlib:gztell");
-    sym = C_intern (&a, 10, "zlib:gzeof");
-    sym = C_intern (&a, 12, "zlib:gzclose");
-    sym = C_intern (&a, 12, "zlib:gzerror");
-    sym = C_intern (&a, 12, "zlib:adler32");
-    sym = C_intern (&a, 10, "zlib:crc32");
-    sym = C_intern (&a, 18, "zlib:deflate-init-");
-    sym = C_intern (&a, 18, "zlib:inflate-init-");
-    sym = C_intern (&a, 19, "zlib:deflate-init2-");
-    sym = C_intern (&a, 19, "zlib:inflate-init2-");
-    sym = C_intern (&a, 29, "zlib:internal-state-dummy-set");
-    sym = C_intern (&a, 29, "zlib:internal-state-dummy-get");
-    sym = C_intern (&a, 23, "zlib:new-internal-state");
-    sym = C_intern (&a, 26, "zlib:delete-internal-state");
-    sym = C_intern (&a, 12, "zlib:ze-rror");
-    sym = C_intern (&a, 23, "zlib:inflate-sync-point");
-    sym = C_intern (&a, 18, "zlib:get-crc-table");
-      
-
- - Much better. The only problem is the identifier - zlib:ze-rror, and we are missing - zlib:deflate-init and zlib:inflate-init - because they are defined as macros (see macro definitions). - -

Attempt #4

- - We make sure to rename zError to - z_error, and we inline some helper functions for the - zlib:...-init macros. We try again. - -
-
-/* File : example.i */
-%module example
-%{
-/* Put headers and other declarations here */
-#include "zlib.h"
-%}
-
-%include typemaps.i
-
-%rename(VERSION) ZLIB_VERSION;
-%rename(z_error) zError;
-
-%include "zconf.h"
-%include "zlib.h"
-
-%inline %{
-/* %inline blocks are seen by SWIG and are inserted into the header
-   portion of example_wrap.c, so that they are also seen by the C
-   compiler. */
-int deflate_init(z_streamp strm, int level) {
-  return deflateInit(strm,level); /* call macro */
-}
-int inflate_init(z_streamp strm) {
-  return inflateInit(strm); /* call macro */
-}
-%}
-
-
-      
-
- - The result is: - -
-
-% swig -chicken -prefix zlib -mixed -I/usr/include example.i
-% grep C_intern example_wrap.c
-  C_word err = C_intern2 (&a, errorhook);
-    sym = C_intern (&a, 18, "zlib:max-mem-level");
-    sym = C_intern (&a, 14, "zlib:max-wbits");
-    sym = C_intern (&a, 13, "zlib:seek-set");
-    sym = C_intern (&a, 13, "zlib:seek-cur");
-    sym = C_intern (&a, 13, "zlib:seek-end");
-    sym = C_intern (&a, 12, "zlib:version");
-    sym = C_intern (&a, 25, "zlib:z-stream-next-in-set");
-    sym = C_intern (&a, 25, "zlib:z-stream-next-in-get");
-    sym = C_intern (&a, 26, "zlib:z-stream-avail-in-set");
-    sym = C_intern (&a, 26, "zlib:z-stream-avail-in-get");
-    sym = C_intern (&a, 26, "zlib:z-stream-total-in-set");
-    sym = C_intern (&a, 26, "zlib:z-stream-total-in-get");
-    sym = C_intern (&a, 26, "zlib:z-stream-next-out-set");
-    sym = C_intern (&a, 26, "zlib:z-stream-next-out-get");
-    sym = C_intern (&a, 27, "zlib:z-stream-avail-out-set");
-    sym = C_intern (&a, 27, "zlib:z-stream-avail-out-get");
-    sym = C_intern (&a, 27, "zlib:z-stream-total-out-set");
-    sym = C_intern (&a, 27, "zlib:z-stream-total-out-get");
-    sym = C_intern (&a, 21, "zlib:z-stream-msg-set");
-    sym = C_intern (&a, 21, "zlib:z-stream-msg-get");
-    sym = C_intern (&a, 23, "zlib:z-stream-state-set");
-    sym = C_intern (&a, 23, "zlib:z-stream-state-get");
-    sym = C_intern (&a, 24, "zlib:z-stream-zalloc-set");
-    sym = C_intern (&a, 24, "zlib:z-stream-zalloc-get");
-    sym = C_intern (&a, 23, "zlib:z-stream-zfree-set");
-    sym = C_intern (&a, 23, "zlib:z-stream-zfree-get");
-    sym = C_intern (&a, 24, "zlib:z-stream-opaque-set");
-    sym = C_intern (&a, 24, "zlib:z-stream-opaque-get");
-    sym = C_intern (&a, 27, "zlib:z-stream-data-type-set");
-    sym = C_intern (&a, 27, "zlib:z-stream-data-type-get");
-    sym = C_intern (&a, 23, "zlib:z-stream-adler-set");
-    sym = C_intern (&a, 23, "zlib:z-stream-adler-get");
-    sym = C_intern (&a, 26, "zlib:z-stream-reserved-set");
-    sym = C_intern (&a, 26, "zlib:z-stream-reserved-get");
-    sym = C_intern (&a, 17, "zlib:new-z-stream");
-    sym = C_intern (&a, 20, "zlib:delete-z-stream");
-    sym = C_intern (&a, 15, "zlib:z-no-flush");
-    sym = C_intern (&a, 20, "zlib:z-partial-flush");
-    sym = C_intern (&a, 17, "zlib:z-sync-flush");
-    sym = C_intern (&a, 17, "zlib:z-full-flush");
-    sym = C_intern (&a, 13, "zlib:z-finish");
-    sym = C_intern (&a, 9, "zlib:z-ok");
-    sym = C_intern (&a, 17, "zlib:z-stream-end");
-    sym = C_intern (&a, 16, "zlib:z-need-dict");
-    sym = C_intern (&a, 12, "zlib:z-errno");
-    sym = C_intern (&a, 19, "zlib:z-stream-error");
-    sym = C_intern (&a, 17, "zlib:z-data-error");
-    sym = C_intern (&a, 16, "zlib:z-mem-error");
-    sym = C_intern (&a, 16, "zlib:z-buf-error");
-    sym = C_intern (&a, 20, "zlib:z-version-error");
-    sym = C_intern (&a, 21, "zlib:z-no-compression");
-    sym = C_intern (&a, 17, "zlib:z-best-speed");
-    sym = C_intern (&a, 23, "zlib:z-best-compression");
-    sym = C_intern (&a, 26, "zlib:z-default-compression");
-    sym = C_intern (&a, 15, "zlib:z-filtered");
-    sym = C_intern (&a, 19, "zlib:z-huffman-only");
-    sym = C_intern (&a, 23, "zlib:z-default-strategy");
-    sym = C_intern (&a, 13, "zlib:z-binary");
-    sym = C_intern (&a, 12, "zlib:z-ascii");
-    sym = C_intern (&a, 14, "zlib:z-unknown");
-    sym = C_intern (&a, 15, "zlib:z-deflated");
-    sym = C_intern (&a, 11, "zlib:z-null");
-    sym = C_intern (&a, 17, "zlib:zlib-version");
-    sym = C_intern (&a, 12, "zlib:deflate");
-    sym = C_intern (&a, 16, "zlib:deflate-end");
-    sym = C_intern (&a, 12, "zlib:inflate");
-    sym = C_intern (&a, 16, "zlib:inflate-end");
-    sym = C_intern (&a, 27, "zlib:deflate-set-dictionary");
-    sym = C_intern (&a, 17, "zlib:deflate-copy");
-    sym = C_intern (&a, 18, "zlib:deflate-reset");
-    sym = C_intern (&a, 19, "zlib:deflate-params");
-    sym = C_intern (&a, 27, "zlib:inflate-set-dictionary");
-    sym = C_intern (&a, 17, "zlib:inflate-sync");
-    sym = C_intern (&a, 18, "zlib:inflate-reset");
-    sym = C_intern (&a, 13, "zlib:compress");
-    sym = C_intern (&a, 14, "zlib:compress2");
-    sym = C_intern (&a, 15, "zlib:uncompress");
-    sym = C_intern (&a, 11, "zlib:gzopen");
-    sym = C_intern (&a, 12, "zlib:gzdopen");
-    sym = C_intern (&a, 16, "zlib:gzsetparams");
-    sym = C_intern (&a, 11, "zlib:gzread");
-    sym = C_intern (&a, 12, "zlib:gzwrite");
-    sym = C_intern (&a, 13, "zlib:gzprintf");
-    sym = C_intern (&a, 11, "zlib:gzputs");
-    sym = C_intern (&a, 11, "zlib:gzgets");
-    sym = C_intern (&a, 11, "zlib:gzputc");
-    sym = C_intern (&a, 11, "zlib:gzgetc");
-    sym = C_intern (&a, 12, "zlib:gzflush");
-    sym = C_intern (&a, 11, "zlib:gzseek");
-    sym = C_intern (&a, 13, "zlib:gzrewind");
-    sym = C_intern (&a, 11, "zlib:gztell");
-    sym = C_intern (&a, 10, "zlib:gzeof");
-    sym = C_intern (&a, 12, "zlib:gzclose");
-    sym = C_intern (&a, 12, "zlib:gzerror");
-    sym = C_intern (&a, 12, "zlib:adler32");
-    sym = C_intern (&a, 10, "zlib:crc32");
-    sym = C_intern (&a, 18, "zlib:deflate-init-");
-    sym = C_intern (&a, 18, "zlib:inflate-init-");
-    sym = C_intern (&a, 19, "zlib:deflate-init2-");
-    sym = C_intern (&a, 19, "zlib:inflate-init2-");
-    sym = C_intern (&a, 29, "zlib:internal-state-dummy-set");
-    sym = C_intern (&a, 29, "zlib:internal-state-dummy-get");
-    sym = C_intern (&a, 23, "zlib:new-internal-state");
-    sym = C_intern (&a, 26, "zlib:delete-internal-state");
-    sym = C_intern (&a, 12, "zlib:z-error");
-    sym = C_intern (&a, 23, "zlib:inflate-sync-point");
-    sym = C_intern (&a, 18, "zlib:get-crc-table");
-    sym = C_intern (&a, 17, "zlib:deflate-init");
-    sym = C_intern (&a, 17, "zlib:inflate-init");
-      
-
- - Perfect! Now let's integrate this zlib extension into a - CHICKEN interpreter. To save some time, in this - Examples/chicken/zlib directory: -
    -
  1. Backup the original example.i.
  2. -
  3. Copy and paste the example.i text from above and - put it into the file called example.i
  4. -
  5. Run 'make' as per Building the - example.
  6. -
  7. Run the resultant executable zlib.
  8. -
- - The interpreter interaction is as follows: - -
-
-% ./zlib
-zlib
-
-  A SWIG example for the CHICKEN compiler
-  Author: Jonah Beckford, February 2003
-
-Scheme Procedures:
-
-zlib:max-mem-level
-zlib:max-wbits
-zlib:seek-set
-zlib:seek-cur
-zlib:seek-end
-zlib:version
-zlib:z-stream-next-in-set
-zlib:z-stream-next-in-get
-zlib:z-stream-avail-in-set
-...
-zlib:get-crc-table
-zlib:deflate-init
-zlib:inflate-init
-; This is the CHICKEN interpreter - Version 0, Build 1095 - windows-cygwin-x86
-; (c)2000-2003 Felix L. Winkelmann
->>> (define s (zlib:new-z-stream))
->>> s
-#<tagged pointer #<c++ "z_stream *">(#<pointer 6d9290>)>
->>> (zlib:z-stream-next-in-get s)
-#f
->>> (zlib:z-stream-next-in-set s "some dummy stream data")
-Error: Type error. Expected _p_Bytef: "bad argument type"
->>> (exit)
-      
-
- - Apparently we cannot use Scheme strings as Bytef *. The SWIG - manual shows many ways how to handle strings and byte arrays, but - to be simplistic, let's just make the Bytef * look - like a char *, which is automatically handled as a - string by SWIG CHICKEN. - -

Attempt #5

- - We make sure to add an %apply construct so that Bytef - * is handled the same as char * to SWIG. We - try again. - -
-
-/* File : example.i */
-%module example
-%{
-/* Put headers and other declarations here */
-#include "zlib.h"
-%}
-
-%include typemaps.i
-
-%rename(VERSION) ZLIB_VERSION;
-%rename(z_error) zError;
-%apply char * { Bytef * };
-
-%include "zconf.h"
-%include "zlib.h"
-
-%inline %{
-/* %inline blocks are seen by SWIG and are inserted into the header
-   portion of example_wrap.c, so that they are also seen by the C
-   compiler. */
-int deflate_init(z_streamp strm, int level) {
-  return deflateInit(strm,level); /* call macro */
-}
-int inflate_init(z_streamp strm) {
-  return inflateInit(strm); /* call macro */
-}
-%}
-      
-
- - Build the example once more.
- - The interpreter interaction is as follows: - -
-
-% ./zlib
-zlib
-
-  A SWIG example for the CHICKEN compiler
-  Author: Jonah Beckford, February 2003
-
-Scheme Procedures:
-
-zlib:max-mem-level
-zlib:max-wbits
-zlib:seek-set
-zlib:seek-cur
-zlib:seek-end
-zlib:version
-zlib:z-stream-next-in-set
-zlib:z-stream-next-in-get
-zlib:z-stream-avail-in-set
-...
-zlib:get-crc-table
-zlib:deflate-init
-zlib:inflate-init
-; This is the CHICKEN interpreter - Version 0, Build 1095 - windows-cygwin-x86
-; (c)2000-2003 Felix L. Winkelmann
->>> (define s (zlib:new-z-stream))
-Init zstream
->>> (zlib:z-stream-zalloc-set s #f) 
->>> (zlib:z-stream-zfree-set s #f)
->>> (zlib:z-stream-opaque-set s #f)
->>> (zlib:deflate-init s (zlib:z-default-compression))
-0
-Deflate something small so we don't need to loop/stream data
->>> (define in "some dummy data")
->>> (define out (make-string 1000))
->>> (zlib:z-stream-next-in-set s in)
->>> (zlib:z-stream-avail-in-set s (string-length in))
->>> (zlib:z-stream-next-out-set s out)
->>> (zlib:z-stream-avail-out-set s (string-length out))
->>> (zlib:deflate s (zlib:z-finish))
-1 ;; (zlib:z-stream-end) == 1, which is good
->>> (zlib:z-stream-total-out-get s)
-23.
->>> out
-"                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        "
-      
-
- - We see the problem ... the compression is occurring as it should, - but we cannot see any of the compressed output. This is because - when SWIG CHICKEN passes a Scheme string to a C function, it - duplicates the string before calling the C function. We want to - save the memory address that - zlib:z-stream-next-out-set is using, so we can - display this later. While we are at it, we can foresee that - compress, compress2 and - uncompress will all need some finessing to work with - mutating strings. - -

Attempt #6

- - When we have to finesse strings, we must use typemaps. As well, - we define some functions to save and restore the - next_out element. We try again. - -
-
-/* File : example.i */
-%module example
-%{
-/* Put headers and other declarations here */
-#include "zlib.h"
-%}
-
-%include typemaps.i
-
-%rename(VERSION) ZLIB_VERSION;
-%rename(z_error) zError;
-%apply char * { Bytef * };
-	
-/* Allow the sourceLen to be automatically filled in from the length
-   of the 'source' string */
-%typemap(in) (const Bytef *source, uLong sourceLen)
-%{  if (!C_swig_is_string ($input)) {
-    swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument $input is not a string");
-  }
-  $2 = (uLong) C_header_size ($input);
-  $1 = C_c_string ($input);
-%}
-
-/* Allocate space the size of which is determined by the Scheme
-   integer argument, and make a temporary integer so we can set
-   destLen. */
-%typemap(in) (Bytef *dest, uLongf *destLen) (uLong len)
-%{  if (!C_swig_is_fixnum ($input)) {
-    swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument $input is not a integer");
-  }
-  len = (uLong) C_unfix ($input);
-  $2 = &len;
-  $1 = (char *) malloc (*$2);
-%}
-
-/* Return the mutated string as a new object. */
-%typemap(argout) (Bytef *dest, uLongf *destLen) 
-(C_word *scmstr) 
-%{  scmstr = C_alloc (C_SIZEOF_STRING (*$2));
-  SWIG_APPEND_VALUE(C_string (&scmstr, *$2, $1));
-  free ($1);
-%}
-	
-%include "zconf.h"
-%include "zlib.h"
-	
-/* Ignore destLen as an input argument, and make a temporary integer so
-   we can set destLen. */
-%typemap(in, numinputs=0) uLongf *destLen (uLong len)
-"$1 = &len;";
-
-/* Return a sized string as a new object. */
-%typemap(argout)
-(void *outstr, uLongf *destLen) (C_word *scmstr) 
-%{  scmstr = C_alloc (C_SIZEOF_STRING (*$2));
-  SWIG_APPEND_VALUE(C_string (&scmstr, *$2, $1));
-%}
-	
-%inline %{
-/* %inline blocks are seen by SWIG and are inserted into the header
-   portion of example_wrap.c, so that they are also seen by the C
-   compiler. */
-int deflate_init(z_streamp strm, int level) {
-  return deflateInit(strm,level); /* call macro */
-}
-int inflate_init(z_streamp strm) {
-  return inflateInit(strm); /* call macro */
-}
-void* z_stream_save_next_out(z_streamp strm) {
-  return (void*) strm->next_out;
-}
-void z_stream_get_next_chunk(z_streamp strm, void *outstr, uLongf *destLen) {
-  *destLen = strm->next_out - (Bytef*)outstr;
-}
-%}
-      
-
- - And that's it. Try building the entire example from the - Makefile. Run ./zlib test-zlib.scm to test it out. - - - diff --git a/Examples/chicken/zlib/example.i b/Examples/chicken/zlib/example.i deleted file mode 100644 index dd962ad56..000000000 --- a/Examples/chicken/zlib/example.i +++ /dev/null @@ -1,76 +0,0 @@ -/* File : example.i */ -%module example -%{ -/* Put headers and other declarations here */ -#include "zlib.h" -%} - -%include typemaps.i - -%rename(VERSION) ZLIB_VERSION; -%rename(z_error) zError; -%apply char * { Bytef * }; - -/* Allow the sourceLen to be automatically filled in from the length - of the 'source' string */ -%typemap(in) (const Bytef *source, uLong sourceLen) -%{ if (!C_swig_is_string ($input)) { - swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument $input is not a string"); - } - $2 = (uLong) C_header_size ($input); - $1 = C_c_string ($input); -%} - -/* Allocate space the size of which is determined by the Scheme - integer argument, and make a temporary integer so we can set - destLen. */ -%typemap(in) (Bytef *dest, uLongf *destLen) (uLong len) -%{ if (!C_swig_is_fixnum ($input)) { - swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument $input is not a integer"); - } - len = (uLong) C_unfix ($input); - $2 = &len; - $1 = (char *) malloc (*$2); -%} - -/* Return the mutated string as a new object. */ -%typemap(argout) (Bytef *dest, uLongf *destLen) -(C_word *scmstr) -%{ scmstr = C_alloc (C_SIZEOF_STRING (*$2)); - SWIG_APPEND_VALUE(C_string (&scmstr, *$2, $1)); - free ($1); -%} - -%include "zconf.h" -%include "zlib.h" - -/* Ignore destLen as an input argument, and make a temporary integer so - we can set destLen. */ -%typemap(numinputs=0) uLongf *destLen (uLong len) -"$1 = &len;"; - -/* Return a sized string as a new object. */ -%typemap(argout) -(void *outstr, uLongf *destLen) (C_word *scmstr) -%{ scmstr = C_alloc (C_SIZEOF_STRING (*$2)); - SWIG_APPEND_VALUE(C_string (&scmstr, *$2, $1)); -%} - -%inline %{ -/* %inline blocks are seen by SWIG and are inserted into the header - portion of example_wrap.c, so that they are also seen by the C - compiler. */ -int deflate_init(z_streamp strm, int level) { - return deflateInit(strm,level); /* call macro */ -} -int inflate_init(z_streamp strm) { - return inflateInit(strm); /* call macro */ -} -void* z_stream_save_next_out(z_streamp strm) { - return (void*) strm->next_out; -} -void z_stream_get_next_chunk(z_streamp strm, void *outstr, uLongf *destLen) { - *destLen = strm->next_out - (Bytef*)outstr; -} -%} - diff --git a/Examples/chicken/zlib/test-zlib.scm b/Examples/chicken/zlib/test-zlib.scm deleted file mode 100644 index a13d801b8..000000000 --- a/Examples/chicken/zlib/test-zlib.scm +++ /dev/null @@ -1,41 +0,0 @@ -(load-library 'example "./zlib.so") - -;; Init zstream -(define s (new-z-stream)) -(z-stream-zalloc-set s #f) -(z-stream-zfree-set s #f) -(z-stream-opaque-set s #f) -(deflate-init s (Z-DEFAULT-COMPRESSION)) - -;; Deflate something small so we don't need to loop/stream data -(define in "some pony et jumping et jack et flash et had a jack pony") -(define out (make-string 1000)) -(printf "to be compressed: ~A~%to be compressed bytes: ~A~%~%" in (string-length in)) -(z-stream-next-in-set s in) -(z-stream-avail-in-set s (string-length in)) -(z-stream-next-out-set s out) -(z-stream-avail-out-set s (string-length out)) -(let* - ((saved-out (z-stream-save-next-out s)) - (ret (deflate s (Z-FINISH)))) - (cond - ((= ret (Z-STREAM-END)) - (printf "deflated properly!~%compressed bytes: ~A~%compressed stream: ~A~%" - (z-stream-total-out-get s) (z-stream-get-next-chunk s saved-out))) - ((= ret (Z-OK)) - (display "only partial deflation ... not enough output space\n")) - (else - (printf "deflate error(~D): ~A ~%" ret (z-stream-msg-get s))))) - -;; Use simple compress routine, and set max output size to 100 -(newline) -(call-with-values (lambda () (compress 100 in)) - (lambda (ret compressed) - (cond - ((= ret (Z-OK)) - (printf "compressed properly!~%compressed bytes: ~A~%compressed stream: ~A~%" - (string-length compressed) compressed)) - (else - (printf "compress error(~D): ~A ~%" ret (z-error ret)))))) - -(exit 0) diff --git a/Examples/guile/check.list b/Examples/guile/check.list index d35b2d693..7ccd0730a 100644 --- a/Examples/guile/check.list +++ b/Examples/guile/check.list @@ -1,6 +1,5 @@ # see top-level Makefile.in constants -matrix simple port multimap diff --git a/Examples/lua/lua.c b/Examples/lua/lua.c index e06e2c5fc..8cffaa503 100644 --- a/Examples/lua/lua.c +++ b/Examples/lua/lua.c @@ -1,5 +1,4 @@ /* -** $Id$ ** Lua stand-alone interpreter ** See Copyright Notice in lua.h */ diff --git a/Examples/test-suite/csharp/li_std_map_runme.cs b/Examples/test-suite/csharp/li_std_map_runme.cs index 685b20e47..ef5314dc7 100644 --- a/Examples/test-suite/csharp/li_std_map_runme.cs +++ b/Examples/test-suite/csharp/li_std_map_runme.cs @@ -1,12 +1,7 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * li_std_map_runme.cs * * SWIG C# tester for std_map.i - * Implementation by Yuval Baror (http://yuval.bar-or.org) - * * This class tests all the functionality of the std_map.i wrapper. * Upon successful testing, the main function doesn't print out anything. * If any error is found - it will be printed on the screen. diff --git a/Examples/test-suite/li_std_queue.i b/Examples/test-suite/li_std_queue.i index 2d322b4d9..6bf71afca 100644 --- a/Examples/test-suite/li_std_queue.i +++ b/Examples/test-suite/li_std_queue.i @@ -1,13 +1,4 @@ -/** - * @file std_queue.i - * @author gga - * @date Sun May 6 01:52:44 2007 - * - * @brief test of std::queue - * - * - */ - +// test of std::queue %module li_std_queue %include std_queue.i diff --git a/Examples/test-suite/li_std_set.i b/Examples/test-suite/li_std_set.i index 8c335b24c..2dcc2f17c 100644 --- a/Examples/test-suite/li_std_set.i +++ b/Examples/test-suite/li_std_set.i @@ -1,18 +1,12 @@ -/** - * @file li_std_set.i - * @author gga - * @date Tue May 1 02:52:47 2007 - * - * @brief a test of set containers. - * Languages should define swig::LANGUAGE_OBJ to be - * an entity of their native pointer type which can be - * included in a STL container. +/* + * a test of set containers. + * Languages should define swig::LANGUAGE_OBJ to be + * an entity of their native pointer type which can be + * included in a STL container. * - * For example: - * swig::LANGUAGE_OBJ is GC_VALUE in Ruby - * swig::LANGUAGE_OBJ is SwigPtr_PyObject in python - * - * + * For example: + * swig::LANGUAGE_OBJ is GC_VALUE in Ruby + * swig::LANGUAGE_OBJ is SwigPtr_PyObject in python */ %module li_std_set diff --git a/Examples/test-suite/li_std_stack.i b/Examples/test-suite/li_std_stack.i index d29254089..19b45d46f 100644 --- a/Examples/test-suite/li_std_stack.i +++ b/Examples/test-suite/li_std_stack.i @@ -1,13 +1,4 @@ -/** - * @file std_stack.i - * @author gga - * @date Sun May 6 01:52:44 2007 - * - * @brief test of std::stack - * - * - */ - +// test of std::stack %module li_std_stack %include std_stack.i diff --git a/Examples/test-suite/ruby/ruby_li_std_speed_runme.rb b/Examples/test-suite/ruby/ruby_li_std_speed_runme.rb index 825f3c593..e79cb46a8 100755 --- a/Examples/test-suite/ruby/ruby_li_std_speed_runme.rb +++ b/Examples/test-suite/ruby/ruby_li_std_speed_runme.rb @@ -3,9 +3,6 @@ # This is a simple speed benchmark suite for std containers, # to verify their O(n) performance. # It is not part of the standard tests. -# -# License:: SWIG -# require 'benchmark' diff --git a/Examples/test-suite/ruby_li_std_speed.i b/Examples/test-suite/ruby_li_std_speed.i index 3c8e60643..bfb0b2776 100644 --- a/Examples/test-suite/ruby_li_std_speed.i +++ b/Examples/test-suite/ruby_li_std_speed.i @@ -1,13 +1,4 @@ -/** - * @file ruby_li_std_speed.i - * @author gga - * @date Fri May 18 18:03:15 2007 - * - * @brief A speed test of the ruby stl - * - * - */ - +// A speed test of the ruby stl %module ruby_li_std_speed %include diff --git a/Examples/xml/example_gif.i b/Examples/xml/example_gif.i deleted file mode 100644 index f0fb3b183..000000000 --- a/Examples/xml/example_gif.i +++ /dev/null @@ -1,329 +0,0 @@ -/* ----------------------------------------------------------------------------- - * gifplot.h - * - * Main header file for the GIFPlot library. - * - * Author(s) : David Beazley (beazley@cs.uchicago.edu) - * Copyright (C) 1995-1996 - * - * See the file LICENSE for information on usage and redistribution. - * ----------------------------------------------------------------------------- */ - -#include -#include -#include -#include -#include -#include - -#ifndef GIFPLOT_H - -/* Pixel is 8-bits */ - -typedef unsigned char Pixel; -typedef float Zvalue; - -/* ------------------------------------------------------------------------ - ColorMap - - Definition and methods for colormaps - ------------------------------------------------------------------------ */ - -typedef struct ColorMap { - unsigned char *cmap; - char *name; -} ColorMap; - -extern ColorMap *new_ColorMap(char *filename); -extern void delete_ColorMap(ColorMap *c); -extern void ColorMap_default(ColorMap *c); -extern void ColorMap_assign(ColorMap *c, int index, int r, int g, int b); -extern int ColorMap_getitem(ColorMap *c, int index); -extern void ColorMap_setitem(ColorMap *c, int index, int value); -extern int ColorMap_write(ColorMap *c, char *filename); - -/* Some default colors */ - -#define BLACK 0 -#define WHITE 1 -#define RED 2 -#define GREEN 3 -#define BLUE 4 -#define YELLOW 5 -#define CYAN 6 -#define MAGENTA 7 - -/*------------------------------------------------------------------------- - FrameBuffer - - This structure defines a simple 8 bit framebuffer. - ------------------------------------------------------------------------- */ - -typedef struct FrameBuffer { - Pixel **pixels; - Zvalue **zbuffer; - unsigned int height; - unsigned int width; - int xmin; /* These are used for clipping */ - int ymin; - int xmax; - int ymax; -} FrameBuffer; - -#define ZMIN 1e+36 - -/* FrameBuffer Methods */ - -extern FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height); -extern void delete_FrameBuffer(FrameBuffer *frame); -extern int FrameBuffer_resize(FrameBuffer *frame, int width, int height); -extern void FrameBuffer_clear(FrameBuffer *frame, Pixel color); -extern void FrameBuffer_plot(FrameBuffer *frame, int x, int y, Pixel color); -extern void FrameBuffer_horizontal(FrameBuffer *frame, int xmin, int xmax, int y, Pixel color); -extern void FrameBuffer_horizontalinterp(FrameBuffer *f, int xmin, int xmax, int y, Pixel c1, Pixel c2); -extern void FrameBuffer_vertical(FrameBuffer *frame, int ymin, int ymax, int x, Pixel color); -extern void FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -extern void FrameBuffer_solidbox(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -extern void FrameBuffer_interpbox(FrameBuffer *f, int x1, int y1, int x2, int y2, Pixel c1, Pixel c2, Pixel c3, Pixel c4); -extern void FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color); -extern void FrameBuffer_solidcircle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color); -extern void FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color); -extern void FrameBuffer_setclip(FrameBuffer *frame, int xmin, int ymin, int xmax, int ymax); -extern void FrameBuffer_noclip(FrameBuffer *frame); -extern int FrameBuffer_makeGIF(FrameBuffer *frame, ColorMap *cmap, void *buffer, unsigned int maxsize); -extern int FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename); -extern void FrameBuffer_zresize(FrameBuffer *f, int width, int height); -extern void FrameBuffer_zclear(FrameBuffer *f); -extern void FrameBuffer_solidtriangle(FrameBuffer *f, int x1, int y1, int x2, int y2, int x3, int y3, Pixel c); -extern void FrameBuffer_interptriangle(FrameBuffer *f, int tx1, int ty1, Pixel c1, - int tx2, int ty2, Pixel c2, int tx3, int ty3, Pixel c3); - -#define HORIZONTAL 1 -#define VERTICAL 2 - -extern void FrameBuffer_drawchar(FrameBuffer *frame, int x, int y, int fgcolor, int bgcolor, char chr, int orientation); -extern void FrameBuffer_drawstring(FrameBuffer *f, int x, int y, int fgcolor, int bgcolor, char *text, int orientation); - -/* ------------------------------------------------------------------------ - PixMap - - The equivalent of "bit-maps". - ------------------------------------------------------------------------ */ - -typedef struct PixMap { - int width; - int height; - int centerx; - int centery; - int *map; -} PixMap; - -/* PIXMAP methods */ - -extern PixMap *new_PixMap(int width, int height, int centerx, int centery); -extern void delete_PixMap(PixMap *pm); -extern void PixMap_set(PixMap *pm, int x, int y, int pix); -extern void FrameBuffer_drawpixmap(FrameBuffer *f, PixMap *pm, int x, int y, int fgcolor, int bgcolor); - -#define TRANSPARENT 0 -#define FOREGROUND 1 -#define BACKGROUND 2 - -/* ------------------------------------------------------------------------ - Plot2D - - Definition and methods for 2D plots. - ------------------------------------------------------------------------ */ - -typedef struct Plot2D { - FrameBuffer *frame; /* what frame buffer are we using */ - int view_xmin; /* Minimum coordinates of view region */ - int view_ymin; - int view_xmax; /* Maximum coordinates of view region */ - int view_ymax; - double xmin; /* Minimum coordinates of plot region */ - double ymin; - double xmax; /* Maximum coordinates of plot region */ - double ymax; - int xscale; /* Type of scaling (LINEAR, LOG, etc..) */ - int yscale; - double dx; /* Private scaling parameters */ - double dy; -} Plot2D; - -/* 2D Plot methods */ - -extern Plot2D *new_Plot2D(FrameBuffer *frame,double xmin,double ymin, double xmax, double ymax); -extern void delete_Plot2D(Plot2D *p2); -extern Plot2D *Plot2D_copy(Plot2D *p2); -extern void Plot2D_clear(Plot2D *p2, Pixel c); -extern void Plot2D_setview(Plot2D *p2, int vxmin, int vymin, int vxmax, int vymax); -extern void Plot2D_setrange(Plot2D *p2, double xmin, double ymin, double xmax, double ymax); -extern void Plot2D_setscale(Plot2D *p2, int xscale, int yscale); -extern void Plot2D_plot(Plot2D *p2, double x, double y, Pixel color); -extern void Plot2D_box(Plot2D *p2, double x1, double y1, double x2, double y2, Pixel color); -extern void Plot2D_solidbox(Plot2D *p2, double x1, double y1,double x2, double y2, Pixel color); -extern void Plot2D_interpbox(Plot2D *p2, double x1, double y1, double x2, double y2, Pixel c1, Pixel c2, Pixel c3, Pixel c4); -extern void Plot2D_circle(Plot2D *p2, double x, double y, double radius, Pixel color); -extern void Plot2D_solidcircle(Plot2D *p2, double x, double y, double radius, Pixel color); -extern void Plot2D_line(Plot2D *p2, double x1, double y1, double x2, double y2, Pixel color); -extern void Plot2D_start(Plot2D *p2); -extern void Plot2D_drawpixmap(Plot2D *p2, PixMap *pm, double x, double y, Pixel color, Pixel bgcolor); -extern void Plot2D_xaxis(Plot2D *p2, double x, double y, double xtick, int ticklength, Pixel c); -extern void Plot2D_yaxis(Plot2D *p2, double x, double y, double ytick, int ticklength, Pixel c); -extern void Plot2D_triangle(Plot2D *p2, double x1, double y1, double x2, double y2, double x3, double y3, Pixel c); -extern void Plot2D_solidtriangle(Plot2D *p2, double x1, double y1, double x2, double y2, double x3, double y3, Pixel c); -extern void Plot2D_interptriangle(Plot2D *p2, double x1, double y1, Pixel c1, - double x2, double y2, Pixel c2, - double x3, double y3, Pixel c3); - -#define LINEAR 10 -#define LOG 11 - -/* ----------------------------------------------------------------------- - Matrix - - Operations on 4x4 transformation matrices and vectors. - Matrices are represented as a double array of 16 elements - ----------------------------------------------------------------------- */ - -typedef double *Matrix; -typedef struct GL_Vector { - double x; - double y; - double z; - double w; -} GL_Vector; - -extern Matrix new_Matrix(); -extern void delete_Matrix(Matrix a); -extern Matrix Matrix_copy(Matrix a); -extern void Matrix_multiply(Matrix a, Matrix b, Matrix c); -extern void Matrix_identity(Matrix a); -extern void Matrix_zero(Matrix a); -extern void Matrix_transpose(Matrix a, Matrix result); -extern void Matrix_invert(Matrix a, Matrix inva); -extern void Matrix_transform(Matrix a, GL_Vector *r, GL_Vector *t); -extern void Matrix_transform4(Matrix a, double rx, double ry, double rz, - double rw, GL_Vector *t); - -extern void Matrix_print(Matrix a); -extern void Matrix_translate(Matrix a, double tx, double ty, double tz); -extern void Matrix_rotatex(Matrix a, double deg); -extern void Matrix_rotatey(Matrix a, double deg); -extern void Matrix_rotatez(Matrix a, double deg); - -/* ----------------------------------------------------------------------- - Plot3D - - Data Structure for 3-D plots - ------------------------------------------------------------------------ */ - -typedef struct Plot3D { - FrameBuffer *frame; /* Frame buffer being used */ - int view_xmin; /* Viewing region */ - int view_ymin; - int view_xmax; - int view_ymax; - double xmin; /* Bounding box */ - double ymin; - double zmin; - double xmax; - double ymax; - double zmax; - double xcenter; /* Center point */ - double ycenter; - double zcenter; - double fovy; /* Field of view */ - double aspect; /* Aspect ratio */ - double znear; /* near "clipping" plane */ - double zfar; /* far "clipping" plane */ - Matrix center_mat; /* Matrix used for centering the model */ - Matrix model_mat; /* Model rotation matrix */ - Matrix view_mat; /* Viewing matrix */ - Matrix fullmodel_mat; /* Full model matrix. Used by sphere plot */ - Matrix trans_mat; /* Total transformation matrix */ - double lookatz; /* Where is the z-lookat point */ - double xshift; /* Used for translation and stuff */ - double yshift; - double zoom; - int width; - int height; - int pers_mode; /* Perspective mode (private) */ - double ortho_left,ortho_right,ortho_bottom,ortho_top; -} Plot3D; - -extern Plot3D *new_Plot3D(FrameBuffer *frame, double xmin, double ymin, double zmin, - double xmax, double ymax, double zmax); -extern void delete_Plot3D(Plot3D *p3); -extern Plot3D *Plot3D_copy(Plot3D *p3); -extern void Plot3D_clear(Plot3D *p3, Pixel Color); -extern void Plot3D_perspective(Plot3D *p3, double fovy, double znear, double zfar); -extern void Plot3D_ortho(Plot3D *p3, double left, double right, double top, double bottom); -extern void Plot3D_lookat(Plot3D *p3, double z); -extern void Plot3D_autoperspective(Plot3D *p3, double fovy); -extern void Plot3D_autoortho(Plot3D *p3); -extern void Plot3D_rotx(Plot3D *p3, double deg); -extern void Plot3D_roty(Plot3D *p3, double deg); -extern void Plot3D_rotz(Plot3D *p3, double deg); -extern void Plot3D_rotl(Plot3D *p3, double deg); -extern void Plot3D_rotr(Plot3D *p3, double deg); -extern void Plot3D_rotd(Plot3D *p3, double deg); -extern void Plot3D_rotu(Plot3D *p3, double deg); -extern void Plot3D_rotc(Plot3D *p3, double deg); -extern void Plot3D_zoom(Plot3D *p3, double percent); -extern void Plot3D_left(Plot3D *p3, double percent); -extern void Plot3D_right(Plot3D *p3, double percent); -extern void Plot3D_down(Plot3D *p3, double percent); -extern void Plot3D_up(Plot3D *p3, double percent); -extern void Plot3D_center(Plot3D *p3, double cx, double cy); - -extern void Plot3D_plot(Plot3D *p3, double x, double y, double z, Pixel Color); - -extern void Plot3D_setview(Plot3D *p3, int vxmin, int vymin, int vxmax, int vymax); -extern void Plot3D_start(Plot3D *p3); -extern void Plot3D_line(Plot3D *p3, double x1, double y1, double z1, - double x2, double y2, double z2, Pixel color); -extern void Plot3D_triangle(Plot3D *p3, double x1, double y1, double z1, - double x2, double y2, double z2, - double x3, double y3, double z3, Pixel color); -extern void Plot3D_solidtriangle(Plot3D *p3, double x1, double y1, double z1, - double x2, double y2, double z2, - double x3, double y3, double z3, Pixel color); - -extern void Plot3D_interptriangle(Plot3D *p3, - double x1, double y1, double z1, Pixel c1, - double x2, double y2, double z2, Pixel c2, - double x3, double y3, double z3, Pixel c3); - -extern void Plot3D_quad(Plot3D *p3, double x1, double y1, double z1, - double x2, double y2, double z2, - double x3, double y3, double z3, - double x4, double y4, double z4, - Pixel color); - -extern void Plot3D_solidquad(Plot3D *p3, double x1, double y1, double z1, - double x2, double y2, double z2, - double x3, double y3, double z3, - double x4, double y4, double z4, - Pixel color); - -extern void Plot3D_interpquad(Plot3D *p3, double x1, double y1, double z1, Pixel c1, - double x2, double y2, double z2, Pixel c2, - double x3, double y3, double z3, Pixel c3, - double x4, double y4, double z4, Pixel c4); - - -extern void Plot3D_solidsphere(Plot3D *p3, double x, double y, double z, double radius,Pixel c); - -extern void Plot3D_outlinesphere(Plot3D *p3, double x, double y, double z, double radius,Pixel c, Pixel bc); - -extern PixMap PixMap_SQUARE; -extern PixMap PixMap_TRIANGLE; -extern PixMap PixMap_CROSS; - -#endif -#define GIFPLOT_H - - - diff --git a/LICENSE b/LICENSE index fdb73d916..d7a422fda 100644 --- a/LICENSE +++ b/LICENSE @@ -1,95 +1,22 @@ -SWIG is distributed under the following terms: +SWIG is free software: you can redistribute it and/or modify it +under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. See the LICENSE-GPL file for +the full terms of the GNU General Public license version 3. -I. +Portions of SWIG are also licensed under the terms of the licenses +in the file LICENSE-UNIVERSITIES. You must observe the terms of +these licenses, as well as the terms of the GNU General Public License, +when you distribute SWIG. -Copyright (c) 1995-1998 -The University of Utah and the Regents of the University of California -All Rights Reserved +The SWIG library and examples, under the Lib and Examples top level +directories, are distributed under the following terms: -Permission is hereby granted, without written agreement and without -license or royalty fees, to use, copy, modify, and distribute this -software and its documentation for any purpose, provided that -(1) The above copyright notice and the following two paragraphs -appear in all copies of the source code and (2) redistributions -including binaries reproduces these notices in the supporting -documentation. Substantial modifications to this software may be -copyrighted by their authors and need not follow the licensing terms -described here, provided that the new terms are clearly indicated in -all files where they apply. - -IN NO EVENT SHALL THE AUTHOR, THE UNIVERSITY OF CALIFORNIA, THE -UNIVERSITY OF UTAH OR DISTRIBUTORS OF THIS SOFTWARE BE LIABLE TO ANY -PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL -DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, -EVEN IF THE AUTHORS OR ANY OF THE ABOVE PARTIES HAVE BEEN ADVISED OF -THE POSSIBILITY OF SUCH DAMAGE. - -THE AUTHOR, THE UNIVERSITY OF CALIFORNIA, AND THE UNIVERSITY OF UTAH -SPECIFICALLY DISCLAIM ANY WARRANTIES,INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND -THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, -SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. - - -II. - -This software includes contributions that are Copyright (c) 1998-2005 -University of Chicago. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -Redistributions of source code must retain the above copyright notice, -this list of conditions and the following disclaimer. Redistributions -in binary form must reproduce the above copyright notice, this list of -conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. Neither the name of -the University of Chicago nor the names of its contributors may be -used to endorse or promote products derived from this software without -specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF CHICAGO AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF -CHICAGO OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -III. - -This software includes contributions that are Copyright (c) 2005-2006 -Arizona Board of Regents (University of Arizona). -All Rights Reserved - -Permission is hereby granted, without written agreement and without -license or royalty fees, to use, copy, modify, and distribute this -software and its documentation for any purpose, provided that -(1) The above copyright notice and the following two paragraphs -appear in all copies of the source code and (2) redistributions -including binaries reproduces these notices in the supporting -documentation. Substantial modifications to this software may be -copyrighted by their authors and need not follow the licensing terms -described here, provided that the new terms are clearly indicated in -all files where they apply. - -THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF ARIZONA AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF -ARIZONA OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + You may copy, modify, distribute, and make derivative works based on + this software, in source code or object code form, without + restriction. If you distribute the software to others, you may do + so according to the terms of your choice. This software is offered as + is, without warranty of any kind. +See the COPYRIGHT file for a list of contributors to SWIG and their +copyright notices. diff --git a/LICENSE-GPL b/LICENSE-GPL new file mode 100644 index 000000000..94a9ed024 --- /dev/null +++ b/LICENSE-GPL @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/LICENSE-UNIVERSITIES b/LICENSE-UNIVERSITIES new file mode 100644 index 000000000..fdb73d916 --- /dev/null +++ b/LICENSE-UNIVERSITIES @@ -0,0 +1,95 @@ +SWIG is distributed under the following terms: + +I. + +Copyright (c) 1995-1998 +The University of Utah and the Regents of the University of California +All Rights Reserved + +Permission is hereby granted, without written agreement and without +license or royalty fees, to use, copy, modify, and distribute this +software and its documentation for any purpose, provided that +(1) The above copyright notice and the following two paragraphs +appear in all copies of the source code and (2) redistributions +including binaries reproduces these notices in the supporting +documentation. Substantial modifications to this software may be +copyrighted by their authors and need not follow the licensing terms +described here, provided that the new terms are clearly indicated in +all files where they apply. + +IN NO EVENT SHALL THE AUTHOR, THE UNIVERSITY OF CALIFORNIA, THE +UNIVERSITY OF UTAH OR DISTRIBUTORS OF THIS SOFTWARE BE LIABLE TO ANY +PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, +EVEN IF THE AUTHORS OR ANY OF THE ABOVE PARTIES HAVE BEEN ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. + +THE AUTHOR, THE UNIVERSITY OF CALIFORNIA, AND THE UNIVERSITY OF UTAH +SPECIFICALLY DISCLAIM ANY WARRANTIES,INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND +THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, +SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + + +II. + +This software includes contributions that are Copyright (c) 1998-2005 +University of Chicago. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. Redistributions +in binary form must reproduce the above copyright notice, this list of +conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. Neither the name of +the University of Chicago nor the names of its contributors may be +used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF CHICAGO AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF +CHICAGO OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +III. + +This software includes contributions that are Copyright (c) 2005-2006 +Arizona Board of Regents (University of Arizona). +All Rights Reserved + +Permission is hereby granted, without written agreement and without +license or royalty fees, to use, copy, modify, and distribute this +software and its documentation for any purpose, provided that +(1) The above copyright notice and the following two paragraphs +appear in all copies of the source code and (2) redistributions +including binaries reproduces these notices in the supporting +documentation. Substantial modifications to this software may be +copyrighted by their authors and need not follow the licensing terms +described here, provided that the new terms are clearly indicated in +all files where they apply. + +THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF ARIZONA AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF +ARIZONA OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/Lib/allegrocl/allegrocl.swg b/Lib/allegrocl/allegrocl.swg index 4479f6ac2..266303113 100644 --- a/Lib/allegrocl/allegrocl.swg +++ b/Lib/allegrocl/allegrocl.swg @@ -289,8 +289,6 @@ $body)" #endif %insert("lisphead") %{ -;; $Id$ - (eval-when (:compile-toplevel :load-toplevel :execute) ;; avoid compiling ef-templates at runtime diff --git a/Lib/allegrocl/longlongs.i b/Lib/allegrocl/longlongs.i index b887a8a0a..4aa54660b 100644 --- a/Lib/allegrocl/longlongs.i +++ b/Lib/allegrocl/longlongs.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * longlongs.i * * Typemap addition for support of 'long long' type and 'unsigned long long diff --git a/Lib/allegrocl/std_list.i b/Lib/allegrocl/std_list.i index c8ab45649..4e260897f 100644 --- a/Lib/allegrocl/std_list.i +++ b/Lib/allegrocl/std_list.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_list.i * * SWIG typemaps for std::list types diff --git a/Lib/allegrocl/std_string.i b/Lib/allegrocl/std_string.i index 4da0148fe..becc322e9 100644 --- a/Lib/allegrocl/std_string.i +++ b/Lib/allegrocl/std_string.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_string.i * * SWIG typemaps for std::string diff --git a/Lib/attribute.i b/Lib/attribute.i index 45c3c5b64..0cc3ff1a3 100644 --- a/Lib/attribute.i +++ b/Lib/attribute.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * attribute.i * * SWIG library file for implementing attributes. diff --git a/Lib/carrays.i b/Lib/carrays.i index 738b4577a..5fc78877c 100644 --- a/Lib/carrays.i +++ b/Lib/carrays.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * carrays.i * * SWIG library file containing macros that can be used to manipulate simple diff --git a/Lib/cdata.i b/Lib/cdata.i index 67601f737..41e8f86ce 100644 --- a/Lib/cdata.i +++ b/Lib/cdata.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * cdata.i * * SWIG library file containing macros for manipulating raw C data as strings. diff --git a/Lib/chicken/chicken.swg b/Lib/chicken/chicken.swg index a8d1b5a57..68f022570 100644 --- a/Lib/chicken/chicken.swg +++ b/Lib/chicken/chicken.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * chicken.swg * * CHICKEN configuration module. diff --git a/Lib/chicken/chickenrun.swg b/Lib/chicken/chickenrun.swg index 8703ea65a..f4e94d6f6 100644 --- a/Lib/chicken/chickenrun.swg +++ b/Lib/chicken/chickenrun.swg @@ -1,9 +1,5 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * chickenrun.swg - * * ----------------------------------------------------------------------------- */ #include diff --git a/Lib/chicken/multi-generic.scm b/Lib/chicken/multi-generic.scm index ae822f37b..9d2e31d34 100644 --- a/Lib/chicken/multi-generic.scm +++ b/Lib/chicken/multi-generic.scm @@ -21,7 +21,7 @@ ;; which functions are used when. ;; Comments, bugs, suggestions: send either to chicken-users@nongnu.org or to -;; Author: John Lenz , most code copied from TinyCLOS +;; Most code copied from TinyCLOS (define (make 'name "multi-generic" diff --git a/Lib/chicken/std_string.i b/Lib/chicken/std_string.i index 2955d0e2f..ce24cba32 100644 --- a/Lib/chicken/std_string.i +++ b/Lib/chicken/std_string.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_string.i * * SWIG typemaps for std::string diff --git a/Lib/chicken/typemaps.i b/Lib/chicken/typemaps.i index d79e20184..56cd18a5d 100644 --- a/Lib/chicken/typemaps.i +++ b/Lib/chicken/typemaps.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * typemaps.i * * Pointer handling diff --git a/Lib/clisp/clisp.swg b/Lib/clisp/clisp.swg index fb6cdbf2a..e1d330cb3 100644 --- a/Lib/clisp/clisp.swg +++ b/Lib/clisp/clisp.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * clisp.swg * ----------------------------------------------------------------------------- */ diff --git a/Lib/cmalloc.i b/Lib/cmalloc.i index 03a61351c..9f58bc03c 100644 --- a/Lib/cmalloc.i +++ b/Lib/cmalloc.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * cmalloc.i * * SWIG library file containing macros that can be used to create objects using diff --git a/Lib/constraints.i b/Lib/constraints.i index 2deb1168a..8bc7f9159 100644 --- a/Lib/constraints.i +++ b/Lib/constraints.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * constraints.i * * SWIG constraints library. diff --git a/Lib/cpointer.i b/Lib/cpointer.i index 1a6e51741..6b15a8417 100644 --- a/Lib/cpointer.i +++ b/Lib/cpointer.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * cpointer.i * * SWIG library file containing macros that can be used to manipulate simple diff --git a/Lib/csharp/arrays_csharp.i b/Lib/csharp/arrays_csharp.i index ea22da584..513330e4e 100644 --- a/Lib/csharp/arrays_csharp.i +++ b/Lib/csharp/arrays_csharp.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * arrays_csharp.i * * This file contains a two approaches to marshaling arrays. The first uses diff --git a/Lib/csharp/csharp.swg b/Lib/csharp/csharp.swg index fe459547c..204cf4b2f 100644 --- a/Lib/csharp/csharp.swg +++ b/Lib/csharp/csharp.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * csharp.swg * * C# typemaps diff --git a/Lib/csharp/csharphead.swg b/Lib/csharp/csharphead.swg index 927a54b3b..9b144d6a5 100644 --- a/Lib/csharp/csharphead.swg +++ b/Lib/csharp/csharphead.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * csharphead.swg * * Support code for exceptions if the SWIG_CSHARP_NO_EXCEPTION_HELPER is not defined diff --git a/Lib/csharp/director.swg b/Lib/csharp/director.swg index 8957ecf42..7768d8c02 100644 --- a/Lib/csharp/director.swg +++ b/Lib/csharp/director.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * director.swg * * This file contains support for director classes so that C# proxy diff --git a/Lib/csharp/enums.swg b/Lib/csharp/enums.swg index be2a6063b..6605da8c8 100644 --- a/Lib/csharp/enums.swg +++ b/Lib/csharp/enums.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * enums.swg * * Include this file in order for C/C++ enums to be wrapped by proper C# enums. diff --git a/Lib/csharp/enumsimple.swg b/Lib/csharp/enumsimple.swg index f50849892..2b1cb182b 100644 --- a/Lib/csharp/enumsimple.swg +++ b/Lib/csharp/enumsimple.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * enumsimple.swg * * This file provides backwards compatible enum wrapping. SWIG versions 1.3.21 diff --git a/Lib/csharp/enumtypesafe.swg b/Lib/csharp/enumtypesafe.swg index 8ba7838ef..a6bf64b9a 100644 --- a/Lib/csharp/enumtypesafe.swg +++ b/Lib/csharp/enumtypesafe.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * enumtypesafe.swg * * Include this file in order for C/C++ enums to be wrapped by the so called diff --git a/Lib/csharp/std_except.i b/Lib/csharp/std_except.i index c86e97a54..27eb84bc2 100644 --- a/Lib/csharp/std_except.i +++ b/Lib/csharp/std_except.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_except.i * * Typemaps used by the STL wrappers that throw exceptions. These typemaps are diff --git a/Lib/csharp/std_map.i b/Lib/csharp/std_map.i index 3b09861a2..a30b6fa70 100644 --- a/Lib/csharp/std_map.i +++ b/Lib/csharp/std_map.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_map.i * * SWIG typemaps for std::map diff --git a/Lib/csharp/std_pair.i b/Lib/csharp/std_pair.i index 78142ffa6..0712ad762 100644 --- a/Lib/csharp/std_pair.i +++ b/Lib/csharp/std_pair.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_pair.i * * SWIG typemaps for std::pair diff --git a/Lib/csharp/std_string.i b/Lib/csharp/std_string.i index d29692717..0d804518b 100644 --- a/Lib/csharp/std_string.i +++ b/Lib/csharp/std_string.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_string.i * * Typemaps for std::string and const std::string& diff --git a/Lib/csharp/std_vector.i b/Lib/csharp/std_vector.i index d3a4a5541..673cced89 100644 --- a/Lib/csharp/std_vector.i +++ b/Lib/csharp/std_vector.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_vector.i * * SWIG typemaps for std::vector diff --git a/Lib/csharp/std_wstring.i b/Lib/csharp/std_wstring.i index 938070e4b..9142d36a5 100644 --- a/Lib/csharp/std_wstring.i +++ b/Lib/csharp/std_wstring.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_wstring.i * * Typemaps for std::wstring and const std::wstring& diff --git a/Lib/csharp/stl.i b/Lib/csharp/stl.i index 66b72e073..9d2e91eee 100644 --- a/Lib/csharp/stl.i +++ b/Lib/csharp/stl.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * stl.i * * Initial STL definition. extended as needed in each language diff --git a/Lib/csharp/typemaps.i b/Lib/csharp/typemaps.i index 56cc6cb61..d50e5c46d 100644 --- a/Lib/csharp/typemaps.i +++ b/Lib/csharp/typemaps.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * typemaps.i * * Pointer and reference handling typemap library diff --git a/Lib/csharp/wchar.i b/Lib/csharp/wchar.i index be87560c3..f02c09a53 100644 --- a/Lib/csharp/wchar.i +++ b/Lib/csharp/wchar.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * wchar.i * * Typemaps for the wchar_t type diff --git a/Lib/cstring.i b/Lib/cstring.i index 4ebdf6857..6829f7597 100644 --- a/Lib/cstring.i +++ b/Lib/cstring.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * cstring.i * ----------------------------------------------------------------------------- */ diff --git a/Lib/cwstring.i b/Lib/cwstring.i index a6b08ae40..f0631d328 100644 --- a/Lib/cwstring.i +++ b/Lib/cwstring.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * cwstring.i * ----------------------------------------------------------------------------- */ diff --git a/Lib/exception.i b/Lib/exception.i index e30ac1a5d..7297a77f5 100644 --- a/Lib/exception.i +++ b/Lib/exception.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * exception.i * * SWIG library file providing language independent exception handling diff --git a/Lib/gcj/cni.swg b/Lib/gcj/cni.swg index 247909a4a..4bd07df06 100644 --- a/Lib/gcj/cni.swg +++ b/Lib/gcj/cni.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * cni.swg * ----------------------------------------------------------------------------- */ diff --git a/Lib/guile/common.scm b/Lib/guile/common.scm index a51d3a71d..17c9ab580 100644 --- a/Lib/guile/common.scm +++ b/Lib/guile/common.scm @@ -3,12 +3,6 @@ ;;;* ;;;* This file contains generic SWIG GOOPS classes for generated ;;;* GOOPS file support -;;;* -;;;* Copyright (C) 2003 John Lenz (jelenz@wisc.edu) -;;;* Copyright (C) 2004 Matthias Koeppe (mkoeppe@mail.math.uni-magdeburg.de) -;;;* -;;;* This file may be freely redistributed without license or fee provided -;;;* this copyright message remains intact. ;;;************************************************************************ (define-module (Swig swigrun)) diff --git a/Lib/guile/cplusplus.i b/Lib/guile/cplusplus.i index cb4cf7434..0dfe71754 100644 --- a/Lib/guile/cplusplus.i +++ b/Lib/guile/cplusplus.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * cplusplus.i * * SWIG typemaps for C++ diff --git a/Lib/guile/guile.i b/Lib/guile/guile.i index 1bf28d6f3..ef270d74b 100644 --- a/Lib/guile/guile.i +++ b/Lib/guile/guile.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * guile.i * * SWIG Configuration File for Guile. diff --git a/Lib/guile/guile_gh.swg b/Lib/guile/guile_gh.swg index 6412a4c61..3b65af897 100644 --- a/Lib/guile/guile_gh.swg +++ b/Lib/guile/guile_gh.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * guile_gh.swg * * This SWIG interface file is processed if the Guile module is run diff --git a/Lib/guile/guile_gh_run.swg b/Lib/guile/guile_gh_run.swg index 5b1fca0aa..0eba1f97e 100644 --- a/Lib/guile/guile_gh_run.swg +++ b/Lib/guile/guile_gh_run.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * guile_gh_run.swg * * Guile GH runtime file diff --git a/Lib/guile/guile_scm.swg b/Lib/guile/guile_scm.swg index caded728d..d12401451 100644 --- a/Lib/guile/guile_scm.swg +++ b/Lib/guile/guile_scm.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * guile_scm.swg * * This SWIG interface file is processed if the Guile module is run diff --git a/Lib/guile/guile_scm_run.swg b/Lib/guile/guile_scm_run.swg index 5da8558fc..91b74095d 100644 --- a/Lib/guile/guile_scm_run.swg +++ b/Lib/guile/guile_scm_run.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * guile_scm_run.swg * ----------------------------------------------------------------------------- */ diff --git a/Lib/guile/guilemain.i b/Lib/guile/guilemain.i index 6f4e4d94d..925b81fee 100644 --- a/Lib/guile/guilemain.i +++ b/Lib/guile/guilemain.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * guilemain.i * * The main functions for a user augmented guile diff --git a/Lib/guile/interpreter.i b/Lib/guile/interpreter.i index 7e8f0777a..524e0694a 100644 --- a/Lib/guile/interpreter.i +++ b/Lib/guile/interpreter.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * interpreter.i * * SWIG file for a simple Guile interpreter diff --git a/Lib/guile/list-vector.i b/Lib/guile/list-vector.i index d98cae59a..c2cd1aea2 100644 --- a/Lib/guile/list-vector.i +++ b/Lib/guile/list-vector.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * list_vector.i * * Guile typemaps for converting between arrays and Scheme lists or vectors diff --git a/Lib/guile/pointer-in-out.i b/Lib/guile/pointer-in-out.i index bc6438759..d8a631ca9 100644 --- a/Lib/guile/pointer-in-out.i +++ b/Lib/guile/pointer-in-out.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * pointer-in-out.i * * Guile typemaps for passing pointers indirectly diff --git a/Lib/guile/ports.i b/Lib/guile/ports.i index 0d0e142e1..5940b4d3b 100644 --- a/Lib/guile/ports.i +++ b/Lib/guile/ports.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * ports.i * * Guile typemaps for handling ports diff --git a/Lib/guile/std_common.i b/Lib/guile/std_common.i index ace5d65a8..a46c42c69 100644 --- a/Lib/guile/std_common.i +++ b/Lib/guile/std_common.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_common.i * * SWIG typemaps for STL - common utilities diff --git a/Lib/guile/std_map.i b/Lib/guile/std_map.i index cc53e1560..19c863096 100644 --- a/Lib/guile/std_map.i +++ b/Lib/guile/std_map.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_map.i * * SWIG typemaps for std::map diff --git a/Lib/guile/std_pair.i b/Lib/guile/std_pair.i index f8c2ea688..35f0cfad5 100644 --- a/Lib/guile/std_pair.i +++ b/Lib/guile/std_pair.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_pair.i * * SWIG typemaps for std::pair diff --git a/Lib/guile/std_string.i b/Lib/guile/std_string.i index f80a65ca5..c10806e98 100644 --- a/Lib/guile/std_string.i +++ b/Lib/guile/std_string.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_string.i * * SWIG typemaps for std::string diff --git a/Lib/guile/std_vector.i b/Lib/guile/std_vector.i index 145db945b..6801daee8 100644 --- a/Lib/guile/std_vector.i +++ b/Lib/guile/std_vector.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_vector.i * * SWIG typemaps for std::vector diff --git a/Lib/guile/stl.i b/Lib/guile/stl.i index 66b72e073..9d2e91eee 100644 --- a/Lib/guile/stl.i +++ b/Lib/guile/stl.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * stl.i * * Initial STL definition. extended as needed in each language diff --git a/Lib/guile/typemaps.i b/Lib/guile/typemaps.i index d9f972850..4f306f7f8 100644 --- a/Lib/guile/typemaps.i +++ b/Lib/guile/typemaps.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * typemaps.i * * Guile-specific typemaps diff --git a/Lib/inttypes.i b/Lib/inttypes.i index 0cc81948e..8450cb840 100644 --- a/Lib/inttypes.i +++ b/Lib/inttypes.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * inttypes.i * * SWIG library file for ISO C99 types: 7.8 Format conversion of integer types diff --git a/Lib/java/arrays_java.i b/Lib/java/arrays_java.i index 95510c3f9..ddaf7408c 100644 --- a/Lib/java/arrays_java.i +++ b/Lib/java/arrays_java.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * arrays_java.i * * These typemaps give more natural support for arrays. The typemaps are not efficient diff --git a/Lib/java/director.swg b/Lib/java/director.swg index fa588671d..07e5a1af1 100644 --- a/Lib/java/director.swg +++ b/Lib/java/director.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * director.swg * * This file contains support for director classes that proxy diff --git a/Lib/java/enums.swg b/Lib/java/enums.swg index 1a8f89b3a..edb67c417 100644 --- a/Lib/java/enums.swg +++ b/Lib/java/enums.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * enums.swg * * Include this file in order for C/C++ enums to be wrapped by proper Java enums. diff --git a/Lib/java/enumsimple.swg b/Lib/java/enumsimple.swg index f45774d0c..e08401869 100644 --- a/Lib/java/enumsimple.swg +++ b/Lib/java/enumsimple.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * enumsimple.swg * * This file provides backwards compatible enum wrapping. SWIG versions 1.3.21 diff --git a/Lib/java/enumtypesafe.swg b/Lib/java/enumtypesafe.swg index a49a9d134..d6c6e5190 100644 --- a/Lib/java/enumtypesafe.swg +++ b/Lib/java/enumtypesafe.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * enumtypesafe.swg * * Include this file in order for C/C++ enums to be wrapped by the so called diff --git a/Lib/java/enumtypeunsafe.swg b/Lib/java/enumtypeunsafe.swg index bda055113..d9a7c4d29 100644 --- a/Lib/java/enumtypeunsafe.swg +++ b/Lib/java/enumtypeunsafe.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * enumtypeunsafe.swg * * Include this file in order for C/C++ enums to be wrapped by integers values. diff --git a/Lib/java/java.swg b/Lib/java/java.swg index bd2357a86..6173502ca 100644 --- a/Lib/java/java.swg +++ b/Lib/java/java.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * java.swg * * Java typemaps diff --git a/Lib/java/javahead.swg b/Lib/java/javahead.swg index 7626bf50d..685bba198 100644 --- a/Lib/java/javahead.swg +++ b/Lib/java/javahead.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * javahead.swg * * Java support code diff --git a/Lib/java/std_except.i b/Lib/java/std_except.i index 15be1deb8..9e23d50e6 100644 --- a/Lib/java/std_except.i +++ b/Lib/java/std_except.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_except.i * * Typemaps used by the STL wrappers that throw exceptions. diff --git a/Lib/java/std_map.i b/Lib/java/std_map.i index 00967d3f9..a7020532c 100644 --- a/Lib/java/std_map.i +++ b/Lib/java/std_map.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_map.i * * SWIG typemaps for std::map diff --git a/Lib/java/std_pair.i b/Lib/java/std_pair.i index dc0604dc5..fe45ee676 100644 --- a/Lib/java/std_pair.i +++ b/Lib/java/std_pair.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_pair.i * * SWIG typemaps for std::pair diff --git a/Lib/java/std_string.i b/Lib/java/std_string.i index 789e17a65..f0d837696 100644 --- a/Lib/java/std_string.i +++ b/Lib/java/std_string.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_string.i * * Typemaps for std::string and const std::string& diff --git a/Lib/java/std_vector.i b/Lib/java/std_vector.i index 29439606b..3f29b19c7 100644 --- a/Lib/java/std_vector.i +++ b/Lib/java/std_vector.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_vector.i * ----------------------------------------------------------------------------- */ diff --git a/Lib/java/std_wstring.i b/Lib/java/std_wstring.i index 989176500..12d8fc14f 100644 --- a/Lib/java/std_wstring.i +++ b/Lib/java/std_wstring.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_wstring.i * * Typemaps for std::wstring and const std::wstring& diff --git a/Lib/java/stl.i b/Lib/java/stl.i index b8d7a654c..04f86014f 100644 --- a/Lib/java/stl.i +++ b/Lib/java/stl.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * stl.i * ----------------------------------------------------------------------------- */ diff --git a/Lib/java/typemaps.i b/Lib/java/typemaps.i index 59f7af99a..74ed99374 100644 --- a/Lib/java/typemaps.i +++ b/Lib/java/typemaps.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * typemaps.i * * Pointer and reference handling typemap library diff --git a/Lib/java/various.i b/Lib/java/various.i index 733b8fa79..7c396de3e 100644 --- a/Lib/java/various.i +++ b/Lib/java/various.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * various.i * * SWIG Typemap library for Java. diff --git a/Lib/lua/_std_common.i b/Lib/lua/_std_common.i index 33cc513c3..e552d0c8f 100644 --- a/Lib/lua/_std_common.i +++ b/Lib/lua/_std_common.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * _std_common.i * * std::helpers for LUA diff --git a/Lib/lua/lua.swg b/Lib/lua/lua.swg index b6d888670..c3f5cecc5 100644 --- a/Lib/lua/lua.swg +++ b/Lib/lua/lua.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * lua.swg * * SWIG Configuration File for Lua. diff --git a/Lib/lua/lua_fnptr.i b/Lib/lua/lua_fnptr.i index c7df6f5a3..7e9facdf3 100644 --- a/Lib/lua/lua_fnptr.i +++ b/Lib/lua/lua_fnptr.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * lua_fnptr.i * * SWIG Library file containing the main typemap code to support Lua modules. diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index 32e1b1617..4c9aa5144 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * luarun.swg * * This file contains the runtime support for Lua modules diff --git a/Lib/lua/luaruntime.swg b/Lib/lua/luaruntime.swg index b82cd56d7..5823d4fcf 100644 --- a/Lib/lua/luaruntime.swg +++ b/Lib/lua/luaruntime.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * luaruntime.swg * * all the runtime code for . diff --git a/Lib/lua/luatypemaps.swg b/Lib/lua/luatypemaps.swg index caa2a6ce1..401541267 100644 --- a/Lib/lua/luatypemaps.swg +++ b/Lib/lua/luatypemaps.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * luatypemaps.swg * * basic typemaps for Lua. diff --git a/Lib/lua/std_except.i b/Lib/lua/std_except.i index ce148ef63..9c736b9ef 100644 --- a/Lib/lua/std_except.i +++ b/Lib/lua/std_except.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * Typemaps used by the STL wrappers that throw exceptions. * These typemaps are used when methods are declared with an STL exception * specification, such as: diff --git a/Lib/lua/std_map.i b/Lib/lua/std_map.i index dd22443d5..84b0c74ff 100644 --- a/Lib/lua/std_map.i +++ b/Lib/lua/std_map.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_map.i * * SWIG typemaps for std::map diff --git a/Lib/lua/std_pair.i b/Lib/lua/std_pair.i index 1b20f74e0..c76361554 100644 --- a/Lib/lua/std_pair.i +++ b/Lib/lua/std_pair.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_pair.i * * std::pair typemaps for LUA diff --git a/Lib/lua/std_string.i b/Lib/lua/std_string.i index fa58f10bb..92f27d738 100644 --- a/Lib/lua/std_string.i +++ b/Lib/lua/std_string.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_string.i * * std::string typemaps for LUA diff --git a/Lib/lua/std_vector.i b/Lib/lua/std_vector.i index c6778087f..f248f0340 100644 --- a/Lib/lua/std_vector.i +++ b/Lib/lua/std_vector.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_vector.i * * std::vector typemaps for LUA diff --git a/Lib/lua/stl.i b/Lib/lua/stl.i index b8d7a654c..04f86014f 100644 --- a/Lib/lua/stl.i +++ b/Lib/lua/stl.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * stl.i * ----------------------------------------------------------------------------- */ diff --git a/Lib/lua/typemaps.i b/Lib/lua/typemaps.i index fa0c0d0e5..084726e58 100644 --- a/Lib/lua/typemaps.i +++ b/Lib/lua/typemaps.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * typemaps.swg * * SWIG Library file containing the main typemap code to support Lua modules. diff --git a/Lib/lua/wchar.i b/Lib/lua/wchar.i index 5b206eb71..5021c1604 100644 --- a/Lib/lua/wchar.i +++ b/Lib/lua/wchar.i @@ -1,12 +1,8 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * wchar.i * * Typemaps for the wchar_t type * These are mapped to a Lua string and are passed around by value. - * * ----------------------------------------------------------------------------- */ // note: only support for pointer right now, not fixed length strings @@ -43,4 +39,4 @@ if ($1==0) {lua_pushfstring(L,"Error in converting to wchar (arg %d)",$input);go free($1); %} -%typemap(typecheck) wchar_t * = char *; \ No newline at end of file +%typemap(typecheck) wchar_t * = char *; diff --git a/Lib/math.i b/Lib/math.i index be931d71b..a37c92d19 100644 --- a/Lib/math.i +++ b/Lib/math.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * math.i * * SWIG library file for floating point operations. diff --git a/Lib/modula3/modula3.swg b/Lib/modula3/modula3.swg index 6a1b4d94d..599a12e5a 100644 --- a/Lib/modula3/modula3.swg +++ b/Lib/modula3/modula3.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * modula3.swg * * Modula3 typemaps diff --git a/Lib/modula3/modula3head.swg b/Lib/modula3/modula3head.swg index b2426be5f..af96a78d1 100644 --- a/Lib/modula3/modula3head.swg +++ b/Lib/modula3/modula3head.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * modula3head.swg * * Modula3 support code diff --git a/Lib/modula3/typemaps.i b/Lib/modula3/typemaps.i index 79ddfda0f..1d76ab5e0 100644 --- a/Lib/modula3/typemaps.i +++ b/Lib/modula3/typemaps.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * typemaps.i * * Pointer and reference handling typemap library diff --git a/Lib/mzscheme/mzrun.swg b/Lib/mzscheme/mzrun.swg index 3b05d2406..a5128da56 100644 --- a/Lib/mzscheme/mzrun.swg +++ b/Lib/mzscheme/mzrun.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * mzrun.swg * ----------------------------------------------------------------------------- */ diff --git a/Lib/mzscheme/mzscheme.swg b/Lib/mzscheme/mzscheme.swg index ed4b2ec9d..9ae242845 100644 --- a/Lib/mzscheme/mzscheme.swg +++ b/Lib/mzscheme/mzscheme.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * mzscheme.swg * * SWIG Configuration File for MzScheme. diff --git a/Lib/mzscheme/std_common.i b/Lib/mzscheme/std_common.i index 8732f811c..1f1ae1ab7 100644 --- a/Lib/mzscheme/std_common.i +++ b/Lib/mzscheme/std_common.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_common.i * * SWIG typemaps for STL - common utilities diff --git a/Lib/mzscheme/std_map.i b/Lib/mzscheme/std_map.i index aff720db6..b2c894509 100644 --- a/Lib/mzscheme/std_map.i +++ b/Lib/mzscheme/std_map.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_map.i * * SWIG typemaps for std::map diff --git a/Lib/mzscheme/std_pair.i b/Lib/mzscheme/std_pair.i index 2ac331e71..d5a65470d 100644 --- a/Lib/mzscheme/std_pair.i +++ b/Lib/mzscheme/std_pair.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_pair.i * * SWIG typemaps for std::pair diff --git a/Lib/mzscheme/std_string.i b/Lib/mzscheme/std_string.i index c9a82efe4..b8b99d9ad 100644 --- a/Lib/mzscheme/std_string.i +++ b/Lib/mzscheme/std_string.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_string.i * * SWIG typemaps for std::string types diff --git a/Lib/mzscheme/std_vector.i b/Lib/mzscheme/std_vector.i index 90a52fc0a..22e1fa96b 100644 --- a/Lib/mzscheme/std_vector.i +++ b/Lib/mzscheme/std_vector.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_vector.i * * SWIG typemaps for std::vector diff --git a/Lib/mzscheme/stl.i b/Lib/mzscheme/stl.i index 946e4b7f0..b19eae58b 100644 --- a/Lib/mzscheme/stl.i +++ b/Lib/mzscheme/stl.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * stl.i * * Initial STL definition. extended as needed in each language diff --git a/Lib/mzscheme/typemaps.i b/Lib/mzscheme/typemaps.i index 334893242..b9f22440c 100644 --- a/Lib/mzscheme/typemaps.i +++ b/Lib/mzscheme/typemaps.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * typemaps.i * ----------------------------------------------------------------------------- */ diff --git a/Lib/ocaml/cstring.i b/Lib/ocaml/cstring.i index e56258264..0d6aa4b69 100644 --- a/Lib/ocaml/cstring.i +++ b/Lib/ocaml/cstring.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * cstring.i * * This file provides typemaps and macros for dealing with various forms diff --git a/Lib/ocaml/director.swg b/Lib/ocaml/director.swg index 87333168f..a21f62102 100644 --- a/Lib/ocaml/director.swg +++ b/Lib/ocaml/director.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * director.swg * * This file contains support for director classes that proxy diff --git a/Lib/ocaml/ocaml.i b/Lib/ocaml/ocaml.i index a46e239d1..e099f7c10 100644 --- a/Lib/ocaml/ocaml.i +++ b/Lib/ocaml/ocaml.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * ocaml.i * * SWIG Configuration File for Ocaml diff --git a/Lib/ocaml/ocamldec.swg b/Lib/ocaml/ocamldec.swg index 3b5290fa1..8e452d3f9 100644 --- a/Lib/ocaml/ocamldec.swg +++ b/Lib/ocaml/ocamldec.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * ocamldec.swg * * Ocaml runtime code -- declarations diff --git a/Lib/ocaml/std_common.i b/Lib/ocaml/std_common.i index b2dff61d2..1c397050c 100644 --- a/Lib/ocaml/std_common.i +++ b/Lib/ocaml/std_common.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_common.i * * SWIG typemaps for STL - common utilities diff --git a/Lib/ocaml/std_deque.i b/Lib/ocaml/std_deque.i index baadb4e53..5b38962bf 100644 --- a/Lib/ocaml/std_deque.i +++ b/Lib/ocaml/std_deque.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_deque.i * * Default std_deque wrapper diff --git a/Lib/ocaml/std_list.i b/Lib/ocaml/std_list.i index 0aea90767..06181cca8 100644 --- a/Lib/ocaml/std_list.i +++ b/Lib/ocaml/std_list.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_list.i * * SWIG typemaps for std::list types diff --git a/Lib/ocaml/std_map.i b/Lib/ocaml/std_map.i index f174f2872..f202e74ed 100644 --- a/Lib/ocaml/std_map.i +++ b/Lib/ocaml/std_map.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_map.i * * SWIG typemaps for std::map diff --git a/Lib/ocaml/std_pair.i b/Lib/ocaml/std_pair.i index dc0604dc5..fe45ee676 100644 --- a/Lib/ocaml/std_pair.i +++ b/Lib/ocaml/std_pair.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_pair.i * * SWIG typemaps for std::pair diff --git a/Lib/ocaml/std_string.i b/Lib/ocaml/std_string.i index 7add3a070..e75e95304 100644 --- a/Lib/ocaml/std_string.i +++ b/Lib/ocaml/std_string.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_string.i * * SWIG typemaps for std::string diff --git a/Lib/ocaml/std_vector.i b/Lib/ocaml/std_vector.i index 91c335562..53d107447 100644 --- a/Lib/ocaml/std_vector.i +++ b/Lib/ocaml/std_vector.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_vector.i * * SWIG typemaps for std::vector types diff --git a/Lib/ocaml/stl.i b/Lib/ocaml/stl.i index 66b72e073..9d2e91eee 100644 --- a/Lib/ocaml/stl.i +++ b/Lib/ocaml/stl.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * stl.i * * Initial STL definition. extended as needed in each language diff --git a/Lib/ocaml/typecheck.i b/Lib/ocaml/typecheck.i index 51e66061b..4c3500690 100644 --- a/Lib/ocaml/typecheck.i +++ b/Lib/ocaml/typecheck.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * typecheck.i * * Typechecking rules diff --git a/Lib/ocaml/typemaps.i b/Lib/ocaml/typemaps.i index 7f978bf7f..39544de94 100644 --- a/Lib/ocaml/typemaps.i +++ b/Lib/ocaml/typemaps.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * typemaps.i * * The Ocaml module handles all types uniformly via typemaps. Here diff --git a/Lib/octave/octcontainer.swg b/Lib/octave/octcontainer.swg index afc3ed147..6613fcfff 100644 --- a/Lib/octave/octcontainer.swg +++ b/Lib/octave/octcontainer.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * octcontainer.swg * * Octave cell <-> C++ container wrapper diff --git a/Lib/octave/octiterators.swg b/Lib/octave/octiterators.swg index 926361e10..0e3fe7033 100644 --- a/Lib/octave/octiterators.swg +++ b/Lib/octave/octiterators.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * octiterators.swg * * Users can derive form the OctSwigIterator to implemet their diff --git a/Lib/perl5/perlmain.i b/Lib/perl5/perlmain.i index f224b9c75..18ecb7eb5 100644 --- a/Lib/perl5/perlmain.i +++ b/Lib/perl5/perlmain.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * perlmain.i * * Code to statically rebuild perl5. diff --git a/Lib/perl5/reference.i b/Lib/perl5/reference.i index d3d745cfc..06712bbd5 100644 --- a/Lib/perl5/reference.i +++ b/Lib/perl5/reference.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * reference.i * * Accept Perl references as pointers diff --git a/Lib/perl5/std_common.i b/Lib/perl5/std_common.i index bc25b353f..c36513912 100644 --- a/Lib/perl5/std_common.i +++ b/Lib/perl5/std_common.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_common.i * * SWIG typemaps for STL - common utilities diff --git a/Lib/perl5/std_list.i b/Lib/perl5/std_list.i index 633e40d9a..c6bca18f6 100644 --- a/Lib/perl5/std_list.i +++ b/Lib/perl5/std_list.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_list.i * * SWIG typemaps for std::list types diff --git a/Lib/perl5/std_map.i b/Lib/perl5/std_map.i index c35f21dc7..b19414597 100644 --- a/Lib/perl5/std_map.i +++ b/Lib/perl5/std_map.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_map.i * * SWIG typemaps for std::map diff --git a/Lib/perl5/std_pair.i b/Lib/perl5/std_pair.i index 78142ffa6..0712ad762 100644 --- a/Lib/perl5/std_pair.i +++ b/Lib/perl5/std_pair.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_pair.i * * SWIG typemaps for std::pair diff --git a/Lib/perl5/std_vector.i b/Lib/perl5/std_vector.i index 7c4f72919..0a61c31e0 100644 --- a/Lib/perl5/std_vector.i +++ b/Lib/perl5/std_vector.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_vector.i * * SWIG typemaps for std::vector types diff --git a/Lib/perl5/stl.i b/Lib/perl5/stl.i index 946e4b7f0..b19eae58b 100644 --- a/Lib/perl5/stl.i +++ b/Lib/perl5/stl.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * stl.i * * Initial STL definition. extended as needed in each language diff --git a/Lib/perl5/typemaps.i b/Lib/perl5/typemaps.i index fc6d8f874..7d96f2ace 100644 --- a/Lib/perl5/typemaps.i +++ b/Lib/perl5/typemaps.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * typemaps.i * * The SWIG typemap library provides a language independent mechanism for diff --git a/Lib/php/const.i b/Lib/php/const.i index 6ddd403d0..08096c98b 100644 --- a/Lib/php/const.i +++ b/Lib/php/const.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * const.i * * Typemaps for constants diff --git a/Lib/php/globalvar.i b/Lib/php/globalvar.i index df8cfade7..34bd5f994 100644 --- a/Lib/php/globalvar.i +++ b/Lib/php/globalvar.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * globalvar.i * * Global variables - add the variable to PHP diff --git a/Lib/php/php.swg b/Lib/php/php.swg index 087525be4..99181472d 100644 --- a/Lib/php/php.swg +++ b/Lib/php/php.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * php.swg * * PHP configuration file diff --git a/Lib/php/phpkw.swg b/Lib/php/phpkw.swg index 3d1a62511..e7d4f2fda 100644 --- a/Lib/php/phpkw.swg +++ b/Lib/php/phpkw.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * phpkw.swg * * The 'keywords' in PHP are global, ie, the following names are fine diff --git a/Lib/php/phprun.swg b/Lib/php/phprun.swg index 5196b95b4..22f23f729 100644 --- a/Lib/php/phprun.swg +++ b/Lib/php/phprun.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * phprun.swg * * PHP runtime library diff --git a/Lib/php/std_common.i b/Lib/php/std_common.i index a779649dd..092bf012b 100644 --- a/Lib/php/std_common.i +++ b/Lib/php/std_common.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_common.i * * SWIG typemaps for STL - common utilities diff --git a/Lib/php/std_map.i b/Lib/php/std_map.i index c6721806b..ede5fbe30 100644 --- a/Lib/php/std_map.i +++ b/Lib/php/std_map.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_map.i * * SWIG typemaps for std::map diff --git a/Lib/php/std_pair.i b/Lib/php/std_pair.i index dc0604dc5..fe45ee676 100644 --- a/Lib/php/std_pair.i +++ b/Lib/php/std_pair.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_pair.i * * SWIG typemaps for std::pair diff --git a/Lib/php/std_string.i b/Lib/php/std_string.i index 08a7cdac9..22c953bf5 100644 --- a/Lib/php/std_string.i +++ b/Lib/php/std_string.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_string.i * * SWIG typemaps for std::string types diff --git a/Lib/php/std_vector.i b/Lib/php/std_vector.i index b54181618..4cfc94f74 100644 --- a/Lib/php/std_vector.i +++ b/Lib/php/std_vector.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_vector.i * * SWIG typemaps for std::vector types diff --git a/Lib/php/stl.i b/Lib/php/stl.i index 66b72e073..9d2e91eee 100644 --- a/Lib/php/stl.i +++ b/Lib/php/stl.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * stl.i * * Initial STL definition. extended as needed in each language diff --git a/Lib/php/typemaps.i b/Lib/php/typemaps.i index 7af301d0d..7bb8c9fa3 100644 --- a/Lib/php/typemaps.i +++ b/Lib/php/typemaps.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * typemaps.i. * * SWIG Typemap library for PHP. diff --git a/Lib/pike/pike.swg b/Lib/pike/pike.swg index e72da8fba..2ba27671e 100644 --- a/Lib/pike/pike.swg +++ b/Lib/pike/pike.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * pike.swg * * Pike configuration module. diff --git a/Lib/pike/pikerun.swg b/Lib/pike/pikerun.swg index 875fcf4e2..451a4e092 100644 --- a/Lib/pike/pikerun.swg +++ b/Lib/pike/pikerun.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * pikerun.swg * * This file contains the runtime support for Pike modules diff --git a/Lib/pike/std_string.i b/Lib/pike/std_string.i index ca1fad822..0694035bf 100644 --- a/Lib/pike/std_string.i +++ b/Lib/pike/std_string.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_string.i * * SWIG typemaps for std::string diff --git a/Lib/pointer.i b/Lib/pointer.i index 16e11b7d1..8015317d7 100644 --- a/Lib/pointer.i +++ b/Lib/pointer.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * pointer.i * ----------------------------------------------------------------------------- */ diff --git a/Lib/python/ccomplex.i b/Lib/python/ccomplex.i index 30f797d74..28872b985 100644 --- a/Lib/python/ccomplex.i +++ b/Lib/python/ccomplex.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * ccomplex.i * * C complex typemaps diff --git a/Lib/python/director.swg b/Lib/python/director.swg index ba9144539..82309dbda 100644 --- a/Lib/python/director.swg +++ b/Lib/python/director.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * director.swg * * This file contains support for director classes that proxy diff --git a/Lib/python/embed15.i b/Lib/python/embed15.i index 32808b1aa..3c419b9a3 100644 --- a/Lib/python/embed15.i +++ b/Lib/python/embed15.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * embed15.i * * SWIG file embedding the Python interpreter in something else. diff --git a/Lib/python/file.i b/Lib/python/file.i index 294ab9178..359c34d2c 100644 --- a/Lib/python/file.i +++ b/Lib/python/file.i @@ -1,11 +1,7 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * file.i * * Typemaps for FILE* - * From the ideas of Luigi Ballabio * ----------------------------------------------------------------------------- */ %types(FILE *); diff --git a/Lib/python/pycontainer.swg b/Lib/python/pycontainer.swg index 7d7fdfc72..efca86cf1 100644 --- a/Lib/python/pycontainer.swg +++ b/Lib/python/pycontainer.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * pycontainer.swg * * Python sequence <-> C++ container wrapper diff --git a/Lib/python/pyiterators.swg b/Lib/python/pyiterators.swg index 301ae4cd9..966f17279 100644 --- a/Lib/python/pyiterators.swg +++ b/Lib/python/pyiterators.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * pyiterators.swg * * Implement a python 'output' iterator for Python 2.2 or higher. diff --git a/Lib/python/pyrun.swg b/Lib/python/pyrun.swg index 38632e1ab..68f5e4b48 100644 --- a/Lib/python/pyrun.swg +++ b/Lib/python/pyrun.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * pyrun.swg * * This file contains the runtime support for Python modules diff --git a/Lib/python/typemaps.i b/Lib/python/typemaps.i index 1c87de61d..5d438ecab 100644 --- a/Lib/python/typemaps.i +++ b/Lib/python/typemaps.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * typemaps.i * * Pointer handling diff --git a/Lib/ruby/director.swg b/Lib/ruby/director.swg index 9a6371ad9..60c086f5b 100644 --- a/Lib/ruby/director.swg +++ b/Lib/ruby/director.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * director.swg * * This file contains support for director classes that proxy diff --git a/Lib/ruby/rubyautodoc.swg b/Lib/ruby/rubyautodoc.swg index ade4bde1d..1e6b0d9dc 100644 --- a/Lib/ruby/rubyautodoc.swg +++ b/Lib/ruby/rubyautodoc.swg @@ -1,13 +1,8 @@ -/** - * @file rubyautodoc.swg - * @author gga - * @date Wed May 2 16:41:59 2007 - * - * @brief This file implements autodoc typemaps for some common - * ruby methods. - * - * - */ +/* ----------------------------------------------------------------------------- + * rubyautodoc.swg + * + * This file implements autodoc typemaps for some common ruby methods. + * ----------------------------------------------------------------------------- */ %define AUTODOC(func, str) %feature("autodoc", str) func; diff --git a/Lib/ruby/rubycontainer.swg b/Lib/ruby/rubycontainer.swg index 919695ec2..c93094aeb 100644 --- a/Lib/ruby/rubycontainer.swg +++ b/Lib/ruby/rubycontainer.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * rubycontainer.swg * * Ruby sequence <-> C++ container wrapper diff --git a/Lib/ruby/rubycontainer_extended.swg b/Lib/ruby/rubycontainer_extended.swg index 360e399ce..09be64aee 100644 --- a/Lib/ruby/rubycontainer_extended.swg +++ b/Lib/ruby/rubycontainer_extended.swg @@ -1,17 +1,13 @@ -/** - * @file rubycontainer_extended.swg - * @author gga - * @date Sat May 5 05:36:01 2007 - * - * @brief This file contains additional functions that make containers - * behave closer to ruby primitive types. - * However, some of these functions place some restrictions on - * the underlying object inside of the container and the iterator - * (that it has to have an == comparison function, that it has to have - * an = assignment operator, etc). - * - */ - +/* ----------------------------------------------------------------------------- + * rubycontainer_extended.swg + * + * This file contains additional functions that make containers + * behave closer to ruby primitive types. + * However, some of these functions place some restrictions on + * the underlying object inside of the container and the iterator + * (that it has to have an == comparison function, that it has to have + * an = assignment operator, etc). + * ----------------------------------------------------------------------------- */ /** * Macro used to add extend functions that require operator== in object. diff --git a/Lib/ruby/rubyiterators.swg b/Lib/ruby/rubyiterators.swg index 466ae221b..aba156a2b 100644 --- a/Lib/ruby/rubyiterators.swg +++ b/Lib/ruby/rubyiterators.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * rubyiterators.swg * * Implement a C++ 'output' iterator for Ruby. diff --git a/Lib/ruby/rubyprimtypes.swg b/Lib/ruby/rubyprimtypes.swg index c2d577995..aff35dcf1 100644 --- a/Lib/ruby/rubyprimtypes.swg +++ b/Lib/ruby/rubyprimtypes.swg @@ -1,9 +1,5 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * rubyprimtypes.swg - * * ----------------------------------------------------------------------------- */ /* ------------------------------------------------------------ * Primitive Types diff --git a/Lib/ruby/rubyrun.swg b/Lib/ruby/rubyrun.swg index 24d861d5a..ccc997a71 100644 --- a/Lib/ruby/rubyrun.swg +++ b/Lib/ruby/rubyrun.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * rubyrun.swg * * This file contains the runtime support for Ruby modules diff --git a/Lib/ruby/rubystdautodoc.swg b/Lib/ruby/rubystdautodoc.swg index ad70f7f8b..e14f65902 100644 --- a/Lib/ruby/rubystdautodoc.swg +++ b/Lib/ruby/rubystdautodoc.swg @@ -1,12 +1,8 @@ -/** - * @file rubystdautodoc.swg - * @author gga - * @date Wed May 2 17:20:39 2007 +/* ----------------------------------------------------------------------------- + * rubystdautodoc.swg * - * @brief This file contains autodocs for standard STL functions. - * - * - */ + * This file contains autodocs for standard STL functions. + * ----------------------------------------------------------------------------- */ // // For STL autodocumentation diff --git a/Lib/ruby/rubytracking.swg b/Lib/ruby/rubytracking.swg index 959d2087e..0a36f4a05 100644 --- a/Lib/ruby/rubytracking.swg +++ b/Lib/ruby/rubytracking.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * rubytracking.swg * * This file contains support for tracking mappings from diff --git a/Lib/ruby/rubywstrings.swg b/Lib/ruby/rubywstrings.swg index 862928c95..bb44fbc6e 100644 --- a/Lib/ruby/rubywstrings.swg +++ b/Lib/ruby/rubywstrings.swg @@ -1,15 +1,11 @@ -/** - * @file rubywstrings.swg - * @author - * @date Fri May 4 17:49:40 2007 - * - * @brief Currently, Ruby does not support Unicode or WChar properly, so these - * are still treated as char arrays for now. - * There are other libraries available that add support to this in - * ruby including WString, FXString, etc. - * - * - */ +/* ----------------------------------------------------------------------------- + * rubywstrings.swg + * + * Currently, Ruby does not support Unicode or WChar properly, so these + * are still treated as char arrays for now. + * There are other libraries available that add support to this in + * ruby including WString, FXString, etc. + * ----------------------------------------------------------------------------- */ /* ------------------------------------------------------------ * utility methods for wchar_t strings diff --git a/Lib/ruby/stl.i b/Lib/ruby/stl.i index 66b72e073..9d2e91eee 100644 --- a/Lib/ruby/stl.i +++ b/Lib/ruby/stl.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * stl.i * * Initial STL definition. extended as needed in each language diff --git a/Lib/ruby/typemaps.i b/Lib/ruby/typemaps.i index 2492e2e03..c4db82161 100644 --- a/Lib/ruby/typemaps.i +++ b/Lib/ruby/typemaps.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * typemaps.i * * Pointer handling diff --git a/Lib/std/_std_deque.i b/Lib/std/_std_deque.i index 026f373d6..c30523c0d 100644 --- a/Lib/std/_std_deque.i +++ b/Lib/std/_std_deque.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * _std_deque.i * * This file contains a generic definition of std::deque along with diff --git a/Lib/std_except.i b/Lib/std_except.i index af9803a62..769a68995 100644 --- a/Lib/std_except.i +++ b/Lib/std_except.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_except.i * * SWIG library file with typemaps to handle and throw STD exceptions in a diff --git a/Lib/stdint.i b/Lib/stdint.i index 7b48ca388..14fe6195e 100644 --- a/Lib/stdint.i +++ b/Lib/stdint.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * stdint.i * * SWIG library file for ISO C99 types: 7.18 Integer types diff --git a/Lib/stl.i b/Lib/stl.i index c3ade01ea..0b236afda 100644 --- a/Lib/stl.i +++ b/Lib/stl.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * stl.i * ----------------------------------------------------------------------------- */ diff --git a/Lib/swigarch.i b/Lib/swigarch.i index 260b60880..f5aea4678 100644 --- a/Lib/swigarch.i +++ b/Lib/swigarch.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * swigarch.i * * SWIG library file for 32bit/64bit code specialization and checking. diff --git a/Lib/swigrun.i b/Lib/swigrun.i index 17a140968..6026a9151 100644 --- a/Lib/swigrun.i +++ b/Lib/swigrun.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * swigrun.i * * Empty module (for now). Placeholder for runtime libs diff --git a/Lib/tcl/mactclinit.c b/Lib/tcl/mactclinit.c deleted file mode 100644 index 5dcf8e7f3..000000000 --- a/Lib/tcl/mactclinit.c +++ /dev/null @@ -1,93 +0,0 @@ -/* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * - * mactclinit.c - * ----------------------------------------------------------------------------- */ - -/* - * tclMacAppInit.c -- - * - * Provides a version of the Tcl_AppInit procedure for the example shell. - * - * Copyright (c) 1993-1994 Lockheed Missle & Space Company, AI Center - * Copyright (c) 1995-1997 Sun Microsystems, Inc. - * - * See the file "license.terms" for information on usage and redistribution - * of this file, and for a DISCLAIMER OF ALL WARRANTIES. - * - * SCCS: @(#) tclMacAppInit.c 1.17 97/01/21 18:13:34 - */ - -#include "tcl.h" -#include "tclInt.h" -#include "tclMacInt.h" - -#if defined(THINK_C) -# include -#elif defined(__MWERKS__) -# include -short InstallConsole _ANSI_ARGS_((short fd)); -#endif - - - -/* - *---------------------------------------------------------------------- - * - * MacintoshInit -- - * - * This procedure calls initalization routines to set up a simple - * console on a Macintosh. This is necessary as the Mac doesn't - * have a stdout & stderr by default. - * - * Results: - * Returns TCL_OK if everything went fine. If it didn't the - * application should probably fail. - * - * Side effects: - * Inits the appropiate console package. - * - *---------------------------------------------------------------------- - */ - -#ifdef __cplusplus -extern "C" -#endif -extern int -MacintoshInit() -{ -#if defined(THINK_C) - - /* Set options for Think C console package */ - /* The console package calls the Mac init calls */ - console_options.pause_atexit = 0; - console_options.title = "\pTcl Interpreter"; - -#elif defined(__MWERKS__) - - /* Set options for CodeWarrior SIOUX package */ - SIOUXSettings.autocloseonquit = true; - SIOUXSettings.showstatusline = true; - SIOUXSettings.asktosaveonclose = false; - InstallConsole(0); - SIOUXSetTitle("\pTcl Interpreter"); - -#elif defined(applec) - - /* Init packages used by MPW SIOW package */ - InitGraf((Ptr)&qd.thePort); - InitFonts(); - InitWindows(); - InitMenus(); - TEInit(); - InitDialogs(nil); - InitCursor(); - -#endif - - TclMacSetEventProc((TclMacConvertEventPtr) SIOUXHandleOneEvent); - - /* No problems with initialization */ - return TCL_OK; -} diff --git a/Lib/tcl/mactkinit.c b/Lib/tcl/mactkinit.c index bfe74029c..78391d445 100644 --- a/Lib/tcl/mactkinit.c +++ b/Lib/tcl/mactkinit.c @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * mactkinit.c * * This is a support file needed to build a new version of Wish. diff --git a/Lib/tcl/std_common.i b/Lib/tcl/std_common.i index 3a6f47042..0718facb8 100644 --- a/Lib/tcl/std_common.i +++ b/Lib/tcl/std_common.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_common.i * * SWIG typemaps for STL - common utilities diff --git a/Lib/tcl/std_pair.i b/Lib/tcl/std_pair.i index 52e96674f..1448d6524 100644 --- a/Lib/tcl/std_pair.i +++ b/Lib/tcl/std_pair.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_pair.i * * Typemaps for std::pair diff --git a/Lib/tcl/std_vector.i b/Lib/tcl/std_vector.i index d913f00cc..3c8dd24b7 100644 --- a/Lib/tcl/std_vector.i +++ b/Lib/tcl/std_vector.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * std_vector.i * ----------------------------------------------------------------------------- */ diff --git a/Lib/tcl/stl.i b/Lib/tcl/stl.i index afd121341..40c7584ec 100644 --- a/Lib/tcl/stl.i +++ b/Lib/tcl/stl.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * stl.i * ----------------------------------------------------------------------------- */ diff --git a/Lib/tcl/tcl8.swg b/Lib/tcl/tcl8.swg index c33cc7681..5da1bc07c 100644 --- a/Lib/tcl/tcl8.swg +++ b/Lib/tcl/tcl8.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * tcl8.swg * * Tcl configuration module. diff --git a/Lib/tcl/tclinterp.i b/Lib/tcl/tclinterp.i index 48cdb6066..3b45b6d4b 100644 --- a/Lib/tcl/tclinterp.i +++ b/Lib/tcl/tclinterp.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * tclinterp.i * * Tcl_Interp *interp diff --git a/Lib/tcl/tclopers.swg b/Lib/tcl/tclopers.swg index 26b74203d..f113ccd19 100644 --- a/Lib/tcl/tclopers.swg +++ b/Lib/tcl/tclopers.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * tclopers.swg * * C++ overloaded operators. diff --git a/Lib/tcl/tclresult.i b/Lib/tcl/tclresult.i index ca0106432..c63b3ee19 100644 --- a/Lib/tcl/tclresult.i +++ b/Lib/tcl/tclresult.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * tclresult.i * ----------------------------------------------------------------------------- */ diff --git a/Lib/tcl/tclrun.swg b/Lib/tcl/tclrun.swg index 6387fb008..eb8bd253c 100644 --- a/Lib/tcl/tclrun.swg +++ b/Lib/tcl/tclrun.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * tclrun.swg * * This file contains the runtime support for Tcl modules and includes diff --git a/Lib/tcl/tclsh.i b/Lib/tcl/tclsh.i index 2e8ed3316..160ba8d8f 100644 --- a/Lib/tcl/tclsh.i +++ b/Lib/tcl/tclsh.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * tclsh.i * * SWIG File for building new tclsh program diff --git a/Lib/tcl/tclwstrings.swg b/Lib/tcl/tclwstrings.swg index 2d344c20f..b3b682e30 100644 --- a/Lib/tcl/tclwstrings.swg +++ b/Lib/tcl/tclwstrings.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * tclwstrings.wg * * Utility methods for wchar strings diff --git a/Lib/tcl/typemaps.i b/Lib/tcl/typemaps.i index 7c9e04a8b..8bee672cc 100644 --- a/Lib/tcl/typemaps.i +++ b/Lib/tcl/typemaps.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * typemaps.i * * Swig typemap library for Tcl8. This file contains various sorts diff --git a/Lib/tcl/wish.i b/Lib/tcl/wish.i index 077ded61f..260032a81 100644 --- a/Lib/tcl/wish.i +++ b/Lib/tcl/wish.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * wish.i * * SWIG File for making wish diff --git a/Lib/typemaps/attribute.swg b/Lib/typemaps/attribute.swg index 4bc6315b7..4dcf15e2d 100644 --- a/Lib/typemaps/attribute.swg +++ b/Lib/typemaps/attribute.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * attribute.swg * * Attribute implementation diff --git a/Lib/typemaps/carrays.swg b/Lib/typemaps/carrays.swg index 27ca11779..cdeab36b7 100644 --- a/Lib/typemaps/carrays.swg +++ b/Lib/typemaps/carrays.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * carrays.swg * * This library file contains macros that can be used to manipulate simple diff --git a/Lib/typemaps/cdata.swg b/Lib/typemaps/cdata.swg index 32b3f5a77..5baf7904c 100644 --- a/Lib/typemaps/cdata.swg +++ b/Lib/typemaps/cdata.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * cdata.swg * * This library file contains macros for manipulating raw C data as strings. diff --git a/Lib/typemaps/cmalloc.swg b/Lib/typemaps/cmalloc.swg index 15f962930..45a6ab990 100644 --- a/Lib/typemaps/cmalloc.swg +++ b/Lib/typemaps/cmalloc.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * cmalloc.swg * * This library file contains macros that can be used to create objects using diff --git a/Lib/typemaps/cpointer.swg b/Lib/typemaps/cpointer.swg index ce1af169e..f797a6895 100644 --- a/Lib/typemaps/cpointer.swg +++ b/Lib/typemaps/cpointer.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * cpointer.swg * * This library file contains macros that can be used to manipulate simple diff --git a/Lib/typemaps/cstrings.swg b/Lib/typemaps/cstrings.swg index 9144da790..c60ef6496 100644 --- a/Lib/typemaps/cstrings.swg +++ b/Lib/typemaps/cstrings.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * cstrings.swg * * This file provides typemaps and macros for dealing with various forms diff --git a/Lib/typemaps/exception.swg b/Lib/typemaps/exception.swg index 17a819cd7..12c4ea658 100644 --- a/Lib/typemaps/exception.swg +++ b/Lib/typemaps/exception.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * exceptions.swg * * This SWIG library file provides language independent exception handling diff --git a/Lib/typemaps/ptrtypes.swg b/Lib/typemaps/ptrtypes.swg index 803377afe..e1bc476ed 100644 --- a/Lib/typemaps/ptrtypes.swg +++ b/Lib/typemaps/ptrtypes.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * ptrtypes.swg * * Value typemaps (Type, const Type&) for "Ptr" types, such as swig diff --git a/Lib/typemaps/swigtypemaps.swg b/Lib/typemaps/swigtypemaps.swg index 08abab028..0e39afe4c 100644 --- a/Lib/typemaps/swigtypemaps.swg +++ b/Lib/typemaps/swigtypemaps.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * swigtypemaps.swg * * Unified Typemap Library frontend diff --git a/Lib/typemaps/typemaps.swg b/Lib/typemaps/typemaps.swg index 6e7505765..4629e8dfa 100644 --- a/Lib/typemaps/typemaps.swg +++ b/Lib/typemaps/typemaps.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * typemaps.swg * * Tcl Pointer handling diff --git a/Lib/uffi/uffi.swg b/Lib/uffi/uffi.swg index 78bd23534..41b085998 100644 --- a/Lib/uffi/uffi.swg +++ b/Lib/uffi/uffi.swg @@ -27,8 +27,6 @@ typedef long size_t; %wrapper %{ -;; $Id$ - (eval-when (compile eval) ;;; You can define your own identifier converter if you want. diff --git a/Lib/wchar.i b/Lib/wchar.i index f106a3529..14de34634 100644 --- a/Lib/wchar.i +++ b/Lib/wchar.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * wchar.i * ----------------------------------------------------------------------------- */ diff --git a/Lib/windows.i b/Lib/windows.i index 08ddc2b22..2c093dacc 100644 --- a/Lib/windows.i +++ b/Lib/windows.i @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * windows.i * * SWIG library file to support types found in windows.h as well as Microsoft diff --git a/Makefile.in b/Makefile.in index 42fa935d6..cd79e1498 100644 --- a/Makefile.in +++ b/Makefile.in @@ -184,50 +184,6 @@ java.actionexample: (cd Examples/$(LANGUAGE)/java && $(MAKE) -s $(chk-set-env) $(ACTION)) \ fi; \ -gifplot-library: - @echo $(ACTION)ing Examples/GIFPlot/Lib - @cd Examples/GIFPlot/Lib && $(MAKE) -k -s $(ACTION) - -check-gifplot: \ - check-tcl-gifplot \ - check-perl5-gifplot \ - check-python-gifplot \ - check-java-gifplot \ - check-guile-gifplot \ - check-mzscheme-gifplot \ - check-ruby-gifplot \ - check-ocaml-gifplot \ - check-octave-gifplot \ - check-php-gifplot \ - check-pike-gifplot \ - check-chicken-gifplot \ -# check-lua-gifplot \ -# check-csharp-gifplot \ -# check-modula3-gifplot - -check-%-gifplot: gifplot-library - @if test -z "$(skip-$*)"; then \ - echo $* unknown; \ - exit 1; \ - fi - @passed=true; \ - up=`$(srcdir)/Tools/capitalize $*`; \ - dir="Examples/GIFPlot/$$up"; \ - if $(skip-$*); then \ - echo skipping $$up $(ACTION); \ - elif [ ! -f $$dir/check.list ]; then \ - echo skipping $$up $(ACTION) "(no $$dir/check.list)"; \ - else \ - all=`sed '/^#/d' $$dir/check.list`; \ - for a in $$all; do \ - echo $(ACTION)ing $$dir/$$a; \ - (cd $$dir/$$a && \ - $(MAKE) -k -s $(chk-set-env) $(ACTION)) \ - || passed=false; \ - done; \ - fi; \ - test $$passed = true - # Checks testcases in the test-suite excluding those which are known to be broken check-test-suite: \ check-tcl-test-suite \ @@ -277,7 +233,7 @@ partialcheck-test-suite: partialcheck-%-test-suite: @$(MAKE) -k -s check-$*-test-suite ACTION=partialcheck NOSKIP=1 -check: check-aliveness check-ccache check-examples check-gifplot check-test-suite +check: check-aliveness check-ccache check-examples check-test-suite # Run known-to-be-broken as well as not broken testcases in the test-suite all-test-suite: \ @@ -337,7 +293,7 @@ broken-%-test-suite: # CLEAN ##################################################################### -clean: clean-objects clean-libfiles clean-examples clean-gifplot clean-test-suite clean-docs +clean: clean-objects clean-libfiles clean-examples clean-test-suite clean-docs clean-objects: clean-source clean-ccache @@ -352,9 +308,6 @@ clean-libfiles: clean-examples: @$(MAKE) -k -s check-examples ACTION=clean -clean-gifplot: - @$(MAKE) -k -s check-gifplot ACTION=clean - clean-test-suite: @$(MAKE) -k -s check-test-suite ACTION=clean NOSKIP=1 @@ -364,9 +317,6 @@ clean-%-examples: clean-%-test-suite: @$(MAKE) -k -s check-$*-test-suite ACTION=clean NOSKIP=1 -clean-%-gifplot: - @$(MAKE) -k -s check-$*-gifplot ACTION=clean - clean-ccache: test -z "$(ENABLE_CCACHE)" || (cd $(CCACHE) && $(MAKE) -s clean) @@ -388,7 +338,7 @@ maintainer-clean: clean-libfiles DISTCLEAN-DEAD = config.status config.log config.cache swig.spec Makefile mkmf.log libtool -distclean: distclean-objects clean-examples clean-gifplot distclean-test-suite clean-docs distclean-dead distclean-ccache +distclean: distclean-objects clean-examples distclean-test-suite clean-docs distclean-dead distclean-ccache distclean-objects: distclean-source diff --git a/README b/README index 3df9e506a..e7b79d2d2 100644 --- a/README +++ b/README @@ -1,6 +1,6 @@ SWIG (Simplified Wrapper and Interface Generator) -Version: 1.3.40 (in progress) +Version: 2.0.0 (in progress) Tagline: SWIG is a compiler that integrates C and C++ with languages including Perl, Python, Tcl, Ruby, PHP, Java, Ocaml, Lua, @@ -13,61 +13,6 @@ the listed languages, or to extend C/C++ programs with a scripting language. This distribution represents the latest development release of SWIG. -The guilty parties working on this are: - -Active Developers: - William Fulton (wsf@fultondesigns.co.uk) (SWIG core, Java, C#, Windows, Cygwin) - Olly Betts (olly@survex.com) (PHP) - John Lenz (Guile, MzScheme updates, Chicken module, runtime system) - Mark Gossage (mark@gossage.cjb.net) (Lua) - Joseph Wang (joe@gnacademy.org) (R) - Gonzalo Garramuno (ggarra@advancedsl.com.ar) (Ruby, Ruby's UTL) - Xavier Delacour (xavier.delacour@gmail.com) (Octave) - -Major contributors include: - Dave Beazley (dave-swig@dabeaz.com) (SWIG core, Python, Tcl, Perl) - Henning Thielemann (swig@henning-thielemann.de) (Modula3) - Matthias Köppe (mkoeppe@mail.math.uni-magdeburg.de) (Guile, MzScheme) - Luigi Ballabio (luigi.ballabio@fastwebnet.it) (STL wrapping) - Mikel Bancroft (mikel@franz.com) (Allegro CL) - Surendra Singhi (efuzzyone@netscape.net) (CLISP, CFFI) - Marcelo Matus (mmatus@acms.arizona.edu) (SWIG core, Python, UTL[python,perl,tcl,ruby]) - Art Yerkes (ayerkes@speakeasy.net) (Ocaml) - Lyle Johnson (lyle@users.sourceforge.net) (Ruby) - Charlie Savage (cfis@interserv.com) (Ruby) - Thien-Thi Nguyen (ttn@glug.org) (build/test/misc) - Richard Palmer (richard@magicality.org) (PHP) - Sam Liddicott - Anonova Ltd (saml@liddicott.com) (PHP) - Tim Hockin - Sun Microsystems (thockin@sun.com) (PHP) - Kevin Ruland (PHP) - Shibukawa Yoshiki (Japanese Translation) - Jason Stewart (jason@openinformatics.com) (Perl5) - Loic Dachary (Perl5) - David Fletcher (Perl5) - Gary Holt (Perl5) - Masaki Fukushima (Ruby) - Scott Michel (scottm@cs.ucla.edu) (Java directors) - Tiger Feng (songyanf@cs.uchicago.edu) (SWIG core) - Mark Rose (mrose@stm.lbl.gov) (Directors) - Jonah Beckford (beckford@usermail.com) (CHICKEN) - Ahmon Dancy (dancy@franz.com) (Allegro CL) - Dirk Gerrits (Allegro CL) - Neil Cawse (C#) - Harco de Hilster (Java) - Alexey Dyachenko (dyachenko@fromru.com) (Tcl) - Bob Techentin (Tcl) - Martin Froehlich (Guile) - Marcio Luis Teixeira (Guile) - Duncan Temple Lang (R) - -Past contributors include: - James Michael DuPont, Clark McGrew, Dustin Mitchell, Ian Cooke, Catalin Dumitrescu, Baran - Kovuk, Oleg Tolmatcev, Tal Shalif, Lluis Padro, Chris Seatory, Igor Bely, Robin Dunn - (See CHANGES for a more complete list). - -Portions also copyrighted by companies/corporations; - Network Applied Communication Laboratory, Inc - Information-technology Promotion Agency, Japan Up-to-date SWIG related information can be found at diff --git a/Source/CParse/cparse.h b/Source/CParse/cparse.h index 9be41c60e..c17577d8c 100644 --- a/Source/CParse/cparse.h +++ b/Source/CParse/cparse.h @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * cparse.h * diff --git a/Source/CParse/cscanner.c b/Source/CParse/cscanner.c index 626958169..c5ad7b908 100644 --- a/Source/CParse/cscanner.c +++ b/Source/CParse/cscanner.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * scanner.c * diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 5645d7a8b..5b6e5511a 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * parser.y * diff --git a/Source/CParse/templ.c b/Source/CParse/templ.c index 14886605f..d3b9b3d99 100644 --- a/Source/CParse/templ.c +++ b/Source/CParse/templ.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * templ.c * diff --git a/Source/CParse/util.c b/Source/CParse/util.c index efae41051..fa934ffc0 100644 --- a/Source/CParse/util.c +++ b/Source/CParse/util.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * util.c * diff --git a/Source/DOH/base.c b/Source/DOH/base.c index 15827f328..245004f87 100644 --- a/Source/DOH/base.c +++ b/Source/DOH/base.c @@ -1,13 +1,15 @@ /* ----------------------------------------------------------------------------- + * 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. + * * base.c * * This file contains the function entry points for dispatching methods on * DOH objects. A number of small utility functions are also included. - * - * Author(s) : David Beazley (beazley@cs.uchicago.edu) - * - * Copyright (C) 1999-2000. The University of Chicago - * See the file LICENSE for information on usage and redistribution. * ----------------------------------------------------------------------------- */ char cvsroot_base_c[] = "$Id$"; diff --git a/Source/DOH/doh.h b/Source/DOH/doh.h index 766e12a34..1ed196058 100644 --- a/Source/DOH/doh.h +++ b/Source/DOH/doh.h @@ -1,14 +1,14 @@ /* ----------------------------------------------------------------------------- + * 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. + * * doh.h * * This file describes of the externally visible functions in DOH. - * - * Author(s) : David Beazley (beazley@cs.uchicago.edu) - * - * Copyright (C) 1999-2000. The University of Chicago - * See the file LICENSE for information on usage and redistribution. - * - * $Id$ * ----------------------------------------------------------------------------- */ #ifndef _DOH_H diff --git a/Source/DOH/dohint.h b/Source/DOH/dohint.h index 1fc5eb7c9..661bed075 100644 --- a/Source/DOH/dohint.h +++ b/Source/DOH/dohint.h @@ -1,15 +1,14 @@ - /* ----------------------------------------------------------------------------- + * 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. + * * dohint.h * * This file describes internally managed objects. - * - * Author(s) : David Beazley (beazley@cs.uchicago.edu) - * - * Copyright (C) 1999-2000. The University of Chicago - * See the file LICENSE for information on usage and redistribution. - * - * $Id$ * ----------------------------------------------------------------------------- */ #ifndef _DOHINT_H diff --git a/Source/DOH/file.c b/Source/DOH/file.c index 65c2336a4..a9ee332bf 100644 --- a/Source/DOH/file.c +++ b/Source/DOH/file.c @@ -1,13 +1,15 @@ /* ----------------------------------------------------------------------------- + * 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. + * * file.c * * This file implements a file-like object that can be built around an * ordinary FILE * or integer file descriptor. - * - * Author(s) : David Beazley (beazley@cs.uchicago.edu) - * - * Copyright (C) 1999-2000. The University of Chicago - * See the file LICENSE for information on usage and redistribution. * ----------------------------------------------------------------------------- */ char cvsroot_file_c[] = "$Id$"; diff --git a/Source/DOH/fio.c b/Source/DOH/fio.c index f544cee64..2ef605c32 100644 --- a/Source/DOH/fio.c +++ b/Source/DOH/fio.c @@ -1,13 +1,15 @@ /* ----------------------------------------------------------------------------- + * 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. + * * fio.c * * This file implements a number of standard I/O operations included * formatted output, readline, and splitting. - * - * Author(s) : David Beazley (beazley@cs.uchicago.edu) - * - * Copyright (C) 1999-2000. The University of Chicago - * See the file LICENSE for information on usage and redistribution. * ----------------------------------------------------------------------------- */ char cvsroot_fio_c[] = "$Id$"; diff --git a/Source/DOH/hash.c b/Source/DOH/hash.c index 045de8b5b..87f8e3c40 100644 --- a/Source/DOH/hash.c +++ b/Source/DOH/hash.c @@ -1,12 +1,14 @@ /* ----------------------------------------------------------------------------- + * 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. + * * hash.c * * Implements a simple hash table object. - * - * Author(s) : David Beazley (beazley@cs.uchicago.edu) - * - * Copyright (C) 1999-2000. The University of Chicago - * See the file LICENSE for information on usage and redistribution. * ----------------------------------------------------------------------------- */ char cvsroot_hash_c[] = "$Id$"; diff --git a/Source/DOH/list.c b/Source/DOH/list.c index 7a1786299..a08cadb5a 100644 --- a/Source/DOH/list.c +++ b/Source/DOH/list.c @@ -1,12 +1,14 @@ /* ----------------------------------------------------------------------------- + * 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. + * * list.c * * Implements a simple list object. - * - * Author(s) : David Beazley (beazley@cs.uchicago.edu) - * - * Copyright (C) 1999-2000. The University of Chicago - * See the file LICENSE for information on usage and redistribution. * ----------------------------------------------------------------------------- */ char cvsroot_list_c[] = "$Id$"; diff --git a/Source/DOH/memory.c b/Source/DOH/memory.c index 1c6063ef3..fcacd6170 100644 --- a/Source/DOH/memory.c +++ b/Source/DOH/memory.c @@ -1,13 +1,15 @@ /* ----------------------------------------------------------------------------- + * 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. + * * memory.c * * This file implements all of DOH's memory management including allocation * of objects and checking of objects. - * - * Author(s) : David Beazley (beazley@cs.uchicago.edu) - * - * Copyright (C) 1999-2000. The University of Chicago - * See the file LICENSE for information on usage and redistribution. * ----------------------------------------------------------------------------- */ char cvsroot_memory_c[] = "$Id$"; diff --git a/Source/DOH/string.c b/Source/DOH/string.c index 141cd58e8..bd36c4094 100644 --- a/Source/DOH/string.c +++ b/Source/DOH/string.c @@ -1,13 +1,15 @@ /* ----------------------------------------------------------------------------- + * 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. + * * string.c * * Implements a string object that supports both sequence operations and * file semantics. - * - * Author(s) : David Beazley (beazley@cs.uchicago.edu) - * - * Copyright (C) 1999-2000. The University of Chicago - * See the file LICENSE for information on usage and redistribution. * ----------------------------------------------------------------------------- */ char cvsroot_string_c[] = "$Id$"; diff --git a/Source/DOH/void.c b/Source/DOH/void.c index 0be01561a..2d684b9cd 100644 --- a/Source/DOH/void.c +++ b/Source/DOH/void.c @@ -1,13 +1,15 @@ /* ----------------------------------------------------------------------------- + * 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. + * * void.c * * Implements a "void" object that is really just a DOH container around * an arbitrary C object represented as a void *. - * - * Author(s) : David Beazley (beazley@cs.uchicago.edu) - * - * Copyright (C) 1999-2000. The University of Chicago - * See the file LICENSE for information on usage and redistribution. * ----------------------------------------------------------------------------- */ char cvsroot_void_c[] = "$Id$"; diff --git a/Source/Include/swigwarn.h b/Source/Include/swigwarn.h index 292aa0ba6..222fb1484 100644 --- a/Source/Include/swigwarn.h +++ b/Source/Include/swigwarn.h @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * swigwarn.h * @@ -16,8 +20,6 @@ * numbers in this file. * ----------------------------------------------------------------------------- */ -/* $Id$ */ - #ifndef SWIGWARN_H_ #define SWIGWARN_H_ diff --git a/Source/Modules/allegrocl.cxx b/Source/Modules/allegrocl.cxx index 1eb12630c..034799567 100644 --- a/Source/Modules/allegrocl.cxx +++ b/Source/Modules/allegrocl.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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 * diff --git a/Source/Modules/allocate.cxx b/Source/Modules/allocate.cxx index e8397e6a6..31f27e1eb 100644 --- a/Source/Modules/allocate.cxx +++ b/Source/Modules/allocate.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * allocate.cxx * diff --git a/Source/Modules/browser.cxx b/Source/Modules/browser.cxx index b1bc7349c..592e12783 100644 --- a/Source/Modules/browser.cxx +++ b/Source/Modules/browser.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * browser.cxx * diff --git a/Source/Modules/cffi.cxx b/Source/Modules/cffi.cxx index 0aa933c56..c8c431e47 100644 --- a/Source/Modules/cffi.cxx +++ b/Source/Modules/cffi.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * cffi.cxx * diff --git a/Source/Modules/chicken.cxx b/Source/Modules/chicken.cxx index 12ef4b454..1d9e9c620 100644 --- a/Source/Modules/chicken.cxx +++ b/Source/Modules/chicken.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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 * diff --git a/Source/Modules/clisp.cxx b/Source/Modules/clisp.cxx index fa73b3a0b..95ee66bc9 100644 --- a/Source/Modules/clisp.cxx +++ b/Source/Modules/clisp.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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 * diff --git a/Source/Modules/contract.cxx b/Source/Modules/contract.cxx index 518dc2997..7a8543928 100644 --- a/Source/Modules/contract.cxx +++ b/Source/Modules/contract.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * contract.cxx * diff --git a/Source/Modules/csharp.cxx b/Source/Modules/csharp.cxx index 05d5c72e1..34f4d69f3 100644 --- a/Source/Modules/csharp.cxx +++ b/Source/Modules/csharp.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * csharp.cxx * diff --git a/Source/Modules/directors.cxx b/Source/Modules/directors.cxx index 158b53502..6064e1758 100644 --- a/Source/Modules/directors.cxx +++ b/Source/Modules/directors.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * directors.cxx * diff --git a/Source/Modules/emit.cxx b/Source/Modules/emit.cxx index a4cf8cebc..fde3b2457 100644 --- a/Source/Modules/emit.cxx +++ b/Source/Modules/emit.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * emit.cxx * diff --git a/Source/Modules/guile.cxx b/Source/Modules/guile.cxx index 0c72de8d0..05ceced22 100644 --- a/Source/Modules/guile.cxx +++ b/Source/Modules/guile.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * guile.cxx * diff --git a/Source/Modules/java.cxx b/Source/Modules/java.cxx index 72556a04b..5135fd74e 100644 --- a/Source/Modules/java.cxx +++ b/Source/Modules/java.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * java.cxx * diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 38658ce9c..479615908 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * lang.cxx * diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 78cd7ce96..4640d9ed7 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * lua.cxx * diff --git a/Source/Modules/main.cxx b/Source/Modules/main.cxx index c824db6f9..2437b35c7 100644 --- a/Source/Modules/main.cxx +++ b/Source/Modules/main.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * main.cxx * diff --git a/Source/Modules/modula3.cxx b/Source/Modules/modula3.cxx index b3568c0bf..e650edcb2 100644 --- a/Source/Modules/modula3.cxx +++ b/Source/Modules/modula3.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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 * diff --git a/Source/Modules/module.cxx b/Source/Modules/module.cxx index 6a0d6bbb9..f4ab560dd 100644 --- a/Source/Modules/module.cxx +++ b/Source/Modules/module.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * module.cxx * diff --git a/Source/Modules/mzscheme.cxx b/Source/Modules/mzscheme.cxx index 28dd8ecd2..d17ccd33c 100644 --- a/Source/Modules/mzscheme.cxx +++ b/Source/Modules/mzscheme.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * mzscheme.cxx * diff --git a/Source/Modules/ocaml.cxx b/Source/Modules/ocaml.cxx index b925328a3..7108484b3 100644 --- a/Source/Modules/ocaml.cxx +++ b/Source/Modules/ocaml.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * ocaml.cxx * diff --git a/Source/Modules/octave.cxx b/Source/Modules/octave.cxx index 39b61e93b..7646da47d 100644 --- a/Source/Modules/octave.cxx +++ b/Source/Modules/octave.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * octave.cxx * diff --git a/Source/Modules/overload.cxx b/Source/Modules/overload.cxx index 511e55004..57d7fac90 100644 --- a/Source/Modules/overload.cxx +++ b/Source/Modules/overload.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * overload.cxx * diff --git a/Source/Modules/perl5.cxx b/Source/Modules/perl5.cxx index eace179a7..d0c019195 100644 --- a/Source/Modules/perl5.cxx +++ b/Source/Modules/perl5.cxx @@ -1,10 +1,10 @@ -/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*- - * vim:expandtab:shiftwidth=2:tabstop=8:smarttab: - */ - /* ---------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * perl5.cxx * diff --git a/Source/Modules/php.cxx b/Source/Modules/php.cxx index ee69c1864..9f91f12d4 100644 --- a/Source/Modules/php.cxx +++ b/Source/Modules/php.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * php.cxx * diff --git a/Source/Modules/pike.cxx b/Source/Modules/pike.cxx index 98f63056c..e59248e95 100644 --- a/Source/Modules/pike.cxx +++ b/Source/Modules/pike.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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 * diff --git a/Source/Modules/python.cxx b/Source/Modules/python.cxx index bd22e79a6..546ab9ec5 100644 --- a/Source/Modules/python.cxx +++ b/Source/Modules/python.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * python.cxx * diff --git a/Source/Modules/r.cxx b/Source/Modules/r.cxx index 8e9aa557d..f1fdff662 100644 --- a/Source/Modules/r.cxx +++ b/Source/Modules/r.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * r.cxx * diff --git a/Source/Modules/ruby.cxx b/Source/Modules/ruby.cxx index 1c13747e5..9badc0d0a 100644 --- a/Source/Modules/ruby.cxx +++ b/Source/Modules/ruby.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * ruby.cxx * diff --git a/Source/Modules/s-exp.cxx b/Source/Modules/s-exp.cxx index 90791ec70..62b93f7c7 100644 --- a/Source/Modules/s-exp.cxx +++ b/Source/Modules/s-exp.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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 * diff --git a/Source/Modules/swigmain.cxx b/Source/Modules/swigmain.cxx index 4208a8c6f..374d08e5a 100644 --- a/Source/Modules/swigmain.cxx +++ b/Source/Modules/swigmain.cxx @@ -1,11 +1,15 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * - * Simplified Wrapper and Interface Generator (SWIG) + * 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. * * swigmain.cxx * + * Simplified Wrapper and Interface Generator (SWIG) + * * This file is the main entry point to SWIG. It collects the command * line options, registers built-in language modules, and instantiates * a module for code generation. If adding new language modules diff --git a/Source/Modules/swigmod.h b/Source/Modules/swigmod.h index 8dec8d0af..075a209d2 100644 --- a/Source/Modules/swigmod.h +++ b/Source/Modules/swigmod.h @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * swigmod.h * diff --git a/Source/Modules/tcl8.cxx b/Source/Modules/tcl8.cxx index 015ac5e45..efbe28c50 100644 --- a/Source/Modules/tcl8.cxx +++ b/Source/Modules/tcl8.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * tcl8.cxx * diff --git a/Source/Modules/typepass.cxx b/Source/Modules/typepass.cxx index d663aed6e..e972cea05 100644 --- a/Source/Modules/typepass.cxx +++ b/Source/Modules/typepass.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * typepass.cxx * diff --git a/Source/Modules/uffi.cxx b/Source/Modules/uffi.cxx index d3f8401f0..f793b5643 100644 --- a/Source/Modules/uffi.cxx +++ b/Source/Modules/uffi.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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 * diff --git a/Source/Modules/utils.cxx b/Source/Modules/utils.cxx index bf8211903..3fe7a2709 100644 --- a/Source/Modules/utils.cxx +++ b/Source/Modules/utils.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * utils.cxx * diff --git a/Source/Modules/xml.cxx b/Source/Modules/xml.cxx index 2edd01cf0..bcfac1acc 100644 --- a/Source/Modules/xml.cxx +++ b/Source/Modules/xml.cxx @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * xml.cxx * diff --git a/Source/Preprocessor/cpp.c b/Source/Preprocessor/cpp.c index 81646171a..bcb1061c8 100644 --- a/Source/Preprocessor/cpp.c +++ b/Source/Preprocessor/cpp.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * cpp.c * diff --git a/Source/Preprocessor/expr.c b/Source/Preprocessor/expr.c index 4da24a774..3e3f39480 100644 --- a/Source/Preprocessor/expr.c +++ b/Source/Preprocessor/expr.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * expr.c * diff --git a/Source/Preprocessor/preprocessor.h b/Source/Preprocessor/preprocessor.h index 3579eede2..8f98dae15 100644 --- a/Source/Preprocessor/preprocessor.h +++ b/Source/Preprocessor/preprocessor.h @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * preprocessor.h * diff --git a/Source/Swig/cwrap.c b/Source/Swig/cwrap.c index 7c6837a2b..208842121 100644 --- a/Source/Swig/cwrap.c +++ b/Source/Swig/cwrap.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * cwrap.c * diff --git a/Source/Swig/deprecate.c b/Source/Swig/deprecate.c index 475d2c6cf..f25b9a650 100644 --- a/Source/Swig/deprecate.c +++ b/Source/Swig/deprecate.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * deprecate.c * diff --git a/Source/Swig/error.c b/Source/Swig/error.c index 156fe06a7..80eede4e3 100644 --- a/Source/Swig/error.c +++ b/Source/Swig/error.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * error.c * diff --git a/Source/Swig/fragment.c b/Source/Swig/fragment.c index 510a01875..896461b30 100644 --- a/Source/Swig/fragment.c +++ b/Source/Swig/fragment.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * fragment.c * diff --git a/Source/Swig/getopt.c b/Source/Swig/getopt.c index cbd051d9f..f6f196bfd 100644 --- a/Source/Swig/getopt.c +++ b/Source/Swig/getopt.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * getopt.c * diff --git a/Source/Swig/include.c b/Source/Swig/include.c index f42eb5d45..710a7ad71 100644 --- a/Source/Swig/include.c +++ b/Source/Swig/include.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * include.c * diff --git a/Source/Swig/misc.c b/Source/Swig/misc.c index 050e5357a..3a78fe7ab 100644 --- a/Source/Swig/misc.c +++ b/Source/Swig/misc.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * misc.c * diff --git a/Source/Swig/naming.c b/Source/Swig/naming.c index 013ce5929..9af0354e2 100644 --- a/Source/Swig/naming.c +++ b/Source/Swig/naming.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * naming.c * diff --git a/Source/Swig/parms.c b/Source/Swig/parms.c index 9b58f5fcb..cb8176377 100644 --- a/Source/Swig/parms.c +++ b/Source/Swig/parms.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * parms.c * diff --git a/Source/Swig/scanner.c b/Source/Swig/scanner.c index 5dc2a091b..3f9f63a0f 100644 --- a/Source/Swig/scanner.c +++ b/Source/Swig/scanner.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * scanner.c * diff --git a/Source/Swig/stype.c b/Source/Swig/stype.c index 3b56e98cb..69919ad55 100644 --- a/Source/Swig/stype.c +++ b/Source/Swig/stype.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * stype.c * diff --git a/Source/Swig/swig.h b/Source/Swig/swig.h index 7eb9ef210..428bcf06d 100644 --- a/Source/Swig/swig.h +++ b/Source/Swig/swig.h @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * swig.h * diff --git a/Source/Swig/swigfile.h b/Source/Swig/swigfile.h index 92c7945e6..632e821e2 100644 --- a/Source/Swig/swigfile.h +++ b/Source/Swig/swigfile.h @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * swigfile.h * diff --git a/Source/Swig/swigopt.h b/Source/Swig/swigopt.h index 11eb5ba99..586f8bbc4 100644 --- a/Source/Swig/swigopt.h +++ b/Source/Swig/swigopt.h @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * swigopt.h * diff --git a/Source/Swig/swigparm.h b/Source/Swig/swigparm.h index 49ae7992e..3e6269eae 100644 --- a/Source/Swig/swigparm.h +++ b/Source/Swig/swigparm.h @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * swigparm.h * diff --git a/Source/Swig/swigscan.h b/Source/Swig/swigscan.h index 3403098df..faec4fe48 100644 --- a/Source/Swig/swigscan.h +++ b/Source/Swig/swigscan.h @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * swigscan.h * diff --git a/Source/Swig/swigtree.h b/Source/Swig/swigtree.h index 5b43006a9..6799398c9 100644 --- a/Source/Swig/swigtree.h +++ b/Source/Swig/swigtree.h @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * swigtree.h * diff --git a/Source/Swig/swigwrap.h b/Source/Swig/swigwrap.h index 0dcf88059..b1f596f72 100644 --- a/Source/Swig/swigwrap.h +++ b/Source/Swig/swigwrap.h @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * swigwrap.h * diff --git a/Source/Swig/symbol.c b/Source/Swig/symbol.c index 055af854f..50dde9159 100644 --- a/Source/Swig/symbol.c +++ b/Source/Swig/symbol.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * symbol.c * diff --git a/Source/Swig/tree.c b/Source/Swig/tree.c index 14d231afa..c80c61081 100644 --- a/Source/Swig/tree.c +++ b/Source/Swig/tree.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * tree.c * diff --git a/Source/Swig/typemap.c b/Source/Swig/typemap.c index 401a99801..a44ecdf6d 100644 --- a/Source/Swig/typemap.c +++ b/Source/Swig/typemap.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * typemap.c * diff --git a/Source/Swig/typeobj.c b/Source/Swig/typeobj.c index 8ff31bc0b..cafecb9a6 100644 --- a/Source/Swig/typeobj.c +++ b/Source/Swig/typeobj.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * typeobj.c * diff --git a/Source/Swig/typesys.c b/Source/Swig/typesys.c index 9b11a08e5..19f14a2a0 100644 --- a/Source/Swig/typesys.c +++ b/Source/Swig/typesys.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * typesys.c * diff --git a/Source/Swig/wrapfunc.c b/Source/Swig/wrapfunc.c index 11518bfc2..2c9f7c86a 100644 --- a/Source/Swig/wrapfunc.c +++ b/Source/Swig/wrapfunc.c @@ -1,6 +1,10 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * 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. * * wrapfunc.c * diff --git a/configure.in b/configure.in index b64bc860a..cf0418220 100644 --- a/configure.in +++ b/configure.in @@ -2,7 +2,7 @@ dnl Process this file with autoconf to produce a configure script. dnl The macros which aren't shipped with the autotools are stored in the dnl Tools/config directory in .m4 files. -AC_INIT([swig],[1.3.40],[http://www.swig.org]) +AC_INIT([swig],[2.0.0],[http://www.swig.org]) AC_PREREQ(2.58) AC_CONFIG_SRCDIR([Source/Swig/swig.h]) AC_CONFIG_AUX_DIR([Tools/config]) @@ -2169,8 +2169,6 @@ AC_CONFIG_FILES([ \ Examples/Makefile \ Examples/guile/Makefile \ Examples/xml/Makefile \ - Examples/GIFPlot/Makefile \ - Examples/GIFPlot/Lib/Makefile \ Examples/test-suite/chicken/Makefile \ Examples/test-suite/csharp/Makefile \ Examples/test-suite/guile/Makefile \ From 30afaae7df8756f1bc3a398e685b7ff2625c4e25 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 6 Mar 2010 12:06:22 +0000 Subject: [PATCH 049/481] Add new GPL license headers to all source files in this branch git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@11914 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/Swig/warn.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Source/Swig/warn.c b/Source/Swig/warn.c index a8dadc70b..dfb2e4af4 100644 --- a/Source/Swig/warn.c +++ b/Source/Swig/warn.c @@ -1,6 +1,10 @@ -/* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. +/* ----------------------------------------------------------------------------- + * 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. * * warn.c * From 1f0cb53d5bb3f018d4f5393c63a225faed918da7 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 4 Jun 2010 21:57:58 +0000 Subject: [PATCH 050/481] minor warning message changes git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@12101 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/CParse/parser.y | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 5b6e5511a..b9749bf01 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -2749,7 +2749,7 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va p = tp; def_supplied = 1; } else if (p && !tp) { /* Variadic template - tp < p */ - Swig_warning(WARN_LANG_NATIVE_UNIMPL,cparse_file, cparse_line,"Only the first variadic argument is currently supported by Swig.\n"); + Swig_warning(WARN_LANG_NATIVE_UNIMPL,cparse_file, cparse_line,"Only the first variadic template argument is currently supported.\n"); break; } } @@ -2945,9 +2945,9 @@ c_declaration : c_decl { appendChild($$,firstChild($5)); } } - | c_lambda_decl { Swig_warning(WARN_LANG_NATIVE_UNIMPL, cparse_file, cparse_line,"Swig doesn't produce wrapper code for lambda expressions and closures yet.\n"); $$ = $1; } - | USING idcolon EQUAL { skip_decl(); Swig_warning(WARN_LANG_NATIVE_UNIMPL, cparse_file, cparse_line,"Swig doesn't support 'using' typedefs yet.\n"); $$ = 0; } - | TEMPLATE LESSTHAN template_parms GREATERTHAN USING idcolon EQUAL { skip_decl(); Swig_warning(WARN_LANG_NATIVE_UNIMPL, cparse_file, cparse_line,"Swig doesn't support template aliasing yet.\n"); $$ = 0; } + | c_lambda_decl { Swig_warning(WARN_LANG_NATIVE_UNIMPL, cparse_file, cparse_line,"SWIG doesn't produce wrapper code for lambda expressions and closures yet.\n"); $$ = $1; } + | USING idcolon EQUAL { skip_decl(); Swig_warning(WARN_LANG_NATIVE_UNIMPL, cparse_file, cparse_line,"SWIG doesn't support 'using' typedefs yet.\n"); $$ = 0; } + | TEMPLATE LESSTHAN template_parms GREATERTHAN USING idcolon EQUAL { skip_decl(); Swig_warning(WARN_LANG_NATIVE_UNIMPL, cparse_file, cparse_line,"SWIG doesn't support template aliasing yet.\n"); $$ = 0; } ; /* ------------------------------------------------------------ From d52ef3191132cc933a7f2d46e244c7ab83ade8c9 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 25 Jun 2010 21:46:57 +0000 Subject: [PATCH 051/481] typo fix git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@12150 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Doc/Manual/Cpp0x.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html index 4466e6cfd..83b54414b 100644 --- a/Doc/Manual/Cpp0x.html +++ b/Doc/Manual/Cpp0x.html @@ -129,7 +129,7 @@ public:

Constructors using the std::initializer_list class are removed from the wrapped class, because the only way to access such a constructor is at compile time using the "= {}" assignment.

-

User should add another constructor with specific arguments +

Users should add another constructor with specific arguments filling the class members manually.

For now, if a user wants to fill the class components like this:

From da182a09f5f40108cd02e8d44490f315bd58b683 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 25 Jun 2010 21:48:07 +0000 Subject: [PATCH 052/481] add in more raw string literals for gcc-4.5 git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@12151 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .../test-suite/cpp0x_raw_string_literals.i | 54 +++++++++++++------ 1 file changed, 37 insertions(+), 17 deletions(-) diff --git a/Examples/test-suite/cpp0x_raw_string_literals.i b/Examples/test-suite/cpp0x_raw_string_literals.i index 1e8515504..f5e804b78 100644 --- a/Examples/test-suite/cpp0x_raw_string_literals.i +++ b/Examples/test-suite/cpp0x_raw_string_literals.i @@ -8,8 +8,14 @@ This module also tests whether Swig correctly parses custom string delimiters. */ %module cpp0x_raw_string_literals -%warnfilter(454) c; -%warnfilter(454) d; +%warnfilter(SWIGWARN_TYPEMAP_CHARLEAK_MSG) aa; +%warnfilter(SWIGWARN_TYPEMAP_CHARLEAK_MSG) bb; +%warnfilter(SWIGWARN_TYPEMAP_CHARLEAK_MSG) ee; +%warnfilter(SWIGWARN_TYPEMAP_CHARLEAK_MSG) ff; +%warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK_MSG) cc; +%warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK_MSG) dd; +%warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK_MSG) gg; +%warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK_MSG) hh; %inline %{ #include @@ -20,25 +26,39 @@ using namespace std; int L = 100; int u8 = 100; int u = 100; -int U = 100; +struct UStruct { + static const int U = 100; +}; int R = 100; int LR = 100; int u8R = 100; int uR = 100; -int UR = 100; +struct URStruct { + static const int UR = 100; +}; -char *a = "ABC"; -wstring wide = L"ABC"; -//char *b = u8"ABC"; // not supported by GCC -char16_t *c = u"ABC"; -char32_t *d = U"ABC"; - -/* Raw string literals are not supported by GCC yet */ -/*char *e = R"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX"; -wstring wide2 = LR"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX"; -char *f = u8R"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX"; -char16_t *g = uR"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX"; -char32_t *h = UR"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX"; -*/ +const char *aa = "ABC"; +wstring wide = L"ABC"; +const char *bb = u8"ABC"; +const char16_t *cc = u"ABC"; +const char32_t *dd = U"ABC"; %} + +/* Raw string literals */ + +#warning TODO: change SWIG support from old R"[ ... ]" to new R"( ... )" + +const char *ee = R"XXX[to be or "not" to be [square parenthesis] (round parenthesis), that is the question!]XXX"; +wstring wide2 = LR"XXX[to be or "not" to be [square parenthesis] (round parenthesis), that is the question!]XXX"; +const char *ff = u8R"XXX[to be or "not" to be [square parenthesis] (round parenthesis), that is the question!]XXX"; +const char16_t *gg = uR"XXX[to be or "not" to be [square parenthesis] (round parenthesis), that is the question!]XXX"; +const char32_t *hh = UR"XXX[to be or "not" to be [square parenthesis] (round parenthesis), that is the question!]XXX"; +%{ +const char *ee = R"XXX(to be or "not" to be [square parenthesis] (round parenthesis), that is the question!)XXX"; +wstring wide2 = LR"XXX(to be or "not" to be [square parenthesis] (round parenthesis), that is the question!)XXX"; +const char *ff = u8R"XXX(to be or "not" to be [square parenthesis] (round parenthesis), that is the question!)XXX"; +const char16_t *gg = uR"XXX(to be or "not" to be [square parenthesis] (round parenthesis), that is the question!)XXX"; +const char32_t *hh = UR"XXX(to be or "not" to be [square parenthesis] (round parenthesis), that is the question!)XXX"; +%} + From adffcd60e1dae33d6d4ff36998eaf0412cbd80e1 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 25 Jun 2010 22:54:45 +0000 Subject: [PATCH 053/481] Raw string literal changes in paper N3077 changes delimiters to use round brackets instead of square brackets git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@12152 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Doc/Manual/Cpp0x.html | 25 +++++----- .../test-suite/cpp0x_raw_string_literals.i | 39 +++++++-------- .../python/cpp0x_raw_string_literals_runme.py | 50 +++++++++++++++++++ Source/Swig/scanner.c | 8 +-- 4 files changed, 83 insertions(+), 39 deletions(-) create mode 100644 Examples/test-suite/python/cpp0x_raw_string_literals_runme.py diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html index 83b54414b..b89b74ad0 100644 --- a/Doc/Manual/Cpp0x.html +++ b/Doc/Manual/Cpp0x.html @@ -460,23 +460,22 @@ arguments defined in the original template<> block:

7.2.18 New string literals

-

SWIG fully supports custom delimiters and unicode string -constants.

+

SWIG fully supports unicode string constants and raw string literals.

 // New string literals
-char      *a = "ABC";
-wstring wide = L"ABC";
-char      *b = u8"ABC";
-char16_t  *c = u"ABC";
-char32_t  *d = U"ABC";
+wstring         aa =  L"Wide string";
+const char     *bb = u8"UTF-8 string";
+const char16_t *cc =  u"UTF-16 string";
+const char32_t *dd =  U"UTF-32 string";
 
-// Custom String delimiter
-char       *e = R"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX";
-wstring wide2 = LR"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX";
-char       *f = u8R"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX";
-char16_t   *g = uR"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX";
-char32_t   *h = UR"XXX[to be or "not" to be [these are parenthesis], this is the question!]XXX";
+// Raw string literals
+const char      *xx =        ")I'm an \"ascii\" \\ string.";
+const char      *ee =   R"XXX()I'm an "ascii" \ string.)XXX"; // same as xx
+wstring          ff =  LR"XXX(I'm a "raw wide" \ string.)XXX";
+const char      *gg = u8R"XXX(I'm a "raw UTF-8" \ string.)XXX";
+const char16_t  *hh =  uR"XXX(I'm a "raw UTF-16" \ string.)XXX";
+const char32_t  *ii =  UR"XXX(I'm a "raw UTF-32" \ string.)XXX";
 

Note: SWIG currently incorrectly parses the odd number of double quotes diff --git a/Examples/test-suite/cpp0x_raw_string_literals.i b/Examples/test-suite/cpp0x_raw_string_literals.i index f5e804b78..612b2baea 100644 --- a/Examples/test-suite/cpp0x_raw_string_literals.i +++ b/Examples/test-suite/cpp0x_raw_string_literals.i @@ -8,14 +8,16 @@ This module also tests whether Swig correctly parses custom string delimiters. */ %module cpp0x_raw_string_literals -%warnfilter(SWIGWARN_TYPEMAP_CHARLEAK_MSG) aa; %warnfilter(SWIGWARN_TYPEMAP_CHARLEAK_MSG) bb; %warnfilter(SWIGWARN_TYPEMAP_CHARLEAK_MSG) ee; -%warnfilter(SWIGWARN_TYPEMAP_CHARLEAK_MSG) ff; +%warnfilter(SWIGWARN_TYPEMAP_CHARLEAK_MSG) gg; +%warnfilter(SWIGWARN_TYPEMAP_CHARLEAK_MSG) xx; %warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK_MSG) cc; %warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK_MSG) dd; -%warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK_MSG) gg; %warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK_MSG) hh; +%warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK_MSG) ii; + +%include %inline %{ #include @@ -38,27 +40,20 @@ struct URStruct { static const int UR = 100; }; -const char *aa = "ABC"; -wstring wide = L"ABC"; -const char *bb = u8"ABC"; -const char16_t *cc = u"ABC"; -const char32_t *dd = U"ABC"; +// New string literals +wstring aa = L"Wide string"; +const char *bb = u8"UTF-8 string"; +const char16_t *cc = u"UTF-16 string"; +const char32_t *dd = U"UTF-32 string"; %} /* Raw string literals */ - -#warning TODO: change SWIG support from old R"[ ... ]" to new R"( ... )" - -const char *ee = R"XXX[to be or "not" to be [square parenthesis] (round parenthesis), that is the question!]XXX"; -wstring wide2 = LR"XXX[to be or "not" to be [square parenthesis] (round parenthesis), that is the question!]XXX"; -const char *ff = u8R"XXX[to be or "not" to be [square parenthesis] (round parenthesis), that is the question!]XXX"; -const char16_t *gg = uR"XXX[to be or "not" to be [square parenthesis] (round parenthesis), that is the question!]XXX"; -const char32_t *hh = UR"XXX[to be or "not" to be [square parenthesis] (round parenthesis), that is the question!]XXX"; -%{ -const char *ee = R"XXX(to be or "not" to be [square parenthesis] (round parenthesis), that is the question!)XXX"; -wstring wide2 = LR"XXX(to be or "not" to be [square parenthesis] (round parenthesis), that is the question!)XXX"; -const char *ff = u8R"XXX(to be or "not" to be [square parenthesis] (round parenthesis), that is the question!)XXX"; -const char16_t *gg = uR"XXX(to be or "not" to be [square parenthesis] (round parenthesis), that is the question!)XXX"; -const char32_t *hh = UR"XXX(to be or "not" to be [square parenthesis] (round parenthesis), that is the question!)XXX"; +%inline %{ +const char *xx = ")I'm an \"ascii\" \\ string."; +const char *ee = R"XXX()I'm an "ascii" \ string.)XXX"; +wstring ff = LR"XXX(I'm a "raw wide" \ string.)XXX"; +const char *gg = u8R"XXX(I'm a "raw UTF-8" \ string.)XXX"; +const char16_t *hh = uR"XXX(I'm a "raw UTF-16" \ string.)XXX"; +const char32_t *ii = UR"XXX(I'm a "raw UTF-32" \ string.)XXX"; %} diff --git a/Examples/test-suite/python/cpp0x_raw_string_literals_runme.py b/Examples/test-suite/python/cpp0x_raw_string_literals_runme.py new file mode 100644 index 000000000..ea7d16550 --- /dev/null +++ b/Examples/test-suite/python/cpp0x_raw_string_literals_runme.py @@ -0,0 +1,50 @@ +from cpp0x_raw_string_literals import * + +if cvar.L != 100: + raise RuntimeError + +if cvar.u8 != 100: + raise RuntimeError + +if cvar.u != 100: + raise RuntimeError + +if UStruct.U != 100: + raise RuntimeError + + +if cvar.R != 100: + raise RuntimeError + +if cvar.LR != 100: + raise RuntimeError + +if cvar.u8R != 100: + raise RuntimeError + +if cvar.uR != 100: + raise RuntimeError + +if URStruct.UR != 100: + raise RuntimeError + + +if cvar.aa != "Wide string": + raise RuntimeError + +if cvar.bb != "UTF-8 string": + raise RuntimeError, cvar.wide + +if cvar.xx != ")I'm an \"ascii\" \\ string.": + raise RuntimeError, cvar.xx + +if cvar.ee != ")I'm an \"ascii\" \\ string.": + raise RuntimeError, cvar.ee + +if cvar.ff != "I'm a \"raw wide\" \\ string.": + raise RuntimeError, cvar.ff + +if cvar.gg != "I'm a \"raw UTF-8\" \\ string.": + raise RuntimeError, cvar.gg + + diff --git a/Source/Swig/scanner.c b/Source/Swig/scanner.c index 3f9f63a0f..ed849bf4d 100644 --- a/Source/Swig/scanner.c +++ b/Source/Swig/scanner.c @@ -673,7 +673,7 @@ static int look(Scanner * s) { Swig_error(cparse_file, cparse_start_line, "Unterminated string\n"); return SWIG_TOKEN_ERROR; } - else if (c == '[') { + else if (c == '(') { state = 20; } else { @@ -698,8 +698,8 @@ static int look(Scanner * s) { Delitem(s->text, DOH_END); get_escape(s); } - } else { /* Custom delimiter string: R"XXXX[value]XXXX" */ - if (c==']') { + } else { /* Custom delimiter string: R"XXXX(value)XXXX" */ + if (c==')') { int i=0; String *end_delimiter = NewStringEmpty(); while ((c = nextchar(s)) != 0 && c!='\"') { @@ -710,7 +710,7 @@ static int look(Scanner * s) { } if (Strcmp( str_delimiter, end_delimiter )==0) { - Delete( end_delimiter ); /* Correct end delimiter ]XXXX" occured */ + Delete( end_delimiter ); /* Correct end delimiter )XXXX" occured */ Delete( str_delimiter ); str_delimiter = 0; return SWIG_TOKEN_STRING; From 8e779193bf8723b5c19a1aacbac6054ddcb7bacc Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 26 Jun 2010 22:43:21 +0000 Subject: [PATCH 054/481] Warning suppression for explicit template instantiations git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@12153 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/cpp0x_template_explicit.i | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Examples/test-suite/cpp0x_template_explicit.i b/Examples/test-suite/cpp0x_template_explicit.i index f05bcf850..644a03e89 100644 --- a/Examples/test-suite/cpp0x_template_explicit.i +++ b/Examples/test-suite/cpp0x_template_explicit.i @@ -3,16 +3,16 @@ using the translation unit). */ %module cpp0x_template_explicit -%warnfilter(320) std::vector; -%warnfilter(320) std::vector; + +#pragma SWIG nowarn=SWIGWARN_PARSE_EXPLICIT_TEMPLATE %inline %{ #include class A { public: - int member; - int memberFunction() { return 100; } + int member; + int memberFunction() { return 100; } }; template class std::vector; From c3b48505e2920d0b3b0c6235af4db66e5668fa39 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 26 Jun 2010 22:48:49 +0000 Subject: [PATCH 055/481] simple formatting changes git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@12154 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .../cpp0x_alternate_function_syntax.i | 2 +- Examples/test-suite/cpp0x_constexpr.i | 4 +-- Examples/test-suite/cpp0x_constructors.i | 24 +++++++-------- Examples/test-suite/cpp0x_decltype.i | 28 ++++++++--------- Examples/test-suite/cpp0x_default_delete.i | 10 +++---- .../cpp0x_explicit_conversion_operators.i | 18 +++++------ Examples/test-suite/cpp0x_function_objects.i | 2 +- Examples/test-suite/cpp0x_hash_tables.i | 24 +++++++-------- Examples/test-suite/cpp0x_initializer_list.i | 6 ++-- Examples/test-suite/cpp0x_lambda_functions.i | 30 +++++++++---------- .../test-suite/cpp0x_null_pointer_constant.i | 8 ++--- .../test-suite/cpp0x_raw_string_literals.i | 4 +-- Examples/test-suite/cpp0x_result_of.i | 6 ++-- Examples/test-suite/cpp0x_rvalue_reference.i | 20 ++++++------- Examples/test-suite/cpp0x_sizeof_object.i | 10 +++---- Examples/test-suite/cpp0x_smart_pointers.i | 2 +- Examples/test-suite/cpp0x_static_assert.i | 6 ++-- .../cpp0x_strongly_typed_enumerations.i | 2 +- .../cpp0x_template_double_brackets.i | 18 +++++------ Examples/test-suite/cpp0x_template_explicit.i | 2 +- Examples/test-suite/cpp0x_template_typedefs.i | 8 ++--- Examples/test-suite/cpp0x_thread_local.i | 4 +-- .../test-suite/cpp0x_uniform_initialization.i | 2 +- .../test-suite/cpp0x_unrestricted_unions.i | 2 +- .../test-suite/cpp0x_userdefined_literals.i | 6 ++-- .../test-suite/cpp0x_variadic_templates.i | 20 ++++++------- 26 files changed, 134 insertions(+), 134 deletions(-) diff --git a/Examples/test-suite/cpp0x_alternate_function_syntax.i b/Examples/test-suite/cpp0x_alternate_function_syntax.i index d8d0ec6c4..6726dad7c 100644 --- a/Examples/test-suite/cpp0x_alternate_function_syntax.i +++ b/Examples/test-suite/cpp0x_alternate_function_syntax.i @@ -1,4 +1,4 @@ -/* This testcase checks whether Swig correctly uses the new alternate functions +/* This testcase checks whether SWIG correctly uses the new alternate functions declarations and definitions introduced in C++0x. */ %module cpp0x_alternate_function_syntax diff --git a/Examples/test-suite/cpp0x_constexpr.i b/Examples/test-suite/cpp0x_constexpr.i index 6cae41825..ae1d292b4 100644 --- a/Examples/test-suite/cpp0x_constexpr.i +++ b/Examples/test-suite/cpp0x_constexpr.i @@ -1,4 +1,4 @@ -/* This interface tests whether Swig supports the new "constexpr" keyword +/* This interface tests whether SWIG supports the new "constexpr" keyword introduced by C++0x. */ %module cpp0x_constexpr @@ -6,7 +6,7 @@ %inline %{ class TestClass { public: - constexpr int func() { return 10; } + constexpr int func() { return 10; } }; %} diff --git a/Examples/test-suite/cpp0x_constructors.i b/Examples/test-suite/cpp0x_constructors.i index 47f030a95..2077efe0c 100644 --- a/Examples/test-suite/cpp0x_constructors.i +++ b/Examples/test-suite/cpp0x_constructors.i @@ -1,4 +1,4 @@ -/* This test checks whether Swig correctly parses the new delegating +/* This test checks whether SWIG correctly parses the new delegating constructors and constructor inheritance. */ %module cpp0x_constructors @@ -6,25 +6,25 @@ %inline %{ class BaseClass { private: - int _val; + int _val; public: - BaseClass(int iValue) { _val = iValue; } + BaseClass(int iValue) { _val = iValue; } }; class DerivedClass: public BaseClass { public: - using BaseClass::BaseClass; // Adds DerivedClass(int) constructor + using BaseClass::BaseClass; // Adds DerivedClass(int) constructor }; class A { public: - int a; - int b; - int c; - - A() : A( 10 ) {} - A(int aa) : A(aa, 20) {} - A(int aa, int bb) : A(aa, bb, 30) {} - A(int aa, int bb, int cc) { a=aa; b=bb; c=cc; } + int a; + int b; + int c; + + A() : A( 10 ) {} + A(int aa) : A(aa, 20) {} + A(int aa, int bb) : A(aa, bb, 30) {} + A(int aa, int bb, int cc) { a=aa; b=bb; c=cc; } }; %} diff --git a/Examples/test-suite/cpp0x_decltype.i b/Examples/test-suite/cpp0x_decltype.i index 316c38962..5a4292454 100644 --- a/Examples/test-suite/cpp0x_decltype.i +++ b/Examples/test-suite/cpp0x_decltype.i @@ -1,19 +1,19 @@ -/* This testcase checks whether Swig correctly uses the new 'decltype()' +/* This testcase checks whether SWIG correctly uses the new 'decltype()' introduced in C++0x. */ %module cpp0x_decltype %inline %{ -class A { -public: - int i; - decltype(i) j; - - auto foo( decltype(i) a ) -> decltype(i) { - if (a==5) - return 10; - else - return 0; - } -}; -%} + class A { + public: + int i; + decltype(i) j; + + auto foo( decltype(i) a ) -> decltype(i) { + if (a==5) + return 10; + else + return 0; + } + }; + %} diff --git a/Examples/test-suite/cpp0x_default_delete.i b/Examples/test-suite/cpp0x_default_delete.i index affcea58e..bdb74ffb1 100644 --- a/Examples/test-suite/cpp0x_default_delete.i +++ b/Examples/test-suite/cpp0x_default_delete.i @@ -1,4 +1,4 @@ -/* This testcase checks whether Swig correctly parses the default and delete +/* This testcase checks whether SWIG correctly parses the default and delete keywords which keep or remove default C++ object construction functions. */ %module cpp0x_default_delete @@ -14,11 +14,11 @@ public: }; struct A1 { - void f(int i); - void f(double i) = delete; /* Don't cast double to int. Compiler returns an error */ + void f(int i); + void f(double i) = delete; /* Don't cast double to int. Compiler returns an error */ }; struct A2 { - void f(int i); - template void f(T) = delete; /* Only accept int */ + void f(int i); + template void f(T) = delete; /* Only accept int */ }; %} diff --git a/Examples/test-suite/cpp0x_explicit_conversion_operators.i b/Examples/test-suite/cpp0x_explicit_conversion_operators.i index 6532efb23..313b5e878 100644 --- a/Examples/test-suite/cpp0x_explicit_conversion_operators.i +++ b/Examples/test-suite/cpp0x_explicit_conversion_operators.i @@ -1,4 +1,4 @@ -/* This interface checks whether Swig correctly compiles the new +/* This interface checks whether SWIG correctly compiles the new explicit conversion operators feature introduced in C++0x. */ %module cpp0x_explicit_conversion_operators @@ -7,22 +7,22 @@ class U { public: - int u; + int u; }; class V { public: - int v; + int v; }; class TestClass { public: - //implicit converting constructor - TestClass( U const &val ) { t=val.u; } - // explicit constructor - explicit TestClass( V const &val ) { t=val.v; } - - int t; + //implicit converting constructor + TestClass( U const &val ) { t=val.u; } + // explicit constructor + explicit TestClass( V const &val ) { t=val.v; } + + int t; }; %} diff --git a/Examples/test-suite/cpp0x_function_objects.i b/Examples/test-suite/cpp0x_function_objects.i index f480addc7..e864137c7 100644 --- a/Examples/test-suite/cpp0x_function_objects.i +++ b/Examples/test-suite/cpp0x_function_objects.i @@ -1,4 +1,4 @@ -/* This testcase checks whether Swig correctly parses function objects +/* This testcase checks whether SWIG correctly parses function objects and the templates for the functions (signature). Function objects are objects which overload the operator() function. */ %module cpp0x_function_objects diff --git a/Examples/test-suite/cpp0x_hash_tables.i b/Examples/test-suite/cpp0x_hash_tables.i index b5eb505a4..fff630ca0 100644 --- a/Examples/test-suite/cpp0x_hash_tables.i +++ b/Examples/test-suite/cpp0x_hash_tables.i @@ -23,21 +23,21 @@ using namespace std; class MyClass { public: - set getSet() { return _set; } - void addSet(int elt) { _set.insert(_set.begin(), elt); } -// map getMap() { return _map; } -// void addMap(int elt1, int elt2) { _map.insert(make_pair(elt1, elt2)); } + set getSet() { return _set; } + void addSet(int elt) { _set.insert(_set.begin(), elt); } +// map getMap() { return _map; } +// void addMap(int elt1, int elt2) { _map.insert(make_pair(elt1, elt2)); } - unordered_set getUnorderedSet() { return _unordered_set; } - void addUnorderedSet(int elt) { _unordered_set.insert(_unordered_set.begin(), elt); } -// unordered_map getUnorderedMap() { return _unordered_map; } -// void addUnorderedMap(int elt1, int elt2) { _unordered_map.insert(make_pair(elt1, elt2)); } + unordered_set getUnorderedSet() { return _unordered_set; } + void addUnorderedSet(int elt) { _unordered_set.insert(_unordered_set.begin(), elt); } +// unordered_map getUnorderedMap() { return _unordered_map; } +// void addUnorderedMap(int elt1, int elt2) { _unordered_map.insert(make_pair(elt1, elt2)); } private: - set _set; -// map _map; + set _set; +// map _map; - unordered_set _unordered_set; -// unordered_map _unordered_map; + unordered_set _unordered_set; +// unordered_map _unordered_map; }; %} diff --git a/Examples/test-suite/cpp0x_initializer_list.i b/Examples/test-suite/cpp0x_initializer_list.i index 3d6893033..aa2791833 100644 --- a/Examples/test-suite/cpp0x_initializer_list.i +++ b/Examples/test-suite/cpp0x_initializer_list.i @@ -1,4 +1,4 @@ -/* This testcase checks whether Swig correctly uses the new initializer_list +/* This testcase checks whether SWIG correctly uses the new initializer_list introduced in C++0x. */ %module cpp0x_initializer_list %warnfilter(520) A; @@ -8,8 +8,8 @@ class A { public: - A( std::initializer_list ) {} - A() {} + A( std::initializer_list ) {} + A() {} }; %} diff --git a/Examples/test-suite/cpp0x_lambda_functions.i b/Examples/test-suite/cpp0x_lambda_functions.i index 7719b59f4..7ca4c08d8 100644 --- a/Examples/test-suite/cpp0x_lambda_functions.i +++ b/Examples/test-suite/cpp0x_lambda_functions.i @@ -1,34 +1,34 @@ -/* This testcase checks whether Swig correctly parses the lambda expressions +/* This testcase checks whether SWIG correctly parses the lambda expressions and closure syntax introduced in C++0x. - Swig supports only lambda syntax and doesn't produce any wrapper code for + SWIG supports only lambda syntax and doesn't produce any wrapper code for this. */ %module cpp0x_lambda_functions %inline %{ struct A { - /* Defined lambda function with return value. */ - auto lambda1 = [](int x, int y) -> int { return x+y; }; - - /* Defined lambda function without return value. - Return value is calculated by compiler, if the function contains a - single statement "return expr;". */ - auto lambda2 = [](int x, int y) { return x+y; }; + /* Defined lambda function with return value. */ + auto lambda1 = [](int x, int y) -> int { return x+y; }; + + /* Defined lambda function without return value. + Return value is calculated by compiler, if the function contains a + single statement "return expr;". */ + auto lambda2 = [](int x, int y) { return x+y; }; }; int runLambda1() { - A myA; - return myA.lambda1(5,6); + A myA; + return myA.lambda1(5,6); } int runLambda2() { - A myA; - return myA.lambda2(5,6); + A myA; + return myA.lambda2(5,6); } /* Inline defined lambda function. */ int runLambda3() { - auto myLambda = [](int x, int y) { return x+y; }; - return myLambda(5,6); + auto myLambda = [](int x, int y) { return x+y; }; + return myLambda(5,6); } %} diff --git a/Examples/test-suite/cpp0x_null_pointer_constant.i b/Examples/test-suite/cpp0x_null_pointer_constant.i index 9057f04be..7069f3f25 100644 --- a/Examples/test-suite/cpp0x_null_pointer_constant.i +++ b/Examples/test-suite/cpp0x_null_pointer_constant.i @@ -1,4 +1,4 @@ -/* This testcase checks whether Swig correctly treats the new nullptr_t +/* This testcase checks whether SWIG correctly treats the new nullptr_t constant introduced in C++0x. */ @@ -9,8 +9,8 @@ class A { public: - A() : _myA(std::nullptr) { } - - A *_myA; + A() : _myA(std::nullptr) { } + + A *_myA; }; %} diff --git a/Examples/test-suite/cpp0x_raw_string_literals.i b/Examples/test-suite/cpp0x_raw_string_literals.i index 612b2baea..39a8bb641 100644 --- a/Examples/test-suite/cpp0x_raw_string_literals.i +++ b/Examples/test-suite/cpp0x_raw_string_literals.i @@ -1,11 +1,11 @@ -/* This module tests whether Swig correctly parses: +/* This module tests whether SWIG correctly parses: - ordinary strings (char_t) - L wide strings (wchar_t) - u8 unicode8 strings (char_t) - u unicode16 strings (char16_t) - U unicode32 strings (char32_t) - This module also tests whether Swig correctly parses custom string delimiters. + This module also tests whether SWIG correctly parses custom string delimiters. */ %module cpp0x_raw_string_literals %warnfilter(SWIGWARN_TYPEMAP_CHARLEAK_MSG) bb; diff --git a/Examples/test-suite/cpp0x_result_of.i b/Examples/test-suite/cpp0x_result_of.i index 4def13a38..42ff6c068 100644 --- a/Examples/test-suite/cpp0x_result_of.i +++ b/Examples/test-suite/cpp0x_result_of.i @@ -1,4 +1,4 @@ -/* This testcase checks whether Swig correctly uses the new result_of class +/* This testcase checks whether SWIG correctly uses the new result_of class and its templating capabilities introduced in C++0x. */ %module cpp0x_result_of @@ -7,12 +7,12 @@ #include double square(double x) { - return (x * x); + return (x * x); } template typename std::result_of::type test_result_impl(Fun fun, Arg arg) { - return fun(arg); + return fun(arg); } %} diff --git a/Examples/test-suite/cpp0x_rvalue_reference.i b/Examples/test-suite/cpp0x_rvalue_reference.i index f6c764aca..5821c5ccf 100644 --- a/Examples/test-suite/cpp0x_rvalue_reference.i +++ b/Examples/test-suite/cpp0x_rvalue_reference.i @@ -1,21 +1,21 @@ -/* This testcase checks whether Swig correctly parses the double ampersand && +/* This testcase checks whether SWIG correctly parses the double ampersand && move operator which is currently mapped to the reference & operator. */ %module cpp0x_rvalue_reference %inline %{ class A { public: - int getAcopy() { return _a; } - int *getAptr() { return &_a; } - int &getAref() { return _a; } - int &&getAmove() { return _a; } + int getAcopy() { return _a; } + int *getAptr() { return &_a; } + int &getAref() { return _a; } + int &&getAmove() { return _a; } - void setAcopy(int a) { _a = a; } - void setAptr(int *a) { _a = *a; } - void setAref(int &a) { _a = a; } - void setAmove(int &&a) { _a = a; } + void setAcopy(int a) { _a = a; } + void setAptr(int *a) { _a = *a; } + void setAref(int &a) { _a = a; } + void setAmove(int &&a) { _a = a; } private: - int _a; + int _a; }; %} diff --git a/Examples/test-suite/cpp0x_sizeof_object.i b/Examples/test-suite/cpp0x_sizeof_object.i index 89e659e81..72299786d 100644 --- a/Examples/test-suite/cpp0x_sizeof_object.i +++ b/Examples/test-suite/cpp0x_sizeof_object.i @@ -1,16 +1,16 @@ -/* This testcase checks whether Swig correctly uses the sizeof() on the +/* This testcase checks whether SWIG correctly uses the sizeof() on the concrete objects and not only types introduced in C++0x. */ %module cpp0x_sizeof_object %inline %{ struct B { - unsigned long member1; - long long member2; - char member3; + unsigned long member1; + long long member2; + char member3; }; struct A { - B member; + B member; }; const int a = sizeof(A::member); diff --git a/Examples/test-suite/cpp0x_smart_pointers.i b/Examples/test-suite/cpp0x_smart_pointers.i index 4f04e1941..400f7ebae 100644 --- a/Examples/test-suite/cpp0x_smart_pointers.i +++ b/Examples/test-suite/cpp0x_smart_pointers.i @@ -1,4 +1,4 @@ -/* This testcase checks whether Swig correctly uses the new general-purpose +/* This testcase checks whether SWIG correctly uses the new general-purpose smart pointers introduced in C++0x: - shared_ptr - weak_ptr diff --git a/Examples/test-suite/cpp0x_static_assert.i b/Examples/test-suite/cpp0x_static_assert.i index 28c244c87..d6413a1e5 100644 --- a/Examples/test-suite/cpp0x_static_assert.i +++ b/Examples/test-suite/cpp0x_static_assert.i @@ -1,4 +1,4 @@ -/* This test case checks whether swig correctly parses and ignores the +/* This test case checks whether SWIG correctly parses and ignores the keywords "static_assert()" inside the class or struct. */ %module cpp0x_static_assert @@ -6,12 +6,12 @@ %inline %{ template struct Check1 { - static_assert(sizeof(int) <= sizeof(T), "not big enough"); + static_assert(sizeof(int) <= sizeof(T), "not big enough"); }; template class Check2 { - static_assert(sizeof(int) <= sizeof(T), "not big enough"); + static_assert(sizeof(int) <= sizeof(T), "not big enough"); }; %} diff --git a/Examples/test-suite/cpp0x_strongly_typed_enumerations.i b/Examples/test-suite/cpp0x_strongly_typed_enumerations.i index 4476122fe..776af5822 100644 --- a/Examples/test-suite/cpp0x_strongly_typed_enumerations.i +++ b/Examples/test-suite/cpp0x_strongly_typed_enumerations.i @@ -1,4 +1,4 @@ -/* This testcase checks whether Swig produces the correct wrapper for the +/* This testcase checks whether SWIG produces the correct wrapper for the strongly typed enums. Enums with the same type are comparable. Enum classes require support for nested classes. */ %module cpp0x_strongly_typed_enumerations diff --git a/Examples/test-suite/cpp0x_template_double_brackets.i b/Examples/test-suite/cpp0x_template_double_brackets.i index 74d2fc768..79d77e704 100644 --- a/Examples/test-suite/cpp0x_template_double_brackets.i +++ b/Examples/test-suite/cpp0x_template_double_brackets.i @@ -1,4 +1,4 @@ -/* This interface checks whether Swig supports the new double angled brackets +/* This interface checks whether SWIG supports the new double angled brackets in the template syntax without having a space inbetween. This feature was introduced in new C++0x standard. */ @@ -10,21 +10,21 @@ std::map< int,std::map > n; class ABC { public: - int a; - int operator>>(ABC &); - int operator<<(ABC &); + int a; + int operator>>(ABC &); + int operator<<(ABC &); }; template class ABC2 { public: - int a; + int a; - template - U operator>>(ABC &); + template + U operator>>(ABC &); - template - U operator<<(ABC &); + template + U operator<<(ABC &); }; %} diff --git a/Examples/test-suite/cpp0x_template_explicit.i b/Examples/test-suite/cpp0x_template_explicit.i index 644a03e89..bbc216ba0 100644 --- a/Examples/test-suite/cpp0x_template_explicit.i +++ b/Examples/test-suite/cpp0x_template_explicit.i @@ -1,4 +1,4 @@ -/* This unit tests whether Swig correctly parses the code and makes wrappers +/* This unit tests whether SWIG correctly parses the code and makes wrappers for the new C++0x extern templates (explicit template instantiation without using the translation unit). */ diff --git a/Examples/test-suite/cpp0x_template_typedefs.i b/Examples/test-suite/cpp0x_template_typedefs.i index 3164b86ae..877539bfb 100644 --- a/Examples/test-suite/cpp0x_template_typedefs.i +++ b/Examples/test-suite/cpp0x_template_typedefs.i @@ -1,12 +1,12 @@ -/* This testcase checks whether Swig correctly parses the template aliasing. */ +/* This testcase checks whether SWIG correctly parses the template aliasing. */ %module cpp0x_template_typedefs %inline %{ template< typename T1, typename T2, int > class SomeType { - T1 a; - T2 b; - int c; + T1 a; + T2 b; + int c; }; template< typename T2 > diff --git a/Examples/test-suite/cpp0x_thread_local.i b/Examples/test-suite/cpp0x_thread_local.i index 35ad970e7..2ec633319 100644 --- a/Examples/test-suite/cpp0x_thread_local.i +++ b/Examples/test-suite/cpp0x_thread_local.i @@ -1,11 +1,11 @@ -/* This testcase checks whether Swig correctly parses the 'thread_local' +/* This testcase checks whether SWIG correctly parses the 'thread_local' keyword before the member type and name. */ %module cpp0x_thread_local %inline %{ struct A { - thread_local int val; + thread_local int val; }; %} diff --git a/Examples/test-suite/cpp0x_uniform_initialization.i b/Examples/test-suite/cpp0x_uniform_initialization.i index 39ed73180..083fac377 100644 --- a/Examples/test-suite/cpp0x_uniform_initialization.i +++ b/Examples/test-suite/cpp0x_uniform_initialization.i @@ -1,4 +1,4 @@ -/* This testcase checks whether Swig syntactically correctly parses the curly +/* This testcase checks whether SWIG syntactically correctly parses the curly brackets {} for uniform member initialization. */ %module cpp0x_uniform_initialization diff --git a/Examples/test-suite/cpp0x_unrestricted_unions.i b/Examples/test-suite/cpp0x_unrestricted_unions.i index a534df466..1cadd7f7c 100644 --- a/Examples/test-suite/cpp0x_unrestricted_unions.i +++ b/Examples/test-suite/cpp0x_unrestricted_unions.i @@ -1,4 +1,4 @@ -/* This testcase checks whether Swig correctly parses the support for types +/* This testcase checks whether SWIG correctly parses the support for types without the defined trivial constructor in the unions. */ %module cpp0x_unrestricted_unions diff --git a/Examples/test-suite/cpp0x_userdefined_literals.i b/Examples/test-suite/cpp0x_userdefined_literals.i index 4488a573b..6604a4293 100644 --- a/Examples/test-suite/cpp0x_userdefined_literals.i +++ b/Examples/test-suite/cpp0x_userdefined_literals.i @@ -1,4 +1,4 @@ -/* This testcase checks whether Swig correctly parses the user-defined literals +/* This testcase checks whether SWIG correctly parses the user-defined literals for the string introduced in C++0x. */ %module cpp0x_userdefined_literals @@ -6,9 +6,9 @@ #include struct OutputType { - int val; + int val; - OutputType(int v) { v=val; } + OutputType(int v) { v=val; } }; /* Note: GCC doesn't support user-defined literals yet! */ diff --git a/Examples/test-suite/cpp0x_variadic_templates.i b/Examples/test-suite/cpp0x_variadic_templates.i index b9320a0d1..c287194d4 100644 --- a/Examples/test-suite/cpp0x_variadic_templates.i +++ b/Examples/test-suite/cpp0x_variadic_templates.i @@ -1,4 +1,4 @@ -/* This testcase checks whether Swig correctly parses and generates the code +/* This testcase checks whether SWIG correctly parses and generates the code for variadic templates. This covers the variadic number of arguments inside the template brackets, new functions sizeof... and multiple inheritance using variadic number of classes. @@ -45,19 +45,19 @@ template struct SizeOf { %inline %{ class A { public: - A() { - a = 100; - } - - int a; + A() { + a = 100; + } + + int a; }; class B { public: - B() { - b = 200; - } - int b; + B() { + b = 200; + } + int b; }; template class MultiInherit : public BaseClasses... { From d8cc75946b236f08f9561a82867997e1021f96ab Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 18 Jul 2010 00:19:22 +0000 Subject: [PATCH 056/481] Improved C++0x rvalue reference implementation differentiating lvalue and rvalue references. The previous implementation treated rvalue references as lvalue references which leads to a number of different wrapping issues. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@12160 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 1 + Examples/test-suite/cpp0x_rvalue_reference.i | 3 +- Examples/test-suite/cpp0x_rvalue_reference2.i | 83 +++++++++++ .../python/cpp0x_rvalue_reference_runme.py | 4 +- Lib/csharp/csharp.swg | 40 ++++-- Source/CParse/parser.y | 136 ++++++++++++++++-- Source/Modules/php.cxx | 2 + Source/Swig/cwrap.c | 48 +++++++ Source/Swig/stype.c | 58 ++++++-- Source/Swig/swig.h | 4 + Source/Swig/typemap.c | 6 +- Source/Swig/typeobj.c | 39 +++++ Source/Swig/typesys.c | 7 + 13 files changed, 399 insertions(+), 32 deletions(-) create mode 100644 Examples/test-suite/cpp0x_rvalue_reference2.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 992406535..443cf2256 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -409,6 +409,7 @@ CPP0X_TEST_CASES = \ cpp0x_function_objects \ cpp0x_strongly_typed_enumerations \ cpp0x_rvalue_reference \ + cpp0x_rvalue_reference2 \ cpp0x_variadic_templates \ cpp0x_alternate_function_syntax \ cpp0x_userdefined_literals \ diff --git a/Examples/test-suite/cpp0x_rvalue_reference.i b/Examples/test-suite/cpp0x_rvalue_reference.i index 5821c5ccf..67686bc0f 100644 --- a/Examples/test-suite/cpp0x_rvalue_reference.i +++ b/Examples/test-suite/cpp0x_rvalue_reference.i @@ -3,12 +3,13 @@ %module cpp0x_rvalue_reference %inline %{ +#include class A { public: int getAcopy() { return _a; } int *getAptr() { return &_a; } int &getAref() { return _a; } - int &&getAmove() { return _a; } + int &&getAmove() { return std::move(_a); } void setAcopy(int a) { _a = a; } void setAptr(int *a) { _a = *a; } diff --git a/Examples/test-suite/cpp0x_rvalue_reference2.i b/Examples/test-suite/cpp0x_rvalue_reference2.i new file mode 100644 index 000000000..a3e9d1784 --- /dev/null +++ b/Examples/test-suite/cpp0x_rvalue_reference2.i @@ -0,0 +1,83 @@ +%module cpp0x_rvalue_reference2 + +// This testcase tests lots of different places that rvalue reference syntax can be used + +%typemap(in) Something && "/*in Something && typemap*/" +%rename(OperatorRValue) Thingy::operator int&&; +%rename(memberFnRenamed) memberFn(short &&i); +%feature("compactdefaultargs") Thingy::compactDefaultArgs(const bool &&b = (const bool &&)PublicGlobalTrue, const UserDef &&u = (const UserDef &&)PublicUserDef); +%feature("exception") Thingy::privateDefaultArgs(const bool &&b = (const bool &&)PrivateTrue); +%ignore Thingy::operator=; + +%inline %{ +#include +struct UserDef { + int a; +}; +static const bool PublicGlobalTrue = true; +static const UserDef PublicUserDef = UserDef(); +struct Thingy { + typedef int Integer; + int val; + int &lvalref; + int &&rvalref; + Thingy(int v) : val(v), lvalref(val), rvalref(22) {} + void refIn(long &i) {} + void rvalueIn(long &&i) {} + short && rvalueInOut(short &&i) { return std::move(i); } + static short && staticRvalueInOut(short &&i) { return std::move(i); } + // test both primitive and user defined rvalue reference default arguments and compactdefaultargs + void compactDefaultArgs(const bool &&b = (const bool &&)PublicGlobalTrue, const UserDef &&u = (const UserDef &&)PublicUserDef) {} + void privateDefaultArgs(const bool &&b = (const bool &&)PrivateTrue) {} + operator int &&() {} + Thingy& operator=(const Thingy& rhs) { + val = rhs.val; + lvalref = rhs.lvalref; + rvalref = rhs.rvalref; + } +private: + static const bool PrivateTrue = true; + Thingy(); +}; + +short && globalRvalueInOut(short &&i) { return std::move(i); } + +Thingy &&globalrrval = Thingy(55); + +short && func(short &&i) { return std::move(i); } +Thingy getit() { return Thingy(22); } + +void rvalrefFunction1(int &&v = (int &&)5) {} +void rvalrefFunctionBYVAL(short (Thingy::*memFunc)(short)) {} +void rvalrefFunctionLVALUE(short &(Thingy::*memFunc)(short &)) {} +void rvalrefFunction2(short && (Thingy::*memFunc)(short &&)) {} +void rvalrefFunction3(short && (*memFunc)(short &&)) {} + +template struct RemoveReference { + typedef T type; +}; + +template struct RemoveReference { + typedef T type; +}; + +template struct RemoveReference { + typedef T type; +}; + +template <> struct RemoveReference { + typedef short type; +}; + +// like std::move +template typename RemoveReference::type&& Move(T&& t) { + return static_cast::type&&>(t); +} +%} + +%template(RemoveReferenceDouble) RemoveReference; +%template(RemoveReferenceFloat) RemoveReference; +%template(RemoveReferenceShort) RemoveReference; +%template(MoveFloat) Move; + + diff --git a/Examples/test-suite/python/cpp0x_rvalue_reference_runme.py b/Examples/test-suite/python/cpp0x_rvalue_reference_runme.py index acf296716..43fbc997e 100644 --- a/Examples/test-suite/python/cpp0x_rvalue_reference_runme.py +++ b/Examples/test-suite/python/cpp0x_rvalue_reference_runme.py @@ -16,7 +16,9 @@ a.setAref(ptr) if a.getAcopy() != 5: raise RunTimeError, ("after A::setAref(): int A::getAcopy() value is ", a.getAcopy(), " should be 5") -a.setAmove(ptr) +rvalueref = a.getAmove() + +a.setAmove(rvalueref) if a.getAcopy() != 5: raise RunTimeError, ("after A::setAmove(): int A::getAcopy() value is ", a.getAcopy(), " should be 5") diff --git a/Lib/csharp/csharp.swg b/Lib/csharp/csharp.swg index 204cf4b2f..ecdf88b25 100644 --- a/Lib/csharp/csharp.swg +++ b/Lib/csharp/csharp.swg @@ -125,6 +125,10 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { %typemap(imtype, out="IntPtr") SWIGTYPE & "HandleRef" %typemap(cstype) SWIGTYPE & "$csclassname" +%typemap(ctype) SWIGTYPE && "void *" +%typemap(imtype, out="IntPtr") SWIGTYPE && "HandleRef" +%typemap(cstype) SWIGTYPE && "$csclassname" + /* pointer to a class member */ %typemap(ctype) SWIGTYPE (CLASS::*) "char *" %typemap(imtype) SWIGTYPE (CLASS::*) "string" @@ -397,6 +401,11 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "$1_type type is null", 0); return $null; } %} +%typemap(in, canthrow=1) SWIGTYPE && %{ $1 = ($1_ltype)$input; + if (!$1) { + SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "$1_type type is null", 0); + return $null; + } %} %typemap(out) SWIGTYPE * %{ $result = (void *)$1; %} %typemap(out, fragment="SWIG_PackData") SWIGTYPE (CLASS::*) %{ char buf[128]; @@ -405,6 +414,7 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { $result = SWIG_csharp_string_callback(buf); %} %typemap(out) SWIGTYPE & %{ $result = (void *)$1; %} +%typemap(out) SWIGTYPE && %{ $result = (void *)$1; %} %typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE * %{ $result = ($1_ltype)$input; %} @@ -522,6 +532,7 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { SWIGTYPE, SWIGTYPE *, SWIGTYPE &, + SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" @@ -539,7 +550,7 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, error_msg); return $null; %} -%typemap(throws, canthrow=1) SWIGTYPE, SWIGTYPE &, SWIGTYPE *, SWIGTYPE [ANY] +%typemap(throws, canthrow=1) SWIGTYPE, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE *, SWIGTYPE [ANY] %{ (void)$1; SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, "C++ $1_type exception thrown"); return $null; %} @@ -570,7 +581,7 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { "$csinput" %typemap(csin) char *, char *&, char[ANY], char[] "$csinput" %typemap(csin) SWIGTYPE "$&csclassname.getCPtr($csinput)" -%typemap(csin) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] "$csclassname.getCPtr($csinput)" +%typemap(csin) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] "$csclassname.getCPtr($csinput)" %typemap(csin) SWIGTYPE (CLASS::*) "$csclassname.getCMemberPtr($csinput)" /* The csout typemap is used for converting function return types from the return type @@ -653,6 +664,10 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { $csclassname ret = new $csclassname($imcall, $owner);$excode return ret; } +%typemap(csout, excode=SWIGEXCODE) SWIGTYPE && { + $csclassname ret = new $csclassname($imcall, $owner);$excode + return ret; + } %typemap(csout, excode=SWIGEXCODE) SWIGTYPE *, SWIGTYPE [] { IntPtr cPtr = $imcall; $csclassname ret = (cPtr == IntPtr.Zero) ? null : new $csclassname(cPtr, $owner);$excode @@ -666,7 +681,7 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { /* Properties */ -%typemap(csvarin, excode=SWIGEXCODE2) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) %{ +%typemap(csvarin, excode=SWIGEXCODE2) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) %{ set { $imcall;$excode } %} @@ -767,6 +782,11 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { $csclassname ret = new $csclassname($imcall, $owner);$excode return ret; } %} +%typemap(csvarout, excode=SWIGEXCODE2) SWIGTYPE && %{ + get { + $csclassname ret = new $csclassname($imcall, $owner);$excode + return ret; + } %} %typemap(csvarout, excode=SWIGEXCODE2) SWIGTYPE *, SWIGTYPE [] %{ get { IntPtr cPtr = $imcall; @@ -814,13 +834,13 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { /* Typemaps used for the generation of proxy and type wrapper class code */ -%typemap(csbase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" -%typemap(csclassmodifiers) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "public class" -%typemap(cscode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" -%typemap(csimports) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "\nusing System;\nusing System.Runtime.InteropServices;\n" +%typemap(csbase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" +%typemap(csclassmodifiers) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "public class" +%typemap(cscode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" +%typemap(csimports) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "\nusing System;\nusing System.Runtime.InteropServices;\n" %typemap(csinterfaces) SWIGTYPE "IDisposable" -%typemap(csinterfaces) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" -%typemap(csinterfaces_derived) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" +%typemap(csinterfaces) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" +%typemap(csinterfaces_derived) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" // Proxy classes (base classes, ie, not derived classes) %typemap(csbody) SWIGTYPE %{ @@ -851,7 +871,7 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { %} // Typewrapper classes -%typemap(csbody) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] %{ +%typemap(csbody) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] %{ private HandleRef swigCPtr; internal $csclassname(IntPtr cPtr, bool futureUse) { diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index b9749bf01..bb644f9db 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -3968,15 +3968,19 @@ cpp_template_decl : TEMPLATE LESSTHAN template_parms GREATERTHAN { template_para Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); if (error) $$ = 0; - } - | TEMPLATE cpptype idcolon { /* Explicit template instantiation */ + } + + /* Explicit template instantiation */ + | TEMPLATE cpptype idcolon { Swig_warning(WARN_PARSE_EXPLICIT_TEMPLATE, cparse_file, cparse_line, "Explicit template instantiation ignored.\n"); - $$ = 0; - } - | EXTERN TEMPLATE cpptype idcolon { /* Explicit template instantiation without the translation unit */ + $$ = 0; + } + + /* Explicit template instantiation without the translation unit */ + | EXTERN TEMPLATE cpptype idcolon { Swig_warning(WARN_PARSE_EXPLICIT_TEMPLATE, cparse_file, cparse_line, "Explicit template instantiation ignored.\n"); - $$ = 0; - } + $$ = 0; + } ; cpp_temp_possible: c_decl { @@ -4395,6 +4399,23 @@ cpp_conversion_operator : storage_class COPERATOR type pointer LPAREN parms RPAR Setattr($$,"conversion_operator","1"); add_symbols($$); } + | storage_class COPERATOR type LAND LPAREN parms RPAREN cpp_vend { + SwigType *decl; + $$ = new_node("cdecl"); + Setattr($$,"type",$3); + Setattr($$,"name",$2); + Setattr($$,"storage",$1); + decl = NewStringEmpty(); + SwigType_add_rvalue_reference(decl); + SwigType_add_function(decl,$6); + if ($8.qualifier) { + SwigType_push(decl,$8.qualifier); + } + Setattr($$,"decl",decl); + Setattr($$,"parms",$6); + Setattr($$,"conversion_operator","1"); + add_symbols($$); + } | storage_class COPERATOR type LPAREN parms RPAREN cpp_vend { String *t = NewStringEmpty(); @@ -4902,6 +4923,15 @@ declarator : pointer notso_direct_declarator { } $$.type = $1; } + | pointer LAND notso_direct_declarator { + $$ = $3; + SwigType_add_rvalue_reference($1); + if ($$.type) { + SwigType_push($1,$$.type); + Delete($$.type); + } + $$.type = $1; + } | direct_declarator { $$ = $1; if (!$$.type) $$.type = NewStringEmpty(); @@ -4920,7 +4950,7 @@ declarator : pointer notso_direct_declarator { /* Adds one S/R conflict */ $$ = $2; $$.type = NewStringEmpty(); - SwigType_add_reference($$.type); + SwigType_add_rvalue_reference($$.type); if ($2.type) { SwigType_push($$.type,$2.type); Delete($2.type); @@ -4990,6 +5020,15 @@ declarator : pointer notso_direct_declarator { } $$.type = $1; } + | pointer LAND PERIOD PERIOD PERIOD notso_direct_declarator { + $$ = $6; + SwigType_add_rvalue_reference($1); + if ($$.type) { + SwigType_push($1,$$.type); + Delete($$.type); + } + $$.type = $1; + } | PERIOD PERIOD PERIOD direct_declarator { $$ = $4; if (!$$.type) $$.type = NewStringEmpty(); @@ -5008,7 +5047,7 @@ declarator : pointer notso_direct_declarator { /* Adds one S/R conflict */ $$ = $5; $$.type = NewStringEmpty(); - SwigType_add_reference($$.type); + SwigType_add_rvalue_reference($$.type); if ($5.type) { SwigType_push($$.type,$5.type); Delete($5.type); @@ -5047,6 +5086,16 @@ declarator : pointer notso_direct_declarator { } $$.type = $1; } + | pointer idcolon DSTAR LAND PERIOD PERIOD PERIOD notso_direct_declarator { + $$ = $8; + SwigType_add_memberpointer($1,$2); + SwigType_add_rvalue_reference($1); + if ($$.type) { + SwigType_push($1,$$.type); + Delete($$.type); + } + $$.type = $1; + } | idcolon DSTAR AND PERIOD PERIOD PERIOD notso_direct_declarator { SwigType *t = NewStringEmpty(); $$ = $7; @@ -5058,6 +5107,17 @@ declarator : pointer notso_direct_declarator { } $$.type = t; } + | idcolon DSTAR LAND PERIOD PERIOD PERIOD notso_direct_declarator { + SwigType *t = NewStringEmpty(); + $$ = $7; + SwigType_add_memberpointer(t,$1); + SwigType_add_rvalue_reference(t); + if ($$.type) { + SwigType_push(t,$$.type); + Delete($$.type); + } + $$.type = t; + } ; notso_direct_declarator : idcolon { @@ -5191,6 +5251,13 @@ direct_declarator : idcolon { } SwigType_add_reference($$.type); } + | LPAREN LAND direct_declarator RPAREN { + $$ = $3; + if (!$$.type) { + $$.type = NewStringEmpty(); + } + SwigType_add_rvalue_reference($$.type); + } | LPAREN idcolon DSTAR direct_declarator RPAREN { SwigType *t; $$ = $4; @@ -5283,6 +5350,13 @@ abstract_declarator : pointer { $$.parms = 0; $$.have_parms = 0; } + | pointer LAND { + $$.type = $1; + SwigType_add_rvalue_reference($$.type); + $$.id = 0; + $$.parms = 0; + $$.have_parms = 0; + } | pointer AND direct_abstract_declarator { $$ = $3; SwigType_add_reference($1); @@ -5292,6 +5366,15 @@ abstract_declarator : pointer { } $$.type = $1; } + | pointer LAND direct_abstract_declarator { + $$ = $3; + SwigType_add_rvalue_reference($1); + if ($$.type) { + SwigType_push($1,$$.type); + Delete($$.type); + } + $$.type = $1; + } | direct_abstract_declarator { $$ = $1; } @@ -5304,6 +5387,15 @@ abstract_declarator : pointer { Delete($2.type); } } + | LAND direct_abstract_declarator { + $$ = $2; + $$.type = NewStringEmpty(); + SwigType_add_rvalue_reference($$.type); + if ($2.type) { + SwigType_push($$.type,$2.type); + Delete($2.type); + } + } | AND { $$.id = 0; $$.parms = 0; @@ -5311,6 +5403,13 @@ abstract_declarator : pointer { $$.type = NewStringEmpty(); SwigType_add_reference($$.type); } + | LAND { + $$.id = 0; + $$.parms = 0; + $$.have_parms = 0; + $$.type = NewStringEmpty(); + SwigType_add_rvalue_reference($$.type); + } | idcolon DSTAR { $$.type = NewStringEmpty(); SwigType_add_memberpointer($$.type,$1); @@ -5821,6 +5920,13 @@ valexpr : exprnum { $$ = $1; } $$.val = NewStringf("(%s) %s", SwigType_str($2.val,0), $5.val); } } + | LPAREN expr LAND RPAREN expr %prec CAST { + $$ = $5; + if ($5.type != T_STRING) { + SwigType_add_rvalue_reference($2.val); + $$.val = NewStringf("(%s) %s", SwigType_str($2.val,0), $5.val); + } + } | LPAREN expr pointer AND RPAREN expr %prec CAST { $$ = $6; if ($6.type != T_STRING) { @@ -5829,10 +5935,22 @@ valexpr : exprnum { $$ = $1; } $$.val = NewStringf("(%s) %s", SwigType_str($2.val,0), $6.val); } } + | LPAREN expr pointer LAND RPAREN expr %prec CAST { + $$ = $6; + if ($6.type != T_STRING) { + SwigType_push($2.val,$3); + SwigType_add_rvalue_reference($2.val); + $$.val = NewStringf("(%s) %s", SwigType_str($2.val,0), $6.val); + } + } | AND expr { $$ = $2; $$.val = NewStringf("&%s",$2.val); } + | LAND expr { + $$ = $2; + $$.val = NewStringf("&&%s",$2.val); + } | STAR expr { $$ = $2; $$.val = NewStringf("*%s",$2.val); diff --git a/Source/Modules/php.cxx b/Source/Modules/php.cxx index 9f91f12d4..94abf58da 100644 --- a/Source/Modules/php.cxx +++ b/Source/Modules/php.cxx @@ -1160,6 +1160,7 @@ public: break; } case T_REFERENCE: + case T_RVALUE_REFERENCE: case T_USER: case T_ARRAY: Clear(value); @@ -1930,6 +1931,7 @@ public: break; case T_POINTER: case T_REFERENCE: + case T_RVALUE_REFERENCE: case T_USER: if (is_shadow(t)) { return NewString(Char(is_shadow(t))); diff --git a/Source/Swig/cwrap.c b/Source/Swig/cwrap.c index 208842121..25dfaea14 100644 --- a/Source/Swig/cwrap.c +++ b/Source/Swig/cwrap.c @@ -68,6 +68,19 @@ static String *Swig_clocal(SwigType *t, const_String_or_char_ptr name, const_Str Delete(lstrname); } break; + case T_RVALUE_REFERENCE: + if (value) { + String *lstrname = SwigType_lstr(t, name); + String *lstr = SwigType_lstr(t, 0); + Printf(decl, "%s = (%s) &%s_defrvalue", lstrname, lstr, name); + Delete(lstrname); + Delete(lstr); + } else { + String *lstrname = SwigType_lstr(t, name); + Printf(decl, "%s = 0", lstrname); + Delete(lstrname); + } + break; case T_VOID: break; case T_VARARGS: @@ -229,6 +242,34 @@ int Swig_cargs(Wrapper *w, ParmList *p) { Delete(defname); Delete(defvalue); } + } else if (tycode == T_RVALUE_REFERENCE) { + if (pvalue) { + SwigType *tvalue; + String *defname, *defvalue, *rvalue, *qvalue; + rvalue = SwigType_typedef_resolve_all(pvalue); + qvalue = SwigType_typedef_qualified(rvalue); + defname = NewStringf("%s_defrvalue", lname); + tvalue = Copy(type); + SwigType_del_rvalue_reference(tvalue); + tycode = SwigType_type(tvalue); + if (tycode != T_USER) { + /* plain primitive type, we copy the the def value */ + String *lstr = SwigType_lstr(tvalue, defname); + defvalue = NewStringf("%s = %s", lstr, qvalue); + Delete(lstr); + } else { + /* user type, we copy the reference value */ + String *str = SwigType_str(type, defname); + defvalue = NewStringf("%s = %s", str, qvalue); + Delete(str); + } + Wrapper_add_localv(w, defname, defvalue, NIL); + Delete(tvalue); + Delete(rvalue); + Delete(qvalue); + Delete(defname); + Delete(defvalue); + } } else if (!pvalue && ((tycode == T_POINTER) || (tycode == T_STRING))) { pvalue = (String *) "0"; } @@ -269,6 +310,13 @@ String *Swig_cresult(SwigType *t, const_String_or_char_ptr name, const_String_or Delete(lstr); } break; + case T_RVALUE_REFERENCE: + { + String *lstr = SwigType_lstr(t, 0); + Printf(fcall, "%s = (%s) &", name, lstr); + Delete(lstr); + } + break; case T_USER: Printf(fcall, "%s = ", name); break; diff --git a/Source/Swig/stype.c b/Source/Swig/stype.c index 69919ad55..a8abf88fe 100644 --- a/Source/Swig/stype.c +++ b/Source/Swig/stype.c @@ -43,6 +43,7 @@ char cvsroot_stype_c[] = "$Id$"; * * 'p.' = Pointer (*) * 'r.' = Reference (&) + * 'z.' = Rvalue reference (&&) * 'a(n).' = Array of size n [n] * 'f(..,..).' = Function with arguments (args) * 'q(str).' = Qualifier (such as const or volatile) (const, volatile) @@ -235,7 +236,7 @@ int SwigType_isconst(SwigType *t) { int SwigType_ismutable(SwigType *t) { int r; SwigType *qt = SwigType_typedef_resolve_all(t); - if (SwigType_isreference(qt) || SwigType_isarray(qt)) { + if (SwigType_isreference(qt) || SwigType_isrvalue_reference(qt) || SwigType_isarray(qt)) { Delete(SwigType_pop(qt)); } r = SwigType_isconst(qt); @@ -423,6 +424,16 @@ SwigType *SwigType_default(SwigType *t) { Delete(nr); #else def = NewString("r.SWIGTYPE"); +#endif + } else if (SwigType_isrvalue_reference(r)) { +#ifdef SWIG_NEW_TYPE_DEFAULT + SwigType *nr = Copy(r); + SwigType_del_rvalue_reference(nr); + def = NewString("z."); + SwigType_add_default(def, nr); + Delete(nr); +#else + def = NewString("z.SWIGTYPE"); #endif } else if (SwigType_isarray(r)) { if (strcmp(cr, "a().SWIGTYPE") == 0) { @@ -597,6 +608,12 @@ String *SwigType_str(SwigType *s, const_String_or_char_ptr id) { Insert(result, 0, "("); Append(result, ")"); } + } else if (SwigType_isrvalue_reference(element)) { + Insert(result, 0, "&&"); + if ((nextelement) && ((SwigType_isfunction(nextelement) || (SwigType_isarray(nextelement))))) { + Insert(result, 0, "("); + Append(result, ")"); + } } else if (SwigType_isarray(element)) { DOH *size; Append(result, "["); @@ -661,7 +678,7 @@ SwigType *SwigType_ltype(SwigType *s) { SwigType *tt = Copy(tc); td = 0; while ((td = SwigType_typedef_resolve(tt))) { - if (td && (SwigType_isconst(td) || SwigType_isarray(td) || SwigType_isreference(td))) { + if (td && (SwigType_isconst(td) || SwigType_isarray(td) || SwigType_isreference(td) || SwigType_isrvalue_reference(td))) { /* We need to use the typedef type */ Delete(tt); tt = td; @@ -701,6 +718,13 @@ SwigType *SwigType_ltype(SwigType *s) { Append(result, "p."); } firstarray = 0; + } else if (SwigType_isrvalue_reference(element)) { + if (notypeconv) { + Append(result, element); + } else { + Append(result, "p."); + } + firstarray = 0; } else if (SwigType_isarray(element) && firstarray) { if (notypeconv) { Append(result, element); @@ -765,6 +789,7 @@ String *SwigType_rcaststr(SwigType *s, const_String_or_char_ptr name) { int clear = 1; int firstarray = 1; int isreference = 0; + int isfunction = 0; int isarray = 0; result = NewStringEmpty(); @@ -777,14 +802,14 @@ String *SwigType_rcaststr(SwigType *s, const_String_or_char_ptr name) { rs = s; } - if ((SwigType_isconst(rs) || SwigType_isarray(rs) || SwigType_isreference(rs))) { + if ((SwigType_isconst(rs) || SwigType_isarray(rs) || SwigType_isreference(rs) || SwigType_isrvalue_reference(rs))) { td = 0; } else { td = SwigType_typedef_resolve(rs); } if (td) { - if ((SwigType_isconst(td) || SwigType_isarray(td) || SwigType_isreference(td))) { + if ((SwigType_isconst(td) || SwigType_isarray(td) || SwigType_isreference(td) || SwigType_isrvalue_reference(td))) { elements = SwigType_split(td); } else { elements = SwigType_split(rs); @@ -836,6 +861,14 @@ String *SwigType_rcaststr(SwigType *s, const_String_or_char_ptr name) { Append(result, ")"); } isreference = 1; + } else if (SwigType_isrvalue_reference(element)) { + Insert(result, 0, "&&"); + if ((nextelement) && ((SwigType_isfunction(nextelement) || (SwigType_isarray(nextelement))))) { + Insert(result, 0, "("); + Append(result, ")"); + } + isreference = 1; + clear = 0; } else if (SwigType_isarray(element)) { DOH *size; if (firstarray && !isreference) { @@ -865,6 +898,7 @@ String *SwigType_rcaststr(SwigType *s, const_String_or_char_ptr name) { } Append(result, ")"); Delete(parms); + isfunction = 1; } else { String *bs = SwigType_namestr(element); Insert(result, 0, " "); @@ -880,10 +914,12 @@ String *SwigType_rcaststr(SwigType *s, const_String_or_char_ptr name) { cast = NewStringf("(%s)", result); } if (name) { - if (isreference) { - if (isarray) - Clear(cast); - Append(cast, "*"); + if (!isfunction) { + if (isreference) { + if (isarray) + Clear(cast); + Append(cast, "*"); + } } Append(cast, name); } @@ -914,6 +950,12 @@ String *SwigType_lcaststr(SwigType *s, const_String_or_char_ptr name) { Delete(str); if (name) Append(result, name); + } else if (SwigType_isrvalue_reference(s)) { + String *str = SwigType_str(s, 0); + Printf(result, "(%s)", str); + Delete(str); + if (name) + Append(result, name); } else if (SwigType_isqualifier(s)) { String *lstr = SwigType_lstr(s, 0); Printf(result, "(%s)%s", lstr, name); diff --git a/Source/Swig/swig.h b/Source/Swig/swig.h index 428bcf06d..07f27774d 100644 --- a/Source/Swig/swig.h +++ b/Source/Swig/swig.h @@ -94,6 +94,7 @@ extern "C" { #define T_FUNCTION 37 #define T_MPOINTER 38 #define T_VARARGS 39 +#define T_RVALUE_REFERENCE 40 #define T_SYMBOL 98 #define T_ERROR 99 @@ -123,6 +124,8 @@ extern "C" { extern SwigType *SwigType_pop_arrays(SwigType *t); extern SwigType *SwigType_add_reference(SwigType *t); extern SwigType *SwigType_del_reference(SwigType *t); + extern SwigType *SwigType_add_rvalue_reference(SwigType *t); + extern SwigType *SwigType_del_rvalue_reference(SwigType *t); extern SwigType *SwigType_add_qualifier(SwigType *t, const_String_or_char_ptr qual); extern SwigType *SwigType_del_qualifier(SwigType *t); extern SwigType *SwigType_add_function(SwigType *t, ParmList *parms); @@ -146,6 +149,7 @@ extern "C" { extern int SwigType_ismemberpointer(SwigType *t); extern int SwigType_isreference(SwigType *t); extern int SwigType_isreference_return(SwigType *t); + extern int SwigType_isrvalue_reference(SwigType *t); extern int SwigType_isarray(SwigType *t); extern int SwigType_prefix_is_simple_1D_array(SwigType *t); extern int SwigType_isfunction(SwigType *t); diff --git a/Source/Swig/typemap.c b/Source/Swig/typemap.c index a44ecdf6d..6595944a0 100644 --- a/Source/Swig/typemap.c +++ b/Source/Swig/typemap.c @@ -942,13 +942,13 @@ int typemap_replace_vars(String *s, ParmList *locals, SwigType *type, SwigType * $*n_ltype */ - if (SwigType_ispointer(ftype) || (SwigType_isarray(ftype)) || (SwigType_isreference(ftype))) { - if (!(SwigType_isarray(type) || SwigType_ispointer(type) || SwigType_isreference(type))) { + if (SwigType_ispointer(ftype) || (SwigType_isarray(ftype)) || (SwigType_isreference(ftype)) || (SwigType_isrvalue_reference(ftype))) { + if (!(SwigType_isarray(type) || SwigType_ispointer(type) || SwigType_isreference(type) || SwigType_isrvalue_reference(type))) { star_type = Copy(ftype); } else { star_type = Copy(type); } - if (!SwigType_isreference(star_type)) { + if (!(SwigType_isreference(star_type) || SwigType_isrvalue_reference(star_type))) { if (SwigType_isarray(star_type)) { SwigType_del_element(star_type); } else { diff --git a/Source/Swig/typeobj.c b/Source/Swig/typeobj.c index cafecb9a6..a72a102aa 100644 --- a/Source/Swig/typeobj.c +++ b/Source/Swig/typeobj.c @@ -45,6 +45,7 @@ char cvsroot_typeobj_c[] = "$Id$"; * * 'p.' = Pointer (*) * 'r.' = Reference (&) + * 'z.' = Rvalue reference (&&) * 'a(n).' = Array of size n [n] * 'f(..,..).' = Function with arguments (args) * 'q(str).' = Qualifier (such as const or volatile) (const, volatile) @@ -75,6 +76,7 @@ char cvsroot_typeobj_c[] = "$Id$"; * * SwigType_add_pointer() * SwigType_add_reference() + * SwigType_add_rvalue_reference() * SwigType_add_array() * * These are used to build new types. There are also functions to undo these @@ -82,12 +84,14 @@ char cvsroot_typeobj_c[] = "$Id$"; * * SwigType_del_pointer() * SwigType_del_reference() + * SwigType_del_rvalue_reference() * SwigType_del_array() * * In addition, there are query functions * * SwigType_ispointer() * SwigType_isreference() + * SwigType_isrvalue_reference() * SwigType_isarray() * * Finally, there are some data extraction functions that can be used to @@ -409,6 +413,41 @@ int SwigType_isreference(SwigType *t) { return 0; } +/* ----------------------------------------------------------------------------- + * Rvalue References + * + * SwigType_add_rvalue_reference() + * SwigType_del_rvalue_reference() + * SwigType_isrvalue_reference() + * + * Add, remove, and test if a type is a rvalue reference. The deletion and query + * functions take into account qualifiers (if any). + * ----------------------------------------------------------------------------- */ + +SwigType *SwigType_add_rvalue_reference(SwigType *t) { + Insert(t, 0, "z."); + return t; +} + +SwigType *SwigType_del_rvalue_reference(SwigType *t) { + char *c = Char(t); + int check = strncmp(c, "z.", 2); + assert(check == 0); + Delslice(t, 0, 2); + return t; +} + +int SwigType_isrvalue_reference(SwigType *t) { + char *c; + if (!t) + return 0; + c = Char(t); + if (strncmp(c, "z.", 2) == 0) { + return 1; + } + return 0; +} + /* ----------------------------------------------------------------------------- * Qualifiers * diff --git a/Source/Swig/typesys.c b/Source/Swig/typesys.c index 19f14a2a0..f6baa5a83 100644 --- a/Source/Swig/typesys.c +++ b/Source/Swig/typesys.c @@ -1206,6 +1206,8 @@ int SwigType_type(SwigType *t) { return T_ARRAY; if (strncmp(c, "r.", 2) == 0) return T_REFERENCE; + if (strncmp(c, "z.", 2) == 0) + return T_RVALUE_REFERENCE; if (strncmp(c, "m(", 2) == 0) return T_MPOINTER; if (strncmp(c, "q(", 2) == 0) { @@ -1540,6 +1542,11 @@ void SwigType_remember_clientdata(SwigType *t, const_String_or_char_ptr clientda SwigType_del_reference(tt); SwigType_add_pointer(tt); SwigType_remember_clientdata(tt, clientdata); + } else if (SwigType_isrvalue_reference(t)) { + SwigType *tt = Copy(t); + SwigType_del_rvalue_reference(tt); + SwigType_add_pointer(tt); + SwigType_remember_clientdata(tt, clientdata); } } From 996455b50e5bbfff54b274538c856034b0c55515 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 24 Jul 2010 00:20:11 +0000 Subject: [PATCH 057/481] sort out c++0x lambda tests and reorder cpp0x tests git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@12182 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 45 ++++++++++--------- Examples/test-suite/cpp0x_lambda_functions.i | 45 +++++++++++++------ .../java/cpp0x_lambda_functions_runme.java | 28 ++++++++++++ 3 files changed, 82 insertions(+), 36 deletions(-) create mode 100644 Examples/test-suite/java/cpp0x_lambda_functions_runme.java diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index f3414f931..5ee7df02f 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -430,33 +430,34 @@ CPP_TEST_CASES += \ # C++0x test cases. CPP0X_TEST_CASES = \ - cpp0x_template_double_brackets \ + cpp0x_alternate_function_syntax \ + cpp0x_constexpr \ + cpp0x_decltype \ + cpp0x_default_delete \ cpp0x_explicit_conversion_operators \ - cpp0x_raw_string_literals \ - cpp0x_static_assert \ - cpp0x_template_explicit \ - cpp0x_uniform_initialization \ cpp0x_function_objects \ - cpp0x_strongly_typed_enumerations \ + cpp0x_initializer_list \ + cpp0x_raw_string_literals \ + cpp0x_result_of \ cpp0x_rvalue_reference \ cpp0x_rvalue_reference2 \ - cpp0x_variadic_templates \ - cpp0x_alternate_function_syntax \ - cpp0x_userdefined_literals \ - cpp0x_decltype \ - cpp0x_result_of \ - cpp0x_default_delete \ cpp0x_sizeof_object \ - cpp0x_initializer_list -# cpp0x_template_typedefs # not supported by any compiler yet -# cpp0x_hash_types # not fully implemented yet -# cpp0x_constructors # not supported by any compiler yet -# cpp0x_lambda_functions # not supported by GCC or MSVC yet -# cpp0x_null_pointer_constant # not supported by any compiler yet -# cpp0x_unrestricted_unions # not supported by any compiler yet -# cpp0x_smart_pointers # not supported by standard library yet -# cpp0x_constexpr # not supported by any compiler yet -# cpp0x_thread_local # not supported by any compiler yet + cpp0x_static_assert \ + cpp0x_strongly_typed_enumerations \ + cpp0x_template_double_brackets \ + cpp0x_template_explicit \ + cpp0x_uniform_initialization \ + cpp0x_userdefined_literals \ + cpp0x_variadic_templates + +# cpp0x_constructors \ # not supported by any compiler yet +# cpp0x_hash_tables \ # not fully implemented yet +# cpp0x_lambda_functions \ # not supported by GCC or MSVC yet +# cpp0x_null_pointer_constant \ # not supported by any compiler yet +# cpp0x_smart_pointers \ # not supported by standard library yet +# cpp0x_template_typedefs \ # not supported by any compiler yet +# cpp0x_thread_local \ # not supported by any compiler yet +# cpp0x_unrestricted_unions \ # not supported by any compiler yet # Broken C++0x test cases. CPP0X_TEST_BROKEN = diff --git a/Examples/test-suite/cpp0x_lambda_functions.i b/Examples/test-suite/cpp0x_lambda_functions.i index 7ca4c08d8..56235e9a6 100644 --- a/Examples/test-suite/cpp0x_lambda_functions.i +++ b/Examples/test-suite/cpp0x_lambda_functions.i @@ -5,30 +5,47 @@ */ %module cpp0x_lambda_functions -%inline %{ -struct A { - /* Defined lambda function with return value. */ - auto lambda1 = [](int x, int y) -> int { return x+y; }; +#pragma SWIG nowarn=SWIGWARN_LANG_NATIVE_UNIMPL - /* Defined lambda function without return value. - Return value is calculated by compiler, if the function contains a - single statement "return expr;". */ - auto lambda2 = [](int x, int y) { return x+y; }; -}; +%inline %{ +/* Defined lambda function with return value. */ +auto lambda1 = [](int x, int y) -> int { return x+y; }; + +/* Defined lambda function without return value. + Return value is calculated by compiler, if the function contains a + single statement "return expr;". */ +auto lambda2 = [](int x, int y) { return x+y; }; + +auto lambda3 = [&](int x, int y) { return x+y; }; +auto lambda4 = [=](int x, int y) { return x+y; }; +int thing = 0; +auto lambda5 = [=,&thing]() { return thing;}; int runLambda1() { - A myA; - return myA.lambda1(5,6); + return lambda1(5,6); } int runLambda2() { - A myA; - return myA.lambda2(5,6); + return lambda2(5,6); +} + +int runLambda3() { + return lambda3(5,6); +} + +int runLambda4() { + return lambda4(5,6); +} + +int runLambda5() { + thing++; + return lambda5(); } /* Inline defined lambda function. */ -int runLambda3() { +int runLambdaInline() { auto myLambda = [](int x, int y) { return x+y; }; return myLambda(5,6); } %} + diff --git a/Examples/test-suite/java/cpp0x_lambda_functions_runme.java b/Examples/test-suite/java/cpp0x_lambda_functions_runme.java new file mode 100644 index 000000000..79545f87e --- /dev/null +++ b/Examples/test-suite/java/cpp0x_lambda_functions_runme.java @@ -0,0 +1,28 @@ +import cpp0x_lambda_functions.*; + +public class cpp0x_lambda_functions_runme { + + static { + try { + System.loadLibrary("cpp0x_lambda_functions"); + } 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); + } + } + + private static void check(int received, int expected) { + if (expected != received) + throw new RuntimeException("check failed, expected: " + expected + " received: " + received); + } + + public static void main(String argv[]) + { + check(cpp0x_lambda_functions.runLambda1(), 11); + check(cpp0x_lambda_functions.runLambda2(), 11); + check(cpp0x_lambda_functions.runLambda3(), 11); + check(cpp0x_lambda_functions.runLambda4(), 11); + check(cpp0x_lambda_functions.runLambda5(), 1); + check(cpp0x_lambda_functions.runLambda5(), 2); + } +} From 368f442508a3a22d1153622bf7d4e685134c9985 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 24 Jul 2010 00:31:10 +0000 Subject: [PATCH 058/481] html fixes git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@12183 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Doc/Manual/Cpp0x.html | 182 +++++++++++++++++++++--------------------- 1 file changed, 91 insertions(+), 91 deletions(-) diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html index b89b74ad0..f983de165 100644 --- a/Doc/Manual/Cpp0x.html +++ b/Doc/Manual/Cpp0x.html @@ -19,7 +19,7 @@

  • Initializer lists
  • Uniform initialization
  • Type inference -
  • Range-based for-loop +
  • Range-based for-loop
  • Lambda functions and expressions
  • Alternate function syntax
  • Object construction improvement @@ -31,8 +31,8 @@
  • Unrestricted unions
  • Variadic templates
  • New string literals -
  • User-defined literals -
  • Thread-local storage +
  • User-defined literals +
  • Thread-local storage
  • Defaulting/deleting of standard functions on C++ objects
  • Type long long int
  • Static assertions @@ -43,7 +43,7 @@
  • Threading facilities
  • Tuple types and hash tables
  • Regular expressions -
  • General-purpose smart pointers +
  • General-purpose smart pointers
  • Extensible random number facility
  • Wrapper reference
  • Polymorphous wrappers for function objects @@ -77,7 +77,7 @@ yet.

    SWIG correctly parses the new operator && the same as the reference operator &.

    The wrapper for the following code is correctly produced:

    -
    +
     class MyClass {
       MyClass(MyClass&& p) : ptr(p.ptr) {p.ptr = 0;}
       MyClass& operator=(MyClass&& p) {
    @@ -85,25 +85,25 @@ class MyClass {
         return *this;
       }
     };
    -
    +

    7.2.2 Generalized constant expressions

    SWIG correctly parses the keyword constexpr, but ignores its functionality. Constant functions cannot be used as constants.

    -
    +
     constexpr int myConstFunc() { return 10; }
     const int a = myConstFunc(); // results in error
    -
    +

    Users needs to use values or predefined constants when defining the new constant value:

    -
    +
     #define MY_CONST 10
     constexpr int myConstFunc() { return MY_CONST; }
     const int a = MY_CONST; // ok
    -
    +

    7.2.3 Extern template

    @@ -111,7 +111,7 @@ const int a = MY_CONST; // ok

    SWIG correctly parses the keywords extern template. However, the explicit template instantiation is not used by SWIG, a %template is still required.

    -
    +
     extern template class std::vector<MyClass>; // explicit instantiation
     
     ...
    @@ -121,7 +121,7 @@ public:
       int a;
       int b;
     };
    -
    +

    7.2.4 Initializer lists

    @@ -134,29 +134,29 @@ filling the class members manually.

    For now, if a user wants to fill the class components like this:

    -
    +
     class A {
     public:
       A( std::initializer_list<int> );
     };
     A a1 = {1,2,3,4};
    -
    +

    You should add another constructor using the std::vector for example:

    -
    +
     class A {
     public:
       A( std::initializer_list<int> );
       A( std::vector<int> );
     };
     A a1 = {1,2,3,4};
    -
    +

    And call it from your target language, for example, in Python:

    -
    +
     >>> a2 = A( [1,2,3,4] )
    -
    +

    7.2.5 Uniform initialization

    @@ -164,7 +164,7 @@ A a1 = {1,2,3,4};

    The curly brackets {} for member initialization are fully supported by SWIG:

    -
    +
     struct BasicStruct {
      int x;
      double y;
    @@ -179,17 +179,17 @@ struct AltStruct {
     
     BasicStruct var1{5, 3.2}; // only fills the struct components
     AltStruct var2{2, 4.3};   // calls the constructor
    -
    +

    Uniform initialization does not affect usage from the target language, for example in Python:

    -
    +
     >>> a = AltStruct(10, 142.15)
     >>> a.x_
     10
     >>> a.y_
     142.15
    -
    +

    7.2.6 Type inference

    @@ -197,16 +197,16 @@ AltStruct var2{2, 4.3}; // calls the constructor

    SWIG supports decltype() with some limitations. Single variables are allowed, however, expressions are not supported yet. For example, the following code will work:

    -
    +
     int i;
     decltype(i) j;
    -
    +

    However, using an expression inside the decltype results in syntax error:

    -
    +
     int i; int j;
     decltype(i+j) k;  // syntax error
    -
    +

    7.2.7 Range-based for-loop

    @@ -218,9 +218,9 @@ ignores it.

    SWIG correctly parses the Lambda functions syntax. For example:

    -
    -auto myLambdaFunc = [this]() { this->SomePrivateMemberFunction() };
    -
    +
    +auto sum = [](int x, int y) -> int { return x+y; };
    +

    The lambda functions are removed from the wrapper class for now, because of the lack of support for closures (scope of the lambda functions) in the target languages.

    @@ -229,36 +229,36 @@ for closures (scope of the lambda functions) in the target languages.

    SWIG fully supports the new definition of functions. For example:

    -
    +
     struct SomeStruct {
       int FuncName(int x, int y);
     };
    -
    +

    can now be written as in C++0x:

    -
    +
     struct SomeStruct {
    -  auto FuncName(int x, int y) -> int;
    +  auto FuncName(int x, int y) -> int;
     };
      
    -auto SomeStruct::FuncName(int x, int y) -> int {
    +auto SomeStruct::FuncName(int x, int y) -> int {
       return x + y;
     }
    -
    +

    The usage in the target languages remains the same, for example in Python:

    -
    +
     >>> a = SomeStruct()
     >>> a.FuncName(10,5)
     15
    -
    +

    SWIG will also deal with type inference for the return type, as per the limitations described earlier. For example:

    -
    +
     auto square(float a, float b) -> decltype(a);
    -
    +

    7.2.10 Object construction improvement

    @@ -267,7 +267,7 @@ auto square(float a, float b) -> decltype(a); (constructor delegation and constructor inheritance) into the class using the using keyword.

    -
    +
     class BaseClass {
     public:
       BaseClass(int iValue);
    @@ -277,7 +277,7 @@ class DerivedClass: public BaseClass {
       public:
       using BaseClass::BaseClass; // Adds DerivedClass(int) constructor
     };
    -
    +

    7.2.11 Null pointer constant

    @@ -289,15 +289,15 @@ constant in the target language.

    SWIG parses the new enum class syntax and forward declarator for the enums:

    -
    +
     enum class MyEnum : unsigned int;
    -
    +

    The strongly typed enumerations are treated the same as the ordinary and anonymous enums. This is because SWIG doesn't support nested classes. This is usually not a problem, however, there may be some name clashes. For example, the following code:

    -
    +
     class Color {
       enum class PrintingColors : unsigned int {
         Cyan, Magenta, Yellow, Black
    @@ -312,11 +312,11 @@ class Color {
         Yellow, Orange, Red, Magenta, Blue, Cyan, Green, Pink, Black, White
       };
     };
    -
    +

    A workaround is to write these as a series of separated classes containing anonymous enums:

    -
    +
     class PrintingColors {
       enum : unsigned int {
         Cyan, Magenta, Yellow, Black
    @@ -334,7 +334,7 @@ class AllColors {
         Yellow, Orange, Red, Magenta, Blue, Cyan, Green, Pink, Black, White
       };
     };
    -
    +

    7.2.13 Double angle brackets

    @@ -343,17 +343,17 @@ class AllColors { template block, if found inside it at the top level, or as the right shift operator >> otherwise.

    -
    +
     std::vector<std::vector<int>> myIntTable;
    -
    +

    The bit shifting operator using the parenthesis around the expressions can be forced. For example

    -
    +
     template<(5>>3)>
     class A {};
    -
    +

    7.2.14 Explicit conversion operators

    @@ -361,7 +361,7 @@ class A {};

    SWIG correctly parses the keyword explicit both for operators and constructors. For example:

    -
    +
     class U {
     public:
             int u;
    @@ -381,7 +381,7 @@ public:
     
             int t;
     };
    -
    +

    The usage of explicit constructors and operators is somehow specific to C++ when assigning the value @@ -397,15 +397,15 @@ to achieve particular copy and compare behaviours.

    SWIG currently parses the new using name = syntax, but ignores the definition:

    -
    +
     using PFD = void (*)(double); // New introduced syntax
    -
    +

    You should still define the typedefs using the old syntax:

    -
    +
     typedef void (*PFD)(double);  // The old style
    -
    +

    7.2.16 Unrestricted unions

    @@ -414,7 +414,7 @@ typedef void (*PFD)(double); // The old style define the trivial constructor. For example, the wrapper for the following code is correctly produced:

    -
    +
     struct point {
       point() {}
       point(int x, int y): x_(x), y_(y) {}
    @@ -426,7 +426,7 @@ union P {
       double w;
       point p;  // Illegal in C++; point has a non-trivial constructor.  However, this is legal in C++0x.
     } p1;
    -
    +

    7.2.17 Variadic templates

    @@ -435,34 +435,34 @@ union P { block, variadic class inheritance and variadic constructor and initializers) with some limitations. The following code is correctly parsed:

    -
    +
     template <typename... BaseClasses> class ClassName : public BaseClasses... {
     public:
        ClassName (BaseClasses&&... baseClasses) : BaseClasses(baseClasses)... {}
     }
    -
    +

    Support for the variadic sizeof() function was also introduced:

    -
    +
     const int SIZE = sizeof...(ClassName<int, int>);
    -
    +

    For now however, the %template directive only accepts at most the number of arguments defined in the original template<> block:

    -
    +
     %template(MyVariant1) ClassName<>         // ok
     %template(MyVariant2) ClassName<int>      // ok
     %template(MyVariant3) ClassName<int, int> // too many arguments
    -
    +

    7.2.18 New string literals

    SWIG fully supports unicode string constants and raw string literals.

    -
    +
     // New string literals
     wstring         aa =  L"Wide string";
     const char     *bb = u8"UTF-8 string";
    @@ -476,7 +476,7 @@ wstring          ff =  LR"XXX(I'm a "raw wide" \ string.)XXX";
     const char      *gg = u8R"XXX(I'm a "raw UTF-8" \ string.)XXX";
     const char16_t  *hh =  uR"XXX(I'm a "raw UTF-16" \ string.)XXX";
     const char32_t  *ii =  UR"XXX(I'm a "raw UTF-32" \ string.)XXX";
    -
    +

    Note: SWIG currently incorrectly parses the odd number of double quotes inside the string due to SWIG's C++ preprocessor.

    @@ -486,13 +486,13 @@ inside the string due to SWIG's C++ preprocessor.

    SWIG correctly parses the new operator""_mysuffix() functions.

    -
    +
     OutputType operator "" _mySuffix(const char * string_values, size_t num_chars);
     OutputType operator "" _mySuffix(const wchar_t * string_values, size_t num_chars);
     OutputType operator "" _mySuffix(const char16_t * string_values, size_t num_chars);
     OutputType operator "" _mySuffix(const char32_t * string_values, size_t num_chars);
     OutputType operator "" _mySuffix(int value);
    -
    +

    The %rename currently doesn't parse the double quotes. Please rename the functions in the code using the #define preprocessor directive.

    @@ -503,11 +503,11 @@ rename the functions in the code using the #define preprocessor directive.

    SWIG correctly parses the thread_local keyword. For example, a variable reachable by the current thread can be defined as:

    -
    +
     struct A {
        thread_local int val;
     };
    -
    +

    The new C++0x threading libraries are ignored because each SWIG target language offers its own threading facilities.

    @@ -518,14 +518,14 @@ its own threading facilities.

    SWIG correctly parses the = delete and = default keywords. For example:

    -
    +
     struct NonCopyable {
       NonCopyable& operator=(const NonCopyable&) = delete; /* Removes operator= */
       NonCopyable(const NonCopyable&) = delete;            /* Removed copy constructor */
       NonCopyable() = default;                             /* Explicitly allows the empty constructor */
       void *operator new(std::size_t) = delete;            /* Removes new NonCopyable */
     };
    -
    +

    This feature is specific to C++ only. The defaulting/deleting is currently ignored, because SWIG automatically produces wrappers for special constructors and operators specific to the target language.

    @@ -540,12 +540,12 @@ automatically produces wrappers for special constructors and operators specific

    SWIG correctly parses and calls the new static_assert function.

    -
    +
     template <typename T>
     struct Check {
       static_assert(sizeof(int) <= sizeof(T), "not big enough");
     };
    -
    +

    7.2.24 Allow sizeof to work on members of classes without an explicit object

    @@ -553,19 +553,19 @@ struct Check {

    SWIG correctly calls the sizeof() on types as well as on the objects. For example:

    -
    +
     struct A {
       int member;
     };
     
     const int SIZE = sizeof(A::member); // does not work with C++03. Okay with C++0x
    -
    +

    In Python:

    -
    +
     >>> SIZE
     8
    -
    +

    7.3 Standard library changes

    @@ -603,7 +603,7 @@ include the tuple header file; it is parsed without any problems.

    The new ref and cref classes are used to instantiate a parameter as a reference of a template function. For example:

    -
    +
     void f( int &r )  { r++; }
      
     // Template function.
    @@ -619,7 +619,7 @@ int main() {
                         // then 'i' will be modified.
       cout << i << endl ;  // Output -> 1
     }
    -
    +

    The ref and cref classes are not wrapped by SWIG because the SWIG target languages do not support referencing.

    @@ -628,20 +628,20 @@ int main() {

    SWIG fully supports function template wrappers and function objects:

    -
    +
     function<int ( int, int )> pF;   // function template wrapper
     
     struct Test {
       bool operator()( short x, short y ); // function object
     };
    -
    +

    7.3.8 Type traits for metaprogramming

    The new C++ metaprogramming is useful at compile time and is aimed specifically for C++ development:

    -
    +
     // First way of operating.
     template< bool B > struct algorithm {
       template< class T1, class T2 > int do_it( T1&, T2& )  { /*...*/ }
    @@ -656,7 +656,7 @@ template< class T1, class T2 > int elaborate( T1 A, T2 B ) {
       // in floating point, otherwise use the first way.
       return algorithm< is_integral<T1>::value && is_floating_point<T2>::value >::do_it( A, B );
     }
    -
    +

    SWIG correctly parses the template specialization, template types and values inside the <> block and the new helper functions: is_convertible, is_integral, is_const etc. However, SWIG still explicitly requires concrete types when using the %template directive, so the C++ metaprogramming features are not really of interest at runtime in the target languages.

    @@ -665,7 +665,7 @@ However, SWIG still explicitly requires concrete types when using the %templ

    SWIG does not wrap the new result_of class introduced in the <functional> header and map the result_of::type to the concrete type yet. For example:

    -
    +
     %inline %{
     #include <functional>
     double square(double x) {
    @@ -680,15 +680,15 @@ typename std::result_of<Fun(Arg)>::type test_result_impl(Fun fun, Arg arg)
     
     %template(test_result) test_result_impl<double(*)(double), double>;
     %constant double (*SQUARE)(double) = square;
    -
    +

    will result in:

    -
    +
     >>> test_result_impl(SQUARE, 5.0)
     <SWIG Object of type 'std::result_of< Fun(Arg) >::type *' at 0x7faf99ed8a50>
    -
    +

    Instead, please use decltype() where possible for now.

    - - + + From fdb9f072a7495f8a0a782032fdf7d9218c8ae16e Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 20 Apr 2012 20:26:13 +0000 Subject: [PATCH 059/481] Fix parsing of forward declaration of C++0x enums git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13010 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .../cpp0x_strongly_typed_enumerations.i | 21 +++++++++++++------ Source/CParse/parser.y | 7 ++++--- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/Examples/test-suite/cpp0x_strongly_typed_enumerations.i b/Examples/test-suite/cpp0x_strongly_typed_enumerations.i index 776af5822..2532d8c6e 100644 --- a/Examples/test-suite/cpp0x_strongly_typed_enumerations.i +++ b/Examples/test-suite/cpp0x_strongly_typed_enumerations.i @@ -7,6 +7,12 @@ %warnfilter(302) Val3; %warnfilter(302) Val4; +/* Forward declarations (illegally accepted by SWIG - oh well!) */ +enum Enum1 : short; +enum Enum3; +enum ; +enum : unsigned short; + %inline %{ enum class Enum1 { Val1, @@ -21,13 +27,16 @@ enum class Enum2 : short { Val3 = 100, Val4 }; +%} -/* Forward declarations. GCC doesn't support them */ -//enum Enum3; // Illegal in C++ and C++0x; no size is explicitly specified. -//enum Enum4 : unsigned int; // Legal in C++0x. -//enum class Enum5; // Legal in C++0x, because enum class declarations have a default type of "int". -//enum class Enum6 : unsigned int; // Legal C++0x. -//enum Enum2 : unsigned short; // Illegal in C++0x, because Enum2 was previously declared with a different type. +// SWIG should fail this one +enum Enum2 : unsigned short; // Illegal in C++0x, because Enum2 was previously declared with a different type. + +%inline %{ +/* Forward declarations. */ +enum Enum4 : unsigned int; // Legal in C++0x. +enum class Enum5; // Legal in C++0x, because enum class declarations have a default type of "int". +enum class Enum6 : unsigned int; // Legal C++0x. enum Enum4 : unsigned int { Val1, Val2, Val3 = 100, Val4 diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 38bb29392..562d69d50 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -3326,14 +3326,15 @@ c_enum_inherit : COLON primitive_type { ; /* ------------------------------------------------------------ enum [class] Name; + enum [class] Name [: base_type]; ------------------------------------------------------------ */ -c_enum_forward_decl : storage_class c_enum_keyword c_enum_inherit ID SEMI { +c_enum_forward_decl : storage_class c_enum_keyword ename c_enum_inherit SEMI { SwigType *ty = 0; $$ = new_node("enumforward"); - ty = NewStringf("enum %s", $4); + ty = NewStringf("enum %s", $3); Setattr($$,"enumkeyword",$2); - Setattr($$,"name",$4); + Setattr($$,"name",$3); Setattr($$,"type",ty); Setattr($$,"sym:weak", "1"); add_symbols($$); From 6f9312d1c1e80ac56560cdc4c2842f14049cd5e5 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 21 Apr 2012 10:06:43 +0000 Subject: [PATCH 060/481] Add support for c++11 strongly typed enums inheriting from non standard primitive types git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13012 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .../cpp0x_strongly_typed_enumerations.i | 29 +++++++++++++++++++ Source/CParse/parser.y | 2 +- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/Examples/test-suite/cpp0x_strongly_typed_enumerations.i b/Examples/test-suite/cpp0x_strongly_typed_enumerations.i index 2532d8c6e..2ce676227 100644 --- a/Examples/test-suite/cpp0x_strongly_typed_enumerations.i +++ b/Examples/test-suite/cpp0x_strongly_typed_enumerations.i @@ -49,4 +49,33 @@ enum class Enum5 { enum class Enum6 : unsigned int { Val1, Val2, Val3 = 300, Val4 }; + +typedef enum class Enum7 : unsigned int { + Val1, Val2, Val3 = 300, Val4 +} Enum7td; + +// enum inherits from non-primitive type +enum class Enum8 : size_t { + Val1, Val2, Val3 = 300, Val4 +}; + +template struct TType { + typedef T type_name; +}; + +enum class Enum10 : TType::type_name { + Val1, Val2, Val3 = 300, Val4 +}; + +/* +TODO +enum class MyClass {AAA, BBB, CCC}; +namespace Space { +enum MyEnum {XXX, YYY, ZZZ}; +} +struct SSS { + MyClass m; +}; +*/ %} + diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 562d69d50..1aefcbd08 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -3319,7 +3319,7 @@ c_enum_keyword : ENUM { base enum type (eg. unsigned short) ------------------------------------------------------------ */ -c_enum_inherit : COLON primitive_type { +c_enum_inherit : COLON type_right { $$ = $2; } | empty { $$ = 0; } From 38f6156a93c83765ae871c04f6e762bd257ad7ae Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 23 Apr 2012 22:15:37 +0000 Subject: [PATCH 061/481] Using C++11 enum classes with just a forward reference. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13013 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .../cpp0x_strongly_typed_enumerations.i | 6 ++++++ Lib/csharp/enums.swg | 8 +++---- Lib/csharp/enumsimple.swg | 8 +++---- Lib/csharp/enumtypesafe.swg | 8 +++---- Lib/php/php.swg | 21 +++++++++++++++---- 5 files changed, 35 insertions(+), 16 deletions(-) diff --git a/Examples/test-suite/cpp0x_strongly_typed_enumerations.i b/Examples/test-suite/cpp0x_strongly_typed_enumerations.i index 2ce676227..dbe6d44bc 100644 --- a/Examples/test-suite/cpp0x_strongly_typed_enumerations.i +++ b/Examples/test-suite/cpp0x_strongly_typed_enumerations.i @@ -67,6 +67,12 @@ enum class Enum10 : TType::type_name { Val1, Val2, Val3 = 300, Val4 }; +// forward declaration, no definition of enum +enum class Enum11 : int; +struct UseEnum11 { + Enum11 myenum11; +}; + /* TODO enum class MyClass {AAA, BBB, CCC}; diff --git a/Lib/csharp/enums.swg b/Lib/csharp/enums.swg index 6605da8c8..65a0c38f8 100644 --- a/Lib/csharp/enums.swg +++ b/Lib/csharp/enums.swg @@ -13,12 +13,12 @@ %typemap(in) const enum SWIGTYPE & ($*1_ltype temp) %{ temp = ($*1_ltype)$input; $1 = &temp; %} -%typemap(out) const enum SWIGTYPE & %{ $result = *$1; %} +%typemap(out) const enum SWIGTYPE & %{ $result = (int)*$1; %} %typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const enum SWIGTYPE & %{ static $*1_ltype temp = ($*1_ltype)$input; $result = &temp; %} -%typemap(directorin) const enum SWIGTYPE & "$input = $1_name;" +%typemap(directorin) const enum SWIGTYPE & "$input = $1_name;" %typemap(csdirectorin) const enum SWIGTYPE & "($*csclassname)$iminput" %typemap(csdirectorout) const enum SWIGTYPE & "(int)$cscall" @@ -48,10 +48,10 @@ %typemap(cstype) enum SWIGTYPE "$csclassname" %typemap(in) enum SWIGTYPE %{ $1 = ($1_ltype)$input; %} -%typemap(out) enum SWIGTYPE %{ $result = $1; %} +%typemap(out) enum SWIGTYPE %{ $result = (int)$1; %} %typemap(directorout) enum SWIGTYPE %{ $result = ($1_ltype)$input; %} -%typemap(directorin) enum SWIGTYPE "$input = $1;" +%typemap(directorin) enum SWIGTYPE "$input = $1;" %typemap(csdirectorin) enum SWIGTYPE "($csclassname)$iminput" %typemap(csdirectorout) enum SWIGTYPE "(int)$cscall" diff --git a/Lib/csharp/enumsimple.swg b/Lib/csharp/enumsimple.swg index 2b1cb182b..e838ad978 100644 --- a/Lib/csharp/enumsimple.swg +++ b/Lib/csharp/enumsimple.swg @@ -15,12 +15,12 @@ %typemap(in) const enum SWIGTYPE & ($*1_ltype temp) %{ temp = ($*1_ltype)$input; $1 = &temp; %} -%typemap(out) const enum SWIGTYPE & %{ $result = *$1; %} +%typemap(out) const enum SWIGTYPE & %{ $result = (int)*$1; %} %typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const enum SWIGTYPE & %{ static $*1_ltype temp = ($*1_ltype)$input; $result = &temp; %} -%typemap(directorin) const enum SWIGTYPE & "$input = $1_name;" +%typemap(directorin) const enum SWIGTYPE & "$input = $1_name;" %typemap(csdirectorin) const enum SWIGTYPE & "$iminput" %typemap(csdirectorout) const enum SWIGTYPE & "$cscall" @@ -50,10 +50,10 @@ %typemap(cstype) enum SWIGTYPE "int" %typemap(in) enum SWIGTYPE %{ $1 = ($1_ltype)$input; %} -%typemap(out) enum SWIGTYPE %{ $result = $1; %} +%typemap(out) enum SWIGTYPE %{ $result = (int)$1; %} %typemap(directorout) enum SWIGTYPE %{ $result = ($1_ltype)$input; %} -%typemap(directorin) enum SWIGTYPE "$input = $1;" +%typemap(directorin) enum SWIGTYPE "$input = $1;" %typemap(csdirectorin) enum SWIGTYPE "$iminput" %typemap(csdirectorout) enum SWIGTYPE "$cscall" diff --git a/Lib/csharp/enumtypesafe.swg b/Lib/csharp/enumtypesafe.swg index a6bf64b9a..e3a22570c 100644 --- a/Lib/csharp/enumtypesafe.swg +++ b/Lib/csharp/enumtypesafe.swg @@ -14,12 +14,12 @@ %typemap(in) const enum SWIGTYPE & ($*1_ltype temp) %{ temp = ($*1_ltype)$input; $1 = &temp; %} -%typemap(out) const enum SWIGTYPE & %{ $result = *$1; %} +%typemap(out) const enum SWIGTYPE & %{ $result = (int)*$1; %} %typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const enum SWIGTYPE & %{ static $*1_ltype temp = ($*1_ltype)$input; $result = &temp; %} -%typemap(directorin) const enum SWIGTYPE & "$input = $1_name;" +%typemap(directorin) const enum SWIGTYPE & "$input = $1_name;" %typemap(csdirectorin) const enum SWIGTYPE & "$*csclassname.swigToEnum($iminput)" %typemap(csdirectorout) const enum SWIGTYPE & "$cscall.swigValue" @@ -49,10 +49,10 @@ %typemap(cstype) enum SWIGTYPE "$csclassname" %typemap(in) enum SWIGTYPE %{ $1 = ($1_ltype)$input; %} -%typemap(out) enum SWIGTYPE %{ $result = $1; %} +%typemap(out) enum SWIGTYPE %{ $result = (int)$1; %} %typemap(directorout) enum SWIGTYPE %{ $result = ($1_ltype)$input; %} -%typemap(directorin) enum SWIGTYPE "$input = $1;" +%typemap(directorin) enum SWIGTYPE "$input = $1;" %typemap(csdirectorin) enum SWIGTYPE "$csclassname.swigToEnum($iminput)" %typemap(csdirectorout) enum SWIGTYPE "$cscall.swigValue" diff --git a/Lib/php/php.swg b/Lib/php/php.swg index f4cc8d2b2..99edcddf5 100644 --- a/Lib/php/php.swg +++ b/Lib/php/php.swg @@ -189,12 +189,16 @@ signed char, unsigned char, bool, - size_t, - enum SWIGTYPE + size_t { ZVAL_LONG(return_value,$1); } +%typemap(out) enum SWIGTYPE +{ + ZVAL_LONG(return_value, (long)$1); +} + %typemap(out) long long %{ if ((long long)LONG_MIN <= $1 && $1 <= (long long)LONG_MAX) { @@ -227,12 +231,16 @@ const signed char &, const unsigned char &, const bool &, - const size_t &, - const enum SWIGTYPE & + const size_t & { ZVAL_LONG(return_value,*$1); } +%typemap(out) const enum SWIGTYPE & +{ + ZVAL_LONG(return_value, (long)*$1); +} + %typemap(out) const long long & %{ if ((long long)LONG_MIN <= *$1 && *$1 <= (long long)LONG_MAX) { @@ -270,6 +278,11 @@ ZVAL_LONG($input,$1_name); } +%typemap(directorin) enum SWIGTYPE +{ + ZVAL_LONG($input, (long)$1_name); +} + %typemap(out) bool { ZVAL_BOOL(return_value,($1)?1:0); From 6d655a7f417a41562d42e3345a34b0d73e821644 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 20 Sep 2012 18:17:52 +0000 Subject: [PATCH 062/481] Add scoped enums into correct correct scope in type system. Note that cpp0x_strongly_typed_enumerations.i still shows further language symbol table problems which need fixing. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13841 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/CParse/parser.y | 68 ++++++++++++++++++++++++++++++------- Source/Modules/typepass.cxx | 5 +-- 2 files changed, 58 insertions(+), 15 deletions(-) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 1aefcbd08..9b7a89a0e 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1690,7 +1690,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %type types_directive template_directive warn_directive ; /* C declarations */ -%type c_declaration c_decl c_decl_tail c_enum_keyword c_enum_inherit c_enum_decl c_enum_forward_decl c_constructor_decl c_lambda_decl c_lambda_decl_front ; +%type c_declaration c_decl c_decl_tail c_enum_key c_enum_inherit c_enum_decl c_enum_forward_decl c_constructor_decl c_lambda_decl c_lambda_decl_front ; %type enumlist edecl; /* C++ declarations */ @@ -3307,11 +3307,14 @@ c_lambda_decl_front : storage_class AUTO idcolon EQUAL LBRACKET { skip_balanced( enum class ------------------------------------------------------------ */ -c_enum_keyword : ENUM { - $$ = (char*)"enumkeyword"; +c_enum_key : ENUM { + $$ = (char *)"enum"; } | ENUM CLASS { - $$ = (char*)"enumclasskeyword"; + $$ = (char *)"enum class"; + } + | ENUM STRUCT { + $$ = (char *)"enum struct"; } ; @@ -3329,12 +3332,16 @@ c_enum_inherit : COLON type_right { enum [class] Name [: base_type]; ------------------------------------------------------------ */ -c_enum_forward_decl : storage_class c_enum_keyword ename c_enum_inherit SEMI { +c_enum_forward_decl : storage_class c_enum_key ename c_enum_inherit SEMI { SwigType *ty = 0; + int scopedenum = $3 && !Equal($2, "enum"); $$ = new_node("enumforward"); ty = NewStringf("enum %s", $3); - Setattr($$,"enumkeyword",$2); + Setattr($$,"enumkey",$2); + if (scopedenum) + SetFlag($$, "scopedenum"); Setattr($$,"name",$3); + Setattr($$,"inherit",$4); Setattr($$,"type",ty); Setattr($$,"sym:weak", "1"); add_symbols($$); @@ -3347,26 +3354,46 @@ c_enum_forward_decl : storage_class c_enum_keyword ename c_enum_inherit SEMI { enum [class] Name [: base_type] { ... } MyEnum [= ...]; * ------------------------------------------------------------ */ -c_enum_decl : storage_class c_enum_keyword ename c_enum_inherit LBRACE enumlist RBRACE SEMI { +c_enum_decl : storage_class c_enum_key ename c_enum_inherit LBRACE enumlist RBRACE SEMI { SwigType *ty = 0; + int scopedenum = $3 && !Equal($2, "enum"); $$ = new_node("enum"); ty = NewStringf("enum %s", $3); - Setattr($$,"enumkeyword",$2); + Setattr($$,"enumkey",$2); + if (scopedenum) + SetFlag($$, "scopedenum"); Setattr($$,"name",$3); Setattr($$,"inherit",$4); Setattr($$,"type",ty); appendChild($$,$6); add_symbols($$); /* Add to tag space */ - add_symbols($6); /* Add enum values to id space */ + + if (scopedenum) { + Swig_symbol_newscope(); + Swig_symbol_setscopename($3); + Delete(Namespaceprefix); + Namespaceprefix = Swig_symbol_qualifiedscopename(0); + } + + add_symbols($6); /* Add enum values to appropriate enum or enum class scope */ + + if (scopedenum) { + Setattr($$,"symtab", Swig_symbol_popscope()); + Delete(Namespaceprefix); + Namespaceprefix = Swig_symbol_qualifiedscopename(0); + } } - | storage_class c_enum_keyword ename c_enum_inherit LBRACE enumlist RBRACE declarator initializer c_decl_tail { + | storage_class c_enum_key ename c_enum_inherit LBRACE enumlist RBRACE declarator initializer c_decl_tail { Node *n; SwigType *ty = 0; String *unnamed = 0; int unnamedinstance = 0; + int scopedenum = $3 && !Equal($2, "enum"); $$ = new_node("enum"); - Setattr($$,"enumkeyword",$2); + Setattr($$,"enumkey",$2); + if (scopedenum) + SetFlag($$, "scopedenum"); Setattr($$,"inherit",$4); if ($3) { Setattr($$,"name",$3); @@ -3433,7 +3460,22 @@ c_enum_decl : storage_class c_enum_keyword ename c_enum_inherit LBRACE enumlist add_symbols($$); /* Add enum to tag space */ set_nextSibling($$,n); Delete(n); - add_symbols($6); /* Add enum values to id space */ + + if (scopedenum) { + Swig_symbol_newscope(); + Swig_symbol_setscopename($3); + Delete(Namespaceprefix); + Namespaceprefix = Swig_symbol_qualifiedscopename(0); + } + + add_symbols($6); /* Add enum values to appropriate enum or enum class scope */ + + if (scopedenum) { + Setattr($$,"symtab", Swig_symbol_popscope()); + Delete(Namespaceprefix); + Namespaceprefix = Swig_symbol_qualifiedscopename(0); + } + add_symbols(n); Delete(unnamed); } @@ -5760,7 +5802,7 @@ type_right : primitive_type { $$ = $1; | TYPE_BOOL { $$ = $1; } | TYPE_VOID { $$ = $1; } | TYPE_TYPEDEF template_decl { $$ = NewStringf("%s%s",$1,$2); } - | c_enum_keyword idcolon { $$ = NewStringf("enum %s", $2); } + | c_enum_key idcolon { $$ = NewStringf("enum %s", $2); } | TYPE_RAW { $$ = $1; } | idcolon { diff --git a/Source/Modules/typepass.cxx b/Source/Modules/typepass.cxx index e0e06d54e..9e05a2f14 100644 --- a/Source/Modules/typepass.cxx +++ b/Source/Modules/typepass.cxx @@ -834,16 +834,17 @@ class TypePass:private Dispatcher { virtual int enumvalueDeclaration(Node *n) { String *name = Getattr(n, "name"); String *value = Getattr(n, "value"); + String *scopedenum = Getattr(parentNode(n), "scopedenum"); if (!value) value = name; if (Strcmp(value, name) == 0) { String *new_value; - if ((nsname || inclass) && cparse_cplusplus) { + if ((nsname || inclass || scopedenum) && cparse_cplusplus) { new_value = NewStringf("%s::%s", SwigType_namestr(Swig_symbol_qualified(n)), value); } else { new_value = NewString(value); } - if ((nsname || inclass) && !cparse_cplusplus) { + if ((nsname || inclass || scopedenum) && !cparse_cplusplus) { String *cppvalue = NewStringf("%s::%s", SwigType_namestr(Swig_symbol_qualified(n)), value); Setattr(n, "cppvalue", cppvalue); /* for target languages that always generate C++ code even when wrapping C code */ } From ecac2d2a68d59a873e63d43a60b09b2eb61e4b9d Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 20 Sep 2012 19:09:38 +0000 Subject: [PATCH 063/481] Improve nullptr constant wrapping git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13842 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Doc/Manual/Cpp0x.html | 3 +-- Examples/test-suite/cpp0x_null_pointer_constant.i | 10 ++++++++-- Source/Modules/octave.cxx | 2 +- Source/Modules/php.cxx | 1 + Source/Modules/python.cxx | 2 +- Source/Modules/ruby.cxx | 2 +- 6 files changed, 13 insertions(+), 7 deletions(-) diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html index f983de165..f34d188ca 100644 --- a/Doc/Manual/Cpp0x.html +++ b/Doc/Manual/Cpp0x.html @@ -282,8 +282,7 @@ class DerivedClass: public BaseClass {

    7.2.11 Null pointer constant

    -

    SWIG correctly maps the std::nullptr constant to the null pointer -constant in the target language.

    +

    The nullptr constant is largely unimportant in wrappers. In the few places it has an effect, it is treated like NULL.

    7.2.12 Strongly typed enumerations

    diff --git a/Examples/test-suite/cpp0x_null_pointer_constant.i b/Examples/test-suite/cpp0x_null_pointer_constant.i index 7069f3f25..dcb5e61bd 100644 --- a/Examples/test-suite/cpp0x_null_pointer_constant.i +++ b/Examples/test-suite/cpp0x_null_pointer_constant.i @@ -4,13 +4,19 @@ %module cpp0x_null_pointer_constant +%feature("autodoc") A::NullPtrMethod; // Triggers conversion of nullptr to None, nil etc in target language +%feature("compactdefaultargs") A::NullPtrMethod; + %inline %{ -#include + +const int *const MyIntegerPtr = nullptr; class A { public: - A() : _myA(std::nullptr) { } + A() : _myA(nullptr) { } A *_myA; + + void NullPtrMethod(double *ptr = nullptr) {} }; %} diff --git a/Source/Modules/octave.cxx b/Source/Modules/octave.cxx index ad425e3c8..d4e0ad57c 100644 --- a/Source/Modules/octave.cxx +++ b/Source/Modules/octave.cxx @@ -390,7 +390,7 @@ public: Append(decl_str, tex_name); if (value) { - if (Strcmp(value, "NULL") == 0) + if (Strcmp(value, "NULL") == 0 || Strcmp(value, "nullptr") == 0) value = NewString("nil"); else if (Strcmp(value, "true") == 0 || Strcmp(value, "TRUE") == 0) value = NewString("true"); diff --git a/Source/Modules/php.cxx b/Source/Modules/php.cxx index e53009aaa..2a1eda53c 100644 --- a/Source/Modules/php.cxx +++ b/Source/Modules/php.cxx @@ -1345,6 +1345,7 @@ public: } } if (Strcmp(value, "NULL") == 0 || + Strcmp(value, "nullptr") == 0 || Strcmp(value, "0") == 0 || Strcmp(value, "0L") == 0) { Clear(value); diff --git a/Source/Modules/python.cxx b/Source/Modules/python.cxx index fed5205e1..bc5138c25 100644 --- a/Source/Modules/python.cxx +++ b/Source/Modules/python.cxx @@ -1444,7 +1444,7 @@ public: return NewString("True"); if (Strcmp(v, "false")==0 || Strcmp(v, "FALSE")==0) return NewString("False"); - if (Strcmp(v, "NULL")==0) + if (Strcmp(v, "NULL")==0 || Strcmp(v, "nullptr")==0) return NewString("None"); } return 0; diff --git a/Source/Modules/ruby.cxx b/Source/Modules/ruby.cxx index bcdfd69d3..a0580b97d 100644 --- a/Source/Modules/ruby.cxx +++ b/Source/Modules/ruby.cxx @@ -384,7 +384,7 @@ private: } if (value) { - if (Strcmp(value, "NULL") == 0) + if (Strcmp(value, "NULL") == 0 || Strcmp(value, "nullptr") == 0) value = NewString("nil"); else if (Strcmp(value, "true") == 0 || Strcmp(value, "TRUE") == 0) value = NewString("true"); From 744659345e68ac7b65f9733302c3e11e68b12948 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 20 Sep 2012 19:14:27 +0000 Subject: [PATCH 064/481] Update c++0x tests run by default for g++-4.6 git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13843 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 5ee7df02f..48453d809 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -437,6 +437,7 @@ CPP0X_TEST_CASES = \ cpp0x_explicit_conversion_operators \ cpp0x_function_objects \ cpp0x_initializer_list \ + cpp0x_null_pointer_constant \ cpp0x_raw_string_literals \ cpp0x_result_of \ cpp0x_rvalue_reference \ @@ -453,11 +454,10 @@ CPP0X_TEST_CASES = \ # cpp0x_constructors \ # not supported by any compiler yet # cpp0x_hash_tables \ # not fully implemented yet # cpp0x_lambda_functions \ # not supported by GCC or MSVC yet -# cpp0x_null_pointer_constant \ # not supported by any compiler yet # cpp0x_smart_pointers \ # not supported by standard library yet # cpp0x_template_typedefs \ # not supported by any compiler yet # cpp0x_thread_local \ # not supported by any compiler yet -# cpp0x_unrestricted_unions \ # not supported by any compiler yet +# cpp0x_unrestricted_unions \ # not supported by any compiler yet (now in gcc-4.6) # Broken C++0x test cases. CPP0X_TEST_BROKEN = From 3578be5753cac54aa9ec904c4cbf5025189c6345 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 20 Sep 2012 19:28:20 +0000 Subject: [PATCH 065/481] Better clarify C++11 smart pointer support git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13844 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Doc/Manual/Cpp0x.html | 5 ++++- Examples/test-suite/common.mk | 1 - Examples/test-suite/cpp0x_smart_pointers.i | 19 ------------------- 3 files changed, 4 insertions(+), 21 deletions(-) delete mode 100644 Examples/test-suite/cpp0x_smart_pointers.i diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html index f34d188ca..c46bfd67c 100644 --- a/Doc/Manual/Cpp0x.html +++ b/Doc/Manual/Cpp0x.html @@ -590,7 +590,10 @@ include the tuple header file; it is parsed without any problems.

    7.3.4 General-purpose smart pointers

    -

    SWIG does not wrap the new shared, weak and unique smart pointers, because the SWIG target languages offer their own garbage collectors.

    +

    +SWIG provides special smart pointer handling for std::tr1::shared_ptr in the same way it has support for boost::shared_ptr. +There is no special smart pointer handling available for std::weak_ptr and std::unique_ptr. +

    7.3.5 Extensible random number facility

    diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 48453d809..b496fe3c4 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -454,7 +454,6 @@ CPP0X_TEST_CASES = \ # cpp0x_constructors \ # not supported by any compiler yet # cpp0x_hash_tables \ # not fully implemented yet # cpp0x_lambda_functions \ # not supported by GCC or MSVC yet -# cpp0x_smart_pointers \ # not supported by standard library yet # cpp0x_template_typedefs \ # not supported by any compiler yet # cpp0x_thread_local \ # not supported by any compiler yet # cpp0x_unrestricted_unions \ # not supported by any compiler yet (now in gcc-4.6) diff --git a/Examples/test-suite/cpp0x_smart_pointers.i b/Examples/test-suite/cpp0x_smart_pointers.i deleted file mode 100644 index 400f7ebae..000000000 --- a/Examples/test-suite/cpp0x_smart_pointers.i +++ /dev/null @@ -1,19 +0,0 @@ -/* This testcase checks whether SWIG correctly uses the new general-purpose - smart pointers introduced in C++0x: - - shared_ptr - - weak_ptr - - unique_ptr -*/ -%module cpp0x_smart_pointers - -%inline %{ -#include -#include -#include - -struct A { - std::shared_ptr a1(new double); - std::unique_ptr a2(new double); - std::weak_ptr a3(a1); -}; -%} From e8deb880c2cadda79d179fea74444ffed2ac58a1 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 21 Sep 2012 05:53:44 +0000 Subject: [PATCH 066/481] Tidy up test and docs on template double brackets git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13845 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Doc/Manual/Cpp0x.html | 8 -------- .../test-suite/cpp0x_template_double_brackets.i | 17 +++++++++++++---- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html index c46bfd67c..c93121200 100644 --- a/Doc/Manual/Cpp0x.html +++ b/Doc/Manual/Cpp0x.html @@ -346,14 +346,6 @@ shift operator >> otherwise.

    std::vector<std::vector<int>> myIntTable;
  • -

    The bit shifting operator using the parenthesis -around the expressions can be forced. For example

    - -
    -template<(5>>3)>
    -class A {};
    -
    -

    7.2.14 Explicit conversion operators

    diff --git a/Examples/test-suite/cpp0x_template_double_brackets.i b/Examples/test-suite/cpp0x_template_double_brackets.i index 79d77e704..6b2230362 100644 --- a/Examples/test-suite/cpp0x_template_double_brackets.i +++ b/Examples/test-suite/cpp0x_template_double_brackets.i @@ -5,14 +5,23 @@ %module cpp0x_template_double_brackets %inline %{ #include -std::map> m; -std::map< int,std::map > n; +std::map> map1; +std::map< int,std::map > map2; +std::map>> map3; +std::map>>> map4; +%} + +// Check streaming operators are still okay +%rename(ExtractionOperator) operator>>; +%rename(InsertionOperator) operator<<; + +%inline %{ class ABC { public: int a; - int operator>>(ABC &); - int operator<<(ABC &); + int operator>>(ABC &) { return 0; } + int operator<<(ABC &) { return 0; } }; template From 171435f9895e59c66c7fc26af695f87302dd6e73 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 21 Sep 2012 06:37:30 +0000 Subject: [PATCH 067/481] Provide unique c++11 warnings which were previously hijacking another warning git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13846 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/CParse/parser.y | 8 ++++---- Source/Include/swigwarn.h | 5 +++++ 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 9b7a89a0e..effe11ccc 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -2899,7 +2899,7 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va p = tp; def_supplied = 1; } else if (p && !tp) { /* Variadic template - tp < p */ - Swig_warning(WARN_LANG_NATIVE_UNIMPL,cparse_file, cparse_line,"Only the first variadic template argument is currently supported.\n"); + Swig_warning(WARN_CPP11_VARIADIC_TEMPLATE,cparse_file, cparse_line,"Only the first variadic template argument is currently supported.\n"); break; } } @@ -3098,9 +3098,9 @@ c_declaration : c_decl { appendChild($$,firstChild($5)); } } - | c_lambda_decl { Swig_warning(WARN_LANG_NATIVE_UNIMPL, cparse_file, cparse_line,"SWIG doesn't produce wrapper code for lambda expressions and closures yet.\n"); $$ = $1; } - | USING idcolon EQUAL { skip_decl(); Swig_warning(WARN_LANG_NATIVE_UNIMPL, cparse_file, cparse_line,"SWIG doesn't support 'using' typedefs yet.\n"); $$ = 0; } - | TEMPLATE LESSTHAN template_parms GREATERTHAN USING idcolon EQUAL { skip_decl(); Swig_warning(WARN_LANG_NATIVE_UNIMPL, cparse_file, cparse_line,"SWIG doesn't support template aliasing yet.\n"); $$ = 0; } + | c_lambda_decl { Swig_warning(WARN_CPP11_LAMBDA, cparse_file, cparse_line,"SWIG doesn't produce wrapper code for lambda expressions and closures yet.\n"); $$ = $1; } + | USING idcolon EQUAL { skip_decl(); Swig_warning(WARN_CPP11_ALIAS_DECLARATION, cparse_file, cparse_line,"SWIG doesn't support the 'using' keyword in type aliasing yet.\n"); $$ = 0; } + | TEMPLATE LESSTHAN template_parms GREATERTHAN USING idcolon EQUAL { skip_decl(); Swig_warning(WARN_CPP11_ALIAS_TEMPLATE, cparse_file, cparse_line,"SWIG doesn't support the 'using' keyword in template aliasing yet.\n"); $$ = 0; } ; /* ------------------------------------------------------------ diff --git a/Source/Include/swigwarn.h b/Source/Include/swigwarn.h index 729764e51..c5e4b8e54 100644 --- a/Source/Include/swigwarn.h +++ b/Source/Include/swigwarn.h @@ -89,6 +89,11 @@ #define WARN_PARSE_NESTED_TEMPLATE 324 #define WARN_PARSE_NAMED_NESTED_CLASS 325 +#define WARN_CPP11_LAMBDA 340 +#define WARN_CPP11_ALIAS_DECLARATION 341 +#define WARN_CPP11_ALIAS_TEMPLATE 342 +#define WARN_CPP11_VARIADIC_TEMPLATE 343 + #define WARN_IGNORE_OPERATOR_NEW 350 /* new */ #define WARN_IGNORE_OPERATOR_DELETE 351 /* delete */ #define WARN_IGNORE_OPERATOR_PLUS 352 /* + */ From dbdbdd94aa44da8e3213c08cd252549578db17a4 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 21 Sep 2012 18:04:15 +0000 Subject: [PATCH 068/481] Some updates to c++11 warning messages and update docs on alias templates git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13847 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Doc/Manual/Cpp0x.html | 46 +++++++++++++++++-- Examples/test-suite/common.mk | 2 +- Examples/test-suite/cpp0x_template_typedefs.i | 3 +- Source/CParse/parser.y | 6 +-- 4 files changed, 47 insertions(+), 10 deletions(-) diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html index c93121200..ef64fecc1 100644 --- a/Doc/Manual/Cpp0x.html +++ b/Doc/Manual/Cpp0x.html @@ -27,7 +27,7 @@
  • Strongly typed enumerations
  • Double angle brackets
  • Explicit conversion operators -
  • Template typedefs +
  • Alias templates
  • Unrestricted unions
  • Variadic templates
  • New string literals @@ -382,17 +382,53 @@ SWIG target languages, because all use their own facilities (eg. classes Cloneab to achieve particular copy and compare behaviours.

    -

    7.2.15 Template typedefs

    +

    7.2.15 Alias templates

    +

    +The following is an example of an alias template: -

    SWIG currently parses the new using name = syntax, but -ignores the definition:

    +
    +template< typename T1, typename T2, int >
    +class SomeType {
    +  T1 a;
    +  T2 b;
    +  int c;
    +};
    +
    +template< typename T2 >
    +using TypedefName = SomeType<char*, T2, 5>;
    +
    + +

    +These are partially supported as SWIG will parse these and identify them, however, they are ignored as they are not added to the type system. A warning such as the following is issued: +

    + +
    +
    +example.i:13: Warning 342: The 'using' keyword in template aliasing is not fully supported yet.
    +
    +
    + +

    +Similarly for non-template type aliasing: +

     using PFD = void (*)(double); // New introduced syntax
     
    -

    You should still define the typedefs using the old syntax:

    +

    +A warning will be issued: +

    + +
    +
    +example.i:17: Warning 341: The 'using' keyword in type aliasing is not fully supported yet.
    +
    +
    + + +

    The equivalent old style typedefs can be used as a workaround:

     typedef void (*PFD)(double);  // The old style
    diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk
    index b496fe3c4..3e5b7789c 100644
    --- a/Examples/test-suite/common.mk
    +++ b/Examples/test-suite/common.mk
    @@ -454,7 +454,7 @@ CPP0X_TEST_CASES = \
     #	cpp0x_constructors \          # not supported by any compiler yet
     #	cpp0x_hash_tables \           # not fully implemented yet
     #	cpp0x_lambda_functions \      # not supported by GCC or MSVC yet
    -#	cpp0x_template_typedefs \     # not supported by any compiler yet
    +#	cpp0x_template_typedefs \     # not supported by any compiler yet (now in gcc-4.7)
     #	cpp0x_thread_local \          # not supported by any compiler yet
     #	cpp0x_unrestricted_unions \   # not supported by any compiler yet (now in gcc-4.6)
     
    diff --git a/Examples/test-suite/cpp0x_template_typedefs.i b/Examples/test-suite/cpp0x_template_typedefs.i
    index 877539bfb..bd7e2b220 100644
    --- a/Examples/test-suite/cpp0x_template_typedefs.i
    +++ b/Examples/test-suite/cpp0x_template_typedefs.i
    @@ -1,4 +1,4 @@
    -/* This testcase checks whether SWIG correctly parses the template aliasing. */
    +/* This testcase checks whether SWIG correctly parses alias templates. */
     %module cpp0x_template_typedefs
     
     %inline %{
    @@ -12,6 +12,7 @@ class SomeType {
     template< typename T2 >
     using TypedefName = SomeType;
     
    +// type aliasing
     typedef void (*PFD)(double);            // Old style
     using PF = void (*)(double);            // New introduced syntax
     %}
    diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y
    index effe11ccc..f601aab9f 100644
    --- a/Source/CParse/parser.y
    +++ b/Source/CParse/parser.y
    @@ -3098,9 +3098,9 @@ c_declaration   : c_decl {
     		    appendChild($$,firstChild($5));
     		  }
                     }
    -                | c_lambda_decl { Swig_warning(WARN_CPP11_LAMBDA, cparse_file, cparse_line,"SWIG doesn't produce wrapper code for lambda expressions and closures yet.\n"); $$ = $1; }
    -                | USING idcolon EQUAL { skip_decl(); Swig_warning(WARN_CPP11_ALIAS_DECLARATION, cparse_file, cparse_line,"SWIG doesn't support the 'using' keyword in type aliasing yet.\n"); $$ = 0; }
    -                | TEMPLATE LESSTHAN template_parms GREATERTHAN USING idcolon EQUAL { skip_decl(); Swig_warning(WARN_CPP11_ALIAS_TEMPLATE, cparse_file, cparse_line,"SWIG doesn't support the 'using' keyword in template aliasing yet.\n"); $$ = 0; }
    +                | c_lambda_decl { Swig_warning(WARN_CPP11_LAMBDA, cparse_file, cparse_line,"Lambda expressions and closures are not fully supported yet.\n"); $$ = $1; }
    +                | USING idcolon EQUAL { skip_decl(); Swig_warning(WARN_CPP11_ALIAS_DECLARATION, cparse_file, cparse_line,"The 'using' keyword in type aliasing is not fully supported yet.\n"); $$ = 0; }
    +                | TEMPLATE LESSTHAN template_parms GREATERTHAN USING idcolon EQUAL { skip_decl(); Swig_warning(WARN_CPP11_ALIAS_TEMPLATE, cparse_file, cparse_line,"The 'using' keyword in template aliasing is not fully supported yet.\n"); $$ = 0; }
                     ;
     
     /* ------------------------------------------------------------
    
    From 4c2a1abd6b69d69cdc816daa7d3980167ab6286d Mon Sep 17 00:00:00 2001
    From: William S Fulton 
    Date: Fri, 21 Sep 2012 18:21:15 +0000
    Subject: [PATCH 069/481] Minor doc tweaks for unrestricted unions
    
    git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13848 626c5289-ae23-0410-ae9c-e8d60b6d4f22
    ---
     Doc/Manual/Cpp0x.html         | 2 +-
     Examples/test-suite/common.mk | 2 +-
     2 files changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html
    index ef64fecc1..09e2b2f47 100644
    --- a/Doc/Manual/Cpp0x.html
    +++ b/Doc/Manual/Cpp0x.html
    @@ -438,7 +438,7 @@ typedef void (*PFD)(double);  // The old style
     
     
     

    SWIG fully supports any type inside a union even if it does not -define the trivial constructor. For example, the wrapper for the following +define a trivial constructor. For example, the wrapper for the following code is correctly produced:

    diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk
    index 3e5b7789c..9755a29e7 100644
    --- a/Examples/test-suite/common.mk
    +++ b/Examples/test-suite/common.mk
    @@ -456,7 +456,7 @@ CPP0X_TEST_CASES = \
     #	cpp0x_lambda_functions \      # not supported by GCC or MSVC yet
     #	cpp0x_template_typedefs \     # not supported by any compiler yet (now in gcc-4.7)
     #	cpp0x_thread_local \          # not supported by any compiler yet
    -#	cpp0x_unrestricted_unions \   # not supported by any compiler yet (now in gcc-4.6)
    +#	cpp0x_unrestricted_unions \   # not supported by any compiler yet (now in gcc-4.6 but generates internal compiler error)
     
     # Broken C++0x test cases.
     CPP0X_TEST_BROKEN = 
    
    From e25da884cb39ad7b11c97214a2b2dd26a7cb2a2f Mon Sep 17 00:00:00 2001
    From: William S Fulton 
    Date: Fri, 21 Sep 2012 19:15:44 +0000
    Subject: [PATCH 070/481] Fix unrestricted unions testcase and add runtime
     example
    
    git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13849 626c5289-ae23-0410-ae9c-e8d60b6d4f22
    ---
     Doc/Manual/Cpp0x.html                         |   11 +-
     Examples/test-suite/common.mk                 |    2 +-
     .../test-suite/cpp0x_unrestricted_unions.i    |    7 +-
     .../python/cpp0x_unrestricted_unions_wrap.cxx | 4046 +++++++++++++++++
     4 files changed, 4061 insertions(+), 5 deletions(-)
     create mode 100644 Examples/test-suite/python/cpp0x_unrestricted_unions_wrap.cxx
    
    diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html
    index 09e2b2f47..a93df57ca 100644
    --- a/Doc/Manual/Cpp0x.html
    +++ b/Doc/Manual/Cpp0x.html
    @@ -439,19 +439,24 @@ typedef void (*PFD)(double);  // The old style
     
     

    SWIG fully supports any type inside a union even if it does not define a trivial constructor. For example, the wrapper for the following -code is correctly produced:

    +code correctly provides access to all members in the union:

     struct point {
       point() {}
    -  point(int x, int y): x_(x), y_(y) {}
    +  point(int x, int y) : x_(x), y_(y) {}
       int x_, y_;
     };
     
    +#include  // For placement 'new' in the constructor below
     union P {
       int z;
       double w;
    -  point p;  // Illegal in C++; point has a non-trivial constructor.  However, this is legal in C++0x.
    +  point p; // Illegal in C++03; legal in C++11.
    +  // Due to the point member, a constructor definition is required.
    +  P() {
    +    new(&p) point();
    +  }
     } p1;
     
    diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 9755a29e7..1dfe35f38 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -448,6 +448,7 @@ CPP0X_TEST_CASES = \ cpp0x_template_double_brackets \ cpp0x_template_explicit \ cpp0x_uniform_initialization \ + cpp0x_unrestricted_unions \ cpp0x_userdefined_literals \ cpp0x_variadic_templates @@ -456,7 +457,6 @@ CPP0X_TEST_CASES = \ # cpp0x_lambda_functions \ # not supported by GCC or MSVC yet # cpp0x_template_typedefs \ # not supported by any compiler yet (now in gcc-4.7) # cpp0x_thread_local \ # not supported by any compiler yet -# cpp0x_unrestricted_unions \ # not supported by any compiler yet (now in gcc-4.6 but generates internal compiler error) # Broken C++0x test cases. CPP0X_TEST_BROKEN = diff --git a/Examples/test-suite/cpp0x_unrestricted_unions.i b/Examples/test-suite/cpp0x_unrestricted_unions.i index 1cadd7f7c..be65fd83d 100644 --- a/Examples/test-suite/cpp0x_unrestricted_unions.i +++ b/Examples/test-suite/cpp0x_unrestricted_unions.i @@ -9,10 +9,15 @@ struct point { int x_, y_; }; +#include // For placement 'new' in the constructor below union P { int z; double w; - point p; + point p; // Illegal in C++03; legal in C++11. + // Due to the point member, a constructor definition is required. + P() { + new(&p) point(); + } } p1; %} diff --git a/Examples/test-suite/python/cpp0x_unrestricted_unions_wrap.cxx b/Examples/test-suite/python/cpp0x_unrestricted_unions_wrap.cxx new file mode 100644 index 000000000..071bb660d --- /dev/null +++ b/Examples/test-suite/python/cpp0x_unrestricted_unions_wrap.cxx @@ -0,0 +1,4046 @@ +/* ---------------------------------------------------------------------------- + * This file was automatically generated by SWIG (http://www.swig.org). + * Version 2.0.1 + * + * This file is not intended to be easily readable and contains a number of + * coding conventions designed to improve portability and efficiency. Do not make + * changes to this file unless you know what you are doing--modify the SWIG + * interface file instead. + * ----------------------------------------------------------------------------- */ + +#define SWIGPYTHON +#define SWIG_PYTHON_DIRECTOR_NO_VTABLE + + +#ifdef __cplusplus +/* SwigValueWrapper is described in swig.swg */ +template class SwigValueWrapper { + struct SwigMovePointer { + T *ptr; + SwigMovePointer(T *p) : ptr(p) { } + ~SwigMovePointer() { delete ptr; } + SwigMovePointer& operator=(SwigMovePointer& rhs) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = rhs.ptr; rhs.ptr = 0; return *this; } + } pointer; + SwigValueWrapper& operator=(const SwigValueWrapper& rhs); + SwigValueWrapper(const SwigValueWrapper& rhs); +public: + SwigValueWrapper() : pointer(0) { } + SwigValueWrapper& operator=(const T& t) { SwigMovePointer tmp(new T(t)); pointer = tmp; return *this; } + operator T&() const { return *pointer.ptr; } + T *operator&() { return pointer.ptr; } +}; + +template T SwigValueInit() { + return T(); +} +#endif + +/* ----------------------------------------------------------------------------- + * This section contains generic SWIG labels for method/variable + * declarations/attributes, and other compiler dependent labels. + * ----------------------------------------------------------------------------- */ + +/* template workaround for compilers that cannot correctly implement the C++ standard */ +#ifndef SWIGTEMPLATEDISAMBIGUATOR +# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560) +# define SWIGTEMPLATEDISAMBIGUATOR template +# elif defined(__HP_aCC) +/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */ +/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */ +# define SWIGTEMPLATEDISAMBIGUATOR template +# else +# define SWIGTEMPLATEDISAMBIGUATOR +# endif +#endif + +/* inline attribute */ +#ifndef SWIGINLINE +# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) +# define SWIGINLINE inline +# else +# define SWIGINLINE +# endif +#endif + +/* attribute recognised by some compilers to avoid 'unused' warnings */ +#ifndef SWIGUNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define SWIGUNUSED __attribute__ ((__unused__)) +# else +# define SWIGUNUSED +# endif +# elif defined(__ICC) +# define SWIGUNUSED __attribute__ ((__unused__)) +# else +# define SWIGUNUSED +# endif +#endif + +#ifndef SWIG_MSC_UNSUPPRESS_4505 +# if defined(_MSC_VER) +# pragma warning(disable : 4505) /* unreferenced local function has been removed */ +# endif +#endif + +#ifndef SWIGUNUSEDPARM +# ifdef __cplusplus +# define SWIGUNUSEDPARM(p) +# else +# define SWIGUNUSEDPARM(p) p SWIGUNUSED +# endif +#endif + +/* internal SWIG method */ +#ifndef SWIGINTERN +# define SWIGINTERN static SWIGUNUSED +#endif + +/* internal inline SWIG method */ +#ifndef SWIGINTERNINLINE +# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE +#endif + +/* exporting methods */ +#if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) +# ifndef GCC_HASCLASSVISIBILITY +# define GCC_HASCLASSVISIBILITY +# endif +#endif + +#ifndef SWIGEXPORT +# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) +# if defined(STATIC_LINKED) +# define SWIGEXPORT +# else +# define SWIGEXPORT __declspec(dllexport) +# endif +# else +# if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) +# define SWIGEXPORT __attribute__ ((visibility("default"))) +# else +# define SWIGEXPORT +# endif +# endif +#endif + +/* calling conventions for Windows */ +#ifndef SWIGSTDCALL +# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) +# define SWIGSTDCALL __stdcall +# else +# define SWIGSTDCALL +# endif +#endif + +/* Deal with Microsoft's attempt at deprecating C standard runtime functions */ +#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) +# define _CRT_SECURE_NO_DEPRECATE +#endif + +/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */ +#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE) +# define _SCL_SECURE_NO_DEPRECATE +#endif + + + +/* Python.h has to appear first */ +#include + +/* ----------------------------------------------------------------------------- + * swigrun.swg + * + * This file contains generic C API SWIG runtime support for pointer + * type checking. + * ----------------------------------------------------------------------------- */ + +/* This should only be incremented when either the layout of swig_type_info changes, + or for whatever reason, the runtime changes incompatibly */ +#define SWIG_RUNTIME_VERSION "4" + +/* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */ +#ifdef SWIG_TYPE_TABLE +# define SWIG_QUOTE_STRING(x) #x +# define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x) +# define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE) +#else +# define SWIG_TYPE_TABLE_NAME +#endif + +/* + You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for + creating a static or dynamic library from the SWIG runtime code. + In 99.9% of the cases, SWIG just needs to declare them as 'static'. + + But only do this if strictly necessary, ie, if you have problems + with your compiler or suchlike. +*/ + +#ifndef SWIGRUNTIME +# define SWIGRUNTIME SWIGINTERN +#endif + +#ifndef SWIGRUNTIMEINLINE +# define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE +#endif + +/* Generic buffer size */ +#ifndef SWIG_BUFFER_SIZE +# define SWIG_BUFFER_SIZE 1024 +#endif + +/* Flags for pointer conversions */ +#define SWIG_POINTER_DISOWN 0x1 +#define SWIG_CAST_NEW_MEMORY 0x2 + +/* Flags for new pointer objects */ +#define SWIG_POINTER_OWN 0x1 + + +/* + Flags/methods for returning states. + + The SWIG conversion methods, as ConvertPtr, return an integer + that tells if the conversion was successful or not. And if not, + an error code can be returned (see swigerrors.swg for the codes). + + Use the following macros/flags to set or process the returning + states. + + In old versions of SWIG, code such as the following was usually written: + + if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) { + // success code + } else { + //fail code + } + + Now you can be more explicit: + + int res = SWIG_ConvertPtr(obj,vptr,ty.flags); + if (SWIG_IsOK(res)) { + // success code + } else { + // fail code + } + + which is the same really, but now you can also do + + Type *ptr; + int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags); + if (SWIG_IsOK(res)) { + // success code + if (SWIG_IsNewObj(res) { + ... + delete *ptr; + } else { + ... + } + } else { + // fail code + } + + I.e., now SWIG_ConvertPtr can return new objects and you can + identify the case and take care of the deallocation. Of course that + also requires SWIG_ConvertPtr to return new result values, such as + + int SWIG_ConvertPtr(obj, ptr,...) { + if () { + if () { + *ptr = ; + return SWIG_NEWOBJ; + } else { + *ptr = ; + return SWIG_OLDOBJ; + } + } else { + return SWIG_BADOBJ; + } + } + + Of course, returning the plain '0(success)/-1(fail)' still works, but you can be + more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the + 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 + + int food(double) + int fooi(int); + + and you call + + food(1) // cast rank '1' (1 -> 1.0) + fooi(1) // cast rank '0' + + just use the SWIG_AddCast()/SWIG_CheckState() +*/ + +#define SWIG_OK (0) +#define SWIG_ERROR (-1) +#define SWIG_IsOK(r) (r >= 0) +#define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) + +/* The CastRankLimit says how many bits are used for the cast rank */ +#define SWIG_CASTRANKLIMIT (1 << 8) +/* The NewMask denotes the object was created (using new/malloc) */ +#define SWIG_NEWOBJMASK (SWIG_CASTRANKLIMIT << 1) +/* The TmpMask is for in/out typemaps that use temporal objects */ +#define SWIG_TMPOBJMASK (SWIG_NEWOBJMASK << 1) +/* Simple returning values */ +#define SWIG_BADOBJ (SWIG_ERROR) +#define SWIG_OLDOBJ (SWIG_OK) +#define SWIG_NEWOBJ (SWIG_OK | SWIG_NEWOBJMASK) +#define SWIG_TMPOBJ (SWIG_OK | SWIG_TMPOBJMASK) +/* Check, add and del mask methods */ +#define SWIG_AddNewMask(r) (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r) +#define SWIG_DelNewMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r) +#define SWIG_IsNewObj(r) (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK)) +#define SWIG_AddTmpMask(r) (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r) +#define SWIG_DelTmpMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r) +#define SWIG_IsTmpObj(r) (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK)) + +/* Cast-Rank Mode */ +#if defined(SWIG_CASTRANK_MODE) +# ifndef SWIG_TypeRank +# define SWIG_TypeRank unsigned long +# endif +# ifndef SWIG_MAXCASTRANK /* Default cast allowed */ +# define SWIG_MAXCASTRANK (2) +# endif +# define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) +# define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) +SWIGINTERNINLINE int SWIG_AddCast(int r) { + return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; +} +SWIGINTERNINLINE int SWIG_CheckState(int r) { + return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; +} +#else /* no cast-rank mode */ +# define SWIG_AddCast +# define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0) +#endif + + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void *(*swig_converter_func)(void *, int *); +typedef struct swig_type_info *(*swig_dycast_func)(void **); + +/* Structure to store information on one type */ +typedef struct swig_type_info { + const char *name; /* mangled name of this type */ + const char *str; /* human readable name of this type */ + swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ + struct swig_cast_info *cast; /* linked list of types that can cast into this type */ + void *clientdata; /* language specific type data */ + int owndata; /* flag if the structure owns the clientdata */ +} swig_type_info; + +/* Structure to store a type and conversion function used for casting */ +typedef struct swig_cast_info { + swig_type_info *type; /* pointer to type that is equivalent to this type */ + swig_converter_func converter; /* function to cast the void pointers */ + struct swig_cast_info *next; /* pointer to next cast in linked list */ + struct swig_cast_info *prev; /* pointer to the previous cast */ +} swig_cast_info; + +/* Structure used to store module information + * Each module generates one structure like this, and the runtime collects + * all of these structures and stores them in a circularly linked list.*/ +typedef struct swig_module_info { + swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ + size_t size; /* Number of types in this module */ + struct swig_module_info *next; /* Pointer to next element in circularly linked list */ + swig_type_info **type_initial; /* Array of initially generated type structures */ + swig_cast_info **cast_initial; /* Array of initially generated casting structures */ + void *clientdata; /* Language specific module data */ +} swig_module_info; + +/* + Compare two type names skipping the space characters, therefore + "char*" == "char *" and "Class" == "Class", etc. + + Return 0 when the two name types are equivalent, as in + strncmp, but skipping ' '. +*/ +SWIGRUNTIME int +SWIG_TypeNameComp(const char *f1, const char *l1, + const char *f2, const char *l2) { + for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { + while ((*f1 == ' ') && (f1 != l1)) ++f1; + while ((*f2 == ' ') && (f2 != l2)) ++f2; + if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; + } + return (int)((l1 - f1) - (l2 - f2)); +} + +/* + Check type equivalence in a name list like ||... + Return 0 if not equal, 1 if equal +*/ +SWIGRUNTIME int +SWIG_TypeEquiv(const char *nb, const char *tb) { + int equiv = 0; + const char* te = tb + strlen(tb); + const char* ne = nb; + while (!equiv && *ne) { + for (nb = ne; *ne; ++ne) { + if (*ne == '|') break; + } + equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; + if (*ne) ++ne; + } + return equiv; +} + +/* + Check type equivalence in a name list like ||... + Return 0 if equal, -1 if nb < tb, 1 if nb > tb +*/ +SWIGRUNTIME int +SWIG_TypeCompare(const char *nb, const char *tb) { + int equiv = 0; + const char* te = tb + strlen(tb); + const char* ne = nb; + while (!equiv && *ne) { + for (nb = ne; *ne; ++ne) { + if (*ne == '|') break; + } + equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; + if (*ne) ++ne; + } + return equiv; +} + + +/* + Check the typename +*/ +SWIGRUNTIME swig_cast_info * +SWIG_TypeCheck(const char *c, swig_type_info *ty) { + if (ty) { + swig_cast_info *iter = ty->cast; + while (iter) { + if (strcmp(iter->type->name, c) == 0) { + if (iter == ty->cast) + return iter; + /* Move iter to the top of the linked list */ + iter->prev->next = iter->next; + if (iter->next) + iter->next->prev = iter->prev; + iter->next = ty->cast; + iter->prev = 0; + if (ty->cast) ty->cast->prev = iter; + ty->cast = iter; + return iter; + } + iter = iter->next; + } + } + return 0; +} + +/* + 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) { + if (ty) { + swig_cast_info *iter = ty->cast; + while (iter) { + if (iter->type == from) { + if (iter == ty->cast) + return iter; + /* Move iter to the top of the linked list */ + iter->prev->next = iter->next; + if (iter->next) + iter->next->prev = iter->prev; + iter->next = ty->cast; + iter->prev = 0; + if (ty->cast) ty->cast->prev = iter; + ty->cast = iter; + return iter; + } + iter = iter->next; + } + } + return 0; +} + +/* + Cast a pointer up an inheritance hierarchy +*/ +SWIGRUNTIMEINLINE void * +SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { + return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); +} + +/* + Dynamic pointer casting. Down an inheritance hierarchy +*/ +SWIGRUNTIME swig_type_info * +SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { + swig_type_info *lastty = ty; + if (!ty || !ty->dcast) return ty; + while (ty && (ty->dcast)) { + ty = (*ty->dcast)(ptr); + if (ty) lastty = ty; + } + return lastty; +} + +/* + Return the name associated with this type +*/ +SWIGRUNTIMEINLINE const char * +SWIG_TypeName(const swig_type_info *ty) { + return ty->name; +} + +/* + Return the pretty name associated with this type, + that is an unmangled type name in a form presentable to the user. +*/ +SWIGRUNTIME const char * +SWIG_TypePrettyName(const swig_type_info *type) { + /* The "str" field contains the equivalent pretty names of the + type, separated by vertical-bar characters. We choose + to print the last name, as it is often (?) the most + specific. */ + if (!type) return NULL; + if (type->str != NULL) { + const char *last_name = type->str; + const char *s; + for (s = type->str; *s; s++) + if (*s == '|') last_name = s+1; + return last_name; + } + else + return type->name; +} + +/* + Set the clientdata field for a type +*/ +SWIGRUNTIME void +SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { + swig_cast_info *cast = ti->cast; + /* if (ti->clientdata == clientdata) return; */ + ti->clientdata = clientdata; + + while (cast) { + if (!cast->converter) { + swig_type_info *tc = cast->type; + if (!tc->clientdata) { + SWIG_TypeClientData(tc, clientdata); + } + } + cast = cast->next; + } +} +SWIGRUNTIME void +SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { + SWIG_TypeClientData(ti, clientdata); + ti->owndata = 1; +} + +/* + Search for a swig_type_info structure only by mangled name + Search is a O(log #types) + + We start searching at module start, and finish searching when start == end. + Note: if start == end at the beginning of the function, we go all the way around + the circular list. +*/ +SWIGRUNTIME swig_type_info * +SWIG_MangledTypeQueryModule(swig_module_info *start, + swig_module_info *end, + const char *name) { + swig_module_info *iter = start; + do { + if (iter->size) { + register size_t l = 0; + register size_t r = iter->size - 1; + do { + /* since l+r >= 0, we can (>> 1) instead (/ 2) */ + register size_t i = (l + r) >> 1; + const char *iname = iter->types[i]->name; + if (iname) { + register int compare = strcmp(name, iname); + if (compare == 0) { + return iter->types[i]; + } else if (compare < 0) { + if (i) { + r = i - 1; + } else { + break; + } + } else if (compare > 0) { + l = i + 1; + } + } else { + break; /* should never happen */ + } + } while (l <= r); + } + iter = iter->next; + } while (iter != end); + return 0; +} + +/* + Search for a swig_type_info structure for either a mangled name or a human readable name. + It first searches the mangled names of the types, which is a O(log #types) + If a type is not found it then searches the human readable names, which is O(#types). + + We start searching at module start, and finish searching when start == end. + Note: if start == end at the beginning of the function, we go all the way around + the circular list. +*/ +SWIGRUNTIME swig_type_info * +SWIG_TypeQueryModule(swig_module_info *start, + swig_module_info *end, + const char *name) { + /* STEP 1: Search the name field using binary search */ + swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); + if (ret) { + return ret; + } else { + /* STEP 2: If the type hasn't been found, do a complete search + of the str field (the human readable name) */ + swig_module_info *iter = start; + do { + register size_t i = 0; + for (; i < iter->size; ++i) { + if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) + return iter->types[i]; + } + iter = iter->next; + } while (iter != end); + } + + /* neither found a match */ + return 0; +} + +/* + Pack binary data into a string +*/ +SWIGRUNTIME char * +SWIG_PackData(char *c, void *ptr, size_t sz) { + static const char hex[17] = "0123456789abcdef"; + register const unsigned char *u = (unsigned char *) ptr; + register const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + register unsigned char uu = *u; + *(c++) = hex[(uu & 0xf0) >> 4]; + *(c++) = hex[uu & 0xf]; + } + return c; +} + +/* + Unpack binary data from a string +*/ +SWIGRUNTIME const char * +SWIG_UnpackData(const char *c, void *ptr, size_t sz) { + register unsigned char *u = (unsigned char *) ptr; + register const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + register char d = *(c++); + register unsigned char uu; + if ((d >= '0') && (d <= '9')) + uu = ((d - '0') << 4); + else if ((d >= 'a') && (d <= 'f')) + uu = ((d - ('a'-10)) << 4); + else + return (char *) 0; + d = *(c++); + if ((d >= '0') && (d <= '9')) + uu |= (d - '0'); + else if ((d >= 'a') && (d <= 'f')) + uu |= (d - ('a'-10)); + else + return (char *) 0; + *u = uu; + } + return c; +} + +/* + Pack 'void *' into a string buffer. +*/ +SWIGRUNTIME char * +SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { + char *r = buff; + if ((2*sizeof(void *) + 2) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r,&ptr,sizeof(void *)); + if (strlen(name) + 1 > (bsz - (r - buff))) return 0; + strcpy(r,name); + return buff; +} + +SWIGRUNTIME const char * +SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { + if (*c != '_') { + if (strcmp(c,"NULL") == 0) { + *ptr = (void *) 0; + return name; + } else { + return 0; + } + } + return SWIG_UnpackData(++c,ptr,sizeof(void *)); +} + +SWIGRUNTIME char * +SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { + char *r = buff; + size_t lname = (name ? strlen(name) : 0); + if ((2*sz + 2 + lname) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r,ptr,sz); + if (lname) { + strncpy(r,name,lname+1); + } else { + *r = 0; + } + return buff; +} + +SWIGRUNTIME const char * +SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { + if (*c != '_') { + if (strcmp(c,"NULL") == 0) { + memset(ptr,0,sz); + return name; + } else { + return 0; + } + } + return SWIG_UnpackData(++c,ptr,sz); +} + +#ifdef __cplusplus +} +#endif + +/* Errors in SWIG */ +#define SWIG_UnknownError -1 +#define SWIG_IOError -2 +#define SWIG_RuntimeError -3 +#define SWIG_IndexError -4 +#define SWIG_TypeError -5 +#define SWIG_DivisionByZero -6 +#define SWIG_OverflowError -7 +#define SWIG_SyntaxError -8 +#define SWIG_ValueError -9 +#define SWIG_SystemError -10 +#define SWIG_AttributeError -11 +#define SWIG_MemoryError -12 +#define SWIG_NullReferenceError -13 + + + +/* Compatibility macros for Python 3 */ +#if PY_VERSION_HEX >= 0x03000000 + +#define PyClass_Check(obj) PyObject_IsInstance(obj, (PyObject *)&PyType_Type) +#define PyInt_Check(x) PyLong_Check(x) +#define PyInt_AsLong(x) PyLong_AsLong(x) +#define PyInt_FromLong(x) PyLong_FromLong(x) +#define PyString_Format(fmt, args) PyUnicode_Format(fmt, args) + +#endif + +#ifndef Py_TYPE +# define Py_TYPE(op) ((op)->ob_type) +#endif + +/* SWIG APIs for compatibility of both Python 2 & 3 */ + +#if PY_VERSION_HEX >= 0x03000000 +# define SWIG_Python_str_FromFormat PyUnicode_FromFormat +#else +# define SWIG_Python_str_FromFormat PyString_FromFormat +#endif + + +/* Warning: This function will allocate a new string in Python 3, + * so please call SWIG_Python_str_DelForPy3(x) to free the space. + */ +SWIGINTERN char* +SWIG_Python_str_AsChar(PyObject *str) +{ +#if PY_VERSION_HEX >= 0x03000000 + char *cstr; + char *newstr; + Py_ssize_t len; + str = PyUnicode_AsUTF8String(str); + PyBytes_AsStringAndSize(str, &cstr, &len); + newstr = (char *) malloc(len+1); + memcpy(newstr, cstr, len+1); + Py_XDECREF(str); + return newstr; +#else + return PyString_AsString(str); +#endif +} + +#if PY_VERSION_HEX >= 0x03000000 +# define SWIG_Python_str_DelForPy3(x) free( (void*) (x) ) +#else +# define SWIG_Python_str_DelForPy3(x) +#endif + + +SWIGINTERN PyObject* +SWIG_Python_str_FromChar(const char *c) +{ +#if PY_VERSION_HEX >= 0x03000000 + return PyUnicode_FromString(c); +#else + return PyString_FromString(c); +#endif +} + +/* Add PyOS_snprintf for old Pythons */ +#if PY_VERSION_HEX < 0x02020000 +# if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WATCOM) +# define PyOS_snprintf _snprintf +# else +# define PyOS_snprintf snprintf +# endif +#endif + +/* A crude PyString_FromFormat implementation for old Pythons */ +#if PY_VERSION_HEX < 0x02020000 + +#ifndef SWIG_PYBUFFER_SIZE +# define SWIG_PYBUFFER_SIZE 1024 +#endif + +static PyObject * +PyString_FromFormat(const char *fmt, ...) { + va_list ap; + char buf[SWIG_PYBUFFER_SIZE * 2]; + int res; + va_start(ap, fmt); + res = vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + return (res < 0 || res >= (int)sizeof(buf)) ? 0 : PyString_FromString(buf); +} +#endif + +/* Add PyObject_Del for old Pythons */ +#if PY_VERSION_HEX < 0x01060000 +# define PyObject_Del(op) PyMem_DEL((op)) +#endif +#ifndef PyObject_DEL +# define PyObject_DEL PyObject_Del +#endif + +/* A crude PyExc_StopIteration exception for old Pythons */ +#if PY_VERSION_HEX < 0x02020000 +# ifndef PyExc_StopIteration +# define PyExc_StopIteration PyExc_RuntimeError +# endif +# ifndef PyObject_GenericGetAttr +# define PyObject_GenericGetAttr 0 +# endif +#endif + +/* Py_NotImplemented is defined in 2.1 and up. */ +#if PY_VERSION_HEX < 0x02010000 +# ifndef Py_NotImplemented +# define Py_NotImplemented PyExc_RuntimeError +# endif +#endif + +/* A crude PyString_AsStringAndSize implementation for old Pythons */ +#if PY_VERSION_HEX < 0x02010000 +# ifndef PyString_AsStringAndSize +# define PyString_AsStringAndSize(obj, s, len) {*s = PyString_AsString(obj); *len = *s ? strlen(*s) : 0;} +# endif +#endif + +/* PySequence_Size for old Pythons */ +#if PY_VERSION_HEX < 0x02000000 +# ifndef PySequence_Size +# define PySequence_Size PySequence_Length +# endif +#endif + +/* PyBool_FromLong for old Pythons */ +#if PY_VERSION_HEX < 0x02030000 +static +PyObject *PyBool_FromLong(long ok) +{ + PyObject *result = ok ? Py_True : Py_False; + Py_INCREF(result); + return result; +} +#endif + +/* Py_ssize_t for old Pythons */ +/* This code is as recommended by: */ +/* http://www.python.org/dev/peps/pep-0353/#conversion-guidelines */ +#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) +typedef int Py_ssize_t; +# define PY_SSIZE_T_MAX INT_MAX +# define PY_SSIZE_T_MIN INT_MIN +#endif + +/* ----------------------------------------------------------------------------- + * error manipulation + * ----------------------------------------------------------------------------- */ + +SWIGRUNTIME PyObject* +SWIG_Python_ErrorType(int code) { + PyObject* type = 0; + switch(code) { + case SWIG_MemoryError: + type = PyExc_MemoryError; + break; + case SWIG_IOError: + type = PyExc_IOError; + break; + case SWIG_RuntimeError: + type = PyExc_RuntimeError; + break; + case SWIG_IndexError: + type = PyExc_IndexError; + break; + case SWIG_TypeError: + type = PyExc_TypeError; + break; + case SWIG_DivisionByZero: + type = PyExc_ZeroDivisionError; + break; + case SWIG_OverflowError: + type = PyExc_OverflowError; + break; + case SWIG_SyntaxError: + type = PyExc_SyntaxError; + break; + case SWIG_ValueError: + type = PyExc_ValueError; + break; + case SWIG_SystemError: + type = PyExc_SystemError; + break; + case SWIG_AttributeError: + type = PyExc_AttributeError; + break; + default: + type = PyExc_RuntimeError; + } + return type; +} + + +SWIGRUNTIME void +SWIG_Python_AddErrorMsg(const char* mesg) +{ + PyObject *type = 0; + PyObject *value = 0; + PyObject *traceback = 0; + + if (PyErr_Occurred()) PyErr_Fetch(&type, &value, &traceback); + if (value) { + char *tmp; + PyObject *old_str = PyObject_Str(value); + PyErr_Clear(); + Py_XINCREF(type); + + PyErr_Format(type, "%s %s", tmp = SWIG_Python_str_AsChar(old_str), mesg); + SWIG_Python_str_DelForPy3(tmp); + Py_DECREF(old_str); + Py_DECREF(value); + } else { + PyErr_SetString(PyExc_RuntimeError, mesg); + } +} + +#if defined(SWIG_PYTHON_NO_THREADS) +# if defined(SWIG_PYTHON_THREADS) +# undef SWIG_PYTHON_THREADS +# endif +#endif +#if defined(SWIG_PYTHON_THREADS) /* Threading support is enabled */ +# if !defined(SWIG_PYTHON_USE_GIL) && !defined(SWIG_PYTHON_NO_USE_GIL) +# if (PY_VERSION_HEX >= 0x02030000) /* For 2.3 or later, use the PyGILState calls */ +# define SWIG_PYTHON_USE_GIL +# endif +# endif +# if defined(SWIG_PYTHON_USE_GIL) /* Use PyGILState threads calls */ +# ifndef SWIG_PYTHON_INITIALIZE_THREADS +# define SWIG_PYTHON_INITIALIZE_THREADS PyEval_InitThreads() +# endif +# ifdef __cplusplus /* C++ code */ + class SWIG_Python_Thread_Block { + bool status; + PyGILState_STATE state; + public: + void end() { if (status) { PyGILState_Release(state); status = false;} } + SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {} + ~SWIG_Python_Thread_Block() { end(); } + }; + class SWIG_Python_Thread_Allow { + bool status; + PyThreadState *save; + public: + void end() { if (status) { PyEval_RestoreThread(save); status = false; }} + SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {} + ~SWIG_Python_Thread_Allow() { end(); } + }; +# define SWIG_PYTHON_THREAD_BEGIN_BLOCK SWIG_Python_Thread_Block _swig_thread_block +# define SWIG_PYTHON_THREAD_END_BLOCK _swig_thread_block.end() +# define SWIG_PYTHON_THREAD_BEGIN_ALLOW SWIG_Python_Thread_Allow _swig_thread_allow +# define SWIG_PYTHON_THREAD_END_ALLOW _swig_thread_allow.end() +# else /* C code */ +# define SWIG_PYTHON_THREAD_BEGIN_BLOCK PyGILState_STATE _swig_thread_block = PyGILState_Ensure() +# define SWIG_PYTHON_THREAD_END_BLOCK PyGILState_Release(_swig_thread_block) +# define SWIG_PYTHON_THREAD_BEGIN_ALLOW PyThreadState *_swig_thread_allow = PyEval_SaveThread() +# define SWIG_PYTHON_THREAD_END_ALLOW PyEval_RestoreThread(_swig_thread_allow) +# endif +# else /* Old thread way, not implemented, user must provide it */ +# if !defined(SWIG_PYTHON_INITIALIZE_THREADS) +# define SWIG_PYTHON_INITIALIZE_THREADS +# endif +# if !defined(SWIG_PYTHON_THREAD_BEGIN_BLOCK) +# define SWIG_PYTHON_THREAD_BEGIN_BLOCK +# endif +# if !defined(SWIG_PYTHON_THREAD_END_BLOCK) +# define SWIG_PYTHON_THREAD_END_BLOCK +# endif +# if !defined(SWIG_PYTHON_THREAD_BEGIN_ALLOW) +# define SWIG_PYTHON_THREAD_BEGIN_ALLOW +# endif +# if !defined(SWIG_PYTHON_THREAD_END_ALLOW) +# define SWIG_PYTHON_THREAD_END_ALLOW +# endif +# endif +#else /* No thread support */ +# define SWIG_PYTHON_INITIALIZE_THREADS +# define SWIG_PYTHON_THREAD_BEGIN_BLOCK +# define SWIG_PYTHON_THREAD_END_BLOCK +# define SWIG_PYTHON_THREAD_BEGIN_ALLOW +# define SWIG_PYTHON_THREAD_END_ALLOW +#endif + +/* ----------------------------------------------------------------------------- + * Python API portion that goes into the runtime + * ----------------------------------------------------------------------------- */ + +#ifdef __cplusplus +extern "C" { +#if 0 +} /* cc-mode */ +#endif +#endif + +/* ----------------------------------------------------------------------------- + * Constant declarations + * ----------------------------------------------------------------------------- */ + +/* Constant Types */ +#define SWIG_PY_POINTER 4 +#define SWIG_PY_BINARY 5 + +/* Constant information structure */ +typedef struct swig_const_info { + int type; + char *name; + long lvalue; + double dvalue; + void *pvalue; + swig_type_info **ptype; +} swig_const_info; + + +/* ----------------------------------------------------------------------------- + * Wrapper of PyInstanceMethod_New() used in Python 3 + * It is exported to the generated module, used for -fastproxy + * ----------------------------------------------------------------------------- */ +SWIGRUNTIME PyObject* SWIG_PyInstanceMethod_New(PyObject *self, PyObject *func) +{ +#if PY_VERSION_HEX >= 0x03000000 + return PyInstanceMethod_New(func); +#else + return NULL; +#endif +} + +#ifdef __cplusplus +#if 0 +{ /* cc-mode */ +#endif +} +#endif + + +/* ----------------------------------------------------------------------------- + * pyrun.swg + * + * This file contains the runtime support for Python modules + * and includes code for managing global variables and pointer + * type checking. + * + * ----------------------------------------------------------------------------- */ + +/* Common SWIG API */ + +/* for raw pointers */ +#define SWIG_Python_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, 0) +#define SWIG_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtr(obj, pptr, type, flags) +#define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, own) +#define SWIG_NewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(ptr, type, flags) +#define SWIG_CheckImplicit(ty) SWIG_Python_CheckImplicit(ty) +#define SWIG_AcquirePtr(ptr, src) SWIG_Python_AcquirePtr(ptr, src) +#define swig_owntype int + +/* for raw packed data */ +#define SWIG_ConvertPacked(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) +#define SWIG_NewPackedObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) + +/* for class or struct pointers */ +#define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_ConvertPtr(obj, pptr, type, flags) +#define SWIG_NewInstanceObj(ptr, type, flags) SWIG_NewPointerObj(ptr, type, flags) + +/* for C or C++ function pointers */ +#define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_Python_ConvertFunctionPtr(obj, pptr, type) +#define SWIG_NewFunctionPtrObj(ptr, type) SWIG_Python_NewPointerObj(ptr, type, 0) + +/* for C++ member pointers, ie, member methods */ +#define SWIG_ConvertMember(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) +#define SWIG_NewMemberObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) + + +/* Runtime API */ + +#define SWIG_GetModule(clientdata) SWIG_Python_GetModule() +#define SWIG_SetModule(clientdata, pointer) SWIG_Python_SetModule(pointer) +#define SWIG_NewClientData(obj) SwigPyClientData_New(obj) + +#define SWIG_SetErrorObj SWIG_Python_SetErrorObj +#define SWIG_SetErrorMsg SWIG_Python_SetErrorMsg +#define SWIG_ErrorType(code) SWIG_Python_ErrorType(code) +#define SWIG_Error(code, msg) SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) +#define SWIG_fail goto fail + + +/* Runtime API implementation */ + +/* Error manipulation */ + +SWIGINTERN void +SWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) { + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + PyErr_SetObject(errtype, obj); + Py_DECREF(obj); + SWIG_PYTHON_THREAD_END_BLOCK; +} + +SWIGINTERN void +SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) { + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + PyErr_SetString(errtype, (char *) msg); + SWIG_PYTHON_THREAD_END_BLOCK; +} + +#define SWIG_Python_Raise(obj, type, desc) SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj) + +/* Set a constant value */ + +SWIGINTERN void +SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) { + PyDict_SetItemString(d, (char*) name, obj); + Py_DECREF(obj); +} + +/* Append a value to the result obj */ + +SWIGINTERN PyObject* +SWIG_Python_AppendOutput(PyObject* result, PyObject* obj) { +#if !defined(SWIG_PYTHON_OUTPUT_TUPLE) + if (!result) { + result = obj; + } else if (result == Py_None) { + Py_DECREF(result); + result = obj; + } else { + if (!PyList_Check(result)) { + PyObject *o2 = result; + result = PyList_New(1); + PyList_SetItem(result, 0, o2); + } + PyList_Append(result,obj); + Py_DECREF(obj); + } + return result; +#else + PyObject* o2; + PyObject* o3; + if (!result) { + result = obj; + } else if (result == Py_None) { + Py_DECREF(result); + result = obj; + } else { + if (!PyTuple_Check(result)) { + o2 = result; + result = PyTuple_New(1); + PyTuple_SET_ITEM(result, 0, o2); + } + o3 = PyTuple_New(1); + PyTuple_SET_ITEM(o3, 0, obj); + o2 = result; + result = PySequence_Concat(o2, o3); + Py_DECREF(o2); + Py_DECREF(o3); + } + return result; +#endif +} + +/* Unpack the argument tuple */ + +SWIGINTERN int +SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs) +{ + if (!args) { + if (!min && !max) { + return 1; + } else { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", + name, (min == max ? "" : "at least "), (int)min); + return 0; + } + } + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple"); + return 0; + } else { + register Py_ssize_t l = PyTuple_GET_SIZE(args); + if (l < min) { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", + name, (min == max ? "" : "at least "), (int)min, (int)l); + return 0; + } else if (l > max) { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", + name, (min == max ? "" : "at most "), (int)max, (int)l); + return 0; + } else { + register int i; + for (i = 0; i < l; ++i) { + objs[i] = PyTuple_GET_ITEM(args, i); + } + for (; l < max; ++l) { + objs[l] = 0; + } + return i + 1; + } + } +} + +/* A functor is a function object with one single object argument */ +#if PY_VERSION_HEX >= 0x02020000 +#define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunctionObjArgs(functor, obj, NULL); +#else +#define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunction(functor, "O", obj); +#endif + +/* + Helper for static pointer initialization for both C and C++ code, for example + static PyObject *SWIG_STATIC_POINTER(MyVar) = NewSomething(...); +*/ +#ifdef __cplusplus +#define SWIG_STATIC_POINTER(var) var +#else +#define SWIG_STATIC_POINTER(var) var = 0; if (!var) var +#endif + +/* ----------------------------------------------------------------------------- + * Pointer declarations + * ----------------------------------------------------------------------------- */ + +/* Flags for new pointer objects */ +#define SWIG_POINTER_NOSHADOW (SWIG_POINTER_OWN << 1) +#define SWIG_POINTER_NEW (SWIG_POINTER_NOSHADOW | SWIG_POINTER_OWN) + +#define SWIG_POINTER_IMPLICIT_CONV (SWIG_POINTER_DISOWN << 1) + +#ifdef __cplusplus +extern "C" { +#if 0 +} /* cc-mode */ +#endif +#endif + +/* How to access Py_None */ +#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) +# ifndef SWIG_PYTHON_NO_BUILD_NONE +# ifndef SWIG_PYTHON_BUILD_NONE +# define SWIG_PYTHON_BUILD_NONE +# endif +# endif +#endif + +#ifdef SWIG_PYTHON_BUILD_NONE +# ifdef Py_None +# undef Py_None +# define Py_None SWIG_Py_None() +# endif +SWIGRUNTIMEINLINE PyObject * +_SWIG_Py_None(void) +{ + PyObject *none = Py_BuildValue((char*)""); + Py_DECREF(none); + return none; +} +SWIGRUNTIME PyObject * +SWIG_Py_None(void) +{ + static PyObject *SWIG_STATIC_POINTER(none) = _SWIG_Py_None(); + return none; +} +#endif + +/* The python void return value */ + +SWIGRUNTIMEINLINE PyObject * +SWIG_Py_Void(void) +{ + PyObject *none = Py_None; + Py_INCREF(none); + return none; +} + +/* SwigPyClientData */ + +typedef struct { + PyObject *klass; + PyObject *newraw; + PyObject *newargs; + PyObject *destroy; + int delargs; + int implicitconv; +} SwigPyClientData; + +SWIGRUNTIMEINLINE int +SWIG_Python_CheckImplicit(swig_type_info *ty) +{ + SwigPyClientData *data = (SwigPyClientData *)ty->clientdata; + return data ? data->implicitconv : 0; +} + +SWIGRUNTIMEINLINE PyObject * +SWIG_Python_ExceptionType(swig_type_info *desc) { + SwigPyClientData *data = desc ? (SwigPyClientData *) desc->clientdata : 0; + PyObject *klass = data ? data->klass : 0; + return (klass ? klass : PyExc_RuntimeError); +} + + +SWIGRUNTIME SwigPyClientData * +SwigPyClientData_New(PyObject* obj) +{ + if (!obj) { + return 0; + } else { + SwigPyClientData *data = (SwigPyClientData *)malloc(sizeof(SwigPyClientData)); + /* the klass element */ + data->klass = obj; + Py_INCREF(data->klass); + /* 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); + } else { +#if (PY_VERSION_HEX < 0x02020000) + data->newraw = 0; +#else + data->newraw = PyObject_GetAttrString(data->klass, (char *)"__new__"); +#endif + if (data->newraw) { + Py_INCREF(data->newraw); + data->newargs = PyTuple_New(1); + PyTuple_SetItem(data->newargs, 0, obj); + } else { + data->newargs = obj; + } + Py_INCREF(data->newargs); + } + /* the destroy method, aka as the C++ delete method */ + data->destroy = PyObject_GetAttrString(data->klass, (char *)"__swig_destroy__"); + if (PyErr_Occurred()) { + PyErr_Clear(); + data->destroy = 0; + } + if (data->destroy) { + int flags; + Py_INCREF(data->destroy); + flags = PyCFunction_GET_FLAGS(data->destroy); +#ifdef METH_O + data->delargs = !(flags & (METH_O)); +#else + data->delargs = 0; +#endif + } else { + data->delargs = 0; + } + data->implicitconv = 0; + return data; + } +} + +SWIGRUNTIME void +SwigPyClientData_Del(SwigPyClientData* data) +{ + Py_XDECREF(data->newraw); + Py_XDECREF(data->newargs); + Py_XDECREF(data->destroy); +} + +/* =============== SwigPyObject =====================*/ + +typedef struct { + PyObject_HEAD + void *ptr; + swig_type_info *ty; + int own; + PyObject *next; +} SwigPyObject; + +SWIGRUNTIME PyObject * +SwigPyObject_long(SwigPyObject *v) +{ + return PyLong_FromVoidPtr(v->ptr); +} + +SWIGRUNTIME PyObject * +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); + if (ofmt) { +#if PY_VERSION_HEX >= 0x03000000 + res = PyUnicode_Format(ofmt,args); +#else + res = PyString_Format(ofmt,args); +#endif + Py_DECREF(ofmt); + } + Py_DECREF(args); + } + } + return res; +} + +SWIGRUNTIME PyObject * +SwigPyObject_oct(SwigPyObject *v) +{ + return SwigPyObject_format("%o",v); +} + +SWIGRUNTIME PyObject * +SwigPyObject_hex(SwigPyObject *v) +{ + return SwigPyObject_format("%x",v); +} + +SWIGRUNTIME PyObject * +#ifdef METH_NOARGS +SwigPyObject_repr(SwigPyObject *v) +#else +SwigPyObject_repr(SwigPyObject *v, PyObject *args) +#endif +{ + const char *name = SWIG_TypePrettyName(v->ty); + PyObject *repr = SWIG_Python_str_FromFormat("", name, v); + if (v->next) { +#ifdef METH_NOARGS + PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next); +#else + PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next, args); +#endif +#if PY_VERSION_HEX >= 0x03000000 + PyObject *joined = PyUnicode_Concat(repr, nrep); + Py_DecRef(repr); + Py_DecRef(nrep); + repr = joined; +#else + PyString_ConcatAndDel(&repr,nrep); +#endif + } + return repr; +} + +SWIGRUNTIME int +SwigPyObject_print(SwigPyObject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) +{ + char *str; +#ifdef METH_NOARGS + PyObject *repr = SwigPyObject_repr(v); +#else + PyObject *repr = SwigPyObject_repr(v, NULL); +#endif + if (repr) { + str = SWIG_Python_str_AsChar(repr); + fputs(str, fp); + SWIG_Python_str_DelForPy3(str); + Py_DECREF(repr); + return 0; + } else { + return 1; + } +} + +SWIGRUNTIME PyObject * +SwigPyObject_str(SwigPyObject *v) +{ + char result[SWIG_BUFFER_SIZE]; + return SWIG_PackVoidPtr(result, v->ptr, v->ty->name, sizeof(result)) ? + SWIG_Python_str_FromChar(result) : 0; +} + +SWIGRUNTIME int +SwigPyObject_compare(SwigPyObject *v, SwigPyObject *w) +{ + void *i = v->ptr; + void *j = w->ptr; + return (i < j) ? -1 : ((i > j) ? 1 : 0); +} + +/* Added for Python 3.x, would it also be useful for Python 2.x? */ +SWIGRUNTIME PyObject* +SwigPyObject_richcompare(SwigPyObject *v, SwigPyObject *w, int op) +{ + PyObject* res; + if( op != Py_EQ && op != Py_NE ) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + if( (SwigPyObject_compare(v, w)==0) == (op == Py_EQ) ) + res = Py_True; + else + res = Py_False; + Py_INCREF(res); + return res; +} + + +SWIGRUNTIME PyTypeObject* _PySwigObject_type(void); + +SWIGRUNTIME PyTypeObject* +SwigPyObject_type(void) { + static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigObject_type(); + return type; +} + +SWIGRUNTIMEINLINE int +SwigPyObject_Check(PyObject *op) { + return (Py_TYPE(op) == SwigPyObject_type()) + || (strcmp(Py_TYPE(op)->tp_name,"SwigPyObject") == 0); +} + +SWIGRUNTIME PyObject * +SwigPyObject_New(void *ptr, swig_type_info *ty, int own); + +SWIGRUNTIME void +SwigPyObject_dealloc(PyObject *v) +{ + SwigPyObject *sobj = (SwigPyObject *) v; + PyObject *next = sobj->next; + if (sobj->own == SWIG_POINTER_OWN) { + swig_type_info *ty = sobj->ty; + SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; + PyObject *destroy = data ? data->destroy : 0; + if (destroy) { + /* destroy is always a VARARGS method */ + PyObject *res; + 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); + } else { + PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); + PyObject *mself = PyCFunction_GET_SELF(destroy); + res = ((*meth)(mself, v)); + } + Py_XDECREF(res); + } +#if !defined(SWIG_PYTHON_SILENT_MEMLEAK) + else { + const char *name = SWIG_TypePrettyName(ty); + printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown")); + } +#endif + } + Py_XDECREF(next); + PyObject_DEL(v); +} + +SWIGRUNTIME PyObject* +SwigPyObject_append(PyObject* v, PyObject* next) +{ + SwigPyObject *sobj = (SwigPyObject *) v; +#ifndef METH_O + PyObject *tmp = 0; + if (!PyArg_ParseTuple(next,(char *)"O:append", &tmp)) return NULL; + next = tmp; +#endif + if (!SwigPyObject_Check(next)) { + return NULL; + } + sobj->next = next; + Py_INCREF(next); + return SWIG_Py_Void(); +} + +SWIGRUNTIME PyObject* +#ifdef METH_NOARGS +SwigPyObject_next(PyObject* v) +#else +SwigPyObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) +#endif +{ + SwigPyObject *sobj = (SwigPyObject *) v; + if (sobj->next) { + Py_INCREF(sobj->next); + return sobj->next; + } else { + return SWIG_Py_Void(); + } +} + +SWIGINTERN PyObject* +#ifdef METH_NOARGS +SwigPyObject_disown(PyObject *v) +#else +SwigPyObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) +#endif +{ + SwigPyObject *sobj = (SwigPyObject *)v; + sobj->own = 0; + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject* +#ifdef METH_NOARGS +SwigPyObject_acquire(PyObject *v) +#else +SwigPyObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) +#endif +{ + SwigPyObject *sobj = (SwigPyObject *)v; + sobj->own = SWIG_POINTER_OWN; + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject* +SwigPyObject_own(PyObject *v, PyObject *args) +{ + PyObject *val = 0; +#if (PY_VERSION_HEX < 0x02020000) + if (!PyArg_ParseTuple(args,(char *)"|O:own",&val)) +#else + if (!PyArg_UnpackTuple(args, (char *)"own", 0, 1, &val)) +#endif + { + return NULL; + } + else + { + SwigPyObject *sobj = (SwigPyObject *)v; + PyObject *obj = PyBool_FromLong(sobj->own); + if (val) { +#ifdef METH_NOARGS + if (PyObject_IsTrue(val)) { + SwigPyObject_acquire(v); + } else { + SwigPyObject_disown(v); + } +#else + if (PyObject_IsTrue(val)) { + SwigPyObject_acquire(v,args); + } else { + SwigPyObject_disown(v,args); + } +#endif + } + return obj; + } +} + +#ifdef METH_O +static PyMethodDef +swigobject_methods[] = { + {(char *)"disown", (PyCFunction)SwigPyObject_disown, METH_NOARGS, (char *)"releases ownership of the pointer"}, + {(char *)"acquire", (PyCFunction)SwigPyObject_acquire, METH_NOARGS, (char *)"aquires ownership of the pointer"}, + {(char *)"own", (PyCFunction)SwigPyObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, + {(char *)"append", (PyCFunction)SwigPyObject_append, METH_O, (char *)"appends another 'this' object"}, + {(char *)"next", (PyCFunction)SwigPyObject_next, METH_NOARGS, (char *)"returns the next 'this' object"}, + {(char *)"__repr__",(PyCFunction)SwigPyObject_repr, METH_NOARGS, (char *)"returns object representation"}, + {0, 0, 0, 0} +}; +#else +static PyMethodDef +swigobject_methods[] = { + {(char *)"disown", (PyCFunction)SwigPyObject_disown, METH_VARARGS, (char *)"releases ownership of the pointer"}, + {(char *)"acquire", (PyCFunction)SwigPyObject_acquire, METH_VARARGS, (char *)"aquires ownership of the pointer"}, + {(char *)"own", (PyCFunction)SwigPyObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, + {(char *)"append", (PyCFunction)SwigPyObject_append, METH_VARARGS, (char *)"appends another 'this' object"}, + {(char *)"next", (PyCFunction)SwigPyObject_next, METH_VARARGS, (char *)"returns the next 'this' object"}, + {(char *)"__repr__",(PyCFunction)SwigPyObject_repr, METH_VARARGS, (char *)"returns object representation"}, + {0, 0, 0, 0} +}; +#endif + +#if PY_VERSION_HEX < 0x02020000 +SWIGINTERN PyObject * +SwigPyObject_getattr(SwigPyObject *sobj,char *name) +{ + return Py_FindMethod(swigobject_methods, (PyObject *)sobj, name); +} +#endif + +SWIGRUNTIME PyTypeObject* +_PySwigObject_type(void) { + static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer"; + + static PyNumberMethods SwigPyObject_as_number = { + (binaryfunc)0, /*nb_add*/ + (binaryfunc)0, /*nb_subtract*/ + (binaryfunc)0, /*nb_multiply*/ + /* nb_divide removed in Python 3 */ +#if PY_VERSION_HEX < 0x03000000 + (binaryfunc)0, /*nb_divide*/ +#endif + (binaryfunc)0, /*nb_remainder*/ + (binaryfunc)0, /*nb_divmod*/ + (ternaryfunc)0,/*nb_power*/ + (unaryfunc)0, /*nb_negative*/ + (unaryfunc)0, /*nb_positive*/ + (unaryfunc)0, /*nb_absolute*/ + (inquiry)0, /*nb_nonzero*/ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + 0, /*nb_and*/ + 0, /*nb_xor*/ + 0, /*nb_or*/ +#if PY_VERSION_HEX < 0x03000000 + 0, /*nb_coerce*/ +#endif + (unaryfunc)SwigPyObject_long, /*nb_int*/ +#if PY_VERSION_HEX < 0x03000000 + (unaryfunc)SwigPyObject_long, /*nb_long*/ +#else + 0, /*nb_reserved*/ +#endif + (unaryfunc)0, /*nb_float*/ +#if PY_VERSION_HEX < 0x03000000 + (unaryfunc)SwigPyObject_oct, /*nb_oct*/ + (unaryfunc)SwigPyObject_hex, /*nb_hex*/ +#endif +#if PY_VERSION_HEX >= 0x03000000 /* 3.0 */ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index, nb_inplace_divide removed */ +#elif PY_VERSION_HEX >= 0x02050000 /* 2.5.0 */ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */ +#elif PY_VERSION_HEX >= 0x02020000 /* 2.2.0 */ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_true_divide */ +#elif PY_VERSION_HEX >= 0x02000000 /* 2.0.0 */ + 0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_or */ +#endif + }; + + static PyTypeObject swigpyobject_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp + = { + /* PyObject header changed in Python 3 */ +#if PY_VERSION_HEX >= 0x03000000 + PyVarObject_HEAD_INIT(&PyType_Type, 0) +#else + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ +#endif + (char *)"SwigPyObject", /* tp_name */ + sizeof(SwigPyObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)SwigPyObject_dealloc, /* tp_dealloc */ + (printfunc)SwigPyObject_print, /* tp_print */ +#if PY_VERSION_HEX < 0x02020000 + (getattrfunc)SwigPyObject_getattr, /* tp_getattr */ +#else + (getattrfunc)0, /* tp_getattr */ +#endif + (setattrfunc)0, /* tp_setattr */ +#if PY_VERSION_HEX >= 0x03000000 + 0, /* tp_reserved in 3.0.1, tp_compare in 3.0.0 but not used */ +#else + (cmpfunc)SwigPyObject_compare, /* tp_compare */ +#endif + (reprfunc)SwigPyObject_repr, /* tp_repr */ + &SwigPyObject_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)0, /* tp_hash */ + (ternaryfunc)0, /* tp_call */ + (reprfunc)SwigPyObject_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + swigobject_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + (richcmpfunc)SwigPyObject_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ +#if PY_VERSION_HEX >= 0x02020000 + 0, /* tp_iter */ + 0, /* tp_iternext */ + swigobject_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ + 0, /* tp_bases */ + 0, /* tp_mro */ + 0, /* tp_cache */ + 0, /* tp_subclasses */ + 0, /* tp_weaklist */ +#endif +#if PY_VERSION_HEX >= 0x02030000 + 0, /* tp_del */ +#endif +#ifdef COUNT_ALLOCS + 0,0,0,0 /* tp_alloc -> tp_next */ +#endif + }; + swigpyobject_type = tmp; + /* for Python 3 we already assigned ob_type in PyVarObject_HEAD_INIT() */ +#if PY_VERSION_HEX < 0x03000000 + swigpyobject_type.ob_type = &PyType_Type; +#endif + type_init = 1; + } + return &swigpyobject_type; +} + +SWIGRUNTIME PyObject * +SwigPyObject_New(void *ptr, swig_type_info *ty, int own) +{ + SwigPyObject *sobj = PyObject_NEW(SwigPyObject, SwigPyObject_type()); + if (sobj) { + sobj->ptr = ptr; + sobj->ty = ty; + sobj->own = own; + sobj->next = 0; + } + return (PyObject *)sobj; +} + +/* ----------------------------------------------------------------------------- + * Implements a simple Swig Packed type, and use it instead of string + * ----------------------------------------------------------------------------- */ + +typedef struct { + PyObject_HEAD + void *pack; + swig_type_info *ty; + size_t size; +} SwigPyPacked; + +SWIGRUNTIME int +SwigPyPacked_print(SwigPyPacked *v, FILE *fp, int SWIGUNUSEDPARM(flags)) +{ + char result[SWIG_BUFFER_SIZE]; + fputs("pack, v->size, 0, sizeof(result))) { + fputs("at ", fp); + fputs(result, fp); + } + fputs(v->ty->name,fp); + fputs(">", fp); + return 0; +} + +SWIGRUNTIME PyObject * +SwigPyPacked_repr(SwigPyPacked *v) +{ + char result[SWIG_BUFFER_SIZE]; + if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { + return SWIG_Python_str_FromFormat("", result, v->ty->name); + } else { + return SWIG_Python_str_FromFormat("", v->ty->name); + } +} + +SWIGRUNTIME PyObject * +SwigPyPacked_str(SwigPyPacked *v) +{ + char result[SWIG_BUFFER_SIZE]; + if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){ + return SWIG_Python_str_FromFormat("%s%s", result, v->ty->name); + } else { + return SWIG_Python_str_FromChar(v->ty->name); + } +} + +SWIGRUNTIME int +SwigPyPacked_compare(SwigPyPacked *v, SwigPyPacked *w) +{ + size_t i = v->size; + size_t j = w->size; + int s = (i < j) ? -1 : ((i > j) ? 1 : 0); + return s ? s : strncmp((char *)v->pack, (char *)w->pack, 2*v->size); +} + +SWIGRUNTIME PyTypeObject* _PySwigPacked_type(void); + +SWIGRUNTIME PyTypeObject* +SwigPyPacked_type(void) { + static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigPacked_type(); + return type; +} + +SWIGRUNTIMEINLINE int +SwigPyPacked_Check(PyObject *op) { + return ((op)->ob_type == _PySwigPacked_type()) + || (strcmp((op)->ob_type->tp_name,"SwigPyPacked") == 0); +} + +SWIGRUNTIME void +SwigPyPacked_dealloc(PyObject *v) +{ + if (SwigPyPacked_Check(v)) { + SwigPyPacked *sobj = (SwigPyPacked *) v; + free(sobj->pack); + } + PyObject_DEL(v); +} + +SWIGRUNTIME PyTypeObject* +_PySwigPacked_type(void) { + static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer"; + static PyTypeObject swigpypacked_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp + = { + /* PyObject header changed in Python 3 */ +#if PY_VERSION_HEX>=0x03000000 + PyVarObject_HEAD_INIT(&PyType_Type, 0) +#else + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ +#endif + (char *)"SwigPyPacked", /* tp_name */ + sizeof(SwigPyPacked), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)SwigPyPacked_dealloc, /* tp_dealloc */ + (printfunc)SwigPyPacked_print, /* tp_print */ + (getattrfunc)0, /* tp_getattr */ + (setattrfunc)0, /* tp_setattr */ +#if PY_VERSION_HEX>=0x03000000 + 0, /* tp_reserved in 3.0.1 */ +#else + (cmpfunc)SwigPyPacked_compare, /* tp_compare */ +#endif + (reprfunc)SwigPyPacked_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)0, /* tp_hash */ + (ternaryfunc)0, /* tp_call */ + (reprfunc)SwigPyPacked_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + swigpacked_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ +#if PY_VERSION_HEX >= 0x02020000 + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ + 0, /* tp_bases */ + 0, /* tp_mro */ + 0, /* tp_cache */ + 0, /* tp_subclasses */ + 0, /* tp_weaklist */ +#endif +#if PY_VERSION_HEX >= 0x02030000 + 0, /* tp_del */ +#endif +#ifdef COUNT_ALLOCS + 0,0,0,0 /* tp_alloc -> tp_next */ +#endif + }; + swigpypacked_type = tmp; + /* for Python 3 the ob_type already assigned in PyVarObject_HEAD_INIT() */ +#if PY_VERSION_HEX < 0x03000000 + swigpypacked_type.ob_type = &PyType_Type; +#endif + type_init = 1; + } + return &swigpypacked_type; +} + +SWIGRUNTIME PyObject * +SwigPyPacked_New(void *ptr, size_t size, swig_type_info *ty) +{ + SwigPyPacked *sobj = PyObject_NEW(SwigPyPacked, SwigPyPacked_type()); + if (sobj) { + void *pack = malloc(size); + if (pack) { + memcpy(pack, ptr, size); + sobj->pack = pack; + sobj->ty = ty; + sobj->size = size; + } else { + PyObject_DEL((PyObject *) sobj); + sobj = 0; + } + } + return (PyObject *) sobj; +} + +SWIGRUNTIME swig_type_info * +SwigPyPacked_UnpackData(PyObject *obj, void *ptr, size_t size) +{ + if (SwigPyPacked_Check(obj)) { + SwigPyPacked *sobj = (SwigPyPacked *)obj; + if (sobj->size != size) return 0; + memcpy(ptr, sobj->pack, size); + return sobj->ty; + } else { + return 0; + } +} + +/* ----------------------------------------------------------------------------- + * pointers/data manipulation + * ----------------------------------------------------------------------------- */ + +SWIGRUNTIMEINLINE PyObject * +_SWIG_This(void) +{ + return SWIG_Python_str_FromChar("this"); +} + +SWIGRUNTIME PyObject * +SWIG_This(void) +{ + static PyObject *SWIG_STATIC_POINTER(swig_this) = _SWIG_This(); + return swig_this; +} + +/* #define SWIG_PYTHON_SLOW_GETSET_THIS */ + +/* TODO: I don't know how to implement the fast getset in Python 3 right now */ +#if PY_VERSION_HEX>=0x03000000 +#define SWIG_PYTHON_SLOW_GETSET_THIS +#endif + +SWIGRUNTIME SwigPyObject * +SWIG_Python_GetSwigThis(PyObject *pyobj) +{ + if (SwigPyObject_Check(pyobj)) { + return (SwigPyObject *) pyobj; + } else { + PyObject *obj = 0; +#if (!defined(SWIG_PYTHON_SLOW_GETSET_THIS) && (PY_VERSION_HEX >= 0x02030000)) + if (PyInstance_Check(pyobj)) { + obj = _PyInstance_Lookup(pyobj, SWIG_This()); + } else { + PyObject **dictptr = _PyObject_GetDictPtr(pyobj); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0; + } else { +#ifdef PyWeakref_CheckProxy + if (PyWeakref_CheckProxy(pyobj)) { + PyObject *wobj = PyWeakref_GET_OBJECT(pyobj); + return wobj ? SWIG_Python_GetSwigThis(wobj) : 0; + } +#endif + obj = PyObject_GetAttr(pyobj,SWIG_This()); + if (obj) { + Py_DECREF(obj); + } else { + if (PyErr_Occurred()) PyErr_Clear(); + return 0; + } + } + } +#else + obj = PyObject_GetAttr(pyobj,SWIG_This()); + if (obj) { + Py_DECREF(obj); + } else { + if (PyErr_Occurred()) PyErr_Clear(); + return 0; + } +#endif + if (obj && !SwigPyObject_Check(obj)) { + /* a PyObject is called 'this', try to get the 'real this' + SwigPyObject from it */ + return SWIG_Python_GetSwigThis(obj); + } + return (SwigPyObject *)obj; + } +} + +/* Acquire a pointer value */ + +SWIGRUNTIME int +SWIG_Python_AcquirePtr(PyObject *obj, int own) { + if (own == SWIG_POINTER_OWN) { + SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj); + if (sobj) { + int oldown = sobj->own; + sobj->own = own; + return oldown; + } + } + return 0; +} + +/* Convert a pointer value */ + +SWIGRUNTIME int +SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) { + if (!obj) return SWIG_ERROR; + if (obj == Py_None) { + if (ptr) *ptr = 0; + return SWIG_OK; + } else { + SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj); + if (own) + *own = 0; + while (sobj) { + void *vptr = sobj->ptr; + if (ty) { + swig_type_info *to = sobj->ty; + if (to == ty) { + /* no type cast needed */ + if (ptr) *ptr = vptr; + break; + } else { + swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); + if (!tc) { + sobj = (SwigPyObject *)sobj->next; + } else { + if (ptr) { + int newmemory = 0; + *ptr = SWIG_TypeCast(tc,vptr,&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 = *own | SWIG_CAST_NEW_MEMORY; + } + } + break; + } + } + } else { + if (ptr) *ptr = vptr; + break; + } + } + if (sobj) { + if (own) + *own = *own | sobj->own; + if (flags & SWIG_POINTER_DISOWN) { + sobj->own = 0; + } + return SWIG_OK; + } else { + int res = SWIG_ERROR; + if (flags & SWIG_POINTER_IMPLICIT_CONV) { + SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; + if (data && !data->implicitconv) { + PyObject *klass = data->klass; + if (klass) { + PyObject *impconv; + data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/ + impconv = SWIG_Python_CallFunctor(klass, obj); + data->implicitconv = 0; + if (PyErr_Occurred()) { + PyErr_Clear(); + impconv = 0; + } + if (impconv) { + SwigPyObject *iobj = SWIG_Python_GetSwigThis(impconv); + if (iobj) { + void *vptr; + res = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0); + if (SWIG_IsOK(res)) { + if (ptr) { + *ptr = vptr; + /* transfer the ownership to 'ptr' */ + iobj->own = 0; + res = SWIG_AddCast(res); + res = SWIG_AddNewMask(res); + } else { + res = SWIG_AddCast(res); + } + } + } + Py_DECREF(impconv); + } + } + } + } + return res; + } + } +} + +/* Convert a function ptr value */ + +SWIGRUNTIME int +SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) { + if (!PyCFunction_Check(obj)) { + return SWIG_ConvertPtr(obj, ptr, ty, 0); + } else { + void *vptr = 0; + + /* here we get the method pointer for callbacks */ + const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc); + const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0; + if (desc) + desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0; + if (!desc) + return SWIG_ERROR; + if (ty) { + swig_cast_info *tc = SWIG_TypeCheck(desc,ty); + if (tc) { + int newmemory = 0; + *ptr = SWIG_TypeCast(tc,vptr,&newmemory); + assert(!newmemory); /* newmemory handling not yet implemented */ + } else { + return SWIG_ERROR; + } + } else { + *ptr = vptr; + } + return SWIG_OK; + } +} + +/* Convert a packed value value */ + +SWIGRUNTIME int +SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) { + swig_type_info *to = SwigPyPacked_UnpackData(obj, ptr, sz); + if (!to) return SWIG_ERROR; + if (ty) { + if (to != ty) { + /* check type cast? */ + swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); + if (!tc) return SWIG_ERROR; + } + } + return SWIG_OK; +} + +/* ----------------------------------------------------------------------------- + * Create a new pointer object + * ----------------------------------------------------------------------------- */ + +/* + Create a new instance object, without calling __init__, and set the + 'this' attribute. +*/ + +SWIGRUNTIME PyObject* +SWIG_Python_NewShadowInstance(SwigPyClientData *data, PyObject *swig_this) +{ +#if (PY_VERSION_HEX >= 0x02020000) + PyObject *inst = 0; + PyObject *newraw = data->newraw; + if (newraw) { + inst = PyObject_Call(newraw, data->newargs, NULL); + if (inst) { +#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); + } + } +#else + PyObject *key = SWIG_This(); + PyObject_SetAttr(inst, key, swig_this); +#endif + } + } else { +#if PY_VERSION_HEX >= 0x03000000 + inst = PyBaseObject_Type.tp_new((PyTypeObject*) data->newargs, Py_None, Py_None); + PyObject_SetAttr(inst, SWIG_This(), swig_this); + Py_TYPE(inst)->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG; +#else + PyObject *dict = PyDict_New(); + PyDict_SetItem(dict, SWIG_This(), swig_this); + inst = PyInstance_NewRaw(data->newargs, dict); + Py_DECREF(dict); +#endif + } + return inst; +#else +#if (PY_VERSION_HEX >= 0x02010000) + PyObject *inst; + PyObject *dict = PyDict_New(); + PyDict_SetItem(dict, SWIG_This(), swig_this); + inst = PyInstance_NewRaw(data->newargs, dict); + Py_DECREF(dict); + return (PyObject *) inst; +#else + PyInstanceObject *inst = PyObject_NEW(PyInstanceObject, &PyInstance_Type); + if (inst == NULL) { + return NULL; + } + inst->in_class = (PyClassObject *)data->newargs; + Py_INCREF(inst->in_class); + inst->in_dict = PyDict_New(); + if (inst->in_dict == NULL) { + Py_DECREF(inst); + return NULL; + } +#ifdef Py_TPFLAGS_HAVE_WEAKREFS + inst->in_weakreflist = NULL; +#endif +#ifdef Py_TPFLAGS_GC + PyObject_GC_Init(inst); +#endif + PyDict_SetItem(inst->in_dict, SWIG_This(), swig_this); + return (PyObject *) inst; +#endif +#endif +} + +SWIGRUNTIME void +SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this) +{ + PyObject *dict; +#if (PY_VERSION_HEX >= 0x02020000) && !defined(SWIG_PYTHON_SLOW_GETSET_THIS) + PyObject **dictptr = _PyObject_GetDictPtr(inst); + if (dictptr != NULL) { + dict = *dictptr; + if (dict == NULL) { + dict = PyDict_New(); + *dictptr = dict; + } + PyDict_SetItem(dict, SWIG_This(), swig_this); + return; + } +#endif + dict = PyObject_GetAttrString(inst, (char*)"__dict__"); + PyDict_SetItem(dict, SWIG_This(), swig_this); + Py_DECREF(dict); +} + + +SWIGINTERN PyObject * +SWIG_Python_InitShadowInstance(PyObject *args) { + PyObject *obj[2]; + if (!SWIG_Python_UnpackTuple(args,(char*)"swiginit", 2, 2, obj)) { + return NULL; + } else { + SwigPyObject *sthis = SWIG_Python_GetSwigThis(obj[0]); + if (sthis) { + SwigPyObject_append((PyObject*) sthis, obj[1]); + } else { + SWIG_Python_SetSwigThis(obj[0], obj[1]); + } + return SWIG_Py_Void(); + } +} + +/* Create a new pointer object */ + +SWIGRUNTIME PyObject * +SWIG_Python_NewPointerObj(void *ptr, swig_type_info *type, int flags) { + if (!ptr) { + return SWIG_Py_Void(); + } else { + int own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0; + PyObject *robj = SwigPyObject_New(ptr, type, own); + SwigPyClientData *clientdata = type ? (SwigPyClientData *)(type->clientdata) : 0; + if (clientdata && !(flags & SWIG_POINTER_NOSHADOW)) { + PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj); + if (inst) { + Py_DECREF(robj); + robj = inst; + } + } + return robj; + } +} + +/* Create a new packed object */ + +SWIGRUNTIMEINLINE PyObject * +SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) { + return ptr ? SwigPyPacked_New((void *) ptr, sz, type) : SWIG_Py_Void(); +} + +/* -----------------------------------------------------------------------------* + * Get type list + * -----------------------------------------------------------------------------*/ + +#ifdef SWIG_LINK_RUNTIME +void *SWIG_ReturnGlobalTypeList(void *); +#endif + +SWIGRUNTIME swig_module_info * +SWIG_Python_GetModule(void) { + static void *type_pointer = (void *)0; + /* first check if module already created */ + if (!type_pointer) { +#ifdef SWIG_LINK_RUNTIME + type_pointer = SWIG_ReturnGlobalTypeList((void *)0); +#else + type_pointer = PyCObject_Import((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, + (char*)"type_pointer" SWIG_TYPE_TABLE_NAME); + if (PyErr_Occurred()) { + PyErr_Clear(); + type_pointer = (void *)0; + } +#endif + } + return (swig_module_info *) type_pointer; +} + +#if PY_MAJOR_VERSION < 2 +/* PyModule_AddObject function was introduced in Python 2.0. The following function + is copied out of Python/modsupport.c in python version 2.3.4 */ +SWIGINTERN int +PyModule_AddObject(PyObject *m, char *name, PyObject *o) +{ + PyObject *dict; + if (!PyModule_Check(m)) { + PyErr_SetString(PyExc_TypeError, + "PyModule_AddObject() needs module as first arg"); + return SWIG_ERROR; + } + if (!o) { + PyErr_SetString(PyExc_TypeError, + "PyModule_AddObject() needs non-NULL value"); + return SWIG_ERROR; + } + + dict = PyModule_GetDict(m); + if (dict == NULL) { + /* Internal error -- modules must have a dict! */ + PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__", + PyModule_GetName(m)); + return SWIG_ERROR; + } + if (PyDict_SetItemString(dict, name, o)) + return SWIG_ERROR; + Py_DECREF(o); + return SWIG_OK; +} +#endif + +SWIGRUNTIME void +SWIG_Python_DestroyModule(void *vptr) +{ + swig_module_info *swig_module = (swig_module_info *) vptr; + swig_type_info **types = swig_module->types; + size_t i; + for (i =0; i < swig_module->size; ++i) { + swig_type_info *ty = types[i]; + if (ty->owndata) { + SwigPyClientData *data = (SwigPyClientData *) ty->clientdata; + if (data) SwigPyClientData_Del(data); + } + } + Py_DECREF(SWIG_This()); +} + +SWIGRUNTIME void +SWIG_Python_SetModule(swig_module_info *swig_module) { + static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} };/* Sentinel */ + +#if PY_VERSION_HEX >= 0x03000000 + /* Add a dummy module object into sys.modules */ + PyObject *module = PyImport_AddModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION); +#else + PyObject *module = Py_InitModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, + swig_empty_runtime_method_table); +#endif + PyObject *pointer = PyCObject_FromVoidPtr((void *) swig_module, SWIG_Python_DestroyModule); + if (pointer && module) { + PyModule_AddObject(module, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME, 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) +{ + PyObject *cache = SWIG_Python_TypeCache(); + PyObject *key = SWIG_Python_str_FromChar(type); + PyObject *obj = PyDict_GetItem(cache, key); + swig_type_info *descriptor; + if (obj) { + descriptor = (swig_type_info *) PyCObject_AsVoidPtr(obj); + } else { + swig_module_info *swig_module = SWIG_Python_GetModule(); + descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type); + if (descriptor) { + obj = PyCObject_FromVoidPtr(descriptor, NULL); + PyDict_SetItem(cache, key, obj); + Py_DECREF(obj); + } + } + Py_DECREF(key); + return descriptor; +} + +/* + For backward compatibility only +*/ +#define SWIG_POINTER_EXCEPTION 0 +#define SWIG_arg_fail(arg) SWIG_Python_ArgFail(arg) +#define SWIG_MustGetPtr(p, type, argnum, flags) SWIG_Python_MustGetPtr(p, type, argnum, flags) + +SWIGRUNTIME int +SWIG_Python_AddErrMesg(const char* mesg, int infront) +{ + if (PyErr_Occurred()) { + PyObject *type = 0; + PyObject *value = 0; + PyObject *traceback = 0; + PyErr_Fetch(&type, &value, &traceback); + if (value) { + char *tmp; + PyObject *old_str = PyObject_Str(value); + Py_XINCREF(type); + PyErr_Clear(); + if (infront) { + PyErr_Format(type, "%s %s", mesg, tmp = SWIG_Python_str_AsChar(old_str)); + } else { + PyErr_Format(type, "%s %s", tmp = SWIG_Python_str_AsChar(old_str), mesg); + } + SWIG_Python_str_DelForPy3(tmp); + Py_DECREF(old_str); + } + return 1; + } else { + return 0; + } +} + +SWIGRUNTIME int +SWIG_Python_ArgFail(int argnum) +{ + if (PyErr_Occurred()) { + /* add information about failing argument */ + char mesg[256]; + PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum); + return SWIG_Python_AddErrMesg(mesg, 1); + } else { + return 0; + } +} + +SWIGRUNTIMEINLINE const char * +SwigPyObject_GetDesc(PyObject *self) +{ + SwigPyObject *v = (SwigPyObject *)self; + swig_type_info *ty = v ? v->ty : 0; + return ty ? ty->str : (char*)""; +} + +SWIGRUNTIME void +SWIG_Python_TypeError(const char *type, PyObject *obj) +{ + if (type) { +#if defined(SWIG_COBJECT_TYPES) + if (obj && SwigPyObject_Check(obj)) { + const char *otype = (const char *) SwigPyObject_GetDesc(obj); + if (otype) { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'SwigPyObject(%s)' is received", + type, otype); + return; + } + } else +#endif + { + const char *otype = (obj ? obj->ob_type->tp_name : 0); + if (otype) { + PyObject *str = PyObject_Str(obj); + const char *cstr = str ? SWIG_Python_str_AsChar(str) : 0; + if (cstr) { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received", + type, otype, cstr); + SWIG_Python_str_DelForPy3(cstr); + } else { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received", + type, otype); + } + Py_XDECREF(str); + return; + } + } + PyErr_Format(PyExc_TypeError, "a '%s' is expected", type); + } else { + PyErr_Format(PyExc_TypeError, "unexpected type is received"); + } +} + + +/* Convert a pointer value, signal an exception on a type mismatch */ +SWIGRUNTIME void * +SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) { + void *result; + if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) { + PyErr_Clear(); +#if SWIG_POINTER_EXCEPTION + if (flags) { + SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj); + SWIG_Python_ArgFail(argnum); + } +#endif + } + return result; +} + + +#ifdef __cplusplus +#if 0 +{ /* cc-mode */ +#endif +} +#endif + + + +#define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) + +#define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else + + + +/* -------- TYPES TABLE (BEGIN) -------- */ + +#define SWIGTYPE_p_P swig_types[0] +#define SWIGTYPE_p_char swig_types[1] +#define SWIGTYPE_p_point swig_types[2] +static swig_type_info *swig_types[4]; +static swig_module_info swig_module = {swig_types, 3, 0, 0, 0, 0}; +#define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) +#define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) + +/* -------- TYPES TABLE (END) -------- */ + +#if (PY_VERSION_HEX <= 0x02000000) +# if !defined(SWIG_PYTHON_CLASSIC) +# error "This python version requires swig to be run with the '-classic' option" +# endif +#endif + +/*----------------------------------------------- + @(target):= _cpp0x_unrestricted_unions.so + ------------------------------------------------*/ +#if PY_VERSION_HEX >= 0x03000000 +# define SWIG_init PyInit__cpp0x_unrestricted_unions + +#else +# define SWIG_init init_cpp0x_unrestricted_unions + +#endif +#define SWIG_name "_cpp0x_unrestricted_unions" + +#define SWIGVERSION 0x020001 +#define SWIG_VERSION SWIGVERSION + + +#define SWIG_as_voidptr(a) const_cast< void * >(static_cast< const void * >(a)) +#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),reinterpret_cast< void** >(a)) + + +#include + + +namespace swig { + class SwigPtr_PyObject { + protected: + PyObject *_obj; + + public: + SwigPtr_PyObject() :_obj(0) + { + } + + SwigPtr_PyObject(const SwigPtr_PyObject& item) : _obj(item._obj) + { + Py_XINCREF(_obj); + } + + SwigPtr_PyObject(PyObject *obj, bool initial_ref = true) :_obj(obj) + { + if (initial_ref) { + Py_XINCREF(_obj); + } + } + + SwigPtr_PyObject & operator=(const SwigPtr_PyObject& item) + { + Py_XINCREF(item._obj); + Py_XDECREF(_obj); + _obj = item._obj; + return *this; + } + + ~SwigPtr_PyObject() + { + Py_XDECREF(_obj); + } + + operator PyObject *() const + { + return _obj; + } + + PyObject *operator->() const + { + return _obj; + } + }; +} + + +namespace swig { + struct SwigVar_PyObject : SwigPtr_PyObject { + SwigVar_PyObject(PyObject* obj = 0) : SwigPtr_PyObject(obj, false) { } + + SwigVar_PyObject & operator = (PyObject* obj) + { + Py_XDECREF(_obj); + _obj = obj; + return *this; + } + }; +} + + +struct point { + point() {} + point(int x, int y) : x_(x), y_(y) {} + int x_, y_; +}; + +#include // For placement 'new' in the constructor below +union P { + int z; + double w; + point p; // Illegal in C++03; legal in C++11. + // Due to the point member, a constructor definition is required. + P() { + new(&p) point(); + } +} p1; + + +#include +#if !defined(SWIG_NO_LLONG_MAX) +# if !defined(LLONG_MAX) && defined(__GNUC__) && defined (__LONG_LONG_MAX__) +# define LLONG_MAX __LONG_LONG_MAX__ +# define LLONG_MIN (-LLONG_MAX - 1LL) +# define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL) +# endif +#endif + + +SWIGINTERN int +SWIG_AsVal_double (PyObject *obj, double *val) +{ + int res = SWIG_TypeError; + if (PyFloat_Check(obj)) { + if (val) *val = PyFloat_AsDouble(obj); + return SWIG_OK; + } else if (PyInt_Check(obj)) { + if (val) *val = PyInt_AsLong(obj); + return SWIG_OK; + } else if (PyLong_Check(obj)) { + double v = PyLong_AsDouble(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_OK; + } else { + PyErr_Clear(); + } + } +#ifdef SWIG_PYTHON_CAST_MODE + { + int dispatch = 0; + double d = PyFloat_AsDouble(obj); + if (!PyErr_Occurred()) { + if (val) *val = d; + return SWIG_AddCast(SWIG_OK); + } else { + PyErr_Clear(); + } + if (!dispatch) { + long v = PyLong_AsLong(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_AddCast(SWIG_AddCast(SWIG_OK)); + } else { + PyErr_Clear(); + } + } + } +#endif + return res; +} + + +#include + + +#include + + +SWIGINTERNINLINE int +SWIG_CanCastAsInteger(double *d, double min, double max) { + double x = *d; + if ((min <= x && x <= max)) { + double fx = floor(x); + double cx = ceil(x); + double rd = ((x - fx) < 0.5) ? fx : cx; /* simple rint */ + if ((errno == EDOM) || (errno == ERANGE)) { + errno = 0; + } else { + double summ, reps, diff; + if (rd < x) { + diff = x - rd; + } else if (rd > x) { + diff = rd - x; + } else { + return 1; + } + summ = rd + x; + reps = diff/summ; + if (reps < 8*DBL_EPSILON) { + *d = rd; + return 1; + } + } + } + return 0; +} + + +SWIGINTERN int +SWIG_AsVal_long (PyObject *obj, long* val) +{ + if (PyInt_Check(obj)) { + if (val) *val = PyInt_AsLong(obj); + return SWIG_OK; + } else if (PyLong_Check(obj)) { + long v = PyLong_AsLong(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_OK; + } else { + PyErr_Clear(); + } + } +#ifdef SWIG_PYTHON_CAST_MODE + { + int dispatch = 0; + long v = PyInt_AsLong(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_AddCast(SWIG_OK); + } else { + PyErr_Clear(); + } + if (!dispatch) { + double d; + int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d)); + if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, LONG_MAX)) { + if (val) *val = (long)(d); + return res; + } + } + } +#endif + return SWIG_TypeError; +} + + +SWIGINTERN int +SWIG_AsVal_int (PyObject * obj, int *val) +{ + long v; + int res = SWIG_AsVal_long (obj, &v); + if (SWIG_IsOK(res)) { + if ((v < INT_MIN || v > INT_MAX)) { + return SWIG_OverflowError; + } else { + if (val) *val = static_cast< int >(v); + } + } + return res; +} + + + #define SWIG_From_long PyInt_FromLong + + +SWIGINTERNINLINE PyObject * +SWIG_From_int (int value) +{ + return SWIG_From_long (value); +} + + + #define SWIG_From_double PyFloat_FromDouble + +#ifdef __cplusplus +extern "C" { +#endif +SWIGINTERN PyObject *_wrap_new_point__SWIG_0(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + point *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)":new_point")) SWIG_fail; + result = (point *)new point(); + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_point, SWIG_POINTER_NEW | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_new_point__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + point *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OO:new_point",&obj0,&obj1)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "new_point" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "new_point" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + result = (point *)new point(arg1,arg2); + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_point, SWIG_POINTER_NEW | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_new_point(PyObject *self, PyObject *args) { + int argc; + PyObject *argv[3]; + int ii; + + if (!PyTuple_Check(args)) SWIG_fail; + argc = (int)PyObject_Length(args); + for (ii = 0; (ii < argc) && (ii < 2); ii++) { + argv[ii] = PyTuple_GET_ITEM(args,ii); + } + if (argc == 0) { + return _wrap_new_point__SWIG_0(self, args); + } + if (argc == 2) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + return _wrap_new_point__SWIG_1(self, args); + } + } + } + +fail: + SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'new_point'.\n" + " Possible C/C++ prototypes are:\n" + " point()\n" + " point(int,int)\n"); + return NULL; +} + + +SWIGINTERN PyObject *_wrap_point_x__set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + point *arg1 = (point *) 0 ; + int arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OO:point_x__set",&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_point, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "point_x__set" "', argument " "1"" of type '" "point *""'"); + } + arg1 = reinterpret_cast< point * >(argp1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "point_x__set" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + if (arg1) (arg1)->x_ = arg2; + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_point_x__get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + point *arg1 = (point *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + int result; + + if (!PyArg_ParseTuple(args,(char *)"O:point_x__get",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_point, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "point_x__get" "', argument " "1"" of type '" "point *""'"); + } + arg1 = reinterpret_cast< point * >(argp1); + result = (int) ((arg1)->x_); + resultobj = SWIG_From_int(static_cast< int >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_point_y__set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + point *arg1 = (point *) 0 ; + int arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OO:point_y__set",&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_point, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "point_y__set" "', argument " "1"" of type '" "point *""'"); + } + arg1 = reinterpret_cast< point * >(argp1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "point_y__set" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + if (arg1) (arg1)->y_ = arg2; + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_point_y__get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + point *arg1 = (point *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + int result; + + if (!PyArg_ParseTuple(args,(char *)"O:point_y__get",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_point, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "point_y__get" "', argument " "1"" of type '" "point *""'"); + } + arg1 = reinterpret_cast< point * >(argp1); + result = (int) ((arg1)->y_); + resultobj = SWIG_From_int(static_cast< int >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_delete_point(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + point *arg1 = (point *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"O:delete_point",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_point, SWIG_POINTER_DISOWN | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_point" "', argument " "1"" of type '" "point *""'"); + } + arg1 = reinterpret_cast< point * >(argp1); + delete arg1; + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *point_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *obj; + if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL; + SWIG_TypeNewClientData(SWIGTYPE_p_point, SWIG_NewClientData(obj)); + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject *_wrap_P_z_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + P *arg1 = (P *) 0 ; + int arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OO:P_z_set",&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_P, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P_z_set" "', argument " "1"" of type '" "P *""'"); + } + arg1 = reinterpret_cast< P * >(argp1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "P_z_set" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + if (arg1) (arg1)->z = arg2; + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_P_z_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + P *arg1 = (P *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + int result; + + if (!PyArg_ParseTuple(args,(char *)"O:P_z_get",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_P, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P_z_get" "', argument " "1"" of type '" "P *""'"); + } + arg1 = reinterpret_cast< P * >(argp1); + result = (int) ((arg1)->z); + resultobj = SWIG_From_int(static_cast< int >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_P_w_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + P *arg1 = (P *) 0 ; + double arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + double val2 ; + int ecode2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OO:P_w_set",&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_P, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P_w_set" "', argument " "1"" of type '" "P *""'"); + } + arg1 = reinterpret_cast< P * >(argp1); + ecode2 = SWIG_AsVal_double(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "P_w_set" "', argument " "2"" of type '" "double""'"); + } + arg2 = static_cast< double >(val2); + if (arg1) (arg1)->w = arg2; + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_P_w_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + P *arg1 = (P *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + double result; + + if (!PyArg_ParseTuple(args,(char *)"O:P_w_get",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_P, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P_w_get" "', argument " "1"" of type '" "P *""'"); + } + arg1 = reinterpret_cast< P * >(argp1); + result = (double) ((arg1)->w); + resultobj = SWIG_From_double(static_cast< double >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_P_p_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + P *arg1 = (P *) 0 ; + point *arg2 = (point *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + void *argp2 = 0 ; + int res2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OO:P_p_set",&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_P, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P_p_set" "', argument " "1"" of type '" "P *""'"); + } + arg1 = reinterpret_cast< P * >(argp1); + res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_point, 0 | 0 ); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P_p_set" "', argument " "2"" of type '" "point *""'"); + } + arg2 = reinterpret_cast< point * >(argp2); + if (arg1) (arg1)->p = *arg2; + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_P_p_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + P *arg1 = (P *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + point *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"O:P_p_get",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_P, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P_p_get" "', argument " "1"" of type '" "P *""'"); + } + arg1 = reinterpret_cast< P * >(argp1); + result = (point *)& ((arg1)->p); + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_point, 0 | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_new_P(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + P *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)":new_P")) SWIG_fail; + result = (P *)new P(); + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_P, SWIG_POINTER_NEW | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_delete_P(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + P *arg1 = (P *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"O:delete_P",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_P, SWIG_POINTER_DISOWN | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_P" "', argument " "1"" of type '" "P *""'"); + } + arg1 = reinterpret_cast< P * >(argp1); + delete arg1; + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *P_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *obj; + if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL; + SWIG_TypeNewClientData(SWIGTYPE_p_P, SWIG_NewClientData(obj)); + return SWIG_Py_Void(); +} + +SWIGINTERN int Swig_var_p1_set(PyObject *_val) { + { + void *argp = 0; + int res = SWIG_ConvertPtr(_val, &argp, SWIGTYPE_p_P, 0 | 0); + if (!SWIG_IsOK(res)) { + SWIG_exception_fail(SWIG_ArgError(res), "in variable '""p1""' of type '""P""'"); + } + if (!argp) { + SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""p1""' of type '""P""'"); + } else { + P * temp; + temp = reinterpret_cast< P * >(argp); + p1 = *temp; + if (SWIG_IsNewObj(res)) delete temp; + } + } + return 0; +fail: + return 1; +} + + +SWIGINTERN PyObject *Swig_var_p1_get(void) { + PyObject *pyobj = 0; + + pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(&p1), SWIGTYPE_p_P, 0 ); + return pyobj; +} + + +static PyMethodDef SwigMethods[] = { + { (char *)"SWIG_PyInstanceMethod_New", (PyCFunction)SWIG_PyInstanceMethod_New, METH_O, NULL}, + { (char *)"new_point", _wrap_new_point, METH_VARARGS, NULL}, + { (char *)"point_x__set", _wrap_point_x__set, METH_VARARGS, NULL}, + { (char *)"point_x__get", _wrap_point_x__get, METH_VARARGS, NULL}, + { (char *)"point_y__set", _wrap_point_y__set, METH_VARARGS, NULL}, + { (char *)"point_y__get", _wrap_point_y__get, METH_VARARGS, NULL}, + { (char *)"delete_point", _wrap_delete_point, METH_VARARGS, NULL}, + { (char *)"point_swigregister", point_swigregister, METH_VARARGS, NULL}, + { (char *)"P_z_set", _wrap_P_z_set, METH_VARARGS, NULL}, + { (char *)"P_z_get", _wrap_P_z_get, METH_VARARGS, NULL}, + { (char *)"P_w_set", _wrap_P_w_set, METH_VARARGS, NULL}, + { (char *)"P_w_get", _wrap_P_w_get, METH_VARARGS, NULL}, + { (char *)"P_p_set", _wrap_P_p_set, METH_VARARGS, NULL}, + { (char *)"P_p_get", _wrap_P_p_get, METH_VARARGS, NULL}, + { (char *)"new_P", _wrap_new_P, METH_VARARGS, NULL}, + { (char *)"delete_P", _wrap_delete_P, METH_VARARGS, NULL}, + { (char *)"P_swigregister", P_swigregister, METH_VARARGS, NULL}, + { NULL, NULL, 0, NULL } +}; + + +/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ + +static swig_type_info _swigt__p_P = {"_p_P", "P *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_point = {"_p_point", "point *", 0, 0, (void*)0, 0}; + +static swig_type_info *swig_type_initial[] = { + &_swigt__p_P, + &_swigt__p_char, + &_swigt__p_point, +}; + +static swig_cast_info _swigc__p_P[] = { {&_swigt__p_P, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_point[] = { {&_swigt__p_point, 0, 0, 0},{0, 0, 0, 0}}; + +static swig_cast_info *swig_cast_initial[] = { + _swigc__p_P, + _swigc__p_char, + _swigc__p_point, +}; + + +/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ + +static swig_const_info swig_const_table[] = { +{0, 0, 0, 0.0, 0, 0}}; + +#ifdef __cplusplus +} +#endif +/* ----------------------------------------------------------------------------- + * Type initialization: + * This problem is tough by the requirement that no dynamic + * memory is used. Also, since swig_type_info structures store pointers to + * swig_cast_info structures and swig_cast_info structures store pointers back + * to swig_type_info structures, we need some lookup code at initialization. + * The idea is that swig generates all the structures that are needed. + * The runtime then collects these partially filled structures. + * The SWIG_InitializeModule function takes these initial arrays out of + * swig_module, and does all the lookup, filling in the swig_module.types + * array with the correct data and linking the correct swig_cast_info + * structures together. + * + * The generated swig_type_info structures are assigned staticly to an initial + * array. We just loop through that array, and handle each type individually. + * First we lookup if this type has been already loaded, and if so, use the + * loaded structure instead of the generated one. Then we have to fill in the + * cast linked list. The cast data is initially stored in something like a + * two-dimensional array. Each row corresponds to a type (there are the same + * number of rows as there are in the swig_type_initial array). Each entry in + * a column is one of the swig_cast_info structures for that type. + * The cast_initial array is actually an array of arrays, because each row has + * a variable number of columns. So to actually build the cast linked list, + * we find the array of casts associated with the type, and loop through it + * adding the casts to the list. The one last trick we need to do is making + * sure the type pointer in the swig_cast_info struct is correct. + * + * First off, we lookup the cast->type name to see if it is already loaded. + * There are three cases to handle: + * 1) If the cast->type has already been loaded AND the type we are adding + * casting info to has not been loaded (it is in this module), THEN we + * replace the cast->type pointer with the type pointer that has already + * been loaded. + * 2) If BOTH types (the one we are adding casting info to, and the + * cast->type) are loaded, THEN the cast info has already been loaded by + * the previous module so we just ignore it. + * 3) Finally, if cast->type has not already been loaded, then we add that + * swig_cast_info to the linked list (because the cast->type) pointer will + * be correct. + * ----------------------------------------------------------------------------- */ + +#ifdef __cplusplus +extern "C" { +#if 0 +} /* c-mode */ +#endif +#endif + +#if 0 +#define SWIGRUNTIME_DEBUG +#endif + + +SWIGRUNTIME void +SWIG_InitializeModule(void *clientdata) { + size_t i; + swig_module_info *module_head, *iter; + int found, init; + + clientdata = clientdata; + + /* check to see if the circular list has been setup, if not, set it up */ + if (swig_module.next==0) { + /* Initialize the swig_module */ + swig_module.type_initial = swig_type_initial; + swig_module.cast_initial = swig_cast_initial; + swig_module.next = &swig_module; + init = 1; + } else { + init = 0; + } + + /* Try and load any already created modules */ + module_head = SWIG_GetModule(clientdata); + if (!module_head) { + /* This is the first module loaded for this interpreter */ + /* so set the swig module into the interpreter */ + SWIG_SetModule(clientdata, &swig_module); + module_head = &swig_module; + } else { + /* the interpreter has loaded a SWIG module, but has it loaded this one? */ + found=0; + iter=module_head; + do { + if (iter==&swig_module) { + found=1; + break; + } + iter=iter->next; + } while (iter!= module_head); + + /* if the is found in the list, then all is done and we may leave */ + if (found) return; + /* otherwise we must add out module into the list */ + swig_module.next = module_head->next; + module_head->next = &swig_module; + } + + /* When multiple interpeters are used, a module could have already been initialized in + a different interpreter, but not yet have a pointer in this interpreter. + In this case, we do not want to continue adding types... everything should be + set up already */ + if (init == 0) return; + + /* Now work on filling in swig_module.types */ +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: size %d\n", swig_module.size); +#endif + for (i = 0; i < swig_module.size; ++i) { + swig_type_info *type = 0; + swig_type_info *ret; + swig_cast_info *cast; + +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); +#endif + + /* if there is another module already loaded */ + if (swig_module.next != &swig_module) { + type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); + } + if (type) { + /* Overwrite clientdata field */ +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: found type %s\n", type->name); +#endif + if (swig_module.type_initial[i]->clientdata) { + type->clientdata = swig_module.type_initial[i]->clientdata; +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); +#endif + } + } else { + type = swig_module.type_initial[i]; + } + + /* Insert casting types */ + cast = swig_module.cast_initial[i]; + while (cast->type) { + /* Don't need to add information already in the list */ + ret = 0; +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); +#endif + if (swig_module.next != &swig_module) { + ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); +#ifdef SWIGRUNTIME_DEBUG + if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); +#endif + } + if (ret) { + if (type == swig_module.type_initial[i]) { +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: skip old type %s\n", ret->name); +#endif + cast->type = ret; + ret = 0; + } else { + /* Check for casting already in the list */ + swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); +#ifdef SWIGRUNTIME_DEBUG + if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); +#endif + if (!ocast) ret = 0; + } + } + + if (!ret) { +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); +#endif + if (type->cast) { + type->cast->prev = cast; + cast->next = type->cast; + } + type->cast = cast; + } + cast++; + } + /* Set entry in modules->types array equal to the type */ + swig_module.types[i] = type; + } + swig_module.types[i] = 0; + +#ifdef SWIGRUNTIME_DEBUG + printf("**** SWIG_InitializeModule: Cast List ******\n"); + for (i = 0; i < swig_module.size; ++i) { + int j = 0; + swig_cast_info *cast = swig_module.cast_initial[i]; + printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); + while (cast->type) { + printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); + cast++; + ++j; + } + printf("---- Total casts: %d\n",j); + } + printf("**** SWIG_InitializeModule: Cast List ******\n"); +#endif +} + +/* This function will propagate the clientdata field of type to +* any new swig_type_info structures that have been added into the list +* of equivalent types. It is like calling +* SWIG_TypeClientData(type, clientdata) a second time. +*/ +SWIGRUNTIME void +SWIG_PropagateClientData(void) { + size_t i; + swig_cast_info *equiv; + static int init_run = 0; + + if (init_run) return; + init_run = 1; + + for (i = 0; i < swig_module.size; i++) { + if (swig_module.types[i]->clientdata) { + equiv = swig_module.types[i]->cast; + while (equiv) { + if (!equiv->converter) { + if (equiv->type && !equiv->type->clientdata) + SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); + } + equiv = equiv->next; + } + } + } +} + +#ifdef __cplusplus +#if 0 +{ + /* c-mode */ +#endif +} +#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 int + swig_varlink_print(swig_varlinkobject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { + char *tmp; + PyObject *str = swig_varlink_str(v); + fprintf(fp,"Swig global variables "); + fprintf(fp,"%s\n", tmp = SWIG_Python_str_AsChar(str)); + SWIG_Python_str_DelForPy3(tmp); + Py_DECREF(str); + return 0; + } + + 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_SetString(PyExc_NameError,"Unknown C global variable"); + } + 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_SetString(PyExc_NameError,"Unknown C global variable"); + } + 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 + = { + /* PyObject header changed in Python 3 */ +#if PY_VERSION_HEX >= 0x03000000 + PyVarObject_HEAD_INIT(&PyType_Type, 0) +#else + PyObject_HEAD_INIT(NULL) + 0, /* Number of items in variable part (ob_size) */ +#endif + (char *)"swigvarlink", /* Type name (tp_name) */ + sizeof(swig_varlinkobject), /* Basic size (tp_basicsize) */ + 0, /* Itemsize (tp_itemsize) */ + (destructor) swig_varlink_dealloc, /* Deallocator (tp_dealloc) */ + (printfunc) swig_varlink_print, /* Print (tp_print) */ + (getattrfunc) swig_varlink_getattr, /* get attr (tp_getattr) */ + (setattrfunc) swig_varlink_setattr, /* Set attr (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 */ +#if PY_VERSION_HEX >= 0x02020000 + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */ +#endif +#if PY_VERSION_HEX >= 0x02030000 + 0, /* tp_del */ +#endif +#ifdef COUNT_ALLOCS + 0,0,0,0 /* tp_alloc -> tp_next */ +#endif + }; + varlink_type = tmp; + /* for Python 3 we already assigned ob_type in PyVarObject_HEAD_INIT() */ +#if PY_VERSION_HEX < 0x03000000 + varlink_type.ob_type = &PyType_Type; +#endif + type_init = 1; + } + 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, 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) { + strncpy(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 *_SWIG_globals = 0; + if (!_SWIG_globals) _SWIG_globals = SWIG_newvarlink(); + return _SWIG_globals; + } + + /* ----------------------------------------------------------------------------- + * constants/methods manipulation + * ----------------------------------------------------------------------------- */ + + /* Install Constants */ + SWIGINTERN void + SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) { + PyObject *obj = 0; + size_t i; + for (i = 0; constants[i].type; ++i) { + switch(constants[i].type) { + case SWIG_PY_POINTER: + obj = SWIG_NewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0); + break; + case SWIG_PY_BINARY: + obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); + break; + default: + obj = 0; + break; + } + if (obj) { + PyDict_SetItemString(d, constants[i].name, obj); + Py_DECREF(obj); + } + } + } + + /* -----------------------------------------------------------------------------*/ + /* Fix SwigMethods to carry the callback ptrs when needed */ + /* -----------------------------------------------------------------------------*/ + + SWIGINTERN void + SWIG_Python_FixMethods(PyMethodDef *methods, + 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; + if (c && (c = strstr(c, "swig_ptr: "))) { + int j; + 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, + strlen(const_table[j].name)) == 0) { + ci = &(const_table[j]); + break; + } + } + if (ci) { + void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0; + if (ptr) { + size_t shift = (ci->ptype) - types; + swig_type_info *ty = types_initial[shift]; + size_t ldoc = (c - methods[i].ml_doc); + size_t lptr = strlen(ty->name)+2*sizeof(void*)+2; + char *ndoc = (char*)malloc(ldoc + lptr + 10); + if (ndoc) { + char *buff = ndoc; + strncpy(buff, methods[i].ml_doc, ldoc); + buff += ldoc; + strncpy(buff, "swig_ptr: ", 10); + buff += 10; + SWIG_PackVoidPtr(buff, ptr, ty->name, lptr); + methods[i].ml_doc = ndoc; + } + } + } + } + } + } + +#ifdef __cplusplus +} +#endif + +/* -----------------------------------------------------------------------------* + * Partial Init method + * -----------------------------------------------------------------------------*/ + +#ifdef __cplusplus +extern "C" +#endif + +SWIGEXPORT +#if PY_VERSION_HEX >= 0x03000000 +PyObject* +#else +void +#endif +SWIG_init(void) { + PyObject *m, *d; +#if PY_VERSION_HEX >= 0x03000000 + static struct PyModuleDef SWIG_module = { + PyModuleDef_HEAD_INIT, + (char *) SWIG_name, + NULL, + -1, + SwigMethods, + NULL, + NULL, + NULL, + NULL + }; +#endif + + /* Fix SwigMethods to carry the callback ptrs when needed */ + SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial); + +#if PY_VERSION_HEX >= 0x03000000 + m = PyModule_Create(&SWIG_module); +#else + m = Py_InitModule((char *) SWIG_name, SwigMethods); +#endif + d = PyModule_GetDict(m); + + SWIG_InitializeModule(0); + SWIG_InstallConstants(d,swig_const_table); + + + PyDict_SetItemString(d,(char*)"cvar", SWIG_globals()); + SWIG_addvarlink(SWIG_globals(),(char*)"p1",Swig_var_p1_get, Swig_var_p1_set); +#if PY_VERSION_HEX >= 0x03000000 + return m; +#else + return; +#endif +} + From dd18423e768804618967463299e08eedb00868f4 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 25 Sep 2012 19:25:14 +0000 Subject: [PATCH 071/481] Update on C++11 user-defined literal status git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13850 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Doc/Manual/Cpp0x.html | 39 +++++++++++++++++-- .../test-suite/cpp0x_userdefined_literals.i | 18 +++++---- 2 files changed, 45 insertions(+), 12 deletions(-) diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html index a93df57ca..d150cbddf 100644 --- a/Doc/Manual/Cpp0x.html +++ b/Doc/Manual/Cpp0x.html @@ -516,18 +516,49 @@ inside the string due to SWIG's C++ preprocessor.

    7.2.19 User-defined literals

    -

    SWIG correctly parses the new operator""_mysuffix() functions.

    +

    +SWIG parses the declaration of user-defined literals, that is, the operator "" _mysuffix() function syntax. +

    +

    +Some examples are the raw literal: +

    +
    +OutputType operator "" _myRawLiteral(const char * value);
    +
    + +

    +numeric cooked literals: +

    +
    +OutputType operator "" _mySuffixIntegral(unsigned long long);
    +OutputType operator "" _mySuffixFloat(long double);
    +
    + +

    +and cooked string literals: +

     OutputType operator "" _mySuffix(const char * string_values, size_t num_chars);
     OutputType operator "" _mySuffix(const wchar_t * string_values, size_t num_chars);
     OutputType operator "" _mySuffix(const char16_t * string_values, size_t num_chars);
     OutputType operator "" _mySuffix(const char32_t * string_values, size_t num_chars);
    -OutputType operator "" _mySuffix(int value);
     
    -

    The %rename currently doesn't parse the double quotes. Please -rename the functions in the code using the #define preprocessor directive.

    +

    +Note that the %rename directive currently does not parse the double quotes, so these can't be easily accessed from +target languages. +

    + +

    +Use of user-defined literals such as the following still give a syntax error: +

    + +
    +OutputType var1 = "1234"_suffix;
    +OutputType var2 = 1234_suffix;
    +OutputType var3 = 3.1416_suffix;
    +

    7.2.20 Thread-local storage

    diff --git a/Examples/test-suite/cpp0x_userdefined_literals.i b/Examples/test-suite/cpp0x_userdefined_literals.i index 6604a4293..b21ff762d 100644 --- a/Examples/test-suite/cpp0x_userdefined_literals.i +++ b/Examples/test-suite/cpp0x_userdefined_literals.i @@ -1,5 +1,5 @@ /* This testcase checks whether SWIG correctly parses the user-defined literals - for the string introduced in C++0x. */ + introduced in C++0x. */ %module cpp0x_userdefined_literals %inline %{ @@ -7,18 +7,20 @@ struct OutputType { int val; - - OutputType(int v) { v=val; } + OutputType(int v) : val(v) {} }; -/* Note: GCC doesn't support user-defined literals yet! */ -struct TT { -OutputType operator "" (const char * string_values, size_t num_chars) { return OutputType(100); } +// Raw literal +OutputType operator "" _myRawLiteral(const char * value) { return OutputType(10); } + +// Cooked numeric literals +OutputType operator "" _mySuffixIntegral(unsigned long long) { return OutputType(20); } +OutputType operator "" _mySuffixFloat(long double) { return OutputType(30); } + +// Cooked string literals OutputType operator "" _mySuffix1(const char * string_values, size_t num_chars) { return OutputType(100); } OutputType operator "" _mySuffix2(const wchar_t * string_values, size_t num_chars) { return OutputType(200); } OutputType operator "" _mySuffix3(const char16_t * string_values, size_t num_chars) { return OutputType(300); } OutputType operator "" _mySuffix4(const char32_t * string_values, size_t num_chars) { return OutputType(400); } -OutputType operator "" _mySuffix5(int value) /* cooked version - ie. atoi() of string */ { return OutputType(500); } -}; %} From 070bf3cc9ea8cbce5abcb142b2e4ba61d66be52e Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 25 Sep 2012 19:29:13 +0000 Subject: [PATCH 072/481] gcc-4.7 now supports alias templates git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13851 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 1dfe35f38..0a637dcd1 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -447,6 +447,7 @@ CPP0X_TEST_CASES = \ cpp0x_strongly_typed_enumerations \ cpp0x_template_double_brackets \ cpp0x_template_explicit \ + cpp0x_template_typedefs \ cpp0x_uniform_initialization \ cpp0x_unrestricted_unions \ cpp0x_userdefined_literals \ @@ -455,7 +456,6 @@ CPP0X_TEST_CASES = \ # cpp0x_constructors \ # not supported by any compiler yet # cpp0x_hash_tables \ # not fully implemented yet # cpp0x_lambda_functions \ # not supported by GCC or MSVC yet -# cpp0x_template_typedefs \ # not supported by any compiler yet (now in gcc-4.7) # cpp0x_thread_local \ # not supported by any compiler yet # Broken C++0x test cases. From 4db087d81fc287bcc41f9455b31d9ba44e704352 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 25 Sep 2012 20:22:15 +0000 Subject: [PATCH 073/481] Delegating constructors and inheriting constructors clarification and split of tests git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13852 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Doc/Manual/Cpp0x.html | 28 +++++++++++++++-- Examples/test-suite/common.mk | 3 +- Examples/test-suite/cpp0x_constructors.i | 30 ------------------- .../cpp0x_delegating_constructors.i | 18 +++++++++++ .../cpp0x_inheriting_constructors.i | 18 +++++++++++ 5 files changed, 63 insertions(+), 34 deletions(-) delete mode 100644 Examples/test-suite/cpp0x_constructors.i create mode 100644 Examples/test-suite/cpp0x_delegating_constructors.i create mode 100644 Examples/test-suite/cpp0x_inheriting_constructors.i diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html index d150cbddf..fa18b67f1 100644 --- a/Doc/Manual/Cpp0x.html +++ b/Doc/Manual/Cpp0x.html @@ -263,9 +263,31 @@ auto square(float a, float b) -> decltype(a);

    7.2.10 Object construction improvement

    -

    SWIG correctly parses and includes the external functions -(constructor delegation and constructor inheritance) into the class -using the using keyword.

    +

    +SWIG is able to handle constructor delegation, such as: +

    + +
    +class A {
    +public:
    +  int a;
    +  int b;
    +  int c;
    +
    +  A() : A( 10 ) {}
    +  A(int aa) : A(aa, 20) {}
    +  A(int aa, int bb) : A(aa, bb, 30) {}
    +  A(int aa, int bb, int cc) { a=aa; b=bb; c=cc; }
    +};
    +
    + +

    +Constructor inheritance is parsed correctly, but the additional constructors are not currently added to the derived proxy class in the target language. Example is shown below: + +

     class BaseClass {
    diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk
    index 0a637dcd1..0b5e368f9 100644
    --- a/Examples/test-suite/common.mk
    +++ b/Examples/test-suite/common.mk
    @@ -434,6 +434,7 @@ CPP0X_TEST_CASES = \
     	cpp0x_constexpr \
     	cpp0x_decltype \
     	cpp0x_default_delete \
    +	cpp0x_delegating_constructors \
     	cpp0x_explicit_conversion_operators \
     	cpp0x_function_objects \
     	cpp0x_initializer_list \
    @@ -453,7 +454,7 @@ CPP0X_TEST_CASES = \
     	cpp0x_userdefined_literals \
     	cpp0x_variadic_templates
     
    -#	cpp0x_constructors \          # not supported by any compiler yet
    +#	cpp0x_inheriting_constructors \ # not supported by gcc-4.7
     #	cpp0x_hash_tables \           # not fully implemented yet
     #	cpp0x_lambda_functions \      # not supported by GCC or MSVC yet
     #	cpp0x_thread_local \          # not supported by any compiler yet
    diff --git a/Examples/test-suite/cpp0x_constructors.i b/Examples/test-suite/cpp0x_constructors.i
    deleted file mode 100644
    index 2077efe0c..000000000
    --- a/Examples/test-suite/cpp0x_constructors.i
    +++ /dev/null
    @@ -1,30 +0,0 @@
    -/* This test checks whether SWIG correctly parses the new delegating
    -   constructors and constructor inheritance.
    -*/
    -%module cpp0x_constructors
    -
    -%inline %{
    -class BaseClass {
    -private:
    -  int _val;
    -public:
    -  BaseClass(int iValue) { _val = iValue; }
    -};
    -
    -class DerivedClass: public BaseClass {
    -public:
    -  using BaseClass::BaseClass; // Adds DerivedClass(int) constructor
    -};
    -
    -class A {
    -public:
    -  int a;
    -  int b;
    -  int c;
    -
    -  A() : A( 10 ) {}
    -  A(int aa) : A(aa, 20) {}
    -  A(int aa, int bb) : A(aa, bb, 30) {}
    -  A(int aa, int bb, int cc) { a=aa; b=bb; c=cc; }
    -};
    -%}
    diff --git a/Examples/test-suite/cpp0x_delegating_constructors.i b/Examples/test-suite/cpp0x_delegating_constructors.i
    new file mode 100644
    index 000000000..679dce242
    --- /dev/null
    +++ b/Examples/test-suite/cpp0x_delegating_constructors.i
    @@ -0,0 +1,18 @@
    +/* This test checks whether SWIG correctly parses the new delegating
    +   constructors.
    +*/
    +%module cpp0x_delegating_constructors
    +
    +%inline %{
    +class A {
    +public:
    +  int a;
    +  int b;
    +  int c;
    +
    +  A() : A( 10 ) {}
    +  A(int aa) : A(aa, 20) {}
    +  A(int aa, int bb) : A(aa, bb, 30) {}
    +  A(int aa, int bb, int cc) { a=aa; b=bb; c=cc; }
    +};
    +%}
    diff --git a/Examples/test-suite/cpp0x_inheriting_constructors.i b/Examples/test-suite/cpp0x_inheriting_constructors.i
    new file mode 100644
    index 000000000..452598360
    --- /dev/null
    +++ b/Examples/test-suite/cpp0x_inheriting_constructors.i
    @@ -0,0 +1,18 @@
    +/* This test checks whether SWIG correctly parses the new constructor
    +   inheritance.
    +*/
    +%module cpp0x_inheriting_constructors
    +
    +%inline %{
    +class BaseClass {
    +private:
    +  int _val;
    +public:
    +  BaseClass(int iValue) { _val = iValue; }
    +};
    +
    +class DerivedClass: public BaseClass {
    +public:
    +  using BaseClass::BaseClass; // Adds DerivedClass(int) constructor
    +};
    +%}
    
    From e68d8024f5d02532f3519a9651d5eec3db653c59 Mon Sep 17 00:00:00 2001
    From: William S Fulton 
    Date: Mon, 1 Oct 2012 18:53:12 +0000
    Subject: [PATCH 074/481] Lambda expressions: parse exception specification in
     lambda functions. Fix lambda testcase for gcc-4.7.
    
    git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13854 626c5289-ae23-0410-ae9c-e8d60b6d4f22
    ---
     Examples/test-suite/cpp0x_lambda_functions.i | 29 ++++++++++++++++++++
     Source/CParse/parser.y                       |  5 ++--
     2 files changed, 32 insertions(+), 2 deletions(-)
    
    diff --git a/Examples/test-suite/cpp0x_lambda_functions.i b/Examples/test-suite/cpp0x_lambda_functions.i
    index 56235e9a6..0f10af471 100644
    --- a/Examples/test-suite/cpp0x_lambda_functions.i
    +++ b/Examples/test-suite/cpp0x_lambda_functions.i
    @@ -19,7 +19,23 @@ auto lambda2 = [](int x, int y) { return x+y; };
     auto lambda3 = [&](int x, int y) { return x+y; };
     auto lambda4 = [=](int x, int y) { return x+y; };
     int thing = 0;
    +#ifdef SWIG
    +// Not strictly correct as captured variables should have non-automatic storage duration, ie shouldn't capture globals. gcc-4.7 warns about this, but we check that SWIG can parse this anyway.
     auto lambda5 = [=,&thing]() { return thing;};
    +#else
    +auto lambda5 = [=]() { return thing;};
    +#endif
    +
    +void fn() {
    +  int stuff = 0;
    +  auto lambdaxxxx = [=,&stuff]() { return thing;};
    +}
    +auto lambda6 = [] (int a, int b) mutable { return a + b; };
    +auto lambda7 = [] (int x, int y) -> int { return x+y; };
    +auto lambda8 = [] (int x, int y) throw() -> int { return x+y; };
    +auto lambda9 = [] (int x, int y) mutable throw() -> int { return x+y; };
    +auto lambda10 = [] (int x, int y) throw(int) { return x+y; };
    +auto lambda11 = [] (int x, int y) mutable throw(int) { return x+y; };
     
     int runLambda1() {
       return lambda1(5,6);
    @@ -49,3 +65,16 @@ int runLambdaInline() {
     }
     %}
     
    +%{
    +// TODO
    +struct LambdaStruct {
    +  static constexpr auto lambda_struct1 = [=]() { return thing;};
    +};
    +auto lambda100 = [] { return thing;};
    +int lambda101 = [] (int a, int b) { return a + b; }(1, 2);
    +int lambda102 = [] (int a, int b) mutable { return a + b; }(1, 2);
    +auto lambda103 = [] () throw () { /* does not throw */ };
    +auto lambda104 = [] () mutable throw () { /* does not throw */ };
    +void lambda_init(int = ([=]{ return 0; })());
    +%}
    +
    diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y
    index f601aab9f..04b69fbc6 100644
    --- a/Source/CParse/parser.y
    +++ b/Source/CParse/parser.y
    @@ -3295,8 +3295,9 @@ cpp_alternate_rettype : primitive_type { $$ = $1; }
        OR
        auto myFunc = [](int x, int y) { return x+y; }
     */
    -c_lambda_decl  : c_lambda_decl_front LPAREN parms RPAREN LBRACE { skip_balanced('{','}'); } SEMI { $$ = 0; }
    -               | c_lambda_decl_front LPAREN parms RPAREN ARROW type LBRACE { skip_balanced('{','}'); } SEMI { $$ = 0; }
    +c_lambda_decl  : c_lambda_decl_front LPAREN parms RPAREN cpp_const LBRACE { skip_balanced('{','}'); } SEMI { $$ = 0; }
    +               | c_lambda_decl_front LPAREN parms RPAREN cpp_const ARROW type LBRACE { skip_balanced('{','}'); } SEMI { $$ = 0; }
    +               ;
     
     c_lambda_decl_front : storage_class AUTO idcolon EQUAL LBRACKET { skip_balanced('[',']'); $$ = 0; }
     
    
    From 7ca8f025ad6d18ffc4dc63f6b5c980b25915137a Mon Sep 17 00:00:00 2001
    From: William S Fulton 
    Date: Tue, 2 Oct 2012 21:12:36 +0000
    Subject: [PATCH 075/481] Add in support for initialising auto variables from
     lambda expressions
    
    git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13858 626c5289-ae23-0410-ae9c-e8d60b6d4f22
    ---
     Examples/test-suite/cpp0x_lambda_functions.i |  8 ++--
     Source/CParse/parser.y                       | 47 +++++++++++++++-----
     2 files changed, 41 insertions(+), 14 deletions(-)
    
    diff --git a/Examples/test-suite/cpp0x_lambda_functions.i b/Examples/test-suite/cpp0x_lambda_functions.i
    index 0f10af471..f0e863ad0 100644
    --- a/Examples/test-suite/cpp0x_lambda_functions.i
    +++ b/Examples/test-suite/cpp0x_lambda_functions.i
    @@ -36,6 +36,10 @@ auto lambda8 = [] (int x, int y) throw() -> int { return x+y; };
     auto lambda9 = [] (int x, int y) mutable throw() -> int { return x+y; };
     auto lambda10 = [] (int x, int y) throw(int) { return x+y; };
     auto lambda11 = [] (int x, int y) mutable throw(int) { return x+y; };
    +auto lambda12 = [] (int a, int b) { return a + b; }(1, 2);
    +auto lambda13 = [] (int a, int b) mutable { return a + b; }(1, 2);
    +auto lambda14 = [] () throw () {};
    +auto lambda15 = [] () mutable throw () {};
     
     int runLambda1() {
       return lambda1(5,6);
    @@ -70,11 +74,9 @@ int runLambdaInline() {
     struct LambdaStruct {
       static constexpr auto lambda_struct1 = [=]() { return thing;};
     };
    +int(*lambda101notauto)(int, int) = [] (int a, int b) { return a + b; };
     auto lambda100 = [] { return thing;};
    -int lambda101 = [] (int a, int b) { return a + b; }(1, 2);
     int lambda102 = [] (int a, int b) mutable { return a + b; }(1, 2);
    -auto lambda103 = [] () throw () { /* does not throw */ };
    -auto lambda104 = [] () mutable throw () { /* does not throw */ };
     void lambda_init(int = ([=]{ return 0; })());
     %}
     
    diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y
    index 04b69fbc6..5681fa721 100644
    --- a/Source/CParse/parser.y
    +++ b/Source/CParse/parser.y
    @@ -1690,7 +1690,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) {
     %type      types_directive template_directive warn_directive ;
     
     /* C declarations */
    -%type      c_declaration c_decl c_decl_tail c_enum_key c_enum_inherit c_enum_decl c_enum_forward_decl c_constructor_decl c_lambda_decl c_lambda_decl_front ;
    +%type      c_declaration c_decl c_decl_tail c_enum_key c_enum_inherit c_enum_decl c_enum_forward_decl c_constructor_decl;
     %type      enumlist edecl;
     
     /* C++ declarations */
    @@ -1698,7 +1698,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) {
     %type      cpp_members cpp_member;
     %type      cpp_constructor_decl cpp_destructor_decl cpp_protection_decl cpp_conversion_operator cpp_static_assert;
     %type      cpp_swig_directive cpp_temp_possible cpp_nested cpp_opt_declarators ;
    -%type      cpp_using_decl cpp_namespace_decl cpp_catch_decl ;
    +%type      cpp_using_decl cpp_namespace_decl cpp_catch_decl cpp_lambda_decl;
     %type      kwargs options;
     
     /* Misc */
    @@ -1735,6 +1735,8 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) {
     %type     type_specifier primitive_type_list ;
     %type      fname stringtype;
     %type      featattr;
    +%type      lambda_introducer lambda_body;
    +%type        lambda_tail;
     
     %%
     
    @@ -3098,7 +3100,7 @@ c_declaration   : c_decl {
     		    appendChild($$,firstChild($5));
     		  }
                     }
    -                | c_lambda_decl { Swig_warning(WARN_CPP11_LAMBDA, cparse_file, cparse_line,"Lambda expressions and closures are not fully supported yet.\n"); $$ = $1; }
    +                | cpp_lambda_decl { Swig_warning(WARN_CPP11_LAMBDA, cparse_file, cparse_line,"Lambda expressions and closures are not fully supported yet.\n"); $$ = $1; }
                     | USING idcolon EQUAL { skip_decl(); Swig_warning(WARN_CPP11_ALIAS_DECLARATION, cparse_file, cparse_line,"The 'using' keyword in type aliasing is not fully supported yet.\n"); $$ = 0; }
                     | TEMPLATE LESSTHAN template_parms GREATERTHAN USING idcolon EQUAL { skip_decl(); Swig_warning(WARN_CPP11_ALIAS_TEMPLATE, cparse_file, cparse_line,"The 'using' keyword in template aliasing is not fully supported yet.\n"); $$ = 0; }
                     ;
    @@ -3290,17 +3292,40 @@ cpp_alternate_rettype : primitive_type { $$ = $1; }
                   | decltype { $$ = $1; }
                   ;
     
    -/* Lambda function syntax introduced in C++0x.
    -   auto myFunc = [](int x, int y) -> int { return x+y; }
    -   OR
    -   auto myFunc = [](int x, int y) { return x+y; }
    +/* 
    +  Lambda functions and expressions, such as:
    +  auto myFunc = [](int x, int y) -> int { return x+y; };
    +  auto myFunc = [](int x, int y) { return x+y; };
    +  auto myFunc = [](int x, int y) { return x+y; }(1, 2);
     */
    -c_lambda_decl  : c_lambda_decl_front LPAREN parms RPAREN cpp_const LBRACE { skip_balanced('{','}'); } SEMI { $$ = 0; }
    -               | c_lambda_decl_front LPAREN parms RPAREN cpp_const ARROW type LBRACE { skip_balanced('{','}'); } SEMI { $$ = 0; }
    -               ;
    +cpp_lambda_decl : storage_class AUTO idcolon EQUAL lambda_introducer LPAREN parms RPAREN cpp_const lambda_body lambda_tail {
    +		  $$ = 0;
    +	        }
    +                | storage_class AUTO idcolon EQUAL lambda_introducer LPAREN parms RPAREN cpp_const ARROW type lambda_body lambda_tail {
    +		  $$ = 0;
    +		}
    +                ;
     
    -c_lambda_decl_front : storage_class AUTO idcolon EQUAL LBRACKET { skip_balanced('[',']'); $$ = 0; }
    +lambda_introducer : LBRACKET {
    +		  skip_balanced('[',']');
    +		  $$ = 0;
    +	        }
    +		;
     
    +lambda_body : LBRACE {
    +		  skip_balanced('{','}');
    +		  $$ = 0;
    +		}
    +
    +lambda_tail :	SEMI {
    +		  $$ = 0;
    +		}
    +		| LPAREN {
    +		  skip_balanced('(',')');
    +		} SEMI {
    +		  $$ = 0;
    +		}
    +		;
     
     /* ------------------------------------------------------------
        enum
    
    From 35458b4a5dc73a340961a378c62e8d98a2f90321 Mon Sep 17 00:00:00 2001
    From: William S Fulton 
    Date: Thu, 4 Oct 2012 06:01:38 +0000
    Subject: [PATCH 076/481] More lambda support - for optional lambda declarators
    
    git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13859 626c5289-ae23-0410-ae9c-e8d60b6d4f22
    ---
     Doc/Manual/Cpp0x.html                        | 17 ++++++++++++++++-
     Examples/test-suite/cpp0x_lambda_functions.i | 11 ++++++-----
     Source/CParse/parser.y                       | 17 +++++++++++------
     3 files changed, 33 insertions(+), 12 deletions(-)
    
    diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html
    index fa18b67f1..d6dce1d18 100644
    --- a/Doc/Manual/Cpp0x.html
    +++ b/Doc/Manual/Cpp0x.html
    @@ -217,14 +217,29 @@ ignores it.

    7.2.8 Lambda functions and expressions

    -

    SWIG correctly parses the Lambda functions syntax. For example:

    +

    SWIG correctly parses most of the Lambda functions syntax. For example:

    +auto val = [] { return something; };
    +auto sum = [](int x, int y) { return x+y; };
     auto sum = [](int x, int y) -> int { return x+y; };
     

    The lambda functions are removed from the wrapper class for now, because of the lack of support for closures (scope of the lambda functions) in the target languages.

    +

    +Lambda functions used to create variables can also be parsed, but due to limited support of auto when +the type is deduced from the expression, the variables are simply ignored. +

    + +
    +auto six = [](int x, int y) { return x+y; }(4, 2);
    +
    + +

    +Better support should be available in a later release. +

    +

    7.2.9 Alternate function syntax

    diff --git a/Examples/test-suite/cpp0x_lambda_functions.i b/Examples/test-suite/cpp0x_lambda_functions.i index f0e863ad0..fabc89079 100644 --- a/Examples/test-suite/cpp0x_lambda_functions.i +++ b/Examples/test-suite/cpp0x_lambda_functions.i @@ -21,14 +21,14 @@ auto lambda4 = [=](int x, int y) { return x+y; }; int thing = 0; #ifdef SWIG // Not strictly correct as captured variables should have non-automatic storage duration, ie shouldn't capture globals. gcc-4.7 warns about this, but we check that SWIG can parse this anyway. -auto lambda5 = [=,&thing]() { return thing;}; +auto lambda5 = [=,&thing]() { return thing; }; #else -auto lambda5 = [=]() { return thing;}; +auto lambda5 = [=]() { return thing; }; #endif void fn() { int stuff = 0; - auto lambdaxxxx = [=,&stuff]() { return thing;}; + auto lambdaxxxx = [=,&stuff]() { return thing; }; } auto lambda6 = [] (int a, int b) mutable { return a + b; }; auto lambda7 = [] (int x, int y) -> int { return x+y; }; @@ -40,6 +40,8 @@ auto lambda12 = [] (int a, int b) { return a + b; }(1, 2); auto lambda13 = [] (int a, int b) mutable { return a + b; }(1, 2); auto lambda14 = [] () throw () {}; auto lambda15 = [] () mutable throw () {}; +auto lambda16 = [] { return thing; }; +auto lambda17 = [] { return thing; }(); int runLambda1() { return lambda1(5,6); @@ -72,10 +74,9 @@ int runLambdaInline() { %{ // TODO struct LambdaStruct { - static constexpr auto lambda_struct1 = [=]() { return thing;}; + static constexpr auto lambda_struct1 = [=]() { return thing; }; }; int(*lambda101notauto)(int, int) = [] (int a, int b) { return a + b; }; -auto lambda100 = [] { return thing;}; int lambda102 = [] (int a, int b) mutable { return a + b; }(1, 2); void lambda_init(int = ([=]{ return 0; })()); %} diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 5681fa721..d91b7adce 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -3292,18 +3292,23 @@ cpp_alternate_rettype : primitive_type { $$ = $1; } | decltype { $$ = $1; } ; -/* - Lambda functions and expressions, such as: - auto myFunc = [](int x, int y) -> int { return x+y; }; - auto myFunc = [](int x, int y) { return x+y; }; - auto myFunc = [](int x, int y) { return x+y; }(1, 2); -*/ +/* ------------------------------------------------------------ + Lambda functions and expressions, such as: + auto myFunc = [] { return something; }; + auto myFunc = [](int x, int y) { return x+y; }; + auto myFunc = [](int x, int y) -> int { return x+y; }; + auto myFunc = [](int x, int y) throw() -> int { return x+y; }; + auto six = [](int x, int y) { return x+y; }(4, 2); + ------------------------------------------------------------ */ cpp_lambda_decl : storage_class AUTO idcolon EQUAL lambda_introducer LPAREN parms RPAREN cpp_const lambda_body lambda_tail { $$ = 0; } | storage_class AUTO idcolon EQUAL lambda_introducer LPAREN parms RPAREN cpp_const ARROW type lambda_body lambda_tail { $$ = 0; } + | storage_class AUTO idcolon EQUAL lambda_introducer lambda_body lambda_tail { + $$ = 0; + } ; lambda_introducer : LBRACKET { From 5ada4e35d133d62e7f65734a81274daa56866c9f Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 4 Oct 2012 06:05:28 +0000 Subject: [PATCH 077/481] One more lambda test using constexpr git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13860 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/cpp0x_lambda_functions.i | 1 + 1 file changed, 1 insertion(+) diff --git a/Examples/test-suite/cpp0x_lambda_functions.i b/Examples/test-suite/cpp0x_lambda_functions.i index fabc89079..0f11f9e63 100644 --- a/Examples/test-suite/cpp0x_lambda_functions.i +++ b/Examples/test-suite/cpp0x_lambda_functions.i @@ -42,6 +42,7 @@ auto lambda14 = [] () throw () {}; auto lambda15 = [] () mutable throw () {}; auto lambda16 = [] { return thing; }; auto lambda17 = [] { return thing; }(); +constexpr auto lambda18 = [] (int x, int y) mutable throw(int) { return x+y; }; int runLambda1() { return lambda1(5,6); From e81b6eccdbd33860aca3079ca782844f4fdeeaea Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 4 Oct 2012 06:12:44 +0000 Subject: [PATCH 078/481] Add lambda tests to test-suite - gcc-4.7 supports these git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13861 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 0b5e368f9..8d39e6369 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -438,6 +438,7 @@ CPP0X_TEST_CASES = \ cpp0x_explicit_conversion_operators \ cpp0x_function_objects \ cpp0x_initializer_list \ + cpp0x_lambda_functions \ cpp0x_null_pointer_constant \ cpp0x_raw_string_literals \ cpp0x_result_of \ @@ -456,7 +457,6 @@ CPP0X_TEST_CASES = \ # cpp0x_inheriting_constructors \ # not supported by gcc-4.7 # cpp0x_hash_tables \ # not fully implemented yet -# cpp0x_lambda_functions \ # not supported by GCC or MSVC yet # cpp0x_thread_local \ # not supported by any compiler yet # Broken C++0x test cases. From b9fd49858dd52786ecd42284fbc8d050587e25b1 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 4 Oct 2012 20:31:40 +0000 Subject: [PATCH 079/481] result_of not working git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13862 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/common.mk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 8d39e6369..a0f91655e 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -441,7 +441,6 @@ CPP0X_TEST_CASES = \ cpp0x_lambda_functions \ cpp0x_null_pointer_constant \ cpp0x_raw_string_literals \ - cpp0x_result_of \ cpp0x_rvalue_reference \ cpp0x_rvalue_reference2 \ cpp0x_sizeof_object \ @@ -457,6 +456,7 @@ CPP0X_TEST_CASES = \ # cpp0x_inheriting_constructors \ # not supported by gcc-4.7 # cpp0x_hash_tables \ # not fully implemented yet +# cpp0x_result_of \ # SWIG does not support # cpp0x_thread_local \ # not supported by any compiler yet # Broken C++0x test cases. From 6a43934ece479789b8e84a533d3db25456fe1dff Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 4 Oct 2012 20:52:51 +0000 Subject: [PATCH 080/481] Update variadic templates git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13863 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Doc/Manual/Cpp0x.html | 10 +++++---- .../test-suite/cpp0x_variadic_templates.i | 21 ++++++++++++------- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html index d6dce1d18..fa895cc6b 100644 --- a/Doc/Manual/Cpp0x.html +++ b/Doc/Manual/Cpp0x.html @@ -500,7 +500,7 @@ union P {

    7.2.17 Variadic templates

    -

    SWIG fully supports the variadic templates syntax (inside the <> +

    SWIG supports the variadic templates syntax (inside the <> block, variadic class inheritance and variadic constructor and initializers) with some limitations. The following code is correctly parsed:

    @@ -517,11 +517,13 @@ public: const int SIZE = sizeof...(ClassName<int, int>);
    -

    For now however, the %template directive only accepts at most the number of -arguments defined in the original template<> block:

    +

    +For now however, the %template directive only accepts one parameter substitution +for the variable template parameters. +

    -%template(MyVariant1) ClassName<>         // ok
    +%template(MyVariant1) ClassName<>         // zero argument not supported
     %template(MyVariant2) ClassName<int>      // ok
     %template(MyVariant3) ClassName<int, int> // too many arguments
     
    diff --git a/Examples/test-suite/cpp0x_variadic_templates.i b/Examples/test-suite/cpp0x_variadic_templates.i index c287194d4..2c0b2eac8 100644 --- a/Examples/test-suite/cpp0x_variadic_templates.i +++ b/Examples/test-suite/cpp0x_variadic_templates.i @@ -4,9 +4,9 @@ using variadic number of classes. */ %module cpp0x_variadic_templates -%warnfilter(507) MultiArgs1; -%warnfilter(507) SizeOf1; -%warnfilter(507) MultiInherit1; +%warnfilter(SWIGWARN_CPP11_VARIADIC_TEMPLATE) MultiArgs; +%warnfilter(SWIGWARN_CPP11_VARIADIC_TEMPLATE) SizeOf; +%warnfilter(SWIGWARN_CPP11_VARIADIC_TEMPLATE) MultiInherit; //////////////////////// // Variadic templates // @@ -36,7 +36,6 @@ template struct SizeOf { }; %} -// TODO %template (SizeOf1) SizeOf; ////////////////////////// @@ -48,7 +47,7 @@ public: A() { a = 100; } - + virtual ~A() {} int a; }; @@ -57,14 +56,22 @@ public: B() { b = 200; } + virtual ~B() {} int b; }; template class MultiInherit : public BaseClasses... { public: - MultiInherit(BaseClasses&... baseClasses) : BaseClasses(baseClasses)... {} + MultiInherit(BaseClasses&... baseClasses) : BaseClasses(baseClasses)... {} + int InstanceMethod() { return 123; } + static int StaticMethod() { return 456; } }; %} + // TODO -%template (MultiInherit1) MultiInherit; +//%template (MultiInherit0) MultiInherit<>; +%template (MultiInherit1) MultiInherit; +// TODO +%template (MultiInherit2) MultiInherit; + From 81d0168e51817fbb4f3fa57dd782793677b89525 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 5 Oct 2012 19:19:56 +0000 Subject: [PATCH 081/481] Autoconf archive macro to detect c++11 - as downloaded from archive git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13865 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Tools/config/ax_cxx_compile_stdcxx_11.m4 | 107 +++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 Tools/config/ax_cxx_compile_stdcxx_11.m4 diff --git a/Tools/config/ax_cxx_compile_stdcxx_11.m4 b/Tools/config/ax_cxx_compile_stdcxx_11.m4 new file mode 100644 index 000000000..0d96c073a --- /dev/null +++ b/Tools/config/ax_cxx_compile_stdcxx_11.m4 @@ -0,0 +1,107 @@ +# ============================================================================ +# http://www.gnu.org/software/autoconf-archive/ax_cxx_compile_stdcxx_11.html +# ============================================================================ +# +# SYNOPSIS +# +# AX_CXX_COMPILE_STDCXX_11([ext|noext]) +# +# DESCRIPTION +# +# Check for baseline language coverage in the compiler for the C++11 +# standard; if necessary, add switches to CXXFLAGS to enable support. +# Errors out if no mode that supports C++11 baseline syntax can be found. +# The 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 +# +# 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 + AC_LANG_ASSERT([C++])dnl + ac_success=no + 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" + 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" + ac_success=yes + break + fi + done + fi]) + + if test x$ac_success = xno; then + AC_MSG_ERROR([*** A compiler with support for C++11 language features is required.]) + fi +]) From 77ccb6f21ce62b9d19d40d7160bdbb7762ec2490 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 7 Oct 2012 18:50:41 +0000 Subject: [PATCH 082/481] Modify autoconf macro to be more flexible about how it is used - sets CXX11FLAGS, HAVE_CXX11_COMPILER and option to not error out git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13866 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Tools/config/ax_cxx_compile_stdcxx_11.m4 | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/Tools/config/ax_cxx_compile_stdcxx_11.m4 b/Tools/config/ax_cxx_compile_stdcxx_11.m4 index 0d96c073a..138ca2aca 100644 --- a/Tools/config/ax_cxx_compile_stdcxx_11.m4 +++ b/Tools/config/ax_cxx_compile_stdcxx_11.m4 @@ -4,15 +4,18 @@ # # SYNOPSIS # -# AX_CXX_COMPILE_STDCXX_11([ext|noext]) +# 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. -# Errors out if no mode that supports C++11 baseline syntax can be found. -# The 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). +# 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. # @@ -20,6 +23,7 @@ # # 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 @@ -50,8 +54,12 @@ AC_DEFUN([AX_CXX_COMPILE_STDCXX_11], [dnl [$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])], @@ -75,6 +83,7 @@ AC_DEFUN([AX_CXX_COMPILE_STDCXX_11], [dnl CXXFLAGS="$ac_save_CXXFLAGS"]) if eval test x\$$cachevar = xyes; then CXXFLAGS="$CXXFLAGS $switch" + CXX11FLAGS=$switch ac_success=yes break fi @@ -95,6 +104,7 @@ AC_DEFUN([AX_CXX_COMPILE_STDCXX_11], [dnl CXXFLAGS="$ac_save_CXXFLAGS"]) if eval test x\$$cachevar = xyes; then CXXFLAGS="$CXXFLAGS $switch" + CXX11FLAGS=$switch ac_success=yes break fi @@ -102,6 +112,10 @@ AC_DEFUN([AX_CXX_COMPILE_STDCXX_11], [dnl fi]) if test x$ac_success = xno; then - AC_MSG_ERROR([*** A compiler with support for C++11 language features is required.]) + 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 ]) From c94418b603a77c15d44162206c4373a4bd0f5d43 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 7 Oct 2012 18:56:48 +0000 Subject: [PATCH 083/481] Improve detection of C++11 compiler and set appropriate flags to use C++11/C++0x features git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/gsoc2009-matevz@13867 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/Makefile.in | 2 +- Examples/guile/Makefile.in | 2 +- configure.in | 19 ++++++++++++------- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 7fe78f359..4b5142267 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -24,7 +24,7 @@ TARGET = CC = @CC@ CXX = @CXX@ -CFLAGS = @PLATFLAGS@ +CFLAGS = @PLATCFLAGS@ CXXFLAGS = @PLATCXXFLAGS@ prefix = @prefix@ exec_prefix= @exec_prefix@ diff --git a/Examples/guile/Makefile.in b/Examples/guile/Makefile.in index a11095599..ec99f5fcd 100644 --- a/Examples/guile/Makefile.in +++ b/Examples/guile/Makefile.in @@ -6,7 +6,7 @@ top_srcdir = @top_srcdir@ SWIG = ../$(top_srcdir)/preinst-swig CC = @CC@ CXX = @CXX@ -CFLAGS = @PLATFLAGS@ +CFLAGS = @PLATCFLAGS@ GUILEINCLUDE = @GUILEINCLUDE@ GUILELINK = @GUILELINK@ SWIGOPT = diff --git a/configure.in b/configure.in index 3e2f2beae..4dda250d2 100644 --- a/configure.in +++ b/configure.in @@ -314,16 +314,21 @@ case $host in esac # Optional CFLAGS used to silence compiler warnings on some platforms. +AC_SUBST(PLATCFLAGS) +PLATCFLAGS= -AC_SUBST(PLATFLAGS) -PLATFLAGS= - -# Add switch to enable C++0x support +# Add switch if necessary to enable C++11 support - just for tests +AC_LANG_PUSH([C++]) +CXXFLAGS_SAVED=$CXXFLAGS +AX_CXX_COMPILE_STDCXX_11([noext], [nostop]) +CXXFLAGS=$CXXFLAGS_SAVED +AC_LANG_POP([C++]) AC_SUBST(PLATCXXFLAGS) -if test "$GCC" = yes; then - PLATCXXFLAGS=$PLATFLAGS" -std=c++0x " +AC_SUBST(HAVE_CXX11_COMPILER) +if test x"$CXX11FLAGS" = x; then + PLATCXXFLAGS="$PLATCFLAGS" else - PLATCXXFLAGS=$PLATFLAGS + PLATCXXFLAGS="$CXX11FLAGS $PLATCFLAGS" fi # Check for specific libraries. Used for SWIG examples From 1f0db4fb9e0a3e6dbd916b7e69eb551ca2bb2f5d Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 13 Jan 2013 00:06:09 +0000 Subject: [PATCH 084/481] Add check-cpp11 target for testing c++11 only tests --- Examples/test-suite/common.mk | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index a0f91655e..c19755018 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -566,6 +566,8 @@ all: $(NOT_BROKEN_TEST_CASES) $(BROKEN_TEST_CASES) check: $(NOT_BROKEN_TEST_CASES) +check-cpp11: $(CPP0X_TEST_CASES:=.cpptest) + # partialcheck target runs SWIG only, ie no compilation or running of tests (for a subset of languages) partialcheck: $(MAKE) check CC=true CXX=true LDSHARED=true CXXSHARED=true RUNTOOL=true COMPILETOOL=true From 7d800a655de565826fd2404fd11d85dccd9c11d1 Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Wed, 16 Jan 2013 08:01:27 +0400 Subject: [PATCH 085/481] Unicode literals --- Examples/test-suite/csharp_features.i | 4 ++ Source/CParse/cscanner.c | 14 +++++- Source/CParse/parser.y | 42 +++++++++++++++-- Source/Swig/cwrap.c | 2 +- Source/Swig/scanner.c | 68 ++++++++++++++++++++++++--- Source/Swig/stype.c | 11 ++++- Source/Swig/swig.h | 3 ++ Source/Swig/swigscan.h | 3 ++ Source/Swig/typesys.c | 4 ++ 9 files changed, 137 insertions(+), 14 deletions(-) diff --git a/Examples/test-suite/csharp_features.i b/Examples/test-suite/csharp_features.i index 578a56a10..f77e3fc9c 100644 --- a/Examples/test-suite/csharp_features.i +++ b/Examples/test-suite/csharp_features.i @@ -1,4 +1,5 @@ %module csharp_features +%include "wchar.i" // SWIG gets the method modifiers wrong occasionally, like with private inheritance, %csmethodmodifiers can fix this %csmethodmodifiers Derived::VirtualMethod() "public virtual" @@ -19,6 +20,9 @@ public: class MoreDerived : public Derived { public: int variable; + // test wide char literals support for C# module + void methodWithDefault1(const wchar_t* s = L"literal with escapes \x1234"){} + void methodWithDefault2(wchar_t c = L'\x1234'){} }; %} diff --git a/Source/CParse/cscanner.c b/Source/CParse/cscanner.c index 23152e884..14a4f4bd0 100644 --- a/Source/CParse/cscanner.c +++ b/Source/CParse/cscanner.c @@ -383,6 +383,10 @@ static int yylook(void) { case SWIG_TOKEN_STRING: yylval.id = Swig_copy_string(Char(Scanner_text(scan))); return STRING; + + case SWIG_TOKEN_WSTRING: + yylval.id = Swig_copy_string(Char(Scanner_text(scan))); + return WSTRING; case SWIG_TOKEN_CHAR: yylval.str = NewString(Scanner_text(scan)); @@ -391,7 +395,15 @@ static int yylook(void) { Printf(stdout,"%d\n", Len(Scanner_text(scan))); } return CHARCONST; - + + case SWIG_TOKEN_WCHAR: + yylval.str = NewString(Scanner_text(scan)); + if (Len(yylval.str) == 0) { + Swig_error(cparse_file, cparse_line, "Empty character constant\n"); + Printf(stdout,"%d\n", Len(Scanner_text(scan))); + } + return WCHARCONST; + /* Numbers */ case SWIG_TOKEN_INT: diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index d91b7adce..cd032eb00 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -13,8 +13,8 @@ * some point. Beware. * ----------------------------------------------------------------------------- */ +%expect 6 %{ - #define yylex yylex char cvsroot_parser_y[] = "$Id$"; @@ -1635,9 +1635,9 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %token ID %token HBLOCK %token POUND -%token STRING +%token STRING WSTRING %token INCLUDE IMPORT INSERT -%token CHARCONST +%token CHARCONST WCHARCONST %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 @@ -1728,7 +1728,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %type abstract_declarator direct_abstract_declarator ctor_end; %type typemap_type; %type idcolon idcolontail idcolonnt idcolontailnt idtemplate stringbrace stringbracesemi; -%type string stringnum ; +%type string stringnum wstring; %type template_parms; %type cpp_end cpp_vend; %type rename_namewarn; @@ -6001,7 +6001,7 @@ definetype : { /* scanner_check_typedef(); */ } expr { $$ = $2; if ($$.type == T_STRING) { $$.rawval = NewStringf("\"%(escape)s\"",$$.val); - } else if ($$.type != T_CHAR) { + } else if ($$.type != T_CHAR && $$.type != T_WSTRING && $$.type != T_WCHAR) { $$.rawval = 0; } $$.bitfield = 0; @@ -6127,6 +6127,11 @@ valexpr : exprnum { $$ = $1; } $$.type = T_ULONG; } | exprcompound { $$ = $1; } + | wstring { + $$.val = NewString($1); + $$.rawval = NewStringf("L\"%s\"", $$.val); + $$.type = T_WSTRING; + } | CHARCONST { $$.val = NewString($1); if (Len($$.val)) { @@ -6139,6 +6144,18 @@ valexpr : exprnum { $$ = $1; } $$.throws = 0; $$.throwf = 0; } + | WCHARCONST { + $$.val = NewString($1); + if (Len($$.val)) { + $$.rawval = NewStringf("L\'%s\'", $$.val); + } else { + $$.rawval = NewString("L'\\0'"); + } + $$.type = T_WCHAR; + $$.bitfield = 0; + $$.throws = 0; + $$.throwf = 0; + } /* grouping */ | LPAREN expr RPAREN %prec CAST { @@ -6661,6 +6678,21 @@ string : string STRING { } | STRING { $$ = $1;} ; +/* Concatenated wide strings: L"str1" L"str2" */ +wstring : wstring WSTRING { + $$ = (char *) malloc(strlen($1)+strlen($2)+1); + strcpy($$,$1); + strcat($$,$2); + } +/* Concatenated wide string and normal string literal: L"str1" "str2" */ +/*not all the compilers support this concatenation mode, so perhaps better to postpone it*/ + /*| wstring STRING { here $2 comes unescaped, we have to escape it back first via NewStringf("%(escape)s)" + $$ = (char *) malloc(strlen($1)+strlen($2)+1); + strcpy($$,$1); + strcat($$,$2); + }*/ + | WSTRING { $$ = $1;} + ; stringbrace : string { $$ = NewString($1); diff --git a/Source/Swig/cwrap.c b/Source/Swig/cwrap.c index 4a461fce8..d335bb0e9 100644 --- a/Source/Swig/cwrap.c +++ b/Source/Swig/cwrap.c @@ -274,7 +274,7 @@ int Swig_cargs(Wrapper *w, ParmList *p) { Delete(defname); Delete(defvalue); } - } else if (!pvalue && ((tycode == T_POINTER) || (tycode == T_STRING))) { + } else if (!pvalue && ((tycode == T_POINTER) || (tycode == T_STRING) || (tycode == T_WSTRING))) { pvalue = (String *) "0"; } if (!altty) { diff --git a/Source/Swig/scanner.c b/Source/Swig/scanner.c index 446a68eb7..c3562c7cc 100644 --- a/Source/Swig/scanner.c +++ b/Source/Swig/scanner.c @@ -509,7 +509,6 @@ static int look(Scanner * s) { state = 4; /* Possibly a SWIG directive */ /* Look for possible identifiers or unicode/delimiter strings */ - else if ((isalpha(c)) || (c == '_') || (s->idstart && strchr(s->idstart, c))) { state = 7; @@ -867,11 +866,15 @@ static int look(Scanner * s) { break; case 7: /* Identifier or true/false or unicode/custom delimiter string */ - if (c=='R') { /* Possibly CUSTOM DELIMITER string */ + if (c == 'R') { /* Possibly CUSTOM DELIMITER string */ state = 72; break; } - else if (c!='u' && c!='U' && c!='L') { /* Definitely an identifier */ + else if (c == 'L') { /* Probably identifier but may be a wide string literal */ + state = 77; + break; + } + else if (c != 'u' && c != 'U') { /* Definitely an identifier */ state = 70; break; } @@ -879,14 +882,14 @@ static int look(Scanner * s) { if ((c = nextchar(s)) == 0) { state = 76; } - else if (c=='\"') { /* Definitely u, U or L string */ + else if (c == '\"') { /* Definitely u, U or L string */ retract(s, 1); state = 1000; } - else if (c=='R') { /* Possibly CUSTOM DELIMITER u, U, L string */ + else if (c == 'R') { /* Possibly CUSTOM DELIMITER u, U, L string */ state = 73; } - else if (c=='8') { /* Possibly u8 string */ + else if (c == '8') { /* Possibly u8 string */ state = 71; } else { @@ -950,6 +953,59 @@ static int look(Scanner * s) { break; + case 77: /*identifier or wide string literal*/ + if ((c = nextchar(s)) == 0) + return SWIG_TOKEN_ID; + else if (c == '\"') { + s->start_line = s->line; + Clear(s->text); + state = 78; + } + else if (c == '\'') { + s->start_line = s->line; + Clear(s->text); + state = 79; + } + else if (isalnum(c) || (c == '_') || (c == '$')) + state = 7; + else { + retract(s, 1); + return SWIG_TOKEN_ID; + } + break; + + case 78: /* Processing a wide string literal*/ + if ((c = nextchar(s)) == 0) { + Swig_error(cparse_file, cparse_start_line, "Unterminated wide string\n"); + return SWIG_TOKEN_ERROR; + } + if (c == '\"') { + Delitem(s->text, DOH_END); + return SWIG_TOKEN_WSTRING; + } else if (c == '\\') { + if ((c = nextchar(s)) == 0) { + Swig_error(cparse_file, cparse_start_line, "Unterminated wide string\n"); + return SWIG_TOKEN_ERROR; + } + } + break; + + case 79: /* Processing a wide char literal */ + if ((c = nextchar(s)) == 0) { + Swig_error(cparse_file, cparse_start_line, "Unterminated character constant\n"); + return SWIG_TOKEN_ERROR; + } + if (c == '\'') { + Delitem(s->text, DOH_END); + return (SWIG_TOKEN_WCHAR); + } else if (c == '\\') { + if ((c = nextchar(s)) == 0) { + Swig_error(cparse_file, cparse_start_line, "Unterminated wide char literal\n"); + return SWIG_TOKEN_ERROR; + } + } + break; + case 75: /* Special identifier $ */ if ((c = nextchar(s)) == 0) return SWIG_TOKEN_DOLLAR; diff --git a/Source/Swig/stype.c b/Source/Swig/stype.c index 32946ead5..b63530b53 100644 --- a/Source/Swig/stype.c +++ b/Source/Swig/stype.c @@ -131,12 +131,21 @@ SwigType *NewSwigType(int t) { case T_UCHAR: return NewString("unsigned char"); break; - case T_STRING:{ + case T_STRING: { SwigType *t = NewString("char"); SwigType_add_pointer(t); return t; break; } + case T_WCHAR: + return NewString("wchar_t"); + break; + case T_WSTRING: { + SwigType *t = NewString("wchar_t"); + SwigType_add_pointer(t); + return t; + break; + } case T_LONGLONG: return NewString("long long"); break; diff --git a/Source/Swig/swig.h b/Source/Swig/swig.h index dc65d9b0d..dceb73753 100644 --- a/Source/Swig/swig.h +++ b/Source/Swig/swig.h @@ -100,6 +100,9 @@ extern "C" { #define T_SYMBOL 98 #define T_ERROR 99 +/* wide string literal, may contain escaped wide chars like \x1234 as well as normal escape sequences */ +#define T_WSTRING 39 + /* --- File interface --- */ diff --git a/Source/Swig/swigscan.h b/Source/Swig/swigscan.h index b07812fbe..ae2e9ea4d 100644 --- a/Source/Swig/swigscan.h +++ b/Source/Swig/swigscan.h @@ -67,6 +67,9 @@ extern void Scanner_freeze_line(Scanner *s, int val); #define SWIG_TOKEN_QUESTION 30 /* ? */ #define SWIG_TOKEN_COMMENT 31 /* C or C++ comment */ #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_ILLEGAL 99 #define SWIG_TOKEN_ERROR -1 diff --git a/Source/Swig/typesys.c b/Source/Swig/typesys.c index a72ce5198..2de9bcb1d 100644 --- a/Source/Swig/typesys.c +++ b/Source/Swig/typesys.c @@ -1194,6 +1194,8 @@ int SwigType_type(SwigType *t) { if (strncmp(c, "p.", 2) == 0) { if (SwigType_type(c + 2) == T_CHAR) return T_STRING; + else if (SwigType_type(c + 2) == T_WCHAR) + return T_WSTRING; else return T_POINTER; } @@ -1236,6 +1238,8 @@ int SwigType_type(SwigType *t) { return T_SCHAR; if (strcmp(c, "unsigned char") == 0) return T_UCHAR; + if (strcmp(c, "wchar_t") == 0) + return T_WCHAR; if (strcmp(c, "float") == 0) return T_FLOAT; if (strcmp(c, "double") == 0) From 144e2ab7b4ea8fb243ae8fb38c6e1aa7ee89cadc Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 21 Jan 2013 19:42:44 +0000 Subject: [PATCH 086/481] Fixes to previous (unicode literals) commit --- Source/Swig/swig.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Source/Swig/swig.h b/Source/Swig/swig.h index dceb73753..0b3edf17e 100644 --- a/Source/Swig/swig.h +++ b/Source/Swig/swig.h @@ -97,11 +97,11 @@ extern "C" { #define T_MPOINTER 38 #define T_VARARGS 39 #define T_RVALUE_REFERENCE 40 +#define T_WSTRING 41 + #define T_SYMBOL 98 #define T_ERROR 99 -/* wide string literal, may contain escaped wide chars like \x1234 as well as normal escape sequences */ -#define T_WSTRING 39 /* --- File interface --- */ From 4b869de2e87e78a04079d5bf6d0db7087501cc5a Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 21 Jan 2013 19:43:14 +0000 Subject: [PATCH 087/481] Cosmetic changes to previous (unicode literals) commit --- Source/Swig/scanner.c | 106 +++++++++++++++++++++--------------------- 1 file changed, 53 insertions(+), 53 deletions(-) diff --git a/Source/Swig/scanner.c b/Source/Swig/scanner.c index c3562c7cc..6389cc988 100644 --- a/Source/Swig/scanner.c +++ b/Source/Swig/scanner.c @@ -953,59 +953,6 @@ static int look(Scanner * s) { break; - case 77: /*identifier or wide string literal*/ - if ((c = nextchar(s)) == 0) - return SWIG_TOKEN_ID; - else if (c == '\"') { - s->start_line = s->line; - Clear(s->text); - state = 78; - } - else if (c == '\'') { - s->start_line = s->line; - Clear(s->text); - state = 79; - } - else if (isalnum(c) || (c == '_') || (c == '$')) - state = 7; - else { - retract(s, 1); - return SWIG_TOKEN_ID; - } - break; - - case 78: /* Processing a wide string literal*/ - if ((c = nextchar(s)) == 0) { - Swig_error(cparse_file, cparse_start_line, "Unterminated wide string\n"); - return SWIG_TOKEN_ERROR; - } - if (c == '\"') { - Delitem(s->text, DOH_END); - return SWIG_TOKEN_WSTRING; - } else if (c == '\\') { - if ((c = nextchar(s)) == 0) { - Swig_error(cparse_file, cparse_start_line, "Unterminated wide string\n"); - return SWIG_TOKEN_ERROR; - } - } - break; - - case 79: /* Processing a wide char literal */ - if ((c = nextchar(s)) == 0) { - Swig_error(cparse_file, cparse_start_line, "Unterminated character constant\n"); - return SWIG_TOKEN_ERROR; - } - if (c == '\'') { - Delitem(s->text, DOH_END); - return (SWIG_TOKEN_WCHAR); - } else if (c == '\\') { - if ((c = nextchar(s)) == 0) { - Swig_error(cparse_file, cparse_start_line, "Unterminated wide char literal\n"); - return SWIG_TOKEN_ERROR; - } - } - break; - case 75: /* Special identifier $ */ if ((c = nextchar(s)) == 0) return SWIG_TOKEN_DOLLAR; @@ -1028,6 +975,59 @@ static int look(Scanner * s) { return SWIG_TOKEN_ID; break; + case 77: /*identifier or wide string literal*/ + if ((c = nextchar(s)) == 0) + return SWIG_TOKEN_ID; + else if (c == '\"') { + s->start_line = s->line; + Clear(s->text); + state = 78; + } + else if (c == '\'') { + s->start_line = s->line; + Clear(s->text); + state = 79; + } + else if (isalnum(c) || (c == '_') || (c == '$')) + state = 7; + else { + retract(s, 1); + return SWIG_TOKEN_ID; + } + break; + + case 78: /* Processing a wide string literal*/ + if ((c = nextchar(s)) == 0) { + Swig_error(cparse_file, cparse_start_line, "Unterminated wide string\n"); + return SWIG_TOKEN_ERROR; + } + if (c == '\"') { + Delitem(s->text, DOH_END); + return SWIG_TOKEN_WSTRING; + } else if (c == '\\') { + if ((c = nextchar(s)) == 0) { + Swig_error(cparse_file, cparse_start_line, "Unterminated wide string\n"); + return SWIG_TOKEN_ERROR; + } + } + break; + + case 79: /* Processing a wide char literal */ + if ((c = nextchar(s)) == 0) { + Swig_error(cparse_file, cparse_start_line, "Unterminated wide character constant\n"); + return SWIG_TOKEN_ERROR; + } + if (c == '\'') { + Delitem(s->text, DOH_END); + return (SWIG_TOKEN_WCHAR); + } else if (c == '\\') { + if ((c = nextchar(s)) == 0) { + Swig_error(cparse_file, cparse_start_line, "Unterminated wide character literal\n"); + return SWIG_TOKEN_ERROR; + } + } + break; + case 8: /* A numerical digit */ if ((c = nextchar(s)) == 0) return SWIG_TOKEN_INT; From d357bec829d08ee96afe8ca8bf6d8631f6b983c9 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 21 Jan 2013 20:04:06 +0000 Subject: [PATCH 088/481] Remove recently added %expect in parser in case of backward compatibility problems --- Source/CParse/parser.y | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index cd032eb00..3b9762b96 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -13,7 +13,12 @@ * some point. Beware. * ----------------------------------------------------------------------------- */ +/* +Removed until we know more about the min versions of Bison and Yacc required for this +to work, see Byacc man page: http://invisible-island.net/byacc/manpage/yacc.html %expect 6 +*/ + %{ #define yylex yylex From 07c35d61e30d371a65b134ca62c44701230cfbd0 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 24 Jan 2013 08:02:34 +0000 Subject: [PATCH 089/481] Fix generated code for rvalue references by converting functions returning an rvalue reference into something that can be taken the address of - via a const ref cast. Now the rvalue_reference tests compile under g++-4.7 (C# only atm) --- Examples/test-suite/common.mk | 1 + Examples/test-suite/cpp0x_rvalue_reference3.i | 65 +++++++++++++++++++ Source/Swig/cwrap.c | 11 +++- 3 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 Examples/test-suite/cpp0x_rvalue_reference3.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index c19755018..1b50ed895 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -443,6 +443,7 @@ CPP0X_TEST_CASES = \ cpp0x_raw_string_literals \ cpp0x_rvalue_reference \ cpp0x_rvalue_reference2 \ + cpp0x_rvalue_reference3 \ cpp0x_sizeof_object \ cpp0x_static_assert \ cpp0x_strongly_typed_enumerations \ diff --git a/Examples/test-suite/cpp0x_rvalue_reference3.i b/Examples/test-suite/cpp0x_rvalue_reference3.i new file mode 100644 index 000000000..c6fe60068 --- /dev/null +++ b/Examples/test-suite/cpp0x_rvalue_reference3.i @@ -0,0 +1,65 @@ +%module cpp0x_rvalue_reference3 + +%inline %{ +#include +struct Thing {}; + +Thing && global_rvalue_ref = Thing(); +Thing *&& global_rvalue_ref_ptr1 = 0; +Thing const*&& global_rvalue_ref_ptr2 = 0; +Thing *const&& global_rvalue_ref_ptr3 = 0; +Thing const*const &&global_rvalue_ref_ptr4 = 0; + +Thing && returnit1() { return std::move(global_rvalue_ref); } +Thing *&& returnit2() { return std::move(global_rvalue_ref_ptr1); } +Thing const*&& returnit3() { return std::move(global_rvalue_ref_ptr2); } +Thing *const&& returnit4() { return std::move(global_rvalue_ref_ptr3); } +Thing const*const&& returnit5() { return std::move(global_rvalue_ref_ptr4); } + +void takeit1(Thing && t) {} +void takeit2(Thing *&& t) {} +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 = 0; + Thing const*&& member_rvalue_ref_ptr2 = 0; + Thing *const&& member_rvalue_ref_ptr3 = 0; + Thing const*const &&member_rvalue_ref_ptr4 = 0; + + Containing() : member_rvalue_ref(Thing()) {} +}; +%} + + +%inline %{ +int && int_global_rvalue_ref = 5; +int *&& int_global_rvalue_ref_ptr1 = 0; +int const*&& int_global_rvalue_ref_ptr2 = 0; +int *const&& int_global_rvalue_ref_ptr3 = 0; +int const*const &&int_global_rvalue_ref_ptr4 = 0; + +int && int_returnit1() { return std::move(int_global_rvalue_ref); } +int *&& int_returnit2() { return std::move(int_global_rvalue_ref_ptr1); } +int const*&& int_returnit3() { return std::move(int_global_rvalue_ref_ptr2); } +int *const&& int_returnit4() { return std::move(int_global_rvalue_ref_ptr3); } +int const*const&& int_returnit5() { return std::move(int_global_rvalue_ref_ptr4); } + +void int_takeit1(int && t) {} +void int_takeit2(int *&& t) {} +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 = 0; + int const*&& member_rvalue_ref_ptr2 = 0; + int *const&& member_rvalue_ref_ptr3 = 0; + int const*const &&member_rvalue_ref_ptr4 = 0; + + IntContaining() : member_rvalue_ref(55) {} +}; +%} diff --git a/Source/Swig/cwrap.c b/Source/Swig/cwrap.c index d335bb0e9..1ec790167 100644 --- a/Source/Swig/cwrap.c +++ b/Source/Swig/cwrap.c @@ -317,7 +317,16 @@ String *Swig_cresult(SwigType *t, const_String_or_char_ptr name, const_String_or case T_RVALUE_REFERENCE: { String *lstr = SwigType_lstr(t, 0); - Printf(fcall, "%s = (%s) &", name, lstr); + SwigType *tt = Copy(t); + SwigType_del_rvalue_reference(tt); + SwigType_add_qualifier(tt, "const"); + SwigType_add_reference(tt); + String *const_lvalue_str = SwigType_rcaststr(tt, 0); + + Printf(fcall, "%s = (%s) &%s", name, lstr, const_lvalue_str); + + Delete(const_lvalue_str); + Delete(tt); Delete(lstr); } break; From 1386b73545ae11c9a35820a2ff2179b64ebc2313 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 24 Jan 2013 19:09:05 +0000 Subject: [PATCH 090/481] More rvalue reference typemaps --- Lib/csharp/csharp.swg | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/Lib/csharp/csharp.swg b/Lib/csharp/csharp.swg index 950e02e5d..5994aa9c0 100644 --- a/Lib/csharp/csharp.swg +++ b/Lib/csharp/csharp.swg @@ -427,6 +427,12 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { %{ $input = (void *) $1; %} %typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE & +%{ if (!$input) { + SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "Unexpected null return for type $1_type", 0); + return $null; + } + $result = ($1_ltype)$input; %} +%typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE && %{ if (!$input) { SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "Unexpected null return for type $1_type", 0); return $null; @@ -434,10 +440,13 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { $result = ($1_ltype)$input; %} %typemap(directorin) SWIGTYPE & %{ $input = ($1_ltype) &$1; %} +%typemap(directorin) SWIGTYPE && +%{ $input = ($1_ltype) &$1; %} %typemap(csdirectorin) SWIGTYPE *, SWIGTYPE (CLASS::*) "($iminput == IntPtr.Zero) ? null : new $csclassname($iminput, false)" %typemap(csdirectorin) SWIGTYPE & "new $csclassname($iminput, false)" -%typemap(csdirectorout) SWIGTYPE *, SWIGTYPE (CLASS::*), SWIGTYPE & "$csclassname.getCPtr($cscall).Handle" +%typemap(csdirectorin) SWIGTYPE && "new $csclassname($iminput, false)" +%typemap(csdirectorout) SWIGTYPE *, SWIGTYPE (CLASS::*), SWIGTYPE &, SWIGTYPE && "$csclassname.getCPtr($cscall).Handle" /* Default array handling */ %typemap(in) SWIGTYPE [] %{ $1 = ($1_ltype)$input; %} @@ -973,6 +982,7 @@ using System.Runtime.InteropServices; /* Array reference typemaps */ %apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } +%apply SWIGTYPE && { SWIGTYPE ((&&)[ANY]) } /* const pointers */ %apply SWIGTYPE * { SWIGTYPE *const } From 556e6469729f82e33b7e8db890a1285ade97b65b Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 24 Jan 2013 20:17:52 +0000 Subject: [PATCH 091/481] Add missing static member to testcase --- Examples/test-suite/cpp0x_rvalue_reference2.i | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Examples/test-suite/cpp0x_rvalue_reference2.i b/Examples/test-suite/cpp0x_rvalue_reference2.i index a3e9d1784..b7f58afee 100644 --- a/Examples/test-suite/cpp0x_rvalue_reference2.i +++ b/Examples/test-suite/cpp0x_rvalue_reference2.i @@ -36,9 +36,10 @@ struct Thingy { rvalref = rhs.rvalref; } private: - static const bool PrivateTrue = true; + static const bool PrivateTrue; Thingy(); }; +const bool Thingy::PrivateTrue = true; short && globalRvalueInOut(short &&i) { return std::move(i); } From 1e472da302e4d7203b5038d8b30f3172e164350c Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 24 Jan 2013 19:24:24 +0000 Subject: [PATCH 092/481] Use CXXFLAGS for c++ code for Go examples --- Examples/Makefile.in | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 4b5142267..6dae4e461 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -1184,8 +1184,8 @@ go: $(SRCS) go_cpp: $(SRCS) $(SWIG) -go -c++ $(GOSWIGARG) $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -g -c $(CCSHARED) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(CXX) -g -c $(CCSHARED) $(CXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) + $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) $(COMPILETOOL) $(GO) -I . $(GOCOMPILEARG) $(GOSRCS) if ! $(GOGCC) ; then \ $(COMPILETOOL) $(GOC) -I $${GOROOT}/pkg/$${GOOS}_$${GOARCH} $(GOCSRCS) && \ From 285198c48fc43a1e890f17537db0e7ed571be054 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 24 Jan 2013 19:09:22 +0000 Subject: [PATCH 093/481] Add rvalue reference typemaps --- Lib/java/java.swg | 43 ++++++++++++++++++++++++++++++++++--------- 1 file changed, 34 insertions(+), 9 deletions(-) diff --git a/Lib/java/java.swg b/Lib/java/java.swg index 44e1337bc..7743eac5d 100644 --- a/Lib/java/java.swg +++ b/Lib/java/java.swg @@ -185,6 +185,10 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { %typemap(jtype) SWIGTYPE & "long" %typemap(jstype) SWIGTYPE & "$javaclassname" +%typemap(jni) SWIGTYPE && "jlong" +%typemap(jtype) SWIGTYPE && "long" +%typemap(jstype) SWIGTYPE && "$javaclassname" + /* pointer to a class member */ %typemap(jni) SWIGTYPE (CLASS::*) "jstring" %typemap(jtype) SWIGTYPE (CLASS::*) "String" @@ -649,6 +653,11 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { 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 * %{ *($&1_ltype)&$result = $1; %} %typemap(out, fragment="SWIG_PackData", noblock=1) SWIGTYPE (CLASS::*) { @@ -659,6 +668,8 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { } %typemap(out) SWIGTYPE & %{ *($&1_ltype)&$result = $1; %} +%typemap(out) SWIGTYPE && +%{ *($&1_ltype)&$result = $1; %} %typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE * %{ $result = *($&1_ltype)&$input; %} @@ -671,6 +682,12 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { %{ *(($&1_ltype)&$input) = ($1_ltype) $1; %} %typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE & +%{ if (!$input) { + SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Unexpected null return for type $1_type"); + return $null; + } + $result = *($&1_ltype)&$input; %} +%typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE && %{ if (!$input) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Unexpected null return for type $1_type"); return $null; @@ -678,10 +695,13 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { $result = *($&1_ltype)&$input; %} %typemap(directorin,descriptor="L$packagepath/$javaclassname;") SWIGTYPE & %{ *($&1_ltype)&$input = ($1_ltype) &$1; %} +%typemap(directorin,descriptor="L$packagepath/$javaclassname;") SWIGTYPE && +%{ *($&1_ltype)&$input = ($1_ltype) &$1; %} %typemap(javadirectorin) SWIGTYPE *, SWIGTYPE (CLASS::*) "($jniinput == 0) ? null : new $javaclassname($jniinput, false)" %typemap(javadirectorin) SWIGTYPE & "new $javaclassname($jniinput, false)" -%typemap(javadirectorout) SWIGTYPE *, SWIGTYPE (CLASS::*), SWIGTYPE & "$javaclassname.getCPtr($javacall)" +%typemap(javadirectorin) SWIGTYPE && "new $javaclassname($jniinput, false)" +%typemap(javadirectorout) SWIGTYPE *, SWIGTYPE (CLASS::*), SWIGTYPE &, SWIGTYPE && "$javaclassname.getCPtr($javacall)" /* Default array handling */ %typemap(in) SWIGTYPE [] %{ $1 = *($&1_ltype)&$input; %} @@ -959,6 +979,7 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { SWIGTYPE, SWIGTYPE *, SWIGTYPE &, + SWIGTYPE &&, SWIGTYPE *const&, SWIGTYPE [], SWIGTYPE (CLASS::*) @@ -978,7 +999,7 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, error_msg); return $null; %} -%typemap(throws) SWIGTYPE, SWIGTYPE &, SWIGTYPE *, SWIGTYPE [], SWIGTYPE [ANY] +%typemap(throws) SWIGTYPE, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE *, SWIGTYPE [], SWIGTYPE [ANY] %{ (void)$1; SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, "C++ $1_type exception thrown"); return $null; %} @@ -1029,7 +1050,7 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { jobjectArray "$javainput" %typemap(javain) SWIGTYPE "$&javaclassname.getCPtr($javainput)" -%typemap(javain) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] "$javaclassname.getCPtr($javainput)" +%typemap(javain) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] "$javaclassname.getCPtr($javainput)" %typemap(javain) SWIGTYPE (CLASS::*) "$javaclassname.getCMemberPtr($javainput)" /* The javaout typemap is used for converting function return types from the return type @@ -1083,6 +1104,9 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { %typemap(javaout) SWIGTYPE & { return new $javaclassname($jnicall, $owner); } +%typemap(javaout) SWIGTYPE && { + return new $javaclassname($jnicall, $owner); + } %typemap(javaout) SWIGTYPE *, SWIGTYPE [] { long cPtr = $jnicall; return (cPtr == 0) ? null : new $javaclassname(cPtr, $owner); @@ -1108,11 +1132,11 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { %{ *($1_ltype)&$result = *$1; %} /* Typemaps used for the generation of proxy and type wrapper class code */ -%typemap(javabase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" -%typemap(javaclassmodifiers) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "public class" -%typemap(javacode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" -%typemap(javaimports) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" -%typemap(javainterfaces) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" +%typemap(javabase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" +%typemap(javaclassmodifiers) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "public class" +%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::*) "" /* javabody typemaps */ @@ -1153,7 +1177,7 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { SWIG_JAVABODY_METHODS(public, public, SWIGTYPE) // Typewrapper classes -%typemap(javabody) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] %{ +%typemap(javabody) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] %{ private long swigCPtr; protected $javaclassname(long cPtr, boolean futureUse) { @@ -1286,6 +1310,7 @@ SWIG_PROXY_CONSTRUCTOR(true, true, SWIGTYPE) /* Array reference typemaps */ %apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } +%apply SWIGTYPE && { SWIGTYPE ((&&)[ANY]) } /* const pointers */ %apply SWIGTYPE * { SWIGTYPE *const } From e87a51ed92891e4f518fc3dcb32288cfe869a43a Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 24 Jan 2013 19:24:52 +0000 Subject: [PATCH 094/481] Add rvalue reference typemaps --- Lib/go/go.swg | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/Lib/go/go.swg b/Lib/go/go.swg index 648e112e1..7eb7c62c7 100644 --- a/Lib/go/go.swg +++ b/Lib/go/go.swg @@ -281,6 +281,21 @@ type _swig_memberptr *byte %typemap(directorout) SWIGTYPE & %{ *($&1_ltype)&$result = $input; %} +%typemap(gotype) SWIGTYPE && +%{$gotypename%} + +%typemap(in) SWIGTYPE && +%{ $1 = *($&1_ltype)&$input; %} + +%typemap(out) SWIGTYPE && +%{ *($&1_ltype)&$result = $1; %} + +%typemap(directorin) SWIGTYPE && +%{ $input = ($1_ltype)&$1_name; %} + +%typemap(directorout) SWIGTYPE && +%{ *($&1_ltype)&$result = $input; %} + /* C arrays turn into Go pointers. If we know the length we can use a slice. */ @@ -398,7 +413,7 @@ type _swig_memberptr *byte %typemap(throws) char * %{ _swig_gopanic($1); %} -%typemap(throws) SWIGTYPE, SWIGTYPE &, SWIGTYPE *, SWIGTYPE [], SWIGTYPE [ANY] +%typemap(throws) SWIGTYPE, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE *, SWIGTYPE [], SWIGTYPE [ANY] %{ (void)$1; _swig_gopanic("C++ $1_type exception thrown"); @@ -504,6 +519,7 @@ type _swig_memberptr *byte SWIGTYPE, SWIGTYPE *, SWIGTYPE &, + SWIGTYPE &&, SWIGTYPE *const&, SWIGTYPE [], SWIGTYPE (CLASS::*) From 0734fa050de474ee4c90908c58be387c4b59e544 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 24 Jan 2013 19:44:27 +0000 Subject: [PATCH 095/481] Add rvalue reference typemaps --- Lib/modula3/modula3.swg | 51 +++++++++++++++++++++++++++++++++-------- 1 file changed, 41 insertions(+), 10 deletions(-) diff --git a/Lib/modula3/modula3.swg b/Lib/modula3/modula3.swg index 3affdd0de..262f8ead4 100644 --- a/Lib/modula3/modula3.swg +++ b/Lib/modula3/modula3.swg @@ -344,6 +344,23 @@ %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 *)" @@ -468,7 +485,12 @@ $1 = &temp; %} //SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "$1_type reference is null"); RETURN $null; } %} -%typemap(out) SWIGTYPE *, SWIGTYPE &, SWIGTYPE (CLASS::*) %{ *($&1_ltype)&$result = $1; %} +%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 */ @@ -552,6 +574,7 @@ $1 = &temp; %} SWIGTYPE, SWIGTYPE *, SWIGTYPE &, + SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" @@ -605,7 +628,7 @@ $1 = &temp; %} enum SWIGTYPE "$input" %typemap(m3in) SWIGTYPE "$&*1_type.getCPtr($input)" -%typemap(m3in) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "$1_basetype.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. */ @@ -636,13 +659,16 @@ $1 = &temp; %} %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 (CLASS::*) %{ +%typemap(m3varin) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) %{ PROCEDURE Set$var (value: $vartype) = BEGIN $imcall; @@ -684,6 +710,10 @@ PROCEDURE Get$var (): $vartype = 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; @@ -691,13 +721,13 @@ PROCEDURE Get$var (): $vartype = } %} /* Typemaps used for the generation of proxy and type wrapper class code */ -%typemap(m3base) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" -%typemap(m3classmodifiers) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "public" -%typemap(m3code) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" -%typemap(m3imports) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "using System;" +%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 (CLASS::*) "" -%typemap(m3ptrconstructormodifiers) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "internal" +%typemap(m3interfaces_derived) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" +%typemap(m3ptrconstructormodifiers) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "internal" %typemap(m3finalize) SWIGTYPE %{ ~$1_basetype() { @@ -724,7 +754,7 @@ PROCEDURE Get$var (): $vartype = base.Dispose(); } -%typemap(m3getcptr) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) %{ +%typemap(m3getcptr) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) %{ internal static IntPtr getCPtr($1_basetype obj) { RETURN (obj == null) ? IntPtr.Zero : obj.swigCPtr; } @@ -748,6 +778,7 @@ FROM BlaBla IMPORT Bla; /* Array reference typemaps */ %apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } +%apply SWIGTYPE && { SWIGTYPE ((&&)[ANY]) } /* const pointers */ %apply SWIGTYPE * { SWIGTYPE *const } From 9bd2fb2cad41246c5e124a3ea4738f045759370f Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 24 Jan 2013 19:48:56 +0000 Subject: [PATCH 096/481] Add rvalue reference typemaps --- Lib/allegrocl/allegrocl.swg | 13 +++++++------ Lib/cffi/cffi.swg | 9 +++++---- Lib/chicken/chicken.swg | 36 ++++++++++++++++++++++++++++++++---- Lib/guile/typemaps.i | 23 +++++++++++++++++++---- Lib/mzscheme/typemaps.i | 15 ++++++++++++--- Lib/pike/pike.swg | 14 +++++++++----- 6 files changed, 84 insertions(+), 26 deletions(-) diff --git a/Lib/allegrocl/allegrocl.swg b/Lib/allegrocl/allegrocl.swg index 87e030ce4..bbfdcdb78 100644 --- a/Lib/allegrocl/allegrocl.swg +++ b/Lib/allegrocl/allegrocl.swg @@ -16,8 +16,7 @@ float, double, long double, char *, void *, enum SWIGTYPE "(cl::setq ACL_ffresult $body)"; %typemap(lout) void "$body"; -%typemap(lout) SWIGTYPE[ANY], SWIGTYPE *, - SWIGTYPE & +%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))) @@ -60,6 +59,7 @@ %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 @@ -95,7 +95,7 @@ and error if a setf operation is performed on the address of this object. long, signed long, unsigned long, float, double, long double, char *, void *, void, enum SWIGTYPE, SWIGTYPE *, SWIGTYPE[], - SWIGTYPE[ANY], SWIGTYPE &, const SWIGTYPE "$1_ltype"; + SWIGTYPE[ANY], SWIGTYPE &, SWIGTYPE &&, const SWIGTYPE "$1_ltype"; %typemap(ctype) SWIGTYPE "$&1_type"; %typemap(in) bool "$1 = (bool)$input;"; @@ -105,7 +105,7 @@ and error if a setf operation is performed on the address of this object. long, signed long, unsigned long, float, double, long double, char *, void *, void, enum SWIGTYPE, SWIGTYPE *, SWIGTYPE[], - SWIGTYPE[ANY], SWIGTYPE & "$1 = $input;"; + 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 @@ -160,7 +160,7 @@ SWIG_TYPECHECK_STRING_ARRAY 1140 int, signed int, unsigned int, long, signed long, unsigned long, enum SWIGTYPE { $1 = 1; }; -%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, +%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE[], SWIGTYPE[ANY], SWIGTYPE { $1 = 1; }; @@ -185,7 +185,7 @@ SWIG_TYPECHECK_STRING_ARRAY 1140 long, signed long, unsigned long, float, double, long double, char *, void *, enum SWIGTYPE, SWIGTYPE *, - SWIGTYPE[ANY], SWIGTYPE & "$result = $1;"; + SWIGTYPE[ANY], SWIGTYPE &, SWIGTYPE && "$result = $1;"; #ifdef __cplusplus %typemap(out) SWIGTYPE "$result = new $1_ltype($1);"; #else @@ -221,6 +221,7 @@ $body)" /* Array reference typemaps */ %apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } +%apply SWIGTYPE && { SWIGTYPE ((&&)[ANY]) } /* const pointers */ %apply SWIGTYPE * { SWIGTYPE *const } diff --git a/Lib/cffi/cffi.swg b/Lib/cffi/cffi.swg index 6ac82f45e..e6a74b835 100644 --- a/Lib/cffi/cffi.swg +++ b/Lib/cffi/cffi.swg @@ -67,7 +67,7 @@ long, signed long, unsigned long, float, double, long double, char *, void *, void, enum SWIGTYPE, SWIGTYPE *, - SWIGTYPE[ANY], SWIGTYPE & "$1_ltype"; + SWIGTYPE[ANY], SWIGTYPE &, SWIGTYPE && "$1_ltype"; %typemap(ctype) SWIGTYPE "$&1_type"; %typemap(in) bool "$1 = (bool)$input;"; @@ -77,7 +77,7 @@ long, signed long, unsigned long, float, double, long double, char *, void *, void, enum SWIGTYPE, SWIGTYPE *, - SWIGTYPE[ANY], SWIGTYPE & "$1 = $input;"; + SWIGTYPE[ANY], SWIGTYPE &, SWIGTYPE && "$1 = $input;"; %typemap(in) SWIGTYPE "$1 = *$input;"; %typemap(out) void ""; @@ -88,7 +88,7 @@ long, signed long, unsigned long, float, double, long double, char *, void *, enum SWIGTYPE, SWIGTYPE *, - SWIGTYPE[ANY], SWIGTYPE & "$result = $1;"; + SWIGTYPE[ANY], SWIGTYPE &, SWIGTYPE && "$result = $1;"; #ifdef __cplusplus %typemap(out) SWIGTYPE "$result = new $1_type($1);"; #else @@ -109,7 +109,7 @@ int, signed int, unsigned int, long, signed long, unsigned long, enum SWIGTYPE { $1 = 1; }; -%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, +%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE[ANY], SWIGTYPE { $1 = 1; }; /* This maps C/C++ types to Lisp classes for overload dispatch */ @@ -132,6 +132,7 @@ /* Array reference typemaps */ %apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } +%apply SWIGTYPE && { SWIGTYPE ((&&)[ANY]) } /* const pointers */ %apply SWIGTYPE * { SWIGTYPE *const } diff --git a/Lib/chicken/chicken.swg b/Lib/chicken/chicken.swg index 112780499..f5779c1b6 100644 --- a/Lib/chicken/chicken.swg +++ b/Lib/chicken/chicken.swg @@ -149,6 +149,7 @@ SIMPLE_TYPEMAP(double, C_c_double, C_flonum, C_swig_is_number, (double), C_SIZEO /* enum SWIGTYPE */ %apply int { enum SWIGTYPE }; %apply const int& { const enum SWIGTYPE& }; +%apply const int& { const enum SWIGTYPE&& }; %typemap(varin) enum SWIGTYPE { @@ -178,7 +179,7 @@ SIMPLE_TYPEMAP(double, C_c_double, C_flonum, C_swig_is_number, (double), C_SIZEO %typemap(freearg) char * "if ($1 != NULL) { free ($1); }" /* Pointers, references, and arrays */ -%typemap(in,closcode="(slot-ref $input 'swig-this)") SWIGTYPE *, SWIGTYPE [], SWIGTYPE & { +%typemap(in,closcode="(slot-ref $input 'swig-this)") SWIGTYPE *, SWIGTYPE [], SWIGTYPE &, SWIGTYPE && { $1 = ($1_ltype)SWIG_MustGetPtr($input, $descriptor, $argnum, $disown); } @@ -199,6 +200,10 @@ SIMPLE_TYPEMAP(double, C_c_double, C_flonum, C_swig_is_number, (double), C_SIZEO $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"); } @@ -216,7 +221,7 @@ SIMPLE_TYPEMAP(double, C_c_double, C_flonum, C_swig_is_number, (double), C_SIZEO $1 = SWIG_MustGetPtr($input, NULL, 1, 0); } -%typemap(out) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] { +%typemap(out) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] { C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER); $result = SWIG_NewPointerObj($1, $descriptor, $owner); } @@ -237,6 +242,11 @@ SIMPLE_TYPEMAP(double, C_c_double, C_flonum, C_swig_is_number, (double), C_SIZEO $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]; @@ -531,7 +541,7 @@ $result = C_SCHEME_UNDEFINED; %typemap(constcode) char * "static const char *$result = $value;" -%typemap(constcode) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] +%typemap(constcode) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] "static const void *$result = (void*) $value;" /* ------------------------------------------------------------ @@ -607,7 +617,7 @@ $result = C_SCHEME_UNDEFINED; $1 = C_swig_is_string ($input); } -%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] { +%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] { void *ptr; $1 = !SWIG_ConvertPtr($input, &ptr, $1_descriptor, 0); } @@ -628,6 +638,17 @@ $result = C_SCHEME_UNDEFINED; } } +%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE && +{ + void *ptr = 0; + if (SWIG_ConvertPtr($input, &ptr, $descriptor, 0)) { + /* error */ + $1 = 0; + } else { + $1 = (ptr != 0); + } +} + %typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE { void *ptr = 0; @@ -673,6 +694,12 @@ $result = C_SCHEME_UNDEFINED; 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 * ------------------------------------------------------------ */ @@ -685,6 +712,7 @@ $result = C_SCHEME_UNDEFINED; /* Array reference typemaps */ %apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } +%apply SWIGTYPE && { SWIGTYPE ((&&)[ANY]) } /* const pointers */ %apply SWIGTYPE * { SWIGTYPE *const } diff --git a/Lib/guile/typemaps.i b/Lib/guile/typemaps.i index c194d4bc9..8e09d0dc0 100644 --- a/Lib/guile/typemaps.i +++ b/Lib/guile/typemaps.i @@ -6,10 +6,10 @@ /* Pointers */ -%typemap(in) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] { +%typemap(in) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] { $1 = ($1_ltype)SWIG_MustGetPtr($input, $descriptor, $argnum, 0); } -%typemap(freearg) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] ""; +%typemap(freearg) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] ""; %typemap(in) void * { $1 = ($1_ltype)SWIG_MustGetPtr($input, NULL, $argnum, 0); @@ -24,6 +24,10 @@ $1 = *(($1_ltype)SWIG_MustGetPtr($input, $descriptor, 1, 0)); } +%typemap(varin) SWIGTYPE && { + $1 = *(($1_ltype)SWIG_MustGetPtr($input, $descriptor, 1, 0)); +} + %typemap(varin) SWIGTYPE [] { scm_wrong_type_arg((char *) FUNC_NAME, 1, $input); } @@ -41,7 +45,7 @@ $1 = SWIG_MustGetPtr($input, NULL, 1, 0); } -%typemap(out) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] { +%typemap(out) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] { $result = SWIG_NewPointerObj ($1, $descriptor, $owner); } @@ -58,6 +62,10 @@ $result = SWIG_NewPointerObj((void *) &$1, $1_descriptor, 0); } +%typemap(varout) SWIGTYPE && { + $result = SWIG_NewPointerObj((void *) &$1, $1_descriptor, 0); +} + %typemap(throws) SWIGTYPE { $<ype temp = new $ltype($1); scm_throw(gh_symbol2scm((char *) "swig-exception"), @@ -71,6 +79,12 @@ SCM_UNDEFINED)); } +%typemap(throws) SWIGTYPE && { + scm_throw(gh_symbol2scm((char *) "swig-exception"), + gh_list(SWIG_NewPointerObj(&$1, $descriptor, 1), + SCM_UNDEFINED)); +} + %typemap(throws) SWIGTYPE * { scm_throw(gh_symbol2scm((char *) "swig-exception"), gh_list(SWIG_NewPointerObj($1, $descriptor, 1), @@ -430,7 +444,7 @@ typedef unsigned long SCM; $1 = SCM_STRINGP($input) ? 1 : 0; } -%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] { +%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] { void *ptr; int res = SWIG_ConvertPtr($input, &ptr, $1_descriptor, 0); $1 = SWIG_CheckState(res); @@ -450,6 +464,7 @@ typedef unsigned long SCM; /* Array reference typemaps */ %apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } +%apply SWIGTYPE && { SWIGTYPE ((&&)[ANY]) } /* const pointers */ %apply SWIGTYPE * { SWIGTYPE *const } diff --git a/Lib/mzscheme/typemaps.i b/Lib/mzscheme/typemaps.i index f12513df8..026ec9567 100644 --- a/Lib/mzscheme/typemaps.i +++ b/Lib/mzscheme/typemaps.i @@ -23,6 +23,10 @@ $1 = *(($1_ltype)SWIG_MustGetPtr($input, $descriptor, 1, 0)); } +%typemap(varin) SWIGTYPE && { + $1 = *(($1_ltype)SWIG_MustGetPtr($input, $descriptor, 1, 0)); +} + %typemap(varin) SWIGTYPE [ANY] { void *temp; int ii; @@ -54,16 +58,20 @@ $result = SWIG_NewPointerObj((void *) &$1, $1_descriptor, 0); } +%typemap(varout) SWIGTYPE && { + $result = SWIG_NewPointerObj((void *) &$1, $1_descriptor, 0); +} + /* C++ References */ #ifdef __cplusplus -%typemap(in) SWIGTYPE &, const SWIGTYPE & { +%typemap(in) SWIGTYPE &, SWIGTYPE && { $1 = ($ltype) SWIG_MustGetPtr($input, $descriptor, $argnum, 0); if ($1 == NULL) scheme_signal_error("swig-type-error (null reference)"); } -%typemap(out) SWIGTYPE &, const SWIGTYPE & { +%typemap(out) SWIGTYPE &, SWIGTYPE && { $result = SWIG_NewPointerObj ($1, $descriptor, $owner); } @@ -321,7 +329,7 @@ REF_MAP(double, SCHEME_REALP, scheme_real_to_double, $1 = (SCHEME_STRINGP($input)) ? 1 : 0; } -%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] { +%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] { void *ptr; if (SWIG_ConvertPtr($input, (void **) &ptr, $1_descriptor, 0)) { $1 = 0; @@ -351,6 +359,7 @@ REF_MAP(double, SCHEME_REALP, scheme_real_to_double, /* Array reference typemaps */ %apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } +%apply SWIGTYPE && { SWIGTYPE ((&&)[ANY]) } /* const pointers */ %apply SWIGTYPE * { SWIGTYPE *const } diff --git a/Lib/pike/pike.swg b/Lib/pike/pike.swg index 0cfec52b0..9b8179e69 100644 --- a/Lib/pike/pike.swg +++ b/Lib/pike/pike.swg @@ -53,6 +53,7 @@ extern "C" { %typemap(in) SWIGTYPE *, SWIGTYPE &, + SWIGTYPE &&, SWIGTYPE [] "SWIG_ConvertPtr($input.u.object, (void **) &$1, $1_descriptor, 1);" @@ -79,7 +80,8 @@ extern "C" { 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), + const enum SWIGTYPE && ($*1_ltype temp) { if ($input.type != T_INT) Pike_error("Bad argument: Expected an integer.\n"); @@ -113,7 +115,7 @@ extern "C" { %typemap(out, pikedesc="tStr") char * "push_text($1);"; /* Pointers, references, and arrays */ -%typemap(out, pikedesc="tObj") SWIGTYPE*, SWIGTYPE &, SWIGTYPE [] "push_object(SWIG_NewPointerObj((void *) $1, $1_descriptor, $owner));"; +%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 ""; @@ -153,7 +155,8 @@ extern "C" { 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), + const enum SWIGTYPE && ($*1_ltype temp) "push_int(*($1));"; %typemap(out, pikedesc="tFloat") const float &, const double & "push_float(*($1));"; @@ -216,7 +219,7 @@ extern "C" { 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 &, + enum SWIGTYPE, enum SWIGTYPE &, SWIGTYPE &&, bool, const bool & { $1 = ($input.type == T_INT) ? 1 : 0; @@ -237,7 +240,7 @@ extern "C" { $1 = ($input.type == T_STRING) ? 1 : 0; } -%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] { +%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] { void *ptr; if (SWIG_ConvertPtr($input.u.object, (void **) &ptr, $1_descriptor, 0) == -1) { $1 = 0; @@ -266,6 +269,7 @@ extern "C" { /* Array reference typemaps */ %apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } +%apply SWIGTYPE && { SWIGTYPE ((&&)[ANY]) } /* const pointers */ %apply SWIGTYPE * { SWIGTYPE *const } From 341a5366ddbbd2bc5747bdeb4c19b9e4ab3bb559 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 24 Jan 2013 19:53:13 +0000 Subject: [PATCH 097/481] Add rvalue reference typemaps --- Lib/lua/lua.swg | 2 +- Lib/lua/luatypemaps.swg | 25 ++++++++++++++++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/Lib/lua/lua.swg b/Lib/lua/lua.swg index a15f14148..f425f16a1 100644 --- a/Lib/lua/lua.swg +++ b/Lib/lua/lua.swg @@ -40,7 +40,7 @@ %typemap(consttab) long long, unsigned long long { SWIG_LUA_STRING, (char *) "$symname", 0, 0, (void *)"$value", 0} -%typemap(consttab) SWIGTYPE *, SWIGTYPE *const, SWIGTYPE &, SWIGTYPE [] +%typemap(consttab) SWIGTYPE *, SWIGTYPE *const, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] { SWIG_LUA_POINTER, (char *)"$symname", 0, 0, (void *)$value, &$1_descriptor} // member function pointers diff --git a/Lib/lua/luatypemaps.swg b/Lib/lua/luatypemaps.swg index 13cd66f4c..4852c0e32 100644 --- a/Lib/lua/luatypemaps.swg +++ b/Lib/lua/luatypemaps.swg @@ -68,8 +68,12 @@ temp=($basetype)lua_tonumber(L,$input); $1=&temp;%} // and const refs %typemap(in,checkfn="lua_isnumber") const enum SWIGTYPE &($basetype temp) %{ temp=($basetype)(int)lua_tonumber(L,$input); $1=&temp;%} +%typemap(in,checkfn="lua_isnumber") const enum SWIGTYPE &&($basetype temp) +%{ temp=($basetype)(int)lua_tonumber(L,$input); $1=&temp;%} %typemap(out) const enum SWIGTYPE & %{ lua_pushnumber(L, (lua_Number) *$1); SWIG_arg++;%} +%typemap(out) const enum SWIGTYPE && +%{ lua_pushnumber(L, (lua_Number) *$1); SWIG_arg++;%} // boolean (which is a special type in lua) @@ -147,9 +151,18 @@ SWIGINTERN int SWIG_lua_isnilstring(lua_State *L, int idx) { } %} +%typemap(in,checkfn="lua_isuserdata") SWIGTYPE&& +%{ + if (!SWIG_IsOK(SWIG_ConvertPtr(L,$input,(void**)&$1,$descriptor,$disown))){ + SWIG_fail_ptr("$symname",$argnum,$descriptor); + } +%} + // out is simple %typemap(out) SWIGTYPE*,SWIGTYPE& %{SWIG_NewPointerObj(L,$1,$descriptor,$owner); SWIG_arg++; %} +%typemap(out) SWIGTYPE*,SWIGTYPE&& +%{SWIG_NewPointerObj(L,$1,$descriptor,$owner); SWIG_arg++; %} // dynamic casts // this uses the SWIG_TypeDynamicCast() which relies on RTTI to find out what the pointer really is @@ -284,7 +297,7 @@ parmeters match which function const unsigned int &, const unsigned short &, const unsigned long &, const signed char&, const unsigned char&, const long long &, const unsigned long long &, - enum SWIGTYPE, const enum SWIGTYPE&, + enum SWIGTYPE, const enum SWIGTYPE&, const enum SWIGTYPE &&, float, double, const float &, const double& { $1 = lua_isnumber(L,$input); @@ -323,6 +336,15 @@ parmeters match which function } } +%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE && { + void *ptr; + if (lua_isuserdata(L,$input)==0 || SWIG_ConvertPtr(L,$input, (void **) &ptr, $1_descriptor, 0)) { + $1 = 0; + } else { + $1 = 1; + } +} + %typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE { void *ptr; if (lua_isuserdata(L,$input)==0 || SWIG_ConvertPtr(L,$input, (void **) &ptr, $&1_descriptor, 0)) { @@ -360,6 +382,7 @@ parmeters match which function // Array reference typemaps %apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } +%apply SWIGTYPE && { SWIGTYPE ((&&)[ANY]) } /* const pointers */ %apply SWIGTYPE * { SWIGTYPE *const } From 8bdfcda66ee58727097a9ff98d2f946e4da9a105 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 24 Jan 2013 19:56:56 +0000 Subject: [PATCH 098/481] Add rvalue reference typemaps --- Lib/ocaml/typecheck.i | 2 +- Lib/ocaml/typemaps.i | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/Lib/ocaml/typecheck.i b/Lib/ocaml/typecheck.i index 4c3500690..a13e1552e 100644 --- a/Lib/ocaml/typecheck.i +++ b/Lib/ocaml/typecheck.i @@ -129,7 +129,7 @@ } } -%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] { +%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] { void *ptr; $1 = !caml_ptr_val_internal($input, &ptr,$descriptor); } diff --git a/Lib/ocaml/typemaps.i b/Lib/ocaml/typemaps.i index e5458a3e2..a729432d7 100644 --- a/Lib/ocaml/typemaps.i +++ b/Lib/ocaml/typemaps.i @@ -34,11 +34,21 @@ $1 = ($ltype) caml_ptr_val($input,$1_descriptor); } +%typemap(in) SWIGTYPE && { + /* %typemap(in) SWIGTYPE && */ + $1 = ($ltype) caml_ptr_val($input,$1_descriptor); +} + %typemap(varin) SWIGTYPE & { /* %typemap(varin) SWIGTYPE & */ $1 = *(($ltype) caml_ptr_val($input,$1_descriptor)); } +%typemap(varin) SWIGTYPE && { + /* %typemap(varin) SWIGTYPE && */ + $1 = *(($ltype) caml_ptr_val($input,$1_descriptor)); +} + %typemap(out) SWIGTYPE & { /* %typemap(out) SWIGTYPE & */ CAML_VALUE *fromval = caml_named_value("create_$ntype_from_ptr"); @@ -49,6 +59,16 @@ } } +%typemap(out) SWIGTYPE && { + /* %typemap(out) SWIGTYPE && */ + CAML_VALUE *fromval = caml_named_value("create_$ntype_from_ptr"); + if( fromval ) { + $result = callback(*fromval,caml_val_ptr((void *) &$1,$1_descriptor)); + } else { + $result = caml_val_ptr ((void *) &$1,$1_descriptor); + } +} + #if 0 %typemap(argout) SWIGTYPE & { CAML_VALUE *fromval = caml_named_value("create_$ntype_from_ptr"); @@ -63,9 +83,23 @@ caml_val_ptr ((void *) $1,$1_descriptor)); } } +%typemap(argout) SWIGTYPE && { + CAML_VALUE *fromval = caml_named_value("create_$ntype_from_ptr"); + if( fromval ) { + swig_result = + caml_list_append(swig_result, + callback(*fromval,caml_val_ptr((void *) $1, + $1_descriptor))); + } else { + swig_result = + caml_list_append(swig_result, + caml_val_ptr ((void *) $1,$1_descriptor)); + } +} #endif %typemap(argout) const SWIGTYPE & { } +%typemap(argout) const SWIGTYPE && { } %typemap(in) SWIGTYPE { $1 = *(($&1_ltype) caml_ptr_val($input,$&1_descriptor)) ; @@ -101,6 +135,7 @@ } %apply SWIGTYPE { const SWIGTYPE & }; +%apply SWIGTYPE { const SWIGTYPE && }; #endif @@ -318,6 +353,7 @@ SIMPLE_MAP(unsigned long long,caml_val_ulong,caml_long_val); /* Array reference typemaps */ %apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } +%apply SWIGTYPE && { SWIGTYPE ((&)[ANY]) } /* const pointers */ %apply SWIGTYPE * { SWIGTYPE *const } From d3769a1fd42c8a54f178ed7a712fa1a513f57733 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 24 Jan 2013 20:18:18 +0000 Subject: [PATCH 099/481] Add rvalue reference typemaps --- Lib/php/const.i | 1 + Lib/php/globalvar.i | 6 +++--- Lib/php/php.swg | 25 +++++++++++++++++++++---- 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/Lib/php/const.i b/Lib/php/const.i index afd7d02b9..375c7df71 100644 --- a/Lib/php/const.i +++ b/Lib/php/const.i @@ -31,6 +31,7 @@ %typemap(consttab) SWIGTYPE *, SWIGTYPE &, + SWIGTYPE &&, SWIGTYPE [] { /* This actually registers it as a global variable and constant. I don't * like it, but I can't figure out the zend_constant code... */ diff --git a/Lib/php/globalvar.i b/Lib/php/globalvar.i index 45fb0223b..1378ae60b 100644 --- a/Lib/php/globalvar.i +++ b/Lib/php/globalvar.i @@ -80,7 +80,7 @@ sizeof(zval *), NULL); } -%typemap(varinit) SWIGTYPE, SWIGTYPE & +%typemap(varinit) SWIGTYPE, SWIGTYPE &, SWIGTYPE && { zval *z_var; @@ -210,7 +210,7 @@ } -%typemap(varin) SWIGTYPE *, SWIGTYPE & +%typemap(varin) SWIGTYPE *, SWIGTYPE &, SWIGTYPE && { zval **z_var; $1_ltype _temp; @@ -336,7 +336,7 @@ deliberate error cos this code looks bogus to me } } -%typemap(varout) SWIGTYPE *, SWIGTYPE & +%typemap(varout) SWIGTYPE *, SWIGTYPE &, SWIGTYPE && { zval **z_var; diff --git a/Lib/php/php.swg b/Lib/php/php.swg index 99edcddf5..de38060ca 100644 --- a/Lib/php/php.swg +++ b/Lib/php/php.swg @@ -115,6 +115,13 @@ } } +%typemap(in) 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"); + } +} + %typemap(in) SWIGTYPE *const& ($*ltype temp) { if(SWIG_ConvertPtr(*$input, (void **) &temp, $*1_descriptor, 0) < 0) { @@ -132,7 +139,8 @@ %typemap(argout) SWIGTYPE *, SWIGTYPE [], - SWIGTYPE&; + SWIGTYPE &, + SWIGTYPE &&; %typemap(in) void * { @@ -241,6 +249,11 @@ ZVAL_LONG(return_value, (long)*$1); } +%typemap(out) const enum SWIGTYPE && +{ + ZVAL_LONG(return_value, (long)*$1); +} + %typemap(out) const long long & %{ if ((long long)LONG_MIN <= *$1 && *$1 <= (long long)LONG_MAX) { @@ -347,7 +360,8 @@ %typemap(out) SWIGTYPE *, SWIGTYPE [], - SWIGTYPE & + SWIGTYPE &, + SWIGTYPE && %{ SWIG_SetPointerZval(return_value, (void *)$1, $1_descriptor, $owner); %} @@ -359,7 +373,8 @@ %typemap(directorin) SWIGTYPE *, SWIGTYPE [], - SWIGTYPE & + SWIGTYPE &, + SWIGTYPE && %{ SWIG_SetPointerZval($input, (void *)&$1_name, $1_descriptor, $owner); %} @@ -454,6 +469,7 @@ SWIGTYPE *, SWIGTYPE [], SWIGTYPE &, + SWIGTYPE &&, SWIGTYPE *const& { void *tmp; @@ -478,7 +494,7 @@ return; } -%typemap(throws) SWIGTYPE, SWIGTYPE &, SWIGTYPE *, SWIGTYPE [], SWIGTYPE [ANY] %{ +%typemap(throws) SWIGTYPE, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE *, SWIGTYPE [], SWIGTYPE [ANY] %{ (void)$1; zend_throw_exception(NULL, const_cast("C++ $1_type exception thrown"), 0 TSRMLS_CC); return; @@ -491,6 +507,7 @@ /* Array reference typemaps */ %apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } +%apply SWIGTYPE && { SWIGTYPE ((&&)[ANY]) } /* const pointers */ %apply SWIGTYPE * { SWIGTYPE *const } From ac74c90fb03b9ce91db0c8d839d52afa3bbc3db8 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 24 Jan 2013 20:23:54 +0000 Subject: [PATCH 100/481] Add rvalue reference typemaps --- Lib/perl5/perltypemaps.swg | 3 ++ Lib/python/pydocs.swg | 2 + Lib/r/rtype.swg | 15 +++++- Lib/tcl/tcltypemaps.swg | 3 +- Lib/typemaps/enumint.swg | 15 +++++- Lib/typemaps/swigtype.swg | 95 +++++++++++++++++++++++++++++++++++++- 6 files changed, 127 insertions(+), 6 deletions(-) diff --git a/Lib/perl5/perltypemaps.swg b/Lib/perl5/perltypemaps.swg index 540974476..d77b862ef 100644 --- a/Lib/perl5/perltypemaps.swg +++ b/Lib/perl5/perltypemaps.swg @@ -84,6 +84,9 @@ %typemap(varout,type="$1_descriptor") SWIGTYPE & "sv_setiv(SvRV($result),PTR2IV(&$1));"; +%typemap(varout,type="$1_descriptor") SWIGTYPE && + "sv_setiv(SvRV($result),PTR2IV(&$1));"; + %typemap(varout,type="$&1_descriptor") SWIGTYPE "sv_setiv(SvRV($result), PTR2IV(&$1));"; diff --git a/Lib/python/pydocs.swg b/Lib/python/pydocs.swg index 862339da7..5f46adaea 100644 --- a/Lib/python/pydocs.swg +++ b/Lib/python/pydocs.swg @@ -5,11 +5,13 @@ %typemap(doc) SWIGTYPE "@param $1_name $1_type value"; %typemap(doc) SWIGTYPE * "@param $1_name $1_type value"; %typemap(doc) const SWIGTYPE & "@param $1_name $1_type value"; +%typemap(doc) const SWIGTYPE && "@param $1_name $1_type value"; %typemap(doc) enum SWIGTYPE "@param $1_name enum $1_type value"; #else %typemap(doc) SWIGTYPE "$1_name: $1_type value"; %typemap(doc) SWIGTYPE * "$1_name: $1_type value"; %typemap(doc) const SWIGTYPE & "$1_name: $1_type value"; +%typemap(doc) const SWIGTYPE && "$1_name: $1_type value"; %typemap(doc) enum SWIGTYPE "$1_name: enum $1_type value"; %typemap(doc) SWIGTYPE *INOUT "$1_name: $1_type input/ouput value"; diff --git a/Lib/r/rtype.swg b/Lib/r/rtype.swg index 5103e43db..9c833273f 100644 --- a/Lib/r/rtype.swg +++ b/Lib/r/rtype.swg @@ -31,9 +31,11 @@ %typemap("rtype") enum SWIGTYPE * "character"; %typemap("rtype") enum SWIGTYPE *const "character"; %typemap("rtype") enum SWIGTYPE & "character"; +%typemap("rtype") enum SWIGTYPE && "character"; %typemap("rtype") SWIGTYPE * "$R_class"; %typemap("rtype") SWIGTYPE *const "$R_class"; %typemap("rtype") SWIGTYPE & "$R_class"; +%typemap("rtype") SWIGTYPE && "$R_class"; %typemap("rtype") SWIGTYPE "$&R_class"; @@ -65,13 +67,15 @@ %{ $input = enumToInteger($input, "$R_class"); %} %typemap(scoercein) enum SWIGTYPE & %{ $input = enumToInteger($input, "$R_class"); %} +%typemap(scoercein) enum SWIGTYPE && + %{ $input = enumToInteger($input, "$R_class"); %} %typemap(scoercein) enum SWIGTYPE * %{ $input = enumToInteger($input, "$R_class"); %} %typemap(scoercein) enum SWIGTYPE *const %{ $input = enumToInteger($input, "$R_class"); %} -%typemap(scoercein) SWIGTYPE, SWIGTYPE *, SWIGTYPE *const, SWIGTYPE & +%typemap(scoercein) SWIGTYPE, SWIGTYPE *, SWIGTYPE *const, SWIGTYPE &, SWIGTYPE && %{ %} /* @@ -81,6 +85,9 @@ %typemap(scoercein) SWIGTYPE & %{ $input = coerceIfNotSubclass($input, "$R_class") %} +%typemap(scoercein) SWIGTYPE && + %{ $input = coerceIfNotSubclass($input, "$R_class") %} + %typemap(scoercein) SWIGTYPE %{ $input = coerceIfNotSubclass($input, "$&R_class") %} */ @@ -116,6 +123,9 @@ string &, std::string & %typemap(scoerceout) enum SWIGTYPE & %{ $result = enumFromInteger($result, "$R_class"); %} +%typemap(scoerceout) enum SWIGTYPE && + %{ $result = enumFromInteger($result, "$R_class"); %} + %typemap(scoerceout) enum SWIGTYPE * %{ $result = enumToInteger($result, "$R_class"); %} @@ -129,6 +139,9 @@ string &, std::string & %typemap(scoerceout) SWIGTYPE & %{ class($result) <- "$R_class"; %} +%typemap(scoerceout) SWIGTYPE && + %{ class($result) <- "$R_class"; %} + %typemap(scoerceout) SWIGTYPE * %{ class($result) <- "$R_class"; %} diff --git a/Lib/tcl/tcltypemaps.swg b/Lib/tcl/tcltypemaps.swg index d93c8869b..c4ee13b92 100644 --- a/Lib/tcl/tcltypemaps.swg +++ b/Lib/tcl/tcltypemaps.swg @@ -66,7 +66,7 @@ #if 1 // Old 1.3.25 typemaps needed to avoid premature object deletion -%typemap(out,noblock=1) SWIGTYPE *INSTANCE, SWIGTYPE &INSTANCE, SWIGTYPE INSTANCE[] { +%typemap(out,noblock=1) SWIGTYPE *INSTANCE, SWIGTYPE &INSTANCE, SWIGTYPE &&INSTANCE, SWIGTYPE INSTANCE[] { Tcl_SetObjResult(interp, SWIG_NewInstanceObj( %as_voidptr($1), $1_descriptor,0)); } @@ -86,5 +86,6 @@ %typemap(out) SWIGTYPE * = SWIGTYPE *INSTANCE; %typemap(out) SWIGTYPE *const = SWIGTYPE *; %typemap(out) SWIGTYPE & = SWIGTYPE &INSTANCE; +%typemap(out) SWIGTYPE && = SWIGTYPE &&INSTANCE; %typemap(out) SWIGTYPE [] = SWIGTYPE INSTANCE[]; %typemap(varout) SWIGTYPE = SWIGTYPE INSTANCE; diff --git a/Lib/typemaps/enumint.swg b/Lib/typemaps/enumint.swg index 854d6f3e1..d048bb6bf 100644 --- a/Lib/typemaps/enumint.swg +++ b/Lib/typemaps/enumint.swg @@ -3,9 +3,20 @@ * ------------------------------------------------------------ */ %apply int { enum SWIGTYPE }; -%apply const int& { const enum SWIGTYPE& }; +%apply const int& { const enum SWIGTYPE & }; +%apply const int& { const enum SWIGTYPE && }; -%typemap(in,fragment=SWIG_AsVal_frag(int),noblock=1) const enum SWIGTYPE& (int val, int ecode, $basetype temp) { +%typemap(in,fragment=SWIG_AsVal_frag(int),noblock=1) const enum SWIGTYPE & (int val, int ecode, $basetype temp) { + ecode = SWIG_AsVal(int)($input, &val); + if (!SWIG_IsOK(ecode)) { + %argument_fail(ecode, "$type", $symname, $argnum); + } else { + temp = %static_cast(val,$basetype); + $1 = &temp; + } +} + +%typemap(in,fragment=SWIG_AsVal_frag(int),noblock=1) const enum SWIGTYPE && (int val, int ecode, $basetype temp) { ecode = SWIG_AsVal(int)($input, &val); if (!SWIG_IsOK(ecode)) { %argument_fail(ecode, "$type", $symname, $argnum); diff --git a/Lib/typemaps/swigtype.swg b/Lib/typemaps/swigtype.swg index f57766962..6155a8abc 100644 --- a/Lib/typemaps/swigtype.swg +++ b/Lib/typemaps/swigtype.swg @@ -67,6 +67,41 @@ } #endif +/* Rvalue reference */ +%typemap(in, noblock=1) SWIGTYPE && (void *argp = 0, int res = 0) { + res = SWIG_ConvertPtr($input, &argp, $descriptor, %convertptr_flags); + if (!SWIG_IsOK(res)) { + %argument_fail(res, "$type", $symname, $argnum); + } + if (!argp) { %argument_nullref("$type", $symname, $argnum); } + $1 = %reinterpret_cast(argp, $ltype); +} +%typemap(freearg) SWIGTYPE && ""; + +#if defined(__cplusplus) && defined(%implicitconv_flag) +%typemap(in,noblock=1,implicitconv=1) const SWIGTYPE && (void *argp = 0, int res = 0) { + res = SWIG_ConvertPtr($input, &argp, $descriptor, %convertptr_flags | %implicitconv_flag); + if (!SWIG_IsOK(res)) { + %argument_fail(res, "$type", $symname, $argnum); + } + if (!argp) { %argument_nullref("$type", $symname, $argnum); } + $1 = %reinterpret_cast(argp, $ltype); +} +%typemap(freearg,noblock=1,match="in",implicitconv=1) const SWIGTYPE && +{ + if (SWIG_IsNewObj(res$argnum)) %delete($1); +} +#else +%typemap(in,noblock=1) const SWIGTYPE && (void *argp, int res = 0) { + res = SWIG_ConvertPtr($input, &argp, $descriptor, %convertptr_flags); + if (!SWIG_IsOK(res)) { + %argument_fail(res, "$type", $symname, $argnum); + } + if (!argp) { %argument_nullref("$type", $symname, $argnum); } + $1 = %reinterpret_cast(argp, $ltype); +} +#endif + /* By value */ #if defined(__cplusplus) && defined(%implicitconv_flag) %typemap(in,implicitconv=1) SWIGTYPE (void *argp, int res = 0) { @@ -102,7 +137,7 @@ * ----------------------------------------------------------------------------- */ /* Pointers, references */ -%typemap(out,noblock=1) SWIGTYPE *, SWIGTYPE &, SWIGTYPE[] { +%typemap(out,noblock=1) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE[] { %set_output(SWIG_NewPointerObj(%as_voidptr($1), $descriptor, $owner | %newpointer_flags)); } @@ -235,6 +270,18 @@ $1 = *(%reinterpret_cast(argp, $ltype)); } +%typemap(varin,warning=SWIGWARN_TYPEMAP_SWIGTYPELEAK_MSG) SWIGTYPE && { + void *argp = 0; + int res = SWIG_ConvertPtr($input, &argp, $descriptor, %convertptr_flags); + if (!SWIG_IsOK(res)) { + %variable_fail(res, "$type", "$name"); + } + if (!argp) { + %variable_nullref("$type", "$name"); + } + $1 = *(%reinterpret_cast(argp, $ltype)); +} + #if defined(__cplusplus) && defined(%implicitconv_flag) %typemap(varin,implicitconv=1) SWIGTYPE { void *argp = 0; @@ -284,6 +331,10 @@ %set_varoutput(SWIG_NewPointerObj(%as_voidptr(&$1), $descriptor, %newpointer_flags)); } +%typemap(varout, noblock=1) SWIGTYPE && { + %set_varoutput(SWIG_NewPointerObj(%as_voidptr(&$1), $descriptor, %newpointer_flags)); +} + /* Value */ %typemap(varout, noblock=1) SWIGTYPE { %set_varoutput(SWIG_NewPointerObj(%as_voidptr(&$1), $&descriptor, %newpointer_flags)); @@ -311,12 +362,23 @@ $1 = SWIG_CheckState(res); } +%typemap(typecheck,precedence=SWIG_TYPECHECK_POINTER,noblock=1) SWIGTYPE && { + void *vptr = 0; + int res = SWIG_ConvertPtr($input, &vptr, $descriptor, 0); + $1 = SWIG_CheckState(res); +} + #if defined(__cplusplus) && defined(%implicitconv_flag) %typemap(typecheck,precedence=SWIG_TYPECHECK_POINTER,noblock=1,implicitconv=1) const SWIGTYPE & { int res = SWIG_ConvertPtr($input, 0, $descriptor, %implicitconv_flag); $1 = SWIG_CheckState(res); } +%typemap(typecheck,precedence=SWIG_TYPECHECK_POINTER,noblock=1,implicitconv=1) const SWIGTYPE && { + int res = SWIG_ConvertPtr($input, 0, $descriptor, %implicitconv_flag); + $1 = SWIG_CheckState(res); +} + %typemap(typecheck,precedence=SWIG_TYPECHECK_POINTER,noblock=1,implicitconv=1) SWIGTYPE { int res = SWIG_ConvertPtr($input, 0, $&descriptor, %implicitconv_flag); $1 = SWIG_CheckState(res); @@ -327,6 +389,11 @@ int res = SWIG_ConvertPtr($input, &vptr, $descriptor, 0); $1 = SWIG_CheckState(res); } +%typemap(typecheck,precedence=SWIG_TYPECHECK_POINTER,noblock=1) const SWIGTYPE && { + void *vptr = 0; + int res = SWIG_ConvertPtr($input, &vptr, $descriptor, 0); + $1 = SWIG_CheckState(res); +} %typemap(typecheck,precedence=SWIG_TYPECHECK_POINTER,noblock=1) SWIGTYPE { void *vptr = 0; @@ -355,6 +422,10 @@ $input = SWIG_NewPointerObj(%as_voidptr(&$1_name), $descriptor, %newpointer_flags); } +%typemap(directorin,noblock=1) SWIGTYPE && { + $input = SWIG_NewPointerObj(%as_voidptr(&$1_name), $descriptor, %newpointer_flags); +} + /* directorout */ #if defined(__cplusplus) && defined(%implicitconv_flag) %typemap(directorout,noblock=1,implicitconv=1) SWIGTYPE (void * swig_argp, int swig_res = 0) { @@ -406,6 +477,22 @@ } } +%typemap(directorout,noblock=1,warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) + SWIGTYPE &&(void *swig_argp, int swig_res, swig_owntype own) { + swig_res = SWIG_ConvertPtrAndOwn($input, &swig_argp, $descriptor, %convertptr_flags | SWIG_POINTER_DISOWN, &own); + if (!SWIG_IsOK(swig_res)) { + %dirout_fail(swig_res,"$type"); + } + if (!swig_argp) { %dirout_nullref("$type"); } + $result = %reinterpret_cast(swig_argp, $ltype); + swig_acquire_ownership_obj(%as_voidptr($result), own /* & TODO: SWIG_POINTER_OWN */); +} +%typemap(directorfree,noblock=1,match="directorout") SWIGTYPE && { + if (director) { + SWIG_AcquirePtr($result, director->swig_release_ownership(%as_voidptr($input))); + } +} + #endif /* SWIG_DIRECTOR_TYPEMAPS */ @@ -413,7 +500,7 @@ * --- Constants --- * ------------------------------------------------------------ */ -%typemap(constcode,noblock=1) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] { +%typemap(constcode,noblock=1) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] { %set_constant("$symname", SWIG_NewPointerObj(%as_voidptr($value),$descriptor,%newpointer_flags)); } @@ -441,6 +528,10 @@ %raise(SWIG_NewPointerObj(%as_voidptr(&$1),$descriptor,0), "$type", $descriptor); } +%typemap(throws,noblock=1) SWIGTYPE && { + %raise(SWIG_NewPointerObj(%as_voidptr(&$1),$descriptor,0), "$type", $descriptor); +} + %typemap(throws,noblock=1) (...) { SWIG_exception_fail(SWIG_RuntimeError,"unknown exception"); } From 34d46510cfbcecdeb4fd1a98a2957ecfe5a2db6a Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 24 Jan 2013 20:53:32 +0000 Subject: [PATCH 101/481] Variadic templates doc update --- Doc/Manual/Cpp0x.html | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html index fa895cc6b..0200fdf5c 100644 --- a/Doc/Manual/Cpp0x.html +++ b/Doc/Manual/Cpp0x.html @@ -511,23 +511,27 @@ public: }
    -

    Support for the variadic sizeof() function was also introduced:

    - -
    -const int SIZE = sizeof...(ClassName<int, int>);
    -
    -

    For now however, the %template directive only accepts one parameter substitution for the variable template parameters.

    -%template(MyVariant1) ClassName<>         // zero argument not supported
    +%template(MyVariant1) ClassName<>         // zero argument not supported yet
     %template(MyVariant2) ClassName<int>      // ok
    -%template(MyVariant3) ClassName<int, int> // too many arguments
    +%template(MyVariant3) ClassName<int, int> // too many arguments not supported yet
     
    +

    Support for the variadic sizeof() function is correctly parsed:

    + +
    +const int SIZE = sizeof...(ClassName<int, int>);
    +
    + +

    +In the above example SIZE is of course wrapped as a constant. +

    +

    7.2.18 New string literals

    From 32f8248e243d8296ff3a5a24b392a645b104abdc Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 28 Jan 2013 07:06:37 +0000 Subject: [PATCH 102/481] Fix shift/shift and shift/reduce errors around variadic templates since merge --- Source/CParse/parser.y | 48 ++++++++++++++++++------------------------ 1 file changed, 21 insertions(+), 27 deletions(-) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index ed698e4ca..f5b5f6e2b 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1772,7 +1772,8 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %type

    typemap_parm tm_list tm_tail ; %type

    templateparameter ; %type templcpptype cpptype access_specifier; -%type base_specifier +%type base_specifier; +%type ellipsis variadic; %type type rawtype type_right anon_bitfield_type decltype ; %type base_list inherit raw_inherit; %type definetype def_args etype; @@ -6429,6 +6430,19 @@ exprcompound : expr PLUS expr { } ; +ellipsis : PERIOD PERIOD PERIOD { + $$ = NewString("..."); + } + ; + +variadic : ellipsis { + $$ = $1; + } + | empty { + $$ = 0; + } + ; + inherit : raw_inherit { $$ = $1; } @@ -6466,7 +6480,7 @@ base_list : base_specifier { base_specifier : opt_virtual { $$ = cparse_line; - } idcolon { + } idcolon variadic { $$ = NewHash(); Setfile($$,cparse_file); Setline($$,$2); @@ -6479,10 +6493,12 @@ base_specifier : opt_virtual { } else { Setattr($$,"access","public"); } + if ($4) + SetFlag($$, "variadic"); } | opt_virtual access_specifier { $$ = cparse_line; - } opt_virtual idcolon { + } opt_virtual idcolon variadic { $$ = NewHash(); Setfile($$,cparse_file); Setline($$,$3); @@ -6493,30 +6509,8 @@ base_specifier : opt_virtual { if (Strcmp($2,"public") != 0) { Swig_warning(WARN_PARSE_PRIVATE_INHERIT, Getfile($$), Getline($$), "%s inheritance from base '%s' (ignored).\n", $2, SwigType_namestr($5)); } - } - | opt_virtual idcolon PERIOD PERIOD PERIOD { /* Variadic inheritance */ - $$ = NewHash(); - Setfile($$,cparse_file); - Setline($$,cparse_line); - Setattr($$,"name",$2); - if (last_cpptype && (Strcmp(last_cpptype,"struct") != 0)) { - Setattr($$,"access","private"); - Swig_warning(WARN_PARSE_NO_ACCESS,cparse_file,cparse_line, - "No access specifier given for base class %s (ignored).\n",$2); - } else { - Setattr($$,"access","public"); - } - } - | opt_virtual access_specifier opt_virtual idcolon PERIOD PERIOD PERIOD { /* Variadic inheritance */ - $$ = NewHash(); - Setfile($$,cparse_file); - Setline($$,cparse_line); - Setattr($$,"name",$4); - Setattr($$,"access",$2); - if (Strcmp($2,"public") != 0) { - Swig_warning(WARN_PARSE_PRIVATE_INHERIT, cparse_file, - cparse_line,"%s inheritance ignored.\n", $2); - } + if ($6) + SetFlag($$, "variadic"); } ; From 2a90cc6a9807c2cd136befaada1ff91276e7d01c Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 28 Jan 2013 07:11:08 +0000 Subject: [PATCH 103/481] Remove generated output that should not be checked in2 --- .../python/cpp0x_unrestricted_unions_wrap.cxx | 4046 ----------------- 1 file changed, 4046 deletions(-) delete mode 100644 Examples/test-suite/python/cpp0x_unrestricted_unions_wrap.cxx diff --git a/Examples/test-suite/python/cpp0x_unrestricted_unions_wrap.cxx b/Examples/test-suite/python/cpp0x_unrestricted_unions_wrap.cxx deleted file mode 100644 index 071bb660d..000000000 --- a/Examples/test-suite/python/cpp0x_unrestricted_unions_wrap.cxx +++ /dev/null @@ -1,4046 +0,0 @@ -/* ---------------------------------------------------------------------------- - * This file was automatically generated by SWIG (http://www.swig.org). - * Version 2.0.1 - * - * This file is not intended to be easily readable and contains a number of - * coding conventions designed to improve portability and efficiency. Do not make - * changes to this file unless you know what you are doing--modify the SWIG - * interface file instead. - * ----------------------------------------------------------------------------- */ - -#define SWIGPYTHON -#define SWIG_PYTHON_DIRECTOR_NO_VTABLE - - -#ifdef __cplusplus -/* SwigValueWrapper is described in swig.swg */ -template class SwigValueWrapper { - struct SwigMovePointer { - T *ptr; - SwigMovePointer(T *p) : ptr(p) { } - ~SwigMovePointer() { delete ptr; } - SwigMovePointer& operator=(SwigMovePointer& rhs) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = rhs.ptr; rhs.ptr = 0; return *this; } - } pointer; - SwigValueWrapper& operator=(const SwigValueWrapper& rhs); - SwigValueWrapper(const SwigValueWrapper& rhs); -public: - SwigValueWrapper() : pointer(0) { } - SwigValueWrapper& operator=(const T& t) { SwigMovePointer tmp(new T(t)); pointer = tmp; return *this; } - operator T&() const { return *pointer.ptr; } - T *operator&() { return pointer.ptr; } -}; - -template T SwigValueInit() { - return T(); -} -#endif - -/* ----------------------------------------------------------------------------- - * This section contains generic SWIG labels for method/variable - * declarations/attributes, and other compiler dependent labels. - * ----------------------------------------------------------------------------- */ - -/* template workaround for compilers that cannot correctly implement the C++ standard */ -#ifndef SWIGTEMPLATEDISAMBIGUATOR -# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560) -# define SWIGTEMPLATEDISAMBIGUATOR template -# elif defined(__HP_aCC) -/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */ -/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */ -# define SWIGTEMPLATEDISAMBIGUATOR template -# else -# define SWIGTEMPLATEDISAMBIGUATOR -# endif -#endif - -/* inline attribute */ -#ifndef SWIGINLINE -# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) -# define SWIGINLINE inline -# else -# define SWIGINLINE -# endif -#endif - -/* attribute recognised by some compilers to avoid 'unused' warnings */ -#ifndef SWIGUNUSED -# if defined(__GNUC__) -# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) -# define SWIGUNUSED __attribute__ ((__unused__)) -# else -# define SWIGUNUSED -# endif -# elif defined(__ICC) -# define SWIGUNUSED __attribute__ ((__unused__)) -# else -# define SWIGUNUSED -# endif -#endif - -#ifndef SWIG_MSC_UNSUPPRESS_4505 -# if defined(_MSC_VER) -# pragma warning(disable : 4505) /* unreferenced local function has been removed */ -# endif -#endif - -#ifndef SWIGUNUSEDPARM -# ifdef __cplusplus -# define SWIGUNUSEDPARM(p) -# else -# define SWIGUNUSEDPARM(p) p SWIGUNUSED -# endif -#endif - -/* internal SWIG method */ -#ifndef SWIGINTERN -# define SWIGINTERN static SWIGUNUSED -#endif - -/* internal inline SWIG method */ -#ifndef SWIGINTERNINLINE -# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE -#endif - -/* exporting methods */ -#if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) -# ifndef GCC_HASCLASSVISIBILITY -# define GCC_HASCLASSVISIBILITY -# endif -#endif - -#ifndef SWIGEXPORT -# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) -# if defined(STATIC_LINKED) -# define SWIGEXPORT -# else -# define SWIGEXPORT __declspec(dllexport) -# endif -# else -# if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) -# define SWIGEXPORT __attribute__ ((visibility("default"))) -# else -# define SWIGEXPORT -# endif -# endif -#endif - -/* calling conventions for Windows */ -#ifndef SWIGSTDCALL -# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) -# define SWIGSTDCALL __stdcall -# else -# define SWIGSTDCALL -# endif -#endif - -/* Deal with Microsoft's attempt at deprecating C standard runtime functions */ -#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) -# define _CRT_SECURE_NO_DEPRECATE -#endif - -/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */ -#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE) -# define _SCL_SECURE_NO_DEPRECATE -#endif - - - -/* Python.h has to appear first */ -#include - -/* ----------------------------------------------------------------------------- - * swigrun.swg - * - * This file contains generic C API SWIG runtime support for pointer - * type checking. - * ----------------------------------------------------------------------------- */ - -/* This should only be incremented when either the layout of swig_type_info changes, - or for whatever reason, the runtime changes incompatibly */ -#define SWIG_RUNTIME_VERSION "4" - -/* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */ -#ifdef SWIG_TYPE_TABLE -# define SWIG_QUOTE_STRING(x) #x -# define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x) -# define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE) -#else -# define SWIG_TYPE_TABLE_NAME -#endif - -/* - You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for - creating a static or dynamic library from the SWIG runtime code. - In 99.9% of the cases, SWIG just needs to declare them as 'static'. - - But only do this if strictly necessary, ie, if you have problems - with your compiler or suchlike. -*/ - -#ifndef SWIGRUNTIME -# define SWIGRUNTIME SWIGINTERN -#endif - -#ifndef SWIGRUNTIMEINLINE -# define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE -#endif - -/* Generic buffer size */ -#ifndef SWIG_BUFFER_SIZE -# define SWIG_BUFFER_SIZE 1024 -#endif - -/* Flags for pointer conversions */ -#define SWIG_POINTER_DISOWN 0x1 -#define SWIG_CAST_NEW_MEMORY 0x2 - -/* Flags for new pointer objects */ -#define SWIG_POINTER_OWN 0x1 - - -/* - Flags/methods for returning states. - - The SWIG conversion methods, as ConvertPtr, return an integer - that tells if the conversion was successful or not. And if not, - an error code can be returned (see swigerrors.swg for the codes). - - Use the following macros/flags to set or process the returning - states. - - In old versions of SWIG, code such as the following was usually written: - - if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) { - // success code - } else { - //fail code - } - - Now you can be more explicit: - - int res = SWIG_ConvertPtr(obj,vptr,ty.flags); - if (SWIG_IsOK(res)) { - // success code - } else { - // fail code - } - - which is the same really, but now you can also do - - Type *ptr; - int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags); - if (SWIG_IsOK(res)) { - // success code - if (SWIG_IsNewObj(res) { - ... - delete *ptr; - } else { - ... - } - } else { - // fail code - } - - I.e., now SWIG_ConvertPtr can return new objects and you can - identify the case and take care of the deallocation. Of course that - also requires SWIG_ConvertPtr to return new result values, such as - - int SWIG_ConvertPtr(obj, ptr,...) { - if () { - if () { - *ptr = ; - return SWIG_NEWOBJ; - } else { - *ptr = ; - return SWIG_OLDOBJ; - } - } else { - return SWIG_BADOBJ; - } - } - - Of course, returning the plain '0(success)/-1(fail)' still works, but you can be - more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the - 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 - - int food(double) - int fooi(int); - - and you call - - food(1) // cast rank '1' (1 -> 1.0) - fooi(1) // cast rank '0' - - just use the SWIG_AddCast()/SWIG_CheckState() -*/ - -#define SWIG_OK (0) -#define SWIG_ERROR (-1) -#define SWIG_IsOK(r) (r >= 0) -#define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) - -/* The CastRankLimit says how many bits are used for the cast rank */ -#define SWIG_CASTRANKLIMIT (1 << 8) -/* The NewMask denotes the object was created (using new/malloc) */ -#define SWIG_NEWOBJMASK (SWIG_CASTRANKLIMIT << 1) -/* The TmpMask is for in/out typemaps that use temporal objects */ -#define SWIG_TMPOBJMASK (SWIG_NEWOBJMASK << 1) -/* Simple returning values */ -#define SWIG_BADOBJ (SWIG_ERROR) -#define SWIG_OLDOBJ (SWIG_OK) -#define SWIG_NEWOBJ (SWIG_OK | SWIG_NEWOBJMASK) -#define SWIG_TMPOBJ (SWIG_OK | SWIG_TMPOBJMASK) -/* Check, add and del mask methods */ -#define SWIG_AddNewMask(r) (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r) -#define SWIG_DelNewMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r) -#define SWIG_IsNewObj(r) (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK)) -#define SWIG_AddTmpMask(r) (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r) -#define SWIG_DelTmpMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r) -#define SWIG_IsTmpObj(r) (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK)) - -/* Cast-Rank Mode */ -#if defined(SWIG_CASTRANK_MODE) -# ifndef SWIG_TypeRank -# define SWIG_TypeRank unsigned long -# endif -# ifndef SWIG_MAXCASTRANK /* Default cast allowed */ -# define SWIG_MAXCASTRANK (2) -# endif -# define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) -# define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) -SWIGINTERNINLINE int SWIG_AddCast(int r) { - return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; -} -SWIGINTERNINLINE int SWIG_CheckState(int r) { - return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; -} -#else /* no cast-rank mode */ -# define SWIG_AddCast -# define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0) -#endif - - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef void *(*swig_converter_func)(void *, int *); -typedef struct swig_type_info *(*swig_dycast_func)(void **); - -/* Structure to store information on one type */ -typedef struct swig_type_info { - const char *name; /* mangled name of this type */ - const char *str; /* human readable name of this type */ - swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ - struct swig_cast_info *cast; /* linked list of types that can cast into this type */ - void *clientdata; /* language specific type data */ - int owndata; /* flag if the structure owns the clientdata */ -} swig_type_info; - -/* Structure to store a type and conversion function used for casting */ -typedef struct swig_cast_info { - swig_type_info *type; /* pointer to type that is equivalent to this type */ - swig_converter_func converter; /* function to cast the void pointers */ - struct swig_cast_info *next; /* pointer to next cast in linked list */ - struct swig_cast_info *prev; /* pointer to the previous cast */ -} swig_cast_info; - -/* Structure used to store module information - * Each module generates one structure like this, and the runtime collects - * all of these structures and stores them in a circularly linked list.*/ -typedef struct swig_module_info { - swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ - size_t size; /* Number of types in this module */ - struct swig_module_info *next; /* Pointer to next element in circularly linked list */ - swig_type_info **type_initial; /* Array of initially generated type structures */ - swig_cast_info **cast_initial; /* Array of initially generated casting structures */ - void *clientdata; /* Language specific module data */ -} swig_module_info; - -/* - Compare two type names skipping the space characters, therefore - "char*" == "char *" and "Class" == "Class", etc. - - Return 0 when the two name types are equivalent, as in - strncmp, but skipping ' '. -*/ -SWIGRUNTIME int -SWIG_TypeNameComp(const char *f1, const char *l1, - const char *f2, const char *l2) { - for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { - while ((*f1 == ' ') && (f1 != l1)) ++f1; - while ((*f2 == ' ') && (f2 != l2)) ++f2; - if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; - } - return (int)((l1 - f1) - (l2 - f2)); -} - -/* - Check type equivalence in a name list like ||... - Return 0 if not equal, 1 if equal -*/ -SWIGRUNTIME int -SWIG_TypeEquiv(const char *nb, const char *tb) { - int equiv = 0; - const char* te = tb + strlen(tb); - const char* ne = nb; - while (!equiv && *ne) { - for (nb = ne; *ne; ++ne) { - if (*ne == '|') break; - } - equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; - if (*ne) ++ne; - } - return equiv; -} - -/* - Check type equivalence in a name list like ||... - Return 0 if equal, -1 if nb < tb, 1 if nb > tb -*/ -SWIGRUNTIME int -SWIG_TypeCompare(const char *nb, const char *tb) { - int equiv = 0; - const char* te = tb + strlen(tb); - const char* ne = nb; - while (!equiv && *ne) { - for (nb = ne; *ne; ++ne) { - if (*ne == '|') break; - } - equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; - if (*ne) ++ne; - } - return equiv; -} - - -/* - Check the typename -*/ -SWIGRUNTIME swig_cast_info * -SWIG_TypeCheck(const char *c, swig_type_info *ty) { - if (ty) { - swig_cast_info *iter = ty->cast; - while (iter) { - if (strcmp(iter->type->name, c) == 0) { - if (iter == ty->cast) - return iter; - /* Move iter to the top of the linked list */ - iter->prev->next = iter->next; - if (iter->next) - iter->next->prev = iter->prev; - iter->next = ty->cast; - iter->prev = 0; - if (ty->cast) ty->cast->prev = iter; - ty->cast = iter; - return iter; - } - iter = iter->next; - } - } - return 0; -} - -/* - 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) { - if (ty) { - swig_cast_info *iter = ty->cast; - while (iter) { - if (iter->type == from) { - if (iter == ty->cast) - return iter; - /* Move iter to the top of the linked list */ - iter->prev->next = iter->next; - if (iter->next) - iter->next->prev = iter->prev; - iter->next = ty->cast; - iter->prev = 0; - if (ty->cast) ty->cast->prev = iter; - ty->cast = iter; - return iter; - } - iter = iter->next; - } - } - return 0; -} - -/* - Cast a pointer up an inheritance hierarchy -*/ -SWIGRUNTIMEINLINE void * -SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { - return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); -} - -/* - Dynamic pointer casting. Down an inheritance hierarchy -*/ -SWIGRUNTIME swig_type_info * -SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { - swig_type_info *lastty = ty; - if (!ty || !ty->dcast) return ty; - while (ty && (ty->dcast)) { - ty = (*ty->dcast)(ptr); - if (ty) lastty = ty; - } - return lastty; -} - -/* - Return the name associated with this type -*/ -SWIGRUNTIMEINLINE const char * -SWIG_TypeName(const swig_type_info *ty) { - return ty->name; -} - -/* - Return the pretty name associated with this type, - that is an unmangled type name in a form presentable to the user. -*/ -SWIGRUNTIME const char * -SWIG_TypePrettyName(const swig_type_info *type) { - /* The "str" field contains the equivalent pretty names of the - type, separated by vertical-bar characters. We choose - to print the last name, as it is often (?) the most - specific. */ - if (!type) return NULL; - if (type->str != NULL) { - const char *last_name = type->str; - const char *s; - for (s = type->str; *s; s++) - if (*s == '|') last_name = s+1; - return last_name; - } - else - return type->name; -} - -/* - Set the clientdata field for a type -*/ -SWIGRUNTIME void -SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { - swig_cast_info *cast = ti->cast; - /* if (ti->clientdata == clientdata) return; */ - ti->clientdata = clientdata; - - while (cast) { - if (!cast->converter) { - swig_type_info *tc = cast->type; - if (!tc->clientdata) { - SWIG_TypeClientData(tc, clientdata); - } - } - cast = cast->next; - } -} -SWIGRUNTIME void -SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { - SWIG_TypeClientData(ti, clientdata); - ti->owndata = 1; -} - -/* - Search for a swig_type_info structure only by mangled name - Search is a O(log #types) - - We start searching at module start, and finish searching when start == end. - Note: if start == end at the beginning of the function, we go all the way around - the circular list. -*/ -SWIGRUNTIME swig_type_info * -SWIG_MangledTypeQueryModule(swig_module_info *start, - swig_module_info *end, - const char *name) { - swig_module_info *iter = start; - do { - if (iter->size) { - register size_t l = 0; - register size_t r = iter->size - 1; - do { - /* since l+r >= 0, we can (>> 1) instead (/ 2) */ - register size_t i = (l + r) >> 1; - const char *iname = iter->types[i]->name; - if (iname) { - register int compare = strcmp(name, iname); - if (compare == 0) { - return iter->types[i]; - } else if (compare < 0) { - if (i) { - r = i - 1; - } else { - break; - } - } else if (compare > 0) { - l = i + 1; - } - } else { - break; /* should never happen */ - } - } while (l <= r); - } - iter = iter->next; - } while (iter != end); - return 0; -} - -/* - Search for a swig_type_info structure for either a mangled name or a human readable name. - It first searches the mangled names of the types, which is a O(log #types) - If a type is not found it then searches the human readable names, which is O(#types). - - We start searching at module start, and finish searching when start == end. - Note: if start == end at the beginning of the function, we go all the way around - the circular list. -*/ -SWIGRUNTIME swig_type_info * -SWIG_TypeQueryModule(swig_module_info *start, - swig_module_info *end, - const char *name) { - /* STEP 1: Search the name field using binary search */ - swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); - if (ret) { - return ret; - } else { - /* STEP 2: If the type hasn't been found, do a complete search - of the str field (the human readable name) */ - swig_module_info *iter = start; - do { - register size_t i = 0; - for (; i < iter->size; ++i) { - if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) - return iter->types[i]; - } - iter = iter->next; - } while (iter != end); - } - - /* neither found a match */ - return 0; -} - -/* - Pack binary data into a string -*/ -SWIGRUNTIME char * -SWIG_PackData(char *c, void *ptr, size_t sz) { - static const char hex[17] = "0123456789abcdef"; - register const unsigned char *u = (unsigned char *) ptr; - register const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - register unsigned char uu = *u; - *(c++) = hex[(uu & 0xf0) >> 4]; - *(c++) = hex[uu & 0xf]; - } - return c; -} - -/* - Unpack binary data from a string -*/ -SWIGRUNTIME const char * -SWIG_UnpackData(const char *c, void *ptr, size_t sz) { - register unsigned char *u = (unsigned char *) ptr; - register const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - register char d = *(c++); - register unsigned char uu; - if ((d >= '0') && (d <= '9')) - uu = ((d - '0') << 4); - else if ((d >= 'a') && (d <= 'f')) - uu = ((d - ('a'-10)) << 4); - else - return (char *) 0; - d = *(c++); - if ((d >= '0') && (d <= '9')) - uu |= (d - '0'); - else if ((d >= 'a') && (d <= 'f')) - uu |= (d - ('a'-10)); - else - return (char *) 0; - *u = uu; - } - return c; -} - -/* - Pack 'void *' into a string buffer. -*/ -SWIGRUNTIME char * -SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { - char *r = buff; - if ((2*sizeof(void *) + 2) > bsz) return 0; - *(r++) = '_'; - r = SWIG_PackData(r,&ptr,sizeof(void *)); - if (strlen(name) + 1 > (bsz - (r - buff))) return 0; - strcpy(r,name); - return buff; -} - -SWIGRUNTIME const char * -SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { - if (*c != '_') { - if (strcmp(c,"NULL") == 0) { - *ptr = (void *) 0; - return name; - } else { - return 0; - } - } - return SWIG_UnpackData(++c,ptr,sizeof(void *)); -} - -SWIGRUNTIME char * -SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { - char *r = buff; - size_t lname = (name ? strlen(name) : 0); - if ((2*sz + 2 + lname) > bsz) return 0; - *(r++) = '_'; - r = SWIG_PackData(r,ptr,sz); - if (lname) { - strncpy(r,name,lname+1); - } else { - *r = 0; - } - return buff; -} - -SWIGRUNTIME const char * -SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { - if (*c != '_') { - if (strcmp(c,"NULL") == 0) { - memset(ptr,0,sz); - return name; - } else { - return 0; - } - } - return SWIG_UnpackData(++c,ptr,sz); -} - -#ifdef __cplusplus -} -#endif - -/* Errors in SWIG */ -#define SWIG_UnknownError -1 -#define SWIG_IOError -2 -#define SWIG_RuntimeError -3 -#define SWIG_IndexError -4 -#define SWIG_TypeError -5 -#define SWIG_DivisionByZero -6 -#define SWIG_OverflowError -7 -#define SWIG_SyntaxError -8 -#define SWIG_ValueError -9 -#define SWIG_SystemError -10 -#define SWIG_AttributeError -11 -#define SWIG_MemoryError -12 -#define SWIG_NullReferenceError -13 - - - -/* Compatibility macros for Python 3 */ -#if PY_VERSION_HEX >= 0x03000000 - -#define PyClass_Check(obj) PyObject_IsInstance(obj, (PyObject *)&PyType_Type) -#define PyInt_Check(x) PyLong_Check(x) -#define PyInt_AsLong(x) PyLong_AsLong(x) -#define PyInt_FromLong(x) PyLong_FromLong(x) -#define PyString_Format(fmt, args) PyUnicode_Format(fmt, args) - -#endif - -#ifndef Py_TYPE -# define Py_TYPE(op) ((op)->ob_type) -#endif - -/* SWIG APIs for compatibility of both Python 2 & 3 */ - -#if PY_VERSION_HEX >= 0x03000000 -# define SWIG_Python_str_FromFormat PyUnicode_FromFormat -#else -# define SWIG_Python_str_FromFormat PyString_FromFormat -#endif - - -/* Warning: This function will allocate a new string in Python 3, - * so please call SWIG_Python_str_DelForPy3(x) to free the space. - */ -SWIGINTERN char* -SWIG_Python_str_AsChar(PyObject *str) -{ -#if PY_VERSION_HEX >= 0x03000000 - char *cstr; - char *newstr; - Py_ssize_t len; - str = PyUnicode_AsUTF8String(str); - PyBytes_AsStringAndSize(str, &cstr, &len); - newstr = (char *) malloc(len+1); - memcpy(newstr, cstr, len+1); - Py_XDECREF(str); - return newstr; -#else - return PyString_AsString(str); -#endif -} - -#if PY_VERSION_HEX >= 0x03000000 -# define SWIG_Python_str_DelForPy3(x) free( (void*) (x) ) -#else -# define SWIG_Python_str_DelForPy3(x) -#endif - - -SWIGINTERN PyObject* -SWIG_Python_str_FromChar(const char *c) -{ -#if PY_VERSION_HEX >= 0x03000000 - return PyUnicode_FromString(c); -#else - return PyString_FromString(c); -#endif -} - -/* Add PyOS_snprintf for old Pythons */ -#if PY_VERSION_HEX < 0x02020000 -# if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WATCOM) -# define PyOS_snprintf _snprintf -# else -# define PyOS_snprintf snprintf -# endif -#endif - -/* A crude PyString_FromFormat implementation for old Pythons */ -#if PY_VERSION_HEX < 0x02020000 - -#ifndef SWIG_PYBUFFER_SIZE -# define SWIG_PYBUFFER_SIZE 1024 -#endif - -static PyObject * -PyString_FromFormat(const char *fmt, ...) { - va_list ap; - char buf[SWIG_PYBUFFER_SIZE * 2]; - int res; - va_start(ap, fmt); - res = vsnprintf(buf, sizeof(buf), fmt, ap); - va_end(ap); - return (res < 0 || res >= (int)sizeof(buf)) ? 0 : PyString_FromString(buf); -} -#endif - -/* Add PyObject_Del for old Pythons */ -#if PY_VERSION_HEX < 0x01060000 -# define PyObject_Del(op) PyMem_DEL((op)) -#endif -#ifndef PyObject_DEL -# define PyObject_DEL PyObject_Del -#endif - -/* A crude PyExc_StopIteration exception for old Pythons */ -#if PY_VERSION_HEX < 0x02020000 -# ifndef PyExc_StopIteration -# define PyExc_StopIteration PyExc_RuntimeError -# endif -# ifndef PyObject_GenericGetAttr -# define PyObject_GenericGetAttr 0 -# endif -#endif - -/* Py_NotImplemented is defined in 2.1 and up. */ -#if PY_VERSION_HEX < 0x02010000 -# ifndef Py_NotImplemented -# define Py_NotImplemented PyExc_RuntimeError -# endif -#endif - -/* A crude PyString_AsStringAndSize implementation for old Pythons */ -#if PY_VERSION_HEX < 0x02010000 -# ifndef PyString_AsStringAndSize -# define PyString_AsStringAndSize(obj, s, len) {*s = PyString_AsString(obj); *len = *s ? strlen(*s) : 0;} -# endif -#endif - -/* PySequence_Size for old Pythons */ -#if PY_VERSION_HEX < 0x02000000 -# ifndef PySequence_Size -# define PySequence_Size PySequence_Length -# endif -#endif - -/* PyBool_FromLong for old Pythons */ -#if PY_VERSION_HEX < 0x02030000 -static -PyObject *PyBool_FromLong(long ok) -{ - PyObject *result = ok ? Py_True : Py_False; - Py_INCREF(result); - return result; -} -#endif - -/* Py_ssize_t for old Pythons */ -/* This code is as recommended by: */ -/* http://www.python.org/dev/peps/pep-0353/#conversion-guidelines */ -#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) -typedef int Py_ssize_t; -# define PY_SSIZE_T_MAX INT_MAX -# define PY_SSIZE_T_MIN INT_MIN -#endif - -/* ----------------------------------------------------------------------------- - * error manipulation - * ----------------------------------------------------------------------------- */ - -SWIGRUNTIME PyObject* -SWIG_Python_ErrorType(int code) { - PyObject* type = 0; - switch(code) { - case SWIG_MemoryError: - type = PyExc_MemoryError; - break; - case SWIG_IOError: - type = PyExc_IOError; - break; - case SWIG_RuntimeError: - type = PyExc_RuntimeError; - break; - case SWIG_IndexError: - type = PyExc_IndexError; - break; - case SWIG_TypeError: - type = PyExc_TypeError; - break; - case SWIG_DivisionByZero: - type = PyExc_ZeroDivisionError; - break; - case SWIG_OverflowError: - type = PyExc_OverflowError; - break; - case SWIG_SyntaxError: - type = PyExc_SyntaxError; - break; - case SWIG_ValueError: - type = PyExc_ValueError; - break; - case SWIG_SystemError: - type = PyExc_SystemError; - break; - case SWIG_AttributeError: - type = PyExc_AttributeError; - break; - default: - type = PyExc_RuntimeError; - } - return type; -} - - -SWIGRUNTIME void -SWIG_Python_AddErrorMsg(const char* mesg) -{ - PyObject *type = 0; - PyObject *value = 0; - PyObject *traceback = 0; - - if (PyErr_Occurred()) PyErr_Fetch(&type, &value, &traceback); - if (value) { - char *tmp; - PyObject *old_str = PyObject_Str(value); - PyErr_Clear(); - Py_XINCREF(type); - - PyErr_Format(type, "%s %s", tmp = SWIG_Python_str_AsChar(old_str), mesg); - SWIG_Python_str_DelForPy3(tmp); - Py_DECREF(old_str); - Py_DECREF(value); - } else { - PyErr_SetString(PyExc_RuntimeError, mesg); - } -} - -#if defined(SWIG_PYTHON_NO_THREADS) -# if defined(SWIG_PYTHON_THREADS) -# undef SWIG_PYTHON_THREADS -# endif -#endif -#if defined(SWIG_PYTHON_THREADS) /* Threading support is enabled */ -# if !defined(SWIG_PYTHON_USE_GIL) && !defined(SWIG_PYTHON_NO_USE_GIL) -# if (PY_VERSION_HEX >= 0x02030000) /* For 2.3 or later, use the PyGILState calls */ -# define SWIG_PYTHON_USE_GIL -# endif -# endif -# if defined(SWIG_PYTHON_USE_GIL) /* Use PyGILState threads calls */ -# ifndef SWIG_PYTHON_INITIALIZE_THREADS -# define SWIG_PYTHON_INITIALIZE_THREADS PyEval_InitThreads() -# endif -# ifdef __cplusplus /* C++ code */ - class SWIG_Python_Thread_Block { - bool status; - PyGILState_STATE state; - public: - void end() { if (status) { PyGILState_Release(state); status = false;} } - SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {} - ~SWIG_Python_Thread_Block() { end(); } - }; - class SWIG_Python_Thread_Allow { - bool status; - PyThreadState *save; - public: - void end() { if (status) { PyEval_RestoreThread(save); status = false; }} - SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {} - ~SWIG_Python_Thread_Allow() { end(); } - }; -# define SWIG_PYTHON_THREAD_BEGIN_BLOCK SWIG_Python_Thread_Block _swig_thread_block -# define SWIG_PYTHON_THREAD_END_BLOCK _swig_thread_block.end() -# define SWIG_PYTHON_THREAD_BEGIN_ALLOW SWIG_Python_Thread_Allow _swig_thread_allow -# define SWIG_PYTHON_THREAD_END_ALLOW _swig_thread_allow.end() -# else /* C code */ -# define SWIG_PYTHON_THREAD_BEGIN_BLOCK PyGILState_STATE _swig_thread_block = PyGILState_Ensure() -# define SWIG_PYTHON_THREAD_END_BLOCK PyGILState_Release(_swig_thread_block) -# define SWIG_PYTHON_THREAD_BEGIN_ALLOW PyThreadState *_swig_thread_allow = PyEval_SaveThread() -# define SWIG_PYTHON_THREAD_END_ALLOW PyEval_RestoreThread(_swig_thread_allow) -# endif -# else /* Old thread way, not implemented, user must provide it */ -# if !defined(SWIG_PYTHON_INITIALIZE_THREADS) -# define SWIG_PYTHON_INITIALIZE_THREADS -# endif -# if !defined(SWIG_PYTHON_THREAD_BEGIN_BLOCK) -# define SWIG_PYTHON_THREAD_BEGIN_BLOCK -# endif -# if !defined(SWIG_PYTHON_THREAD_END_BLOCK) -# define SWIG_PYTHON_THREAD_END_BLOCK -# endif -# if !defined(SWIG_PYTHON_THREAD_BEGIN_ALLOW) -# define SWIG_PYTHON_THREAD_BEGIN_ALLOW -# endif -# if !defined(SWIG_PYTHON_THREAD_END_ALLOW) -# define SWIG_PYTHON_THREAD_END_ALLOW -# endif -# endif -#else /* No thread support */ -# define SWIG_PYTHON_INITIALIZE_THREADS -# define SWIG_PYTHON_THREAD_BEGIN_BLOCK -# define SWIG_PYTHON_THREAD_END_BLOCK -# define SWIG_PYTHON_THREAD_BEGIN_ALLOW -# define SWIG_PYTHON_THREAD_END_ALLOW -#endif - -/* ----------------------------------------------------------------------------- - * Python API portion that goes into the runtime - * ----------------------------------------------------------------------------- */ - -#ifdef __cplusplus -extern "C" { -#if 0 -} /* cc-mode */ -#endif -#endif - -/* ----------------------------------------------------------------------------- - * Constant declarations - * ----------------------------------------------------------------------------- */ - -/* Constant Types */ -#define SWIG_PY_POINTER 4 -#define SWIG_PY_BINARY 5 - -/* Constant information structure */ -typedef struct swig_const_info { - int type; - char *name; - long lvalue; - double dvalue; - void *pvalue; - swig_type_info **ptype; -} swig_const_info; - - -/* ----------------------------------------------------------------------------- - * Wrapper of PyInstanceMethod_New() used in Python 3 - * It is exported to the generated module, used for -fastproxy - * ----------------------------------------------------------------------------- */ -SWIGRUNTIME PyObject* SWIG_PyInstanceMethod_New(PyObject *self, PyObject *func) -{ -#if PY_VERSION_HEX >= 0x03000000 - return PyInstanceMethod_New(func); -#else - return NULL; -#endif -} - -#ifdef __cplusplus -#if 0 -{ /* cc-mode */ -#endif -} -#endif - - -/* ----------------------------------------------------------------------------- - * pyrun.swg - * - * This file contains the runtime support for Python modules - * and includes code for managing global variables and pointer - * type checking. - * - * ----------------------------------------------------------------------------- */ - -/* Common SWIG API */ - -/* for raw pointers */ -#define SWIG_Python_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, 0) -#define SWIG_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtr(obj, pptr, type, flags) -#define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, own) -#define SWIG_NewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(ptr, type, flags) -#define SWIG_CheckImplicit(ty) SWIG_Python_CheckImplicit(ty) -#define SWIG_AcquirePtr(ptr, src) SWIG_Python_AcquirePtr(ptr, src) -#define swig_owntype int - -/* for raw packed data */ -#define SWIG_ConvertPacked(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) -#define SWIG_NewPackedObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) - -/* for class or struct pointers */ -#define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_ConvertPtr(obj, pptr, type, flags) -#define SWIG_NewInstanceObj(ptr, type, flags) SWIG_NewPointerObj(ptr, type, flags) - -/* for C or C++ function pointers */ -#define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_Python_ConvertFunctionPtr(obj, pptr, type) -#define SWIG_NewFunctionPtrObj(ptr, type) SWIG_Python_NewPointerObj(ptr, type, 0) - -/* for C++ member pointers, ie, member methods */ -#define SWIG_ConvertMember(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) -#define SWIG_NewMemberObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) - - -/* Runtime API */ - -#define SWIG_GetModule(clientdata) SWIG_Python_GetModule() -#define SWIG_SetModule(clientdata, pointer) SWIG_Python_SetModule(pointer) -#define SWIG_NewClientData(obj) SwigPyClientData_New(obj) - -#define SWIG_SetErrorObj SWIG_Python_SetErrorObj -#define SWIG_SetErrorMsg SWIG_Python_SetErrorMsg -#define SWIG_ErrorType(code) SWIG_Python_ErrorType(code) -#define SWIG_Error(code, msg) SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) -#define SWIG_fail goto fail - - -/* Runtime API implementation */ - -/* Error manipulation */ - -SWIGINTERN void -SWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) { - SWIG_PYTHON_THREAD_BEGIN_BLOCK; - PyErr_SetObject(errtype, obj); - Py_DECREF(obj); - SWIG_PYTHON_THREAD_END_BLOCK; -} - -SWIGINTERN void -SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) { - SWIG_PYTHON_THREAD_BEGIN_BLOCK; - PyErr_SetString(errtype, (char *) msg); - SWIG_PYTHON_THREAD_END_BLOCK; -} - -#define SWIG_Python_Raise(obj, type, desc) SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj) - -/* Set a constant value */ - -SWIGINTERN void -SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) { - PyDict_SetItemString(d, (char*) name, obj); - Py_DECREF(obj); -} - -/* Append a value to the result obj */ - -SWIGINTERN PyObject* -SWIG_Python_AppendOutput(PyObject* result, PyObject* obj) { -#if !defined(SWIG_PYTHON_OUTPUT_TUPLE) - if (!result) { - result = obj; - } else if (result == Py_None) { - Py_DECREF(result); - result = obj; - } else { - if (!PyList_Check(result)) { - PyObject *o2 = result; - result = PyList_New(1); - PyList_SetItem(result, 0, o2); - } - PyList_Append(result,obj); - Py_DECREF(obj); - } - return result; -#else - PyObject* o2; - PyObject* o3; - if (!result) { - result = obj; - } else if (result == Py_None) { - Py_DECREF(result); - result = obj; - } else { - if (!PyTuple_Check(result)) { - o2 = result; - result = PyTuple_New(1); - PyTuple_SET_ITEM(result, 0, o2); - } - o3 = PyTuple_New(1); - PyTuple_SET_ITEM(o3, 0, obj); - o2 = result; - result = PySequence_Concat(o2, o3); - Py_DECREF(o2); - Py_DECREF(o3); - } - return result; -#endif -} - -/* Unpack the argument tuple */ - -SWIGINTERN int -SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs) -{ - if (!args) { - if (!min && !max) { - return 1; - } else { - PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", - name, (min == max ? "" : "at least "), (int)min); - return 0; - } - } - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple"); - return 0; - } else { - register Py_ssize_t l = PyTuple_GET_SIZE(args); - if (l < min) { - PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", - name, (min == max ? "" : "at least "), (int)min, (int)l); - return 0; - } else if (l > max) { - PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", - name, (min == max ? "" : "at most "), (int)max, (int)l); - return 0; - } else { - register int i; - for (i = 0; i < l; ++i) { - objs[i] = PyTuple_GET_ITEM(args, i); - } - for (; l < max; ++l) { - objs[l] = 0; - } - return i + 1; - } - } -} - -/* A functor is a function object with one single object argument */ -#if PY_VERSION_HEX >= 0x02020000 -#define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunctionObjArgs(functor, obj, NULL); -#else -#define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunction(functor, "O", obj); -#endif - -/* - Helper for static pointer initialization for both C and C++ code, for example - static PyObject *SWIG_STATIC_POINTER(MyVar) = NewSomething(...); -*/ -#ifdef __cplusplus -#define SWIG_STATIC_POINTER(var) var -#else -#define SWIG_STATIC_POINTER(var) var = 0; if (!var) var -#endif - -/* ----------------------------------------------------------------------------- - * Pointer declarations - * ----------------------------------------------------------------------------- */ - -/* Flags for new pointer objects */ -#define SWIG_POINTER_NOSHADOW (SWIG_POINTER_OWN << 1) -#define SWIG_POINTER_NEW (SWIG_POINTER_NOSHADOW | SWIG_POINTER_OWN) - -#define SWIG_POINTER_IMPLICIT_CONV (SWIG_POINTER_DISOWN << 1) - -#ifdef __cplusplus -extern "C" { -#if 0 -} /* cc-mode */ -#endif -#endif - -/* How to access Py_None */ -#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) -# ifndef SWIG_PYTHON_NO_BUILD_NONE -# ifndef SWIG_PYTHON_BUILD_NONE -# define SWIG_PYTHON_BUILD_NONE -# endif -# endif -#endif - -#ifdef SWIG_PYTHON_BUILD_NONE -# ifdef Py_None -# undef Py_None -# define Py_None SWIG_Py_None() -# endif -SWIGRUNTIMEINLINE PyObject * -_SWIG_Py_None(void) -{ - PyObject *none = Py_BuildValue((char*)""); - Py_DECREF(none); - return none; -} -SWIGRUNTIME PyObject * -SWIG_Py_None(void) -{ - static PyObject *SWIG_STATIC_POINTER(none) = _SWIG_Py_None(); - return none; -} -#endif - -/* The python void return value */ - -SWIGRUNTIMEINLINE PyObject * -SWIG_Py_Void(void) -{ - PyObject *none = Py_None; - Py_INCREF(none); - return none; -} - -/* SwigPyClientData */ - -typedef struct { - PyObject *klass; - PyObject *newraw; - PyObject *newargs; - PyObject *destroy; - int delargs; - int implicitconv; -} SwigPyClientData; - -SWIGRUNTIMEINLINE int -SWIG_Python_CheckImplicit(swig_type_info *ty) -{ - SwigPyClientData *data = (SwigPyClientData *)ty->clientdata; - return data ? data->implicitconv : 0; -} - -SWIGRUNTIMEINLINE PyObject * -SWIG_Python_ExceptionType(swig_type_info *desc) { - SwigPyClientData *data = desc ? (SwigPyClientData *) desc->clientdata : 0; - PyObject *klass = data ? data->klass : 0; - return (klass ? klass : PyExc_RuntimeError); -} - - -SWIGRUNTIME SwigPyClientData * -SwigPyClientData_New(PyObject* obj) -{ - if (!obj) { - return 0; - } else { - SwigPyClientData *data = (SwigPyClientData *)malloc(sizeof(SwigPyClientData)); - /* the klass element */ - data->klass = obj; - Py_INCREF(data->klass); - /* 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); - } else { -#if (PY_VERSION_HEX < 0x02020000) - data->newraw = 0; -#else - data->newraw = PyObject_GetAttrString(data->klass, (char *)"__new__"); -#endif - if (data->newraw) { - Py_INCREF(data->newraw); - data->newargs = PyTuple_New(1); - PyTuple_SetItem(data->newargs, 0, obj); - } else { - data->newargs = obj; - } - Py_INCREF(data->newargs); - } - /* the destroy method, aka as the C++ delete method */ - data->destroy = PyObject_GetAttrString(data->klass, (char *)"__swig_destroy__"); - if (PyErr_Occurred()) { - PyErr_Clear(); - data->destroy = 0; - } - if (data->destroy) { - int flags; - Py_INCREF(data->destroy); - flags = PyCFunction_GET_FLAGS(data->destroy); -#ifdef METH_O - data->delargs = !(flags & (METH_O)); -#else - data->delargs = 0; -#endif - } else { - data->delargs = 0; - } - data->implicitconv = 0; - return data; - } -} - -SWIGRUNTIME void -SwigPyClientData_Del(SwigPyClientData* data) -{ - Py_XDECREF(data->newraw); - Py_XDECREF(data->newargs); - Py_XDECREF(data->destroy); -} - -/* =============== SwigPyObject =====================*/ - -typedef struct { - PyObject_HEAD - void *ptr; - swig_type_info *ty; - int own; - PyObject *next; -} SwigPyObject; - -SWIGRUNTIME PyObject * -SwigPyObject_long(SwigPyObject *v) -{ - return PyLong_FromVoidPtr(v->ptr); -} - -SWIGRUNTIME PyObject * -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); - if (ofmt) { -#if PY_VERSION_HEX >= 0x03000000 - res = PyUnicode_Format(ofmt,args); -#else - res = PyString_Format(ofmt,args); -#endif - Py_DECREF(ofmt); - } - Py_DECREF(args); - } - } - return res; -} - -SWIGRUNTIME PyObject * -SwigPyObject_oct(SwigPyObject *v) -{ - return SwigPyObject_format("%o",v); -} - -SWIGRUNTIME PyObject * -SwigPyObject_hex(SwigPyObject *v) -{ - return SwigPyObject_format("%x",v); -} - -SWIGRUNTIME PyObject * -#ifdef METH_NOARGS -SwigPyObject_repr(SwigPyObject *v) -#else -SwigPyObject_repr(SwigPyObject *v, PyObject *args) -#endif -{ - const char *name = SWIG_TypePrettyName(v->ty); - PyObject *repr = SWIG_Python_str_FromFormat("", name, v); - if (v->next) { -#ifdef METH_NOARGS - PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next); -#else - PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next, args); -#endif -#if PY_VERSION_HEX >= 0x03000000 - PyObject *joined = PyUnicode_Concat(repr, nrep); - Py_DecRef(repr); - Py_DecRef(nrep); - repr = joined; -#else - PyString_ConcatAndDel(&repr,nrep); -#endif - } - return repr; -} - -SWIGRUNTIME int -SwigPyObject_print(SwigPyObject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) -{ - char *str; -#ifdef METH_NOARGS - PyObject *repr = SwigPyObject_repr(v); -#else - PyObject *repr = SwigPyObject_repr(v, NULL); -#endif - if (repr) { - str = SWIG_Python_str_AsChar(repr); - fputs(str, fp); - SWIG_Python_str_DelForPy3(str); - Py_DECREF(repr); - return 0; - } else { - return 1; - } -} - -SWIGRUNTIME PyObject * -SwigPyObject_str(SwigPyObject *v) -{ - char result[SWIG_BUFFER_SIZE]; - return SWIG_PackVoidPtr(result, v->ptr, v->ty->name, sizeof(result)) ? - SWIG_Python_str_FromChar(result) : 0; -} - -SWIGRUNTIME int -SwigPyObject_compare(SwigPyObject *v, SwigPyObject *w) -{ - void *i = v->ptr; - void *j = w->ptr; - return (i < j) ? -1 : ((i > j) ? 1 : 0); -} - -/* Added for Python 3.x, would it also be useful for Python 2.x? */ -SWIGRUNTIME PyObject* -SwigPyObject_richcompare(SwigPyObject *v, SwigPyObject *w, int op) -{ - PyObject* res; - if( op != Py_EQ && op != Py_NE ) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - if( (SwigPyObject_compare(v, w)==0) == (op == Py_EQ) ) - res = Py_True; - else - res = Py_False; - Py_INCREF(res); - return res; -} - - -SWIGRUNTIME PyTypeObject* _PySwigObject_type(void); - -SWIGRUNTIME PyTypeObject* -SwigPyObject_type(void) { - static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigObject_type(); - return type; -} - -SWIGRUNTIMEINLINE int -SwigPyObject_Check(PyObject *op) { - return (Py_TYPE(op) == SwigPyObject_type()) - || (strcmp(Py_TYPE(op)->tp_name,"SwigPyObject") == 0); -} - -SWIGRUNTIME PyObject * -SwigPyObject_New(void *ptr, swig_type_info *ty, int own); - -SWIGRUNTIME void -SwigPyObject_dealloc(PyObject *v) -{ - SwigPyObject *sobj = (SwigPyObject *) v; - PyObject *next = sobj->next; - if (sobj->own == SWIG_POINTER_OWN) { - swig_type_info *ty = sobj->ty; - SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; - PyObject *destroy = data ? data->destroy : 0; - if (destroy) { - /* destroy is always a VARARGS method */ - PyObject *res; - 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); - } else { - PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); - PyObject *mself = PyCFunction_GET_SELF(destroy); - res = ((*meth)(mself, v)); - } - Py_XDECREF(res); - } -#if !defined(SWIG_PYTHON_SILENT_MEMLEAK) - else { - const char *name = SWIG_TypePrettyName(ty); - printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown")); - } -#endif - } - Py_XDECREF(next); - PyObject_DEL(v); -} - -SWIGRUNTIME PyObject* -SwigPyObject_append(PyObject* v, PyObject* next) -{ - SwigPyObject *sobj = (SwigPyObject *) v; -#ifndef METH_O - PyObject *tmp = 0; - if (!PyArg_ParseTuple(next,(char *)"O:append", &tmp)) return NULL; - next = tmp; -#endif - if (!SwigPyObject_Check(next)) { - return NULL; - } - sobj->next = next; - Py_INCREF(next); - return SWIG_Py_Void(); -} - -SWIGRUNTIME PyObject* -#ifdef METH_NOARGS -SwigPyObject_next(PyObject* v) -#else -SwigPyObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) -#endif -{ - SwigPyObject *sobj = (SwigPyObject *) v; - if (sobj->next) { - Py_INCREF(sobj->next); - return sobj->next; - } else { - return SWIG_Py_Void(); - } -} - -SWIGINTERN PyObject* -#ifdef METH_NOARGS -SwigPyObject_disown(PyObject *v) -#else -SwigPyObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) -#endif -{ - SwigPyObject *sobj = (SwigPyObject *)v; - sobj->own = 0; - return SWIG_Py_Void(); -} - -SWIGINTERN PyObject* -#ifdef METH_NOARGS -SwigPyObject_acquire(PyObject *v) -#else -SwigPyObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) -#endif -{ - SwigPyObject *sobj = (SwigPyObject *)v; - sobj->own = SWIG_POINTER_OWN; - return SWIG_Py_Void(); -} - -SWIGINTERN PyObject* -SwigPyObject_own(PyObject *v, PyObject *args) -{ - PyObject *val = 0; -#if (PY_VERSION_HEX < 0x02020000) - if (!PyArg_ParseTuple(args,(char *)"|O:own",&val)) -#else - if (!PyArg_UnpackTuple(args, (char *)"own", 0, 1, &val)) -#endif - { - return NULL; - } - else - { - SwigPyObject *sobj = (SwigPyObject *)v; - PyObject *obj = PyBool_FromLong(sobj->own); - if (val) { -#ifdef METH_NOARGS - if (PyObject_IsTrue(val)) { - SwigPyObject_acquire(v); - } else { - SwigPyObject_disown(v); - } -#else - if (PyObject_IsTrue(val)) { - SwigPyObject_acquire(v,args); - } else { - SwigPyObject_disown(v,args); - } -#endif - } - return obj; - } -} - -#ifdef METH_O -static PyMethodDef -swigobject_methods[] = { - {(char *)"disown", (PyCFunction)SwigPyObject_disown, METH_NOARGS, (char *)"releases ownership of the pointer"}, - {(char *)"acquire", (PyCFunction)SwigPyObject_acquire, METH_NOARGS, (char *)"aquires ownership of the pointer"}, - {(char *)"own", (PyCFunction)SwigPyObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, - {(char *)"append", (PyCFunction)SwigPyObject_append, METH_O, (char *)"appends another 'this' object"}, - {(char *)"next", (PyCFunction)SwigPyObject_next, METH_NOARGS, (char *)"returns the next 'this' object"}, - {(char *)"__repr__",(PyCFunction)SwigPyObject_repr, METH_NOARGS, (char *)"returns object representation"}, - {0, 0, 0, 0} -}; -#else -static PyMethodDef -swigobject_methods[] = { - {(char *)"disown", (PyCFunction)SwigPyObject_disown, METH_VARARGS, (char *)"releases ownership of the pointer"}, - {(char *)"acquire", (PyCFunction)SwigPyObject_acquire, METH_VARARGS, (char *)"aquires ownership of the pointer"}, - {(char *)"own", (PyCFunction)SwigPyObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, - {(char *)"append", (PyCFunction)SwigPyObject_append, METH_VARARGS, (char *)"appends another 'this' object"}, - {(char *)"next", (PyCFunction)SwigPyObject_next, METH_VARARGS, (char *)"returns the next 'this' object"}, - {(char *)"__repr__",(PyCFunction)SwigPyObject_repr, METH_VARARGS, (char *)"returns object representation"}, - {0, 0, 0, 0} -}; -#endif - -#if PY_VERSION_HEX < 0x02020000 -SWIGINTERN PyObject * -SwigPyObject_getattr(SwigPyObject *sobj,char *name) -{ - return Py_FindMethod(swigobject_methods, (PyObject *)sobj, name); -} -#endif - -SWIGRUNTIME PyTypeObject* -_PySwigObject_type(void) { - static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer"; - - static PyNumberMethods SwigPyObject_as_number = { - (binaryfunc)0, /*nb_add*/ - (binaryfunc)0, /*nb_subtract*/ - (binaryfunc)0, /*nb_multiply*/ - /* nb_divide removed in Python 3 */ -#if PY_VERSION_HEX < 0x03000000 - (binaryfunc)0, /*nb_divide*/ -#endif - (binaryfunc)0, /*nb_remainder*/ - (binaryfunc)0, /*nb_divmod*/ - (ternaryfunc)0,/*nb_power*/ - (unaryfunc)0, /*nb_negative*/ - (unaryfunc)0, /*nb_positive*/ - (unaryfunc)0, /*nb_absolute*/ - (inquiry)0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ -#if PY_VERSION_HEX < 0x03000000 - 0, /*nb_coerce*/ -#endif - (unaryfunc)SwigPyObject_long, /*nb_int*/ -#if PY_VERSION_HEX < 0x03000000 - (unaryfunc)SwigPyObject_long, /*nb_long*/ -#else - 0, /*nb_reserved*/ -#endif - (unaryfunc)0, /*nb_float*/ -#if PY_VERSION_HEX < 0x03000000 - (unaryfunc)SwigPyObject_oct, /*nb_oct*/ - (unaryfunc)SwigPyObject_hex, /*nb_hex*/ -#endif -#if PY_VERSION_HEX >= 0x03000000 /* 3.0 */ - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index, nb_inplace_divide removed */ -#elif PY_VERSION_HEX >= 0x02050000 /* 2.5.0 */ - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */ -#elif PY_VERSION_HEX >= 0x02020000 /* 2.2.0 */ - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_true_divide */ -#elif PY_VERSION_HEX >= 0x02000000 /* 2.0.0 */ - 0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_or */ -#endif - }; - - static PyTypeObject swigpyobject_type; - static int type_init = 0; - if (!type_init) { - const PyTypeObject tmp - = { - /* PyObject header changed in Python 3 */ -#if PY_VERSION_HEX >= 0x03000000 - PyVarObject_HEAD_INIT(&PyType_Type, 0) -#else - PyObject_HEAD_INIT(NULL) - 0, /* ob_size */ -#endif - (char *)"SwigPyObject", /* tp_name */ - sizeof(SwigPyObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)SwigPyObject_dealloc, /* tp_dealloc */ - (printfunc)SwigPyObject_print, /* tp_print */ -#if PY_VERSION_HEX < 0x02020000 - (getattrfunc)SwigPyObject_getattr, /* tp_getattr */ -#else - (getattrfunc)0, /* tp_getattr */ -#endif - (setattrfunc)0, /* tp_setattr */ -#if PY_VERSION_HEX >= 0x03000000 - 0, /* tp_reserved in 3.0.1, tp_compare in 3.0.0 but not used */ -#else - (cmpfunc)SwigPyObject_compare, /* tp_compare */ -#endif - (reprfunc)SwigPyObject_repr, /* tp_repr */ - &SwigPyObject_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)0, /* tp_hash */ - (ternaryfunc)0, /* tp_call */ - (reprfunc)SwigPyObject_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - swigobject_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - (richcmpfunc)SwigPyObject_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ -#if PY_VERSION_HEX >= 0x02020000 - 0, /* tp_iter */ - 0, /* tp_iternext */ - swigobject_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ - 0, /* tp_is_gc */ - 0, /* tp_bases */ - 0, /* tp_mro */ - 0, /* tp_cache */ - 0, /* tp_subclasses */ - 0, /* tp_weaklist */ -#endif -#if PY_VERSION_HEX >= 0x02030000 - 0, /* tp_del */ -#endif -#ifdef COUNT_ALLOCS - 0,0,0,0 /* tp_alloc -> tp_next */ -#endif - }; - swigpyobject_type = tmp; - /* for Python 3 we already assigned ob_type in PyVarObject_HEAD_INIT() */ -#if PY_VERSION_HEX < 0x03000000 - swigpyobject_type.ob_type = &PyType_Type; -#endif - type_init = 1; - } - return &swigpyobject_type; -} - -SWIGRUNTIME PyObject * -SwigPyObject_New(void *ptr, swig_type_info *ty, int own) -{ - SwigPyObject *sobj = PyObject_NEW(SwigPyObject, SwigPyObject_type()); - if (sobj) { - sobj->ptr = ptr; - sobj->ty = ty; - sobj->own = own; - sobj->next = 0; - } - return (PyObject *)sobj; -} - -/* ----------------------------------------------------------------------------- - * Implements a simple Swig Packed type, and use it instead of string - * ----------------------------------------------------------------------------- */ - -typedef struct { - PyObject_HEAD - void *pack; - swig_type_info *ty; - size_t size; -} SwigPyPacked; - -SWIGRUNTIME int -SwigPyPacked_print(SwigPyPacked *v, FILE *fp, int SWIGUNUSEDPARM(flags)) -{ - char result[SWIG_BUFFER_SIZE]; - fputs("pack, v->size, 0, sizeof(result))) { - fputs("at ", fp); - fputs(result, fp); - } - fputs(v->ty->name,fp); - fputs(">", fp); - return 0; -} - -SWIGRUNTIME PyObject * -SwigPyPacked_repr(SwigPyPacked *v) -{ - char result[SWIG_BUFFER_SIZE]; - if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { - return SWIG_Python_str_FromFormat("", result, v->ty->name); - } else { - return SWIG_Python_str_FromFormat("", v->ty->name); - } -} - -SWIGRUNTIME PyObject * -SwigPyPacked_str(SwigPyPacked *v) -{ - char result[SWIG_BUFFER_SIZE]; - if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){ - return SWIG_Python_str_FromFormat("%s%s", result, v->ty->name); - } else { - return SWIG_Python_str_FromChar(v->ty->name); - } -} - -SWIGRUNTIME int -SwigPyPacked_compare(SwigPyPacked *v, SwigPyPacked *w) -{ - size_t i = v->size; - size_t j = w->size; - int s = (i < j) ? -1 : ((i > j) ? 1 : 0); - return s ? s : strncmp((char *)v->pack, (char *)w->pack, 2*v->size); -} - -SWIGRUNTIME PyTypeObject* _PySwigPacked_type(void); - -SWIGRUNTIME PyTypeObject* -SwigPyPacked_type(void) { - static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigPacked_type(); - return type; -} - -SWIGRUNTIMEINLINE int -SwigPyPacked_Check(PyObject *op) { - return ((op)->ob_type == _PySwigPacked_type()) - || (strcmp((op)->ob_type->tp_name,"SwigPyPacked") == 0); -} - -SWIGRUNTIME void -SwigPyPacked_dealloc(PyObject *v) -{ - if (SwigPyPacked_Check(v)) { - SwigPyPacked *sobj = (SwigPyPacked *) v; - free(sobj->pack); - } - PyObject_DEL(v); -} - -SWIGRUNTIME PyTypeObject* -_PySwigPacked_type(void) { - static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer"; - static PyTypeObject swigpypacked_type; - static int type_init = 0; - if (!type_init) { - const PyTypeObject tmp - = { - /* PyObject header changed in Python 3 */ -#if PY_VERSION_HEX>=0x03000000 - PyVarObject_HEAD_INIT(&PyType_Type, 0) -#else - PyObject_HEAD_INIT(NULL) - 0, /* ob_size */ -#endif - (char *)"SwigPyPacked", /* tp_name */ - sizeof(SwigPyPacked), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)SwigPyPacked_dealloc, /* tp_dealloc */ - (printfunc)SwigPyPacked_print, /* tp_print */ - (getattrfunc)0, /* tp_getattr */ - (setattrfunc)0, /* tp_setattr */ -#if PY_VERSION_HEX>=0x03000000 - 0, /* tp_reserved in 3.0.1 */ -#else - (cmpfunc)SwigPyPacked_compare, /* tp_compare */ -#endif - (reprfunc)SwigPyPacked_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)0, /* tp_hash */ - (ternaryfunc)0, /* tp_call */ - (reprfunc)SwigPyPacked_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - swigpacked_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ -#if PY_VERSION_HEX >= 0x02020000 - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ - 0, /* tp_is_gc */ - 0, /* tp_bases */ - 0, /* tp_mro */ - 0, /* tp_cache */ - 0, /* tp_subclasses */ - 0, /* tp_weaklist */ -#endif -#if PY_VERSION_HEX >= 0x02030000 - 0, /* tp_del */ -#endif -#ifdef COUNT_ALLOCS - 0,0,0,0 /* tp_alloc -> tp_next */ -#endif - }; - swigpypacked_type = tmp; - /* for Python 3 the ob_type already assigned in PyVarObject_HEAD_INIT() */ -#if PY_VERSION_HEX < 0x03000000 - swigpypacked_type.ob_type = &PyType_Type; -#endif - type_init = 1; - } - return &swigpypacked_type; -} - -SWIGRUNTIME PyObject * -SwigPyPacked_New(void *ptr, size_t size, swig_type_info *ty) -{ - SwigPyPacked *sobj = PyObject_NEW(SwigPyPacked, SwigPyPacked_type()); - if (sobj) { - void *pack = malloc(size); - if (pack) { - memcpy(pack, ptr, size); - sobj->pack = pack; - sobj->ty = ty; - sobj->size = size; - } else { - PyObject_DEL((PyObject *) sobj); - sobj = 0; - } - } - return (PyObject *) sobj; -} - -SWIGRUNTIME swig_type_info * -SwigPyPacked_UnpackData(PyObject *obj, void *ptr, size_t size) -{ - if (SwigPyPacked_Check(obj)) { - SwigPyPacked *sobj = (SwigPyPacked *)obj; - if (sobj->size != size) return 0; - memcpy(ptr, sobj->pack, size); - return sobj->ty; - } else { - return 0; - } -} - -/* ----------------------------------------------------------------------------- - * pointers/data manipulation - * ----------------------------------------------------------------------------- */ - -SWIGRUNTIMEINLINE PyObject * -_SWIG_This(void) -{ - return SWIG_Python_str_FromChar("this"); -} - -SWIGRUNTIME PyObject * -SWIG_This(void) -{ - static PyObject *SWIG_STATIC_POINTER(swig_this) = _SWIG_This(); - return swig_this; -} - -/* #define SWIG_PYTHON_SLOW_GETSET_THIS */ - -/* TODO: I don't know how to implement the fast getset in Python 3 right now */ -#if PY_VERSION_HEX>=0x03000000 -#define SWIG_PYTHON_SLOW_GETSET_THIS -#endif - -SWIGRUNTIME SwigPyObject * -SWIG_Python_GetSwigThis(PyObject *pyobj) -{ - if (SwigPyObject_Check(pyobj)) { - return (SwigPyObject *) pyobj; - } else { - PyObject *obj = 0; -#if (!defined(SWIG_PYTHON_SLOW_GETSET_THIS) && (PY_VERSION_HEX >= 0x02030000)) - if (PyInstance_Check(pyobj)) { - obj = _PyInstance_Lookup(pyobj, SWIG_This()); - } else { - PyObject **dictptr = _PyObject_GetDictPtr(pyobj); - if (dictptr != NULL) { - PyObject *dict = *dictptr; - obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0; - } else { -#ifdef PyWeakref_CheckProxy - if (PyWeakref_CheckProxy(pyobj)) { - PyObject *wobj = PyWeakref_GET_OBJECT(pyobj); - return wobj ? SWIG_Python_GetSwigThis(wobj) : 0; - } -#endif - obj = PyObject_GetAttr(pyobj,SWIG_This()); - if (obj) { - Py_DECREF(obj); - } else { - if (PyErr_Occurred()) PyErr_Clear(); - return 0; - } - } - } -#else - obj = PyObject_GetAttr(pyobj,SWIG_This()); - if (obj) { - Py_DECREF(obj); - } else { - if (PyErr_Occurred()) PyErr_Clear(); - return 0; - } -#endif - if (obj && !SwigPyObject_Check(obj)) { - /* a PyObject is called 'this', try to get the 'real this' - SwigPyObject from it */ - return SWIG_Python_GetSwigThis(obj); - } - return (SwigPyObject *)obj; - } -} - -/* Acquire a pointer value */ - -SWIGRUNTIME int -SWIG_Python_AcquirePtr(PyObject *obj, int own) { - if (own == SWIG_POINTER_OWN) { - SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj); - if (sobj) { - int oldown = sobj->own; - sobj->own = own; - return oldown; - } - } - return 0; -} - -/* Convert a pointer value */ - -SWIGRUNTIME int -SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) { - if (!obj) return SWIG_ERROR; - if (obj == Py_None) { - if (ptr) *ptr = 0; - return SWIG_OK; - } else { - SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj); - if (own) - *own = 0; - while (sobj) { - void *vptr = sobj->ptr; - if (ty) { - swig_type_info *to = sobj->ty; - if (to == ty) { - /* no type cast needed */ - if (ptr) *ptr = vptr; - break; - } else { - swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); - if (!tc) { - sobj = (SwigPyObject *)sobj->next; - } else { - if (ptr) { - int newmemory = 0; - *ptr = SWIG_TypeCast(tc,vptr,&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 = *own | SWIG_CAST_NEW_MEMORY; - } - } - break; - } - } - } else { - if (ptr) *ptr = vptr; - break; - } - } - if (sobj) { - if (own) - *own = *own | sobj->own; - if (flags & SWIG_POINTER_DISOWN) { - sobj->own = 0; - } - return SWIG_OK; - } else { - int res = SWIG_ERROR; - if (flags & SWIG_POINTER_IMPLICIT_CONV) { - SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; - if (data && !data->implicitconv) { - PyObject *klass = data->klass; - if (klass) { - PyObject *impconv; - data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/ - impconv = SWIG_Python_CallFunctor(klass, obj); - data->implicitconv = 0; - if (PyErr_Occurred()) { - PyErr_Clear(); - impconv = 0; - } - if (impconv) { - SwigPyObject *iobj = SWIG_Python_GetSwigThis(impconv); - if (iobj) { - void *vptr; - res = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0); - if (SWIG_IsOK(res)) { - if (ptr) { - *ptr = vptr; - /* transfer the ownership to 'ptr' */ - iobj->own = 0; - res = SWIG_AddCast(res); - res = SWIG_AddNewMask(res); - } else { - res = SWIG_AddCast(res); - } - } - } - Py_DECREF(impconv); - } - } - } - } - return res; - } - } -} - -/* Convert a function ptr value */ - -SWIGRUNTIME int -SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) { - if (!PyCFunction_Check(obj)) { - return SWIG_ConvertPtr(obj, ptr, ty, 0); - } else { - void *vptr = 0; - - /* here we get the method pointer for callbacks */ - const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc); - const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0; - if (desc) - desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0; - if (!desc) - return SWIG_ERROR; - if (ty) { - swig_cast_info *tc = SWIG_TypeCheck(desc,ty); - if (tc) { - int newmemory = 0; - *ptr = SWIG_TypeCast(tc,vptr,&newmemory); - assert(!newmemory); /* newmemory handling not yet implemented */ - } else { - return SWIG_ERROR; - } - } else { - *ptr = vptr; - } - return SWIG_OK; - } -} - -/* Convert a packed value value */ - -SWIGRUNTIME int -SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) { - swig_type_info *to = SwigPyPacked_UnpackData(obj, ptr, sz); - if (!to) return SWIG_ERROR; - if (ty) { - if (to != ty) { - /* check type cast? */ - swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); - if (!tc) return SWIG_ERROR; - } - } - return SWIG_OK; -} - -/* ----------------------------------------------------------------------------- - * Create a new pointer object - * ----------------------------------------------------------------------------- */ - -/* - Create a new instance object, without calling __init__, and set the - 'this' attribute. -*/ - -SWIGRUNTIME PyObject* -SWIG_Python_NewShadowInstance(SwigPyClientData *data, PyObject *swig_this) -{ -#if (PY_VERSION_HEX >= 0x02020000) - PyObject *inst = 0; - PyObject *newraw = data->newraw; - if (newraw) { - inst = PyObject_Call(newraw, data->newargs, NULL); - if (inst) { -#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); - } - } -#else - PyObject *key = SWIG_This(); - PyObject_SetAttr(inst, key, swig_this); -#endif - } - } else { -#if PY_VERSION_HEX >= 0x03000000 - inst = PyBaseObject_Type.tp_new((PyTypeObject*) data->newargs, Py_None, Py_None); - PyObject_SetAttr(inst, SWIG_This(), swig_this); - Py_TYPE(inst)->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG; -#else - PyObject *dict = PyDict_New(); - PyDict_SetItem(dict, SWIG_This(), swig_this); - inst = PyInstance_NewRaw(data->newargs, dict); - Py_DECREF(dict); -#endif - } - return inst; -#else -#if (PY_VERSION_HEX >= 0x02010000) - PyObject *inst; - PyObject *dict = PyDict_New(); - PyDict_SetItem(dict, SWIG_This(), swig_this); - inst = PyInstance_NewRaw(data->newargs, dict); - Py_DECREF(dict); - return (PyObject *) inst; -#else - PyInstanceObject *inst = PyObject_NEW(PyInstanceObject, &PyInstance_Type); - if (inst == NULL) { - return NULL; - } - inst->in_class = (PyClassObject *)data->newargs; - Py_INCREF(inst->in_class); - inst->in_dict = PyDict_New(); - if (inst->in_dict == NULL) { - Py_DECREF(inst); - return NULL; - } -#ifdef Py_TPFLAGS_HAVE_WEAKREFS - inst->in_weakreflist = NULL; -#endif -#ifdef Py_TPFLAGS_GC - PyObject_GC_Init(inst); -#endif - PyDict_SetItem(inst->in_dict, SWIG_This(), swig_this); - return (PyObject *) inst; -#endif -#endif -} - -SWIGRUNTIME void -SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this) -{ - PyObject *dict; -#if (PY_VERSION_HEX >= 0x02020000) && !defined(SWIG_PYTHON_SLOW_GETSET_THIS) - PyObject **dictptr = _PyObject_GetDictPtr(inst); - if (dictptr != NULL) { - dict = *dictptr; - if (dict == NULL) { - dict = PyDict_New(); - *dictptr = dict; - } - PyDict_SetItem(dict, SWIG_This(), swig_this); - return; - } -#endif - dict = PyObject_GetAttrString(inst, (char*)"__dict__"); - PyDict_SetItem(dict, SWIG_This(), swig_this); - Py_DECREF(dict); -} - - -SWIGINTERN PyObject * -SWIG_Python_InitShadowInstance(PyObject *args) { - PyObject *obj[2]; - if (!SWIG_Python_UnpackTuple(args,(char*)"swiginit", 2, 2, obj)) { - return NULL; - } else { - SwigPyObject *sthis = SWIG_Python_GetSwigThis(obj[0]); - if (sthis) { - SwigPyObject_append((PyObject*) sthis, obj[1]); - } else { - SWIG_Python_SetSwigThis(obj[0], obj[1]); - } - return SWIG_Py_Void(); - } -} - -/* Create a new pointer object */ - -SWIGRUNTIME PyObject * -SWIG_Python_NewPointerObj(void *ptr, swig_type_info *type, int flags) { - if (!ptr) { - return SWIG_Py_Void(); - } else { - int own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0; - PyObject *robj = SwigPyObject_New(ptr, type, own); - SwigPyClientData *clientdata = type ? (SwigPyClientData *)(type->clientdata) : 0; - if (clientdata && !(flags & SWIG_POINTER_NOSHADOW)) { - PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj); - if (inst) { - Py_DECREF(robj); - robj = inst; - } - } - return robj; - } -} - -/* Create a new packed object */ - -SWIGRUNTIMEINLINE PyObject * -SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) { - return ptr ? SwigPyPacked_New((void *) ptr, sz, type) : SWIG_Py_Void(); -} - -/* -----------------------------------------------------------------------------* - * Get type list - * -----------------------------------------------------------------------------*/ - -#ifdef SWIG_LINK_RUNTIME -void *SWIG_ReturnGlobalTypeList(void *); -#endif - -SWIGRUNTIME swig_module_info * -SWIG_Python_GetModule(void) { - static void *type_pointer = (void *)0; - /* first check if module already created */ - if (!type_pointer) { -#ifdef SWIG_LINK_RUNTIME - type_pointer = SWIG_ReturnGlobalTypeList((void *)0); -#else - type_pointer = PyCObject_Import((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, - (char*)"type_pointer" SWIG_TYPE_TABLE_NAME); - if (PyErr_Occurred()) { - PyErr_Clear(); - type_pointer = (void *)0; - } -#endif - } - return (swig_module_info *) type_pointer; -} - -#if PY_MAJOR_VERSION < 2 -/* PyModule_AddObject function was introduced in Python 2.0. The following function - is copied out of Python/modsupport.c in python version 2.3.4 */ -SWIGINTERN int -PyModule_AddObject(PyObject *m, char *name, PyObject *o) -{ - PyObject *dict; - if (!PyModule_Check(m)) { - PyErr_SetString(PyExc_TypeError, - "PyModule_AddObject() needs module as first arg"); - return SWIG_ERROR; - } - if (!o) { - PyErr_SetString(PyExc_TypeError, - "PyModule_AddObject() needs non-NULL value"); - return SWIG_ERROR; - } - - dict = PyModule_GetDict(m); - if (dict == NULL) { - /* Internal error -- modules must have a dict! */ - PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__", - PyModule_GetName(m)); - return SWIG_ERROR; - } - if (PyDict_SetItemString(dict, name, o)) - return SWIG_ERROR; - Py_DECREF(o); - return SWIG_OK; -} -#endif - -SWIGRUNTIME void -SWIG_Python_DestroyModule(void *vptr) -{ - swig_module_info *swig_module = (swig_module_info *) vptr; - swig_type_info **types = swig_module->types; - size_t i; - for (i =0; i < swig_module->size; ++i) { - swig_type_info *ty = types[i]; - if (ty->owndata) { - SwigPyClientData *data = (SwigPyClientData *) ty->clientdata; - if (data) SwigPyClientData_Del(data); - } - } - Py_DECREF(SWIG_This()); -} - -SWIGRUNTIME void -SWIG_Python_SetModule(swig_module_info *swig_module) { - static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} };/* Sentinel */ - -#if PY_VERSION_HEX >= 0x03000000 - /* Add a dummy module object into sys.modules */ - PyObject *module = PyImport_AddModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION); -#else - PyObject *module = Py_InitModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, - swig_empty_runtime_method_table); -#endif - PyObject *pointer = PyCObject_FromVoidPtr((void *) swig_module, SWIG_Python_DestroyModule); - if (pointer && module) { - PyModule_AddObject(module, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME, 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) -{ - PyObject *cache = SWIG_Python_TypeCache(); - PyObject *key = SWIG_Python_str_FromChar(type); - PyObject *obj = PyDict_GetItem(cache, key); - swig_type_info *descriptor; - if (obj) { - descriptor = (swig_type_info *) PyCObject_AsVoidPtr(obj); - } else { - swig_module_info *swig_module = SWIG_Python_GetModule(); - descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type); - if (descriptor) { - obj = PyCObject_FromVoidPtr(descriptor, NULL); - PyDict_SetItem(cache, key, obj); - Py_DECREF(obj); - } - } - Py_DECREF(key); - return descriptor; -} - -/* - For backward compatibility only -*/ -#define SWIG_POINTER_EXCEPTION 0 -#define SWIG_arg_fail(arg) SWIG_Python_ArgFail(arg) -#define SWIG_MustGetPtr(p, type, argnum, flags) SWIG_Python_MustGetPtr(p, type, argnum, flags) - -SWIGRUNTIME int -SWIG_Python_AddErrMesg(const char* mesg, int infront) -{ - if (PyErr_Occurred()) { - PyObject *type = 0; - PyObject *value = 0; - PyObject *traceback = 0; - PyErr_Fetch(&type, &value, &traceback); - if (value) { - char *tmp; - PyObject *old_str = PyObject_Str(value); - Py_XINCREF(type); - PyErr_Clear(); - if (infront) { - PyErr_Format(type, "%s %s", mesg, tmp = SWIG_Python_str_AsChar(old_str)); - } else { - PyErr_Format(type, "%s %s", tmp = SWIG_Python_str_AsChar(old_str), mesg); - } - SWIG_Python_str_DelForPy3(tmp); - Py_DECREF(old_str); - } - return 1; - } else { - return 0; - } -} - -SWIGRUNTIME int -SWIG_Python_ArgFail(int argnum) -{ - if (PyErr_Occurred()) { - /* add information about failing argument */ - char mesg[256]; - PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum); - return SWIG_Python_AddErrMesg(mesg, 1); - } else { - return 0; - } -} - -SWIGRUNTIMEINLINE const char * -SwigPyObject_GetDesc(PyObject *self) -{ - SwigPyObject *v = (SwigPyObject *)self; - swig_type_info *ty = v ? v->ty : 0; - return ty ? ty->str : (char*)""; -} - -SWIGRUNTIME void -SWIG_Python_TypeError(const char *type, PyObject *obj) -{ - if (type) { -#if defined(SWIG_COBJECT_TYPES) - if (obj && SwigPyObject_Check(obj)) { - const char *otype = (const char *) SwigPyObject_GetDesc(obj); - if (otype) { - PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'SwigPyObject(%s)' is received", - type, otype); - return; - } - } else -#endif - { - const char *otype = (obj ? obj->ob_type->tp_name : 0); - if (otype) { - PyObject *str = PyObject_Str(obj); - const char *cstr = str ? SWIG_Python_str_AsChar(str) : 0; - if (cstr) { - PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received", - type, otype, cstr); - SWIG_Python_str_DelForPy3(cstr); - } else { - PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received", - type, otype); - } - Py_XDECREF(str); - return; - } - } - PyErr_Format(PyExc_TypeError, "a '%s' is expected", type); - } else { - PyErr_Format(PyExc_TypeError, "unexpected type is received"); - } -} - - -/* Convert a pointer value, signal an exception on a type mismatch */ -SWIGRUNTIME void * -SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) { - void *result; - if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) { - PyErr_Clear(); -#if SWIG_POINTER_EXCEPTION - if (flags) { - SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj); - SWIG_Python_ArgFail(argnum); - } -#endif - } - return result; -} - - -#ifdef __cplusplus -#if 0 -{ /* cc-mode */ -#endif -} -#endif - - - -#define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) - -#define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else - - - -/* -------- TYPES TABLE (BEGIN) -------- */ - -#define SWIGTYPE_p_P swig_types[0] -#define SWIGTYPE_p_char swig_types[1] -#define SWIGTYPE_p_point swig_types[2] -static swig_type_info *swig_types[4]; -static swig_module_info swig_module = {swig_types, 3, 0, 0, 0, 0}; -#define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) -#define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) - -/* -------- TYPES TABLE (END) -------- */ - -#if (PY_VERSION_HEX <= 0x02000000) -# if !defined(SWIG_PYTHON_CLASSIC) -# error "This python version requires swig to be run with the '-classic' option" -# endif -#endif - -/*----------------------------------------------- - @(target):= _cpp0x_unrestricted_unions.so - ------------------------------------------------*/ -#if PY_VERSION_HEX >= 0x03000000 -# define SWIG_init PyInit__cpp0x_unrestricted_unions - -#else -# define SWIG_init init_cpp0x_unrestricted_unions - -#endif -#define SWIG_name "_cpp0x_unrestricted_unions" - -#define SWIGVERSION 0x020001 -#define SWIG_VERSION SWIGVERSION - - -#define SWIG_as_voidptr(a) const_cast< void * >(static_cast< const void * >(a)) -#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),reinterpret_cast< void** >(a)) - - -#include - - -namespace swig { - class SwigPtr_PyObject { - protected: - PyObject *_obj; - - public: - SwigPtr_PyObject() :_obj(0) - { - } - - SwigPtr_PyObject(const SwigPtr_PyObject& item) : _obj(item._obj) - { - Py_XINCREF(_obj); - } - - SwigPtr_PyObject(PyObject *obj, bool initial_ref = true) :_obj(obj) - { - if (initial_ref) { - Py_XINCREF(_obj); - } - } - - SwigPtr_PyObject & operator=(const SwigPtr_PyObject& item) - { - Py_XINCREF(item._obj); - Py_XDECREF(_obj); - _obj = item._obj; - return *this; - } - - ~SwigPtr_PyObject() - { - Py_XDECREF(_obj); - } - - operator PyObject *() const - { - return _obj; - } - - PyObject *operator->() const - { - return _obj; - } - }; -} - - -namespace swig { - struct SwigVar_PyObject : SwigPtr_PyObject { - SwigVar_PyObject(PyObject* obj = 0) : SwigPtr_PyObject(obj, false) { } - - SwigVar_PyObject & operator = (PyObject* obj) - { - Py_XDECREF(_obj); - _obj = obj; - return *this; - } - }; -} - - -struct point { - point() {} - point(int x, int y) : x_(x), y_(y) {} - int x_, y_; -}; - -#include // For placement 'new' in the constructor below -union P { - int z; - double w; - point p; // Illegal in C++03; legal in C++11. - // Due to the point member, a constructor definition is required. - P() { - new(&p) point(); - } -} p1; - - -#include -#if !defined(SWIG_NO_LLONG_MAX) -# if !defined(LLONG_MAX) && defined(__GNUC__) && defined (__LONG_LONG_MAX__) -# define LLONG_MAX __LONG_LONG_MAX__ -# define LLONG_MIN (-LLONG_MAX - 1LL) -# define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL) -# endif -#endif - - -SWIGINTERN int -SWIG_AsVal_double (PyObject *obj, double *val) -{ - int res = SWIG_TypeError; - if (PyFloat_Check(obj)) { - if (val) *val = PyFloat_AsDouble(obj); - return SWIG_OK; - } else if (PyInt_Check(obj)) { - if (val) *val = PyInt_AsLong(obj); - return SWIG_OK; - } else if (PyLong_Check(obj)) { - double v = PyLong_AsDouble(obj); - if (!PyErr_Occurred()) { - if (val) *val = v; - return SWIG_OK; - } else { - PyErr_Clear(); - } - } -#ifdef SWIG_PYTHON_CAST_MODE - { - int dispatch = 0; - double d = PyFloat_AsDouble(obj); - if (!PyErr_Occurred()) { - if (val) *val = d; - return SWIG_AddCast(SWIG_OK); - } else { - PyErr_Clear(); - } - if (!dispatch) { - long v = PyLong_AsLong(obj); - if (!PyErr_Occurred()) { - if (val) *val = v; - return SWIG_AddCast(SWIG_AddCast(SWIG_OK)); - } else { - PyErr_Clear(); - } - } - } -#endif - return res; -} - - -#include - - -#include - - -SWIGINTERNINLINE int -SWIG_CanCastAsInteger(double *d, double min, double max) { - double x = *d; - if ((min <= x && x <= max)) { - double fx = floor(x); - double cx = ceil(x); - double rd = ((x - fx) < 0.5) ? fx : cx; /* simple rint */ - if ((errno == EDOM) || (errno == ERANGE)) { - errno = 0; - } else { - double summ, reps, diff; - if (rd < x) { - diff = x - rd; - } else if (rd > x) { - diff = rd - x; - } else { - return 1; - } - summ = rd + x; - reps = diff/summ; - if (reps < 8*DBL_EPSILON) { - *d = rd; - return 1; - } - } - } - return 0; -} - - -SWIGINTERN int -SWIG_AsVal_long (PyObject *obj, long* val) -{ - if (PyInt_Check(obj)) { - if (val) *val = PyInt_AsLong(obj); - return SWIG_OK; - } else if (PyLong_Check(obj)) { - long v = PyLong_AsLong(obj); - if (!PyErr_Occurred()) { - if (val) *val = v; - return SWIG_OK; - } else { - PyErr_Clear(); - } - } -#ifdef SWIG_PYTHON_CAST_MODE - { - int dispatch = 0; - long v = PyInt_AsLong(obj); - if (!PyErr_Occurred()) { - if (val) *val = v; - return SWIG_AddCast(SWIG_OK); - } else { - PyErr_Clear(); - } - if (!dispatch) { - double d; - int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d)); - if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, LONG_MAX)) { - if (val) *val = (long)(d); - return res; - } - } - } -#endif - return SWIG_TypeError; -} - - -SWIGINTERN int -SWIG_AsVal_int (PyObject * obj, int *val) -{ - long v; - int res = SWIG_AsVal_long (obj, &v); - if (SWIG_IsOK(res)) { - if ((v < INT_MIN || v > INT_MAX)) { - return SWIG_OverflowError; - } else { - if (val) *val = static_cast< int >(v); - } - } - return res; -} - - - #define SWIG_From_long PyInt_FromLong - - -SWIGINTERNINLINE PyObject * -SWIG_From_int (int value) -{ - return SWIG_From_long (value); -} - - - #define SWIG_From_double PyFloat_FromDouble - -#ifdef __cplusplus -extern "C" { -#endif -SWIGINTERN PyObject *_wrap_new_point__SWIG_0(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - PyObject *resultobj = 0; - point *result = 0 ; - - if (!PyArg_ParseTuple(args,(char *)":new_point")) SWIG_fail; - result = (point *)new point(); - resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_point, SWIG_POINTER_NEW | 0 ); - return resultobj; -fail: - return NULL; -} - - -SWIGINTERN PyObject *_wrap_new_point__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - PyObject *resultobj = 0; - int arg1 ; - int arg2 ; - int val1 ; - int ecode1 = 0 ; - int val2 ; - int ecode2 = 0 ; - PyObject * obj0 = 0 ; - PyObject * obj1 = 0 ; - point *result = 0 ; - - if (!PyArg_ParseTuple(args,(char *)"OO:new_point",&obj0,&obj1)) SWIG_fail; - ecode1 = SWIG_AsVal_int(obj0, &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "new_point" "', argument " "1"" of type '" "int""'"); - } - arg1 = static_cast< int >(val1); - ecode2 = SWIG_AsVal_int(obj1, &val2); - if (!SWIG_IsOK(ecode2)) { - SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "new_point" "', argument " "2"" of type '" "int""'"); - } - arg2 = static_cast< int >(val2); - result = (point *)new point(arg1,arg2); - resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_point, SWIG_POINTER_NEW | 0 ); - return resultobj; -fail: - return NULL; -} - - -SWIGINTERN PyObject *_wrap_new_point(PyObject *self, PyObject *args) { - int argc; - PyObject *argv[3]; - int ii; - - if (!PyTuple_Check(args)) SWIG_fail; - argc = (int)PyObject_Length(args); - for (ii = 0; (ii < argc) && (ii < 2); ii++) { - argv[ii] = PyTuple_GET_ITEM(args,ii); - } - if (argc == 0) { - return _wrap_new_point__SWIG_0(self, args); - } - if (argc == 2) { - int _v; - { - int res = SWIG_AsVal_int(argv[0], NULL); - _v = SWIG_CheckState(res); - } - if (_v) { - { - int res = SWIG_AsVal_int(argv[1], NULL); - _v = SWIG_CheckState(res); - } - if (_v) { - return _wrap_new_point__SWIG_1(self, args); - } - } - } - -fail: - SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'new_point'.\n" - " Possible C/C++ prototypes are:\n" - " point()\n" - " point(int,int)\n"); - return NULL; -} - - -SWIGINTERN PyObject *_wrap_point_x__set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - PyObject *resultobj = 0; - point *arg1 = (point *) 0 ; - int arg2 ; - void *argp1 = 0 ; - int res1 = 0 ; - int val2 ; - int ecode2 = 0 ; - PyObject * obj0 = 0 ; - PyObject * obj1 = 0 ; - - if (!PyArg_ParseTuple(args,(char *)"OO:point_x__set",&obj0,&obj1)) SWIG_fail; - res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_point, 0 | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "point_x__set" "', argument " "1"" of type '" "point *""'"); - } - arg1 = reinterpret_cast< point * >(argp1); - ecode2 = SWIG_AsVal_int(obj1, &val2); - if (!SWIG_IsOK(ecode2)) { - SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "point_x__set" "', argument " "2"" of type '" "int""'"); - } - arg2 = static_cast< int >(val2); - if (arg1) (arg1)->x_ = arg2; - resultobj = SWIG_Py_Void(); - return resultobj; -fail: - return NULL; -} - - -SWIGINTERN PyObject *_wrap_point_x__get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - PyObject *resultobj = 0; - point *arg1 = (point *) 0 ; - void *argp1 = 0 ; - int res1 = 0 ; - PyObject * obj0 = 0 ; - int result; - - if (!PyArg_ParseTuple(args,(char *)"O:point_x__get",&obj0)) SWIG_fail; - res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_point, 0 | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "point_x__get" "', argument " "1"" of type '" "point *""'"); - } - arg1 = reinterpret_cast< point * >(argp1); - result = (int) ((arg1)->x_); - resultobj = SWIG_From_int(static_cast< int >(result)); - return resultobj; -fail: - return NULL; -} - - -SWIGINTERN PyObject *_wrap_point_y__set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - PyObject *resultobj = 0; - point *arg1 = (point *) 0 ; - int arg2 ; - void *argp1 = 0 ; - int res1 = 0 ; - int val2 ; - int ecode2 = 0 ; - PyObject * obj0 = 0 ; - PyObject * obj1 = 0 ; - - if (!PyArg_ParseTuple(args,(char *)"OO:point_y__set",&obj0,&obj1)) SWIG_fail; - res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_point, 0 | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "point_y__set" "', argument " "1"" of type '" "point *""'"); - } - arg1 = reinterpret_cast< point * >(argp1); - ecode2 = SWIG_AsVal_int(obj1, &val2); - if (!SWIG_IsOK(ecode2)) { - SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "point_y__set" "', argument " "2"" of type '" "int""'"); - } - arg2 = static_cast< int >(val2); - if (arg1) (arg1)->y_ = arg2; - resultobj = SWIG_Py_Void(); - return resultobj; -fail: - return NULL; -} - - -SWIGINTERN PyObject *_wrap_point_y__get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - PyObject *resultobj = 0; - point *arg1 = (point *) 0 ; - void *argp1 = 0 ; - int res1 = 0 ; - PyObject * obj0 = 0 ; - int result; - - if (!PyArg_ParseTuple(args,(char *)"O:point_y__get",&obj0)) SWIG_fail; - res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_point, 0 | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "point_y__get" "', argument " "1"" of type '" "point *""'"); - } - arg1 = reinterpret_cast< point * >(argp1); - result = (int) ((arg1)->y_); - resultobj = SWIG_From_int(static_cast< int >(result)); - return resultobj; -fail: - return NULL; -} - - -SWIGINTERN PyObject *_wrap_delete_point(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - PyObject *resultobj = 0; - point *arg1 = (point *) 0 ; - void *argp1 = 0 ; - int res1 = 0 ; - PyObject * obj0 = 0 ; - - if (!PyArg_ParseTuple(args,(char *)"O:delete_point",&obj0)) SWIG_fail; - res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_point, SWIG_POINTER_DISOWN | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_point" "', argument " "1"" of type '" "point *""'"); - } - arg1 = reinterpret_cast< point * >(argp1); - delete arg1; - resultobj = SWIG_Py_Void(); - return resultobj; -fail: - return NULL; -} - - -SWIGINTERN PyObject *point_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - PyObject *obj; - if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL; - SWIG_TypeNewClientData(SWIGTYPE_p_point, SWIG_NewClientData(obj)); - return SWIG_Py_Void(); -} - -SWIGINTERN PyObject *_wrap_P_z_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - PyObject *resultobj = 0; - P *arg1 = (P *) 0 ; - int arg2 ; - void *argp1 = 0 ; - int res1 = 0 ; - int val2 ; - int ecode2 = 0 ; - PyObject * obj0 = 0 ; - PyObject * obj1 = 0 ; - - if (!PyArg_ParseTuple(args,(char *)"OO:P_z_set",&obj0,&obj1)) SWIG_fail; - res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_P, 0 | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P_z_set" "', argument " "1"" of type '" "P *""'"); - } - arg1 = reinterpret_cast< P * >(argp1); - ecode2 = SWIG_AsVal_int(obj1, &val2); - if (!SWIG_IsOK(ecode2)) { - SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "P_z_set" "', argument " "2"" of type '" "int""'"); - } - arg2 = static_cast< int >(val2); - if (arg1) (arg1)->z = arg2; - resultobj = SWIG_Py_Void(); - return resultobj; -fail: - return NULL; -} - - -SWIGINTERN PyObject *_wrap_P_z_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - PyObject *resultobj = 0; - P *arg1 = (P *) 0 ; - void *argp1 = 0 ; - int res1 = 0 ; - PyObject * obj0 = 0 ; - int result; - - if (!PyArg_ParseTuple(args,(char *)"O:P_z_get",&obj0)) SWIG_fail; - res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_P, 0 | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P_z_get" "', argument " "1"" of type '" "P *""'"); - } - arg1 = reinterpret_cast< P * >(argp1); - result = (int) ((arg1)->z); - resultobj = SWIG_From_int(static_cast< int >(result)); - return resultobj; -fail: - return NULL; -} - - -SWIGINTERN PyObject *_wrap_P_w_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - PyObject *resultobj = 0; - P *arg1 = (P *) 0 ; - double arg2 ; - void *argp1 = 0 ; - int res1 = 0 ; - double val2 ; - int ecode2 = 0 ; - PyObject * obj0 = 0 ; - PyObject * obj1 = 0 ; - - if (!PyArg_ParseTuple(args,(char *)"OO:P_w_set",&obj0,&obj1)) SWIG_fail; - res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_P, 0 | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P_w_set" "', argument " "1"" of type '" "P *""'"); - } - arg1 = reinterpret_cast< P * >(argp1); - ecode2 = SWIG_AsVal_double(obj1, &val2); - if (!SWIG_IsOK(ecode2)) { - SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "P_w_set" "', argument " "2"" of type '" "double""'"); - } - arg2 = static_cast< double >(val2); - if (arg1) (arg1)->w = arg2; - resultobj = SWIG_Py_Void(); - return resultobj; -fail: - return NULL; -} - - -SWIGINTERN PyObject *_wrap_P_w_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - PyObject *resultobj = 0; - P *arg1 = (P *) 0 ; - void *argp1 = 0 ; - int res1 = 0 ; - PyObject * obj0 = 0 ; - double result; - - if (!PyArg_ParseTuple(args,(char *)"O:P_w_get",&obj0)) SWIG_fail; - res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_P, 0 | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P_w_get" "', argument " "1"" of type '" "P *""'"); - } - arg1 = reinterpret_cast< P * >(argp1); - result = (double) ((arg1)->w); - resultobj = SWIG_From_double(static_cast< double >(result)); - return resultobj; -fail: - return NULL; -} - - -SWIGINTERN PyObject *_wrap_P_p_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - PyObject *resultobj = 0; - P *arg1 = (P *) 0 ; - point *arg2 = (point *) 0 ; - void *argp1 = 0 ; - int res1 = 0 ; - void *argp2 = 0 ; - int res2 = 0 ; - PyObject * obj0 = 0 ; - PyObject * obj1 = 0 ; - - if (!PyArg_ParseTuple(args,(char *)"OO:P_p_set",&obj0,&obj1)) SWIG_fail; - res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_P, 0 | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P_p_set" "', argument " "1"" of type '" "P *""'"); - } - arg1 = reinterpret_cast< P * >(argp1); - res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_point, 0 | 0 ); - if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P_p_set" "', argument " "2"" of type '" "point *""'"); - } - arg2 = reinterpret_cast< point * >(argp2); - if (arg1) (arg1)->p = *arg2; - resultobj = SWIG_Py_Void(); - return resultobj; -fail: - return NULL; -} - - -SWIGINTERN PyObject *_wrap_P_p_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - PyObject *resultobj = 0; - P *arg1 = (P *) 0 ; - void *argp1 = 0 ; - int res1 = 0 ; - PyObject * obj0 = 0 ; - point *result = 0 ; - - if (!PyArg_ParseTuple(args,(char *)"O:P_p_get",&obj0)) SWIG_fail; - res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_P, 0 | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P_p_get" "', argument " "1"" of type '" "P *""'"); - } - arg1 = reinterpret_cast< P * >(argp1); - result = (point *)& ((arg1)->p); - resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_point, 0 | 0 ); - return resultobj; -fail: - return NULL; -} - - -SWIGINTERN PyObject *_wrap_new_P(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - PyObject *resultobj = 0; - P *result = 0 ; - - if (!PyArg_ParseTuple(args,(char *)":new_P")) SWIG_fail; - result = (P *)new P(); - resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_P, SWIG_POINTER_NEW | 0 ); - return resultobj; -fail: - return NULL; -} - - -SWIGINTERN PyObject *_wrap_delete_P(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - PyObject *resultobj = 0; - P *arg1 = (P *) 0 ; - void *argp1 = 0 ; - int res1 = 0 ; - PyObject * obj0 = 0 ; - - if (!PyArg_ParseTuple(args,(char *)"O:delete_P",&obj0)) SWIG_fail; - res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_P, SWIG_POINTER_DISOWN | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_P" "', argument " "1"" of type '" "P *""'"); - } - arg1 = reinterpret_cast< P * >(argp1); - delete arg1; - resultobj = SWIG_Py_Void(); - return resultobj; -fail: - return NULL; -} - - -SWIGINTERN PyObject *P_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - PyObject *obj; - if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL; - SWIG_TypeNewClientData(SWIGTYPE_p_P, SWIG_NewClientData(obj)); - return SWIG_Py_Void(); -} - -SWIGINTERN int Swig_var_p1_set(PyObject *_val) { - { - void *argp = 0; - int res = SWIG_ConvertPtr(_val, &argp, SWIGTYPE_p_P, 0 | 0); - if (!SWIG_IsOK(res)) { - SWIG_exception_fail(SWIG_ArgError(res), "in variable '""p1""' of type '""P""'"); - } - if (!argp) { - SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""p1""' of type '""P""'"); - } else { - P * temp; - temp = reinterpret_cast< P * >(argp); - p1 = *temp; - if (SWIG_IsNewObj(res)) delete temp; - } - } - return 0; -fail: - return 1; -} - - -SWIGINTERN PyObject *Swig_var_p1_get(void) { - PyObject *pyobj = 0; - - pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(&p1), SWIGTYPE_p_P, 0 ); - return pyobj; -} - - -static PyMethodDef SwigMethods[] = { - { (char *)"SWIG_PyInstanceMethod_New", (PyCFunction)SWIG_PyInstanceMethod_New, METH_O, NULL}, - { (char *)"new_point", _wrap_new_point, METH_VARARGS, NULL}, - { (char *)"point_x__set", _wrap_point_x__set, METH_VARARGS, NULL}, - { (char *)"point_x__get", _wrap_point_x__get, METH_VARARGS, NULL}, - { (char *)"point_y__set", _wrap_point_y__set, METH_VARARGS, NULL}, - { (char *)"point_y__get", _wrap_point_y__get, METH_VARARGS, NULL}, - { (char *)"delete_point", _wrap_delete_point, METH_VARARGS, NULL}, - { (char *)"point_swigregister", point_swigregister, METH_VARARGS, NULL}, - { (char *)"P_z_set", _wrap_P_z_set, METH_VARARGS, NULL}, - { (char *)"P_z_get", _wrap_P_z_get, METH_VARARGS, NULL}, - { (char *)"P_w_set", _wrap_P_w_set, METH_VARARGS, NULL}, - { (char *)"P_w_get", _wrap_P_w_get, METH_VARARGS, NULL}, - { (char *)"P_p_set", _wrap_P_p_set, METH_VARARGS, NULL}, - { (char *)"P_p_get", _wrap_P_p_get, METH_VARARGS, NULL}, - { (char *)"new_P", _wrap_new_P, METH_VARARGS, NULL}, - { (char *)"delete_P", _wrap_delete_P, METH_VARARGS, NULL}, - { (char *)"P_swigregister", P_swigregister, METH_VARARGS, NULL}, - { NULL, NULL, 0, NULL } -}; - - -/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ - -static swig_type_info _swigt__p_P = {"_p_P", "P *", 0, 0, (void*)0, 0}; -static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; -static swig_type_info _swigt__p_point = {"_p_point", "point *", 0, 0, (void*)0, 0}; - -static swig_type_info *swig_type_initial[] = { - &_swigt__p_P, - &_swigt__p_char, - &_swigt__p_point, -}; - -static swig_cast_info _swigc__p_P[] = { {&_swigt__p_P, 0, 0, 0},{0, 0, 0, 0}}; -static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; -static swig_cast_info _swigc__p_point[] = { {&_swigt__p_point, 0, 0, 0},{0, 0, 0, 0}}; - -static swig_cast_info *swig_cast_initial[] = { - _swigc__p_P, - _swigc__p_char, - _swigc__p_point, -}; - - -/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ - -static swig_const_info swig_const_table[] = { -{0, 0, 0, 0.0, 0, 0}}; - -#ifdef __cplusplus -} -#endif -/* ----------------------------------------------------------------------------- - * Type initialization: - * This problem is tough by the requirement that no dynamic - * memory is used. Also, since swig_type_info structures store pointers to - * swig_cast_info structures and swig_cast_info structures store pointers back - * to swig_type_info structures, we need some lookup code at initialization. - * The idea is that swig generates all the structures that are needed. - * The runtime then collects these partially filled structures. - * The SWIG_InitializeModule function takes these initial arrays out of - * swig_module, and does all the lookup, filling in the swig_module.types - * array with the correct data and linking the correct swig_cast_info - * structures together. - * - * The generated swig_type_info structures are assigned staticly to an initial - * array. We just loop through that array, and handle each type individually. - * First we lookup if this type has been already loaded, and if so, use the - * loaded structure instead of the generated one. Then we have to fill in the - * cast linked list. The cast data is initially stored in something like a - * two-dimensional array. Each row corresponds to a type (there are the same - * number of rows as there are in the swig_type_initial array). Each entry in - * a column is one of the swig_cast_info structures for that type. - * The cast_initial array is actually an array of arrays, because each row has - * a variable number of columns. So to actually build the cast linked list, - * we find the array of casts associated with the type, and loop through it - * adding the casts to the list. The one last trick we need to do is making - * sure the type pointer in the swig_cast_info struct is correct. - * - * First off, we lookup the cast->type name to see if it is already loaded. - * There are three cases to handle: - * 1) If the cast->type has already been loaded AND the type we are adding - * casting info to has not been loaded (it is in this module), THEN we - * replace the cast->type pointer with the type pointer that has already - * been loaded. - * 2) If BOTH types (the one we are adding casting info to, and the - * cast->type) are loaded, THEN the cast info has already been loaded by - * the previous module so we just ignore it. - * 3) Finally, if cast->type has not already been loaded, then we add that - * swig_cast_info to the linked list (because the cast->type) pointer will - * be correct. - * ----------------------------------------------------------------------------- */ - -#ifdef __cplusplus -extern "C" { -#if 0 -} /* c-mode */ -#endif -#endif - -#if 0 -#define SWIGRUNTIME_DEBUG -#endif - - -SWIGRUNTIME void -SWIG_InitializeModule(void *clientdata) { - size_t i; - swig_module_info *module_head, *iter; - int found, init; - - clientdata = clientdata; - - /* check to see if the circular list has been setup, if not, set it up */ - if (swig_module.next==0) { - /* Initialize the swig_module */ - swig_module.type_initial = swig_type_initial; - swig_module.cast_initial = swig_cast_initial; - swig_module.next = &swig_module; - init = 1; - } else { - init = 0; - } - - /* Try and load any already created modules */ - module_head = SWIG_GetModule(clientdata); - if (!module_head) { - /* This is the first module loaded for this interpreter */ - /* so set the swig module into the interpreter */ - SWIG_SetModule(clientdata, &swig_module); - module_head = &swig_module; - } else { - /* the interpreter has loaded a SWIG module, but has it loaded this one? */ - found=0; - iter=module_head; - do { - if (iter==&swig_module) { - found=1; - break; - } - iter=iter->next; - } while (iter!= module_head); - - /* if the is found in the list, then all is done and we may leave */ - if (found) return; - /* otherwise we must add out module into the list */ - swig_module.next = module_head->next; - module_head->next = &swig_module; - } - - /* When multiple interpeters are used, a module could have already been initialized in - a different interpreter, but not yet have a pointer in this interpreter. - In this case, we do not want to continue adding types... everything should be - set up already */ - if (init == 0) return; - - /* Now work on filling in swig_module.types */ -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: size %d\n", swig_module.size); -#endif - for (i = 0; i < swig_module.size; ++i) { - swig_type_info *type = 0; - swig_type_info *ret; - swig_cast_info *cast; - -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); -#endif - - /* if there is another module already loaded */ - if (swig_module.next != &swig_module) { - type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); - } - if (type) { - /* Overwrite clientdata field */ -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: found type %s\n", type->name); -#endif - if (swig_module.type_initial[i]->clientdata) { - type->clientdata = swig_module.type_initial[i]->clientdata; -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); -#endif - } - } else { - type = swig_module.type_initial[i]; - } - - /* Insert casting types */ - cast = swig_module.cast_initial[i]; - while (cast->type) { - /* Don't need to add information already in the list */ - ret = 0; -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); -#endif - if (swig_module.next != &swig_module) { - ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); -#ifdef SWIGRUNTIME_DEBUG - if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); -#endif - } - if (ret) { - if (type == swig_module.type_initial[i]) { -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: skip old type %s\n", ret->name); -#endif - cast->type = ret; - ret = 0; - } else { - /* Check for casting already in the list */ - swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); -#ifdef SWIGRUNTIME_DEBUG - if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); -#endif - if (!ocast) ret = 0; - } - } - - if (!ret) { -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); -#endif - if (type->cast) { - type->cast->prev = cast; - cast->next = type->cast; - } - type->cast = cast; - } - cast++; - } - /* Set entry in modules->types array equal to the type */ - swig_module.types[i] = type; - } - swig_module.types[i] = 0; - -#ifdef SWIGRUNTIME_DEBUG - printf("**** SWIG_InitializeModule: Cast List ******\n"); - for (i = 0; i < swig_module.size; ++i) { - int j = 0; - swig_cast_info *cast = swig_module.cast_initial[i]; - printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); - while (cast->type) { - printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); - cast++; - ++j; - } - printf("---- Total casts: %d\n",j); - } - printf("**** SWIG_InitializeModule: Cast List ******\n"); -#endif -} - -/* This function will propagate the clientdata field of type to -* any new swig_type_info structures that have been added into the list -* of equivalent types. It is like calling -* SWIG_TypeClientData(type, clientdata) a second time. -*/ -SWIGRUNTIME void -SWIG_PropagateClientData(void) { - size_t i; - swig_cast_info *equiv; - static int init_run = 0; - - if (init_run) return; - init_run = 1; - - for (i = 0; i < swig_module.size; i++) { - if (swig_module.types[i]->clientdata) { - equiv = swig_module.types[i]->cast; - while (equiv) { - if (!equiv->converter) { - if (equiv->type && !equiv->type->clientdata) - SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); - } - equiv = equiv->next; - } - } - } -} - -#ifdef __cplusplus -#if 0 -{ - /* c-mode */ -#endif -} -#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 int - swig_varlink_print(swig_varlinkobject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { - char *tmp; - PyObject *str = swig_varlink_str(v); - fprintf(fp,"Swig global variables "); - fprintf(fp,"%s\n", tmp = SWIG_Python_str_AsChar(str)); - SWIG_Python_str_DelForPy3(tmp); - Py_DECREF(str); - return 0; - } - - 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_SetString(PyExc_NameError,"Unknown C global variable"); - } - 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_SetString(PyExc_NameError,"Unknown C global variable"); - } - 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 - = { - /* PyObject header changed in Python 3 */ -#if PY_VERSION_HEX >= 0x03000000 - PyVarObject_HEAD_INIT(&PyType_Type, 0) -#else - PyObject_HEAD_INIT(NULL) - 0, /* Number of items in variable part (ob_size) */ -#endif - (char *)"swigvarlink", /* Type name (tp_name) */ - sizeof(swig_varlinkobject), /* Basic size (tp_basicsize) */ - 0, /* Itemsize (tp_itemsize) */ - (destructor) swig_varlink_dealloc, /* Deallocator (tp_dealloc) */ - (printfunc) swig_varlink_print, /* Print (tp_print) */ - (getattrfunc) swig_varlink_getattr, /* get attr (tp_getattr) */ - (setattrfunc) swig_varlink_setattr, /* Set attr (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 */ -#if PY_VERSION_HEX >= 0x02020000 - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */ -#endif -#if PY_VERSION_HEX >= 0x02030000 - 0, /* tp_del */ -#endif -#ifdef COUNT_ALLOCS - 0,0,0,0 /* tp_alloc -> tp_next */ -#endif - }; - varlink_type = tmp; - /* for Python 3 we already assigned ob_type in PyVarObject_HEAD_INIT() */ -#if PY_VERSION_HEX < 0x03000000 - varlink_type.ob_type = &PyType_Type; -#endif - type_init = 1; - } - 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, 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) { - strncpy(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 *_SWIG_globals = 0; - if (!_SWIG_globals) _SWIG_globals = SWIG_newvarlink(); - return _SWIG_globals; - } - - /* ----------------------------------------------------------------------------- - * constants/methods manipulation - * ----------------------------------------------------------------------------- */ - - /* Install Constants */ - SWIGINTERN void - SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) { - PyObject *obj = 0; - size_t i; - for (i = 0; constants[i].type; ++i) { - switch(constants[i].type) { - case SWIG_PY_POINTER: - obj = SWIG_NewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0); - break; - case SWIG_PY_BINARY: - obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); - break; - default: - obj = 0; - break; - } - if (obj) { - PyDict_SetItemString(d, constants[i].name, obj); - Py_DECREF(obj); - } - } - } - - /* -----------------------------------------------------------------------------*/ - /* Fix SwigMethods to carry the callback ptrs when needed */ - /* -----------------------------------------------------------------------------*/ - - SWIGINTERN void - SWIG_Python_FixMethods(PyMethodDef *methods, - 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; - if (c && (c = strstr(c, "swig_ptr: "))) { - int j; - 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, - strlen(const_table[j].name)) == 0) { - ci = &(const_table[j]); - break; - } - } - if (ci) { - void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0; - if (ptr) { - size_t shift = (ci->ptype) - types; - swig_type_info *ty = types_initial[shift]; - size_t ldoc = (c - methods[i].ml_doc); - size_t lptr = strlen(ty->name)+2*sizeof(void*)+2; - char *ndoc = (char*)malloc(ldoc + lptr + 10); - if (ndoc) { - char *buff = ndoc; - strncpy(buff, methods[i].ml_doc, ldoc); - buff += ldoc; - strncpy(buff, "swig_ptr: ", 10); - buff += 10; - SWIG_PackVoidPtr(buff, ptr, ty->name, lptr); - methods[i].ml_doc = ndoc; - } - } - } - } - } - } - -#ifdef __cplusplus -} -#endif - -/* -----------------------------------------------------------------------------* - * Partial Init method - * -----------------------------------------------------------------------------*/ - -#ifdef __cplusplus -extern "C" -#endif - -SWIGEXPORT -#if PY_VERSION_HEX >= 0x03000000 -PyObject* -#else -void -#endif -SWIG_init(void) { - PyObject *m, *d; -#if PY_VERSION_HEX >= 0x03000000 - static struct PyModuleDef SWIG_module = { - PyModuleDef_HEAD_INIT, - (char *) SWIG_name, - NULL, - -1, - SwigMethods, - NULL, - NULL, - NULL, - NULL - }; -#endif - - /* Fix SwigMethods to carry the callback ptrs when needed */ - SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial); - -#if PY_VERSION_HEX >= 0x03000000 - m = PyModule_Create(&SWIG_module); -#else - m = Py_InitModule((char *) SWIG_name, SwigMethods); -#endif - d = PyModule_GetDict(m); - - SWIG_InitializeModule(0); - SWIG_InstallConstants(d,swig_const_table); - - - PyDict_SetItemString(d,(char*)"cvar", SWIG_globals()); - SWIG_addvarlink(SWIG_globals(),(char*)"p1",Swig_var_p1_get, Swig_var_p1_set); -#if PY_VERSION_HEX >= 0x03000000 - return m; -#else - return; -#endif -} - From a043b55b69d4587a1bd95b934b85acb683e415e6 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 1 Feb 2013 19:17:21 +0000 Subject: [PATCH 104/481] Better clarification about polymorphic wrappers for function objects - std::function --- Doc/Manual/Cpp0x.html | 24 +++++++++++++-- Examples/test-suite/cpp0x_function_objects.i | 29 +++++++++++++++---- .../python/cpp0x_function_objects_runme.py | 8 ++--- 3 files changed, 48 insertions(+), 13 deletions(-) diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html index 0200fdf5c..aa8c41225 100644 --- a/Doc/Manual/Cpp0x.html +++ b/Doc/Manual/Cpp0x.html @@ -735,14 +735,32 @@ int main() {

    7.3.7 Polymorphous wrappers for function objects

    -

    SWIG fully supports function template wrappers and function objects:

    +

    +SWIG supports functor classes in some languages in a very natural way. +However nothing is provided yet for the new std::function template. +SWIG will parse usage of the template like any other template. +

    -function<int ( int, int )> pF;   // function template wrapper
    +%rename(__call__) Test::operator(); // Default renaming used for Python
     
     struct Test {
    -  bool operator()( short x, short y ); // function object
    +  bool operator()(int x, int y); // function object
     };
    +
    +#include <functional>
    +std::function<void (int, int)> pF = Test;   // function template wrapper
    +
    +
    + +

    +Example of supported usage of the plain functor from Python is shown below. +It does not involve std::function. +

    + +
    +t = Test() +b = t(1,2) # invoke C++ function object

    7.3.8 Type traits for metaprogramming

    diff --git a/Examples/test-suite/cpp0x_function_objects.i b/Examples/test-suite/cpp0x_function_objects.i index e864137c7..4b9895ca8 100644 --- a/Examples/test-suite/cpp0x_function_objects.i +++ b/Examples/test-suite/cpp0x_function_objects.i @@ -1,18 +1,35 @@ /* This testcase checks whether SWIG correctly parses function objects and the templates for the functions (signature). - Function objects are objects which overload the operator() function. */ + Function objects are objects which overload the operator() function. + The std::function does not provide any seamless support in the target languages yet. +*/ %module cpp0x_function_objects -%inline %{ -//function pF; // not supported yet by the compiler +%rename(__call__) Test::operator(); +%inline %{ struct Test { int value; - void operator()(short x, short y) { - value=10; + void operator()(int x, int y) { + value=x+y; } - + Test() : value(0) {} } test; + +#include +std::function pF = test; + +int testit1(Test new_test, int a, int b) { + pF = new_test; + pF(a, b); + return new_test.value; +} + +int testit2(int a, int b) { + test(a, b); + return test.value; +} + %} diff --git a/Examples/test-suite/python/cpp0x_function_objects_runme.py b/Examples/test-suite/python/cpp0x_function_objects_runme.py index edbd88e1c..ed8f888b1 100644 --- a/Examples/test-suite/python/cpp0x_function_objects_runme.py +++ b/Examples/test-suite/python/cpp0x_function_objects_runme.py @@ -3,10 +3,10 @@ import sys t = cpp0x_function_objects.Test() if t.value != 0: - raise RuntimeError,"Runtime cpp0x_function_objects failed. t.value should be 0, but is", t.value + raise RuntimeError("Runtime cpp0x_function_objects failed. t.value should be 0, but is " + str(t.value)) -t(1,2) # sets value +t(1,2) # adds numbers and sets value -if t.value != 10: - raise RuntimeError,"Runtime cpp0x_function_objects failed. t.value not changed - should be 10, but is", t.value +if t.value != 3: + raise RuntimeError("Runtime cpp0x_function_objects failed. t.value not changed - should be 3, but is " + str(t.value)) From c8ff23de0c5fdc60a7a5335bcf937ac25a6a3d39 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 2 Feb 2013 01:15:28 +0000 Subject: [PATCH 105/481] Initialization list doc updates and new tests. Fix functions with default arguments that are initializer lists --- Doc/Manual/Cpp0x.html | 32 ++++++++++++++----- Examples/test-suite/cpp0x_initializer_list.i | 9 +++++- .../test-suite/cpp0x_uniform_initialization.i | 31 ++++++++++++++++-- .../python/cpp0x_initializer_list_runme.py | 5 +++ .../cpp0x_uniform_initialization_runme.py | 21 ++++++++++++ Source/CParse/parser.y | 12 +++++-- 6 files changed, 96 insertions(+), 14 deletions(-) create mode 100644 Examples/test-suite/python/cpp0x_initializer_list_runme.py create mode 100644 Examples/test-suite/python/cpp0x_uniform_initialization_runme.py diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html index aa8c41225..341cb3ce5 100644 --- a/Doc/Manual/Cpp0x.html +++ b/Doc/Manual/Cpp0x.html @@ -126,13 +126,14 @@ public:

    7.2.4 Initializer lists

    -

    Constructors using the std::initializer_list class are removed -from the wrapped class, because the only way to access such a -constructor is at compile time using the "= {}" assignment.

    -

    Users should add another constructor with specific arguments -filling the class members manually.

    +

    +Constructors using the std::initializer_list class are removed +from the wrapped class because the only way to access such a +constructor is at compile time using the initialization list syntax. +Initializer lists are very much a C++ construct and not very accessible from wrappers. +

    -

    For now, if a user wants to fill the class components like this:

    +

    For now, if you want to fill the class components like this:

     class A {
    @@ -142,7 +143,7 @@ public:
     A a1 = {1,2,3,4};
     
    -

    You should add another constructor using the std::vector for example:

    +

    you could add another constructor using std::vector for example:

     class A {
    @@ -153,11 +154,26 @@ public:
     A a1 = {1,2,3,4};
     
    -

    And call it from your target language, for example, in Python:

    +

    And then construct it from your target language, for example, in Python:

     >>> a2 = A( [1,2,3,4] )
     
    +

    +std::initializer_list is simply a container that can only be initialised at compile time. +As such it is possible to write typemaps for a target language container to map onto +std::initializer_list. However, this can only be done for a fixed number of elements ... +there is no way to construct an initializer list with a variable number of arguments at runtime. +This is not particularly flexible though outside of C++ static initialization, +hence the need to provide an alternative for use from a target language. +

    + +

    +Initializer lists can appear in any function or method, not just constructors. +SWIG only ignores the constructors as this is where they commonly occur. +Users are recommended to manually ignore any other methods using an initialization list with %ignore. +

    +

    7.2.5 Uniform initialization

    diff --git a/Examples/test-suite/cpp0x_initializer_list.i b/Examples/test-suite/cpp0x_initializer_list.i index aa2791833..9d85766e2 100644 --- a/Examples/test-suite/cpp0x_initializer_list.i +++ b/Examples/test-suite/cpp0x_initializer_list.i @@ -1,7 +1,7 @@ /* This testcase checks whether SWIG correctly uses the new initializer_list introduced in C++0x. */ %module cpp0x_initializer_list -%warnfilter(520) A; +%warnfilter(SWIGWARN_LANG_INITIALIZER_LIST) A; %inline %{ #include @@ -10,6 +10,13 @@ class A { public: A( std::initializer_list ) {} A() {} + A(double d) {} +}; +class B { +public: + B( std::initializer_list, std::initializer_list ) {} + B() {} + void method(std::initializer_list init) {} }; %} diff --git a/Examples/test-suite/cpp0x_uniform_initialization.i b/Examples/test-suite/cpp0x_uniform_initialization.i index 083fac377..81a3e45de 100644 --- a/Examples/test-suite/cpp0x_uniform_initialization.i +++ b/Examples/test-suite/cpp0x_uniform_initialization.i @@ -1,7 +1,11 @@ -/* This testcase checks whether SWIG syntactically correctly parses the curly - brackets {} for uniform member initialization. */ +/* This testcase checks whether SWIG syntactically correctly parses the initialization syntax using + {} braces for uniform member initialization. */ %module cpp0x_uniform_initialization +%include + +%template(VectorInt) std::vector; + %inline %{ struct BasicStruct { int x; @@ -10,6 +14,8 @@ struct BasicStruct { struct AltStruct { AltStruct(int x, double y) : x_{x}, y_{y} {} + int getX() { return x_; } + double getY() { return y_; } private: int x_; @@ -19,4 +25,25 @@ private: BasicStruct var1{5, 3.2}; // only fills the struct components AltStruct var2{2, 4.3}; // calls the constructor +class MoreInit +{ +public: + int yarray[5] {1,2,3,4,5}; + char *charptr {nullptr}; + std::vector vi {1,2,3,4,5}; + + MoreInit() {} + + int more1(std::vector vv = {1,2,3,4}) { + int sum = 0; + for (int i : vv) + sum += i; + return sum; + } +}; +const int arr1[] = {1,2,3}; +const int arr2[]{1,2,3}; +const int arr3[][3]{ {1,2,3}, {4,5,6} }; +const int arr4[][3] = { {1,2,3}, {4,5,6} }; %} + diff --git a/Examples/test-suite/python/cpp0x_initializer_list_runme.py b/Examples/test-suite/python/cpp0x_initializer_list_runme.py new file mode 100644 index 000000000..5c8c153a5 --- /dev/null +++ b/Examples/test-suite/python/cpp0x_initializer_list_runme.py @@ -0,0 +1,5 @@ +import cpp0x_initializer_list + +a = cpp0x_initializer_list.A() +a = cpp0x_initializer_list.A(11.1) + diff --git a/Examples/test-suite/python/cpp0x_uniform_initialization_runme.py b/Examples/test-suite/python/cpp0x_uniform_initialization_runme.py new file mode 100644 index 000000000..42228f3d7 --- /dev/null +++ b/Examples/test-suite/python/cpp0x_uniform_initialization_runme.py @@ -0,0 +1,21 @@ +import cpp0x_uniform_initialization + +var1 = cpp0x_uniform_initialization.cvar.var1 +if var1.x != 5: + raise RuntimeError +var2 = cpp0x_uniform_initialization.cvar.var2 +if var2.getX() != 2: + raise RuntimeError + +m = cpp0x_uniform_initialization.MoreInit() +if m.charptr != None: + raise RuntimeError, m.charptr +m.charptr = "hello sir" +if m.charptr != "hello sir": + raise RuntimeError, m.charptr +if m.more1(m.vi) != 15: + raise RuntimeError, m.vi +if m.more1( [-1,1,2] ) != 2: + raise RuntimeError, m.vi +if m.more1() != 10: + raise RuntimeError diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index f5b5f6e2b..b3eb72493 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -5165,7 +5165,7 @@ def_args : EQUAL definetype { } | EQUAL LBRACE { skip_balanced('{','}'); - $$.val = 0; + $$.val = NewString(scanner_ccode); $$.rawval = 0; $$.type = T_INT; $$.bitfield = 0; @@ -6625,7 +6625,10 @@ mem_initializer_list : mem_initializer | mem_initializer_list COMMA mem_initializer PERIOD PERIOD PERIOD ; -mem_initializer : idcolon LPAREN { skip_balanced('(',')'); Clear(scanner_ccode); } +mem_initializer : idcolon LPAREN { + skip_balanced('(',')'); + Clear(scanner_ccode); + } /* Uniform initialization in C++0x. Example: struct MyStruct { @@ -6634,7 +6637,10 @@ mem_initializer : idcolon LPAREN { skip_balanced('(',')'); Clear(scanner_ccode); double y_; }; */ - | idcolon LBRACE { skip_balanced('{','}'); Clear(scanner_ccode); } + | idcolon LBRACE { + skip_balanced('{','}'); + Clear(scanner_ccode); + } ; template_decl : LESSTHAN valparms GREATERTHAN { From d613ef42f2973050cb7f399d51f64b8c5dbe72b2 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 4 Feb 2013 07:12:05 +0000 Subject: [PATCH 106/481] Rework std::initializer_list handling to warn about usage in any method, not just constructors. A typemap is used to issue the warning and can be overridden with user defined behaviour. --- Doc/Manual/Cpp0x.html | 130 +++++++++++--- Doc/Manual/Warnings.html | 1 + Examples/test-suite/common.mk | 1 + Examples/test-suite/cpp0x_initializer_list.i | 20 ++- .../cpp0x_initializer_list_extend.i | 29 +++ .../cpp0x_initializer_list_extend_runme.py | 4 + Lib/swig.swg | 169 +++++++++--------- Lib/swigwarnings.swg | 1 + Source/CParse/parser.y | 36 ++-- Source/Include/swigwarn.h | 2 +- 10 files changed, 259 insertions(+), 134 deletions(-) create mode 100644 Examples/test-suite/cpp0x_initializer_list_extend.i create mode 100644 Examples/test-suite/python/cpp0x_initializer_list_extend_runme.py diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html index 341cb3ce5..30a70e75e 100644 --- a/Doc/Manual/Cpp0x.html +++ b/Doc/Manual/Cpp0x.html @@ -125,53 +125,133 @@ public:

    7.2.4 Initializer lists

    -

    -Constructors using the std::initializer_list class are removed -from the wrapped class because the only way to access such a -constructor is at compile time using the initialization list syntax. -Initializer lists are very much a C++ construct and not very accessible from wrappers. +Initializer lists are very much a C++ compiler construct and are not very accessible from wrappers as +they are intended for compile time initialization of classes using the special std::initializer_list type. +SWIG detects usage of initializer lists and will emit a special informative warning each time one is used:

    -

    For now, if you want to fill the class components like this:

    +
    +
    +example.i:33: Warning 476: Initialization using std::initializer_list.
    +
    +
    + +

    +Initializer lists usually appear in constructors but can appear in any function or method. +They often appear in constructors which are overloaded with alternative approaches to initializing a class, +such as the std container's push_back method for adding elements to a container. +The recommended approach then is to simply ignore the initializer-list constructor, for example: +

    -class A {
    +%ignore Container::Container(std::initializer_list<int>);
    +class Container {
     public:
    -  A( std::initializer_list<int> );
    +  Container(std::initializer_list<int>); // initializer-list constructor
    +  Container();
    +  void push_back(const int &);
    +  ...
     };
    -A a1 = {1,2,3,4};
     
    -

    you could add another constructor using std::vector for example:

    +

    Alternatively you could modify the class and add another constructor for initialization by some other means, +for example by a std::vector:

    -class A {
    +%include <std_vector.i>
    +class Container {
     public:
    -  A( std::initializer_list<int> );
    -  A( std::vector<int> );
    +  Container(const std::vector<int> &);
    +  Container(std::initializer_list<int>); // initializer-list constructor
    +  Container();
    +  void push_back(const int &);
    +  ...
     };
    -A a1 = {1,2,3,4};
     
    -

    And then construct it from your target language, for example, in Python:

    +

    And then call this constructor from your target language, for example, in Python, the following will call the constructor taking the std::vector:

    +
    ->>> a2 = A( [1,2,3,4] )
    +>>> c = Container( [1,2,3,4] )
     

    -std::initializer_list is simply a container that can only be initialised at compile time. -As such it is possible to write typemaps for a target language container to map onto -std::initializer_list. However, this can only be done for a fixed number of elements ... -there is no way to construct an initializer list with a variable number of arguments at runtime. -This is not particularly flexible though outside of C++ static initialization, -hence the need to provide an alternative for use from a target language. +If you are unable to modify the class being wrapped, consider ignoring the initializer-list constructor and using +%extend to add in an alternative constructor: +

    + +
    +%include <std_vector.i>
    +%extend Container {
    +  Container(const std::vector<int> &elements) {
    +    Container *c = new Container();
    +    for (int element : elements)
    +      c->push_back(element);
    +    return c;
    +  }
    +}
    +
    +%ignore Container::Container(std::initializer_list<int>);
    +
    +class Container {
    +public:
    +  Container(std::initializer_list<int>); // initializer-list constructor
    +  Container();
    +  void push_back(const int &);
    +  ...
    +};
    +
    + +

    +The above makes the wrappers look is as if the class had been declared as follows: +

    + +
    +%include <std_vector.i>
    +class Container {
    +public:
    +  Container(const std::vector<int> &);
    +//  Container(std::initializer_list<int>); // initializer-list constructor (ignored)
    +  Container();
    +  void push_back(const int &);
    +  ...
    +};
    +
    + +

    +std::initializer_list is simply a container that can only be initialized at compile time. +As it is just a C++ type, it is possible to write typemaps for a target language container to map onto +std::initializer_list. However, this can only be done for a fixed number of elements as +initializer lists are not designed to be constructed with a variable number of arguments at runtime. +The example below is a very simple approach which ignores any parameters passed in and merely initializes +with a fixed list of fixed integer values chosen at compile time: +

    + +
    +%typemap(in) std::initializer_list<int> {
    +  $1 = {10, 20, 30, 40, 50};
    +}
    +class Container {
    +public:
    +  Container(std::initializer_list<int>); // initializer-list constructor
    +  Container();
    +  void push_back(const int &);
    +  ...
    +};
    +
    + +

    +Any attempt at passing in values from the target language will be ignored and replaced by {10, 20, 30, 40, 50}. +Needless to say, this approach is very limited, but could be improved upon, but only slightly. +A typemap could be written to map a fixed number of elements on to the std::initializer_list, +but with values decided at runtime. +The typemaps would be target language specific.

    -Initializer lists can appear in any function or method, not just constructors. -SWIG only ignores the constructors as this is where they commonly occur. -Users are recommended to manually ignore any other methods using an initialization list with %ignore. +Note that the default typemap for std::initializer_list does nothing but issue the warning +and hence any user supplied typemaps will override it and suppress the warning.

    7.2.5 Uniform initialization

    diff --git a/Doc/Manual/Warnings.html b/Doc/Manual/Warnings.html index 1571146f1..d8e76a471 100644 --- a/Doc/Manual/Warnings.html +++ b/Doc/Manual/Warnings.html @@ -497,6 +497,7 @@ example.i(4) : Syntax error in input.
  • 471. Unable to use return type type in director method
  • 474. Method method usage of the optimal attribute ignored in the out typemap as the following cannot be used to generate optimal code: code
  • 475. Multiple calls to method might be generated due to optimal attribute usage in the out typemap. +
  • 476. Initialization using std::initializer_list. diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 915decfc2..4b4228db8 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -486,6 +486,7 @@ CPP0X_TEST_CASES = \ cpp0x_explicit_conversion_operators \ cpp0x_function_objects \ cpp0x_initializer_list \ + cpp0x_initializer_list_extend \ cpp0x_lambda_functions \ cpp0x_null_pointer_constant \ cpp0x_raw_string_literals \ diff --git a/Examples/test-suite/cpp0x_initializer_list.i b/Examples/test-suite/cpp0x_initializer_list.i index 9d85766e2..14833390e 100644 --- a/Examples/test-suite/cpp0x_initializer_list.i +++ b/Examples/test-suite/cpp0x_initializer_list.i @@ -1,22 +1,34 @@ -/* This testcase checks whether SWIG correctly uses the new initializer_list +/* This testcase shows a few simple ways to deal with the new initializer_list introduced in C++0x. */ %module cpp0x_initializer_list -%warnfilter(SWIGWARN_LANG_INITIALIZER_LIST) A; + +%warnfilter(SWIGWARN_TYPEMAP_INITIALIZER_LIST) B::B; +%ignore A::A(std::initializer_list); +%ignore B::method; + +%typemap(in) std::initializer_list { + $1 = {"Ab", "Fab"}; +} %inline %{ #include class A { public: - A( std::initializer_list ) {} + A(std::initializer_list) {} A() {} A(double d) {} }; class B { public: - B( std::initializer_list, std::initializer_list ) {} + B(std::initializer_list, std::initializer_list) {} B() {} void method(std::initializer_list init) {} }; +class C { +public: + C(std::initializer_list) {} + C() {} +}; %} diff --git a/Examples/test-suite/cpp0x_initializer_list_extend.i b/Examples/test-suite/cpp0x_initializer_list_extend.i new file mode 100644 index 000000000..d8443e622 --- /dev/null +++ b/Examples/test-suite/cpp0x_initializer_list_extend.i @@ -0,0 +1,29 @@ +/* This testcase shows how to replace std_initializer_list with std_vector. */ + +%module cpp0x_initializer_list_extend + +%ignore Container::Container(std::initializer_list); +%include +%template(VectorInt) std::vector; + +%extend Container { + Container(const std::vector &elements) { + Container *c = new Container(); + for (int element : elements) + c->push_back(element); + return c; + } +} + + +%inline %{ +#include + +class Container { +public: + Container(std::initializer_list) {} + Container() {} + void push_back(const int&) {} +}; +%} + diff --git a/Examples/test-suite/python/cpp0x_initializer_list_extend_runme.py b/Examples/test-suite/python/cpp0x_initializer_list_extend_runme.py new file mode 100644 index 000000000..b07231408 --- /dev/null +++ b/Examples/test-suite/python/cpp0x_initializer_list_extend_runme.py @@ -0,0 +1,4 @@ +import cpp0x_initializer_list_extend + +c = cpp0x_initializer_list_extend.Container( [10, 20, 30, 40] ) + diff --git a/Lib/swig.swg b/Lib/swig.swg index 97e7c80a4..ad6b7b64b 100644 --- a/Lib/swig.swg +++ b/Lib/swig.swg @@ -309,6 +309,88 @@ static int NAME(TYPE x) { %include +/* ----------------------------------------------------------------------------- + * Overloading support + * ----------------------------------------------------------------------------- */ + +/* + * Function/method overloading support. This is done through typemaps, + * but also involve a precedence level. + */ + +/* Macro for overload resolution */ + +%define %typecheck(_x...) %typemap(typecheck, precedence=_x) %enddef + +/* Macros for precedence levels */ + +%define SWIG_TYPECHECK_POINTER 0 %enddef +%define SWIG_TYPECHECK_ITERATOR 5 %enddef +%define SWIG_TYPECHECK_VOIDPTR 10 %enddef +%define SWIG_TYPECHECK_BOOL 15 %enddef +%define SWIG_TYPECHECK_UINT8 20 %enddef +%define SWIG_TYPECHECK_INT8 25 %enddef +%define SWIG_TYPECHECK_UINT16 30 %enddef +%define SWIG_TYPECHECK_INT16 35 %enddef +%define SWIG_TYPECHECK_UINT32 40 %enddef +%define SWIG_TYPECHECK_INT32 45 %enddef +%define SWIG_TYPECHECK_SIZE 47 %enddef +%define SWIG_TYPECHECK_PTRDIFF 48 %enddef +%define SWIG_TYPECHECK_UINT64 50 %enddef +%define SWIG_TYPECHECK_INT64 55 %enddef +%define SWIG_TYPECHECK_UINT128 60 %enddef +%define SWIG_TYPECHECK_INT128 65 %enddef +%define SWIG_TYPECHECK_INTEGER 70 %enddef +%define SWIG_TYPECHECK_FLOAT 80 %enddef +%define SWIG_TYPECHECK_DOUBLE 90 %enddef +%define SWIG_TYPECHECK_CPLXFLT 95 %enddef +%define SWIG_TYPECHECK_CPLXDBL 100 %enddef +%define SWIG_TYPECHECK_COMPLEX 105 %enddef +%define SWIG_TYPECHECK_UNICHAR 110 %enddef +%define SWIG_TYPECHECK_STDUNISTRING 115 %enddef +%define SWIG_TYPECHECK_UNISTRING 120 %enddef +%define SWIG_TYPECHECK_CHAR 130 %enddef +%define SWIG_TYPECHECK_STDSTRING 135 %enddef +%define SWIG_TYPECHECK_STRING 140 %enddef +%define SWIG_TYPECHECK_PAIR 150 %enddef +%define SWIG_TYPECHECK_VECTOR 160 %enddef +%define SWIG_TYPECHECK_DEQUE 170 %enddef +%define SWIG_TYPECHECK_LIST 180 %enddef +%define SWIG_TYPECHECK_SET 190 %enddef +%define SWIG_TYPECHECK_MULTISET 200 %enddef +%define SWIG_TYPECHECK_MAP 210 %enddef +%define SWIG_TYPECHECK_MULTIMAP 220 %enddef +%define SWIG_TYPECHECK_STACK 230 %enddef +%define SWIG_TYPECHECK_QUEUE 240 %enddef + +%define SWIG_TYPECHECK_BOOL_ARRAY 1015 %enddef +%define SWIG_TYPECHECK_INT8_ARRAY 1025 %enddef +%define SWIG_TYPECHECK_INT16_ARRAY 1035 %enddef +%define SWIG_TYPECHECK_INT32_ARRAY 1045 %enddef +%define SWIG_TYPECHECK_INT64_ARRAY 1055 %enddef +%define SWIG_TYPECHECK_INT128_ARRAY 1065 %enddef +%define SWIG_TYPECHECK_FLOAT_ARRAY 1080 %enddef +%define SWIG_TYPECHECK_DOUBLE_ARRAY 1090 %enddef +%define SWIG_TYPECHECK_CHAR_ARRAY 1130 %enddef +%define SWIG_TYPECHECK_STRING_ARRAY 1140 %enddef +%define SWIG_TYPECHECK_OBJECT_ARRAY 1150 %enddef + +%define SWIG_TYPECHECK_BOOL_PTR 2015 %enddef +%define SWIG_TYPECHECK_UINT8_PTR 2020 %enddef +%define SWIG_TYPECHECK_INT8_PTR 2025 %enddef +%define SWIG_TYPECHECK_UINT16_PTR 2030 %enddef +%define SWIG_TYPECHECK_INT16_PTR 2035 %enddef +%define SWIG_TYPECHECK_UINT32_PTR 2040 %enddef +%define SWIG_TYPECHECK_INT32_PTR 2045 %enddef +%define SWIG_TYPECHECK_UINT64_PTR 2050 %enddef +%define SWIG_TYPECHECK_INT64_PTR 2055 %enddef +%define SWIG_TYPECHECK_FLOAT_PTR 2080 %enddef +%define SWIG_TYPECHECK_DOUBLE_PTR 2090 %enddef +%define SWIG_TYPECHECK_CHAR_PTR 2130 %enddef + +%define SWIG_TYPECHECK_SWIGOBJECT 5000 %enddef + + /* ----------------------------------------------------------------------------- * Default handling of certain overloaded operators * ----------------------------------------------------------------------------- */ @@ -340,6 +422,10 @@ static int NAME(TYPE x) { /* Define std namespace */ namespace std { + /* Warn about std::initializer_list usage. The constructor/method where used should probably be ignored. See docs. */ + template class initializer_list {}; + %typemap(in, warning=SWIGWARN_TYPEMAP_INITIALIZER_LIST_MSG) initializer_list "" + %typemap(typecheck, precedence=SWIG_TYPECHECK_POINTER) initializer_list "" } #endif @@ -500,89 +586,6 @@ namespace std { } } -/* ----------------------------------------------------------------------------- - * Overloading support - * ----------------------------------------------------------------------------- */ - -/* - * Function/method overloading support. This is done through typemaps, - * but also involve a precedence level. - */ - -/* Macro for overload resolution */ - -%define %typecheck(_x...) %typemap(typecheck, precedence=_x) %enddef - -/* Macros for precedence levels */ - -%define SWIG_TYPECHECK_POINTER 0 %enddef -%define SWIG_TYPECHECK_ITERATOR 5 %enddef -%define SWIG_TYPECHECK_VOIDPTR 10 %enddef -%define SWIG_TYPECHECK_BOOL 15 %enddef -%define SWIG_TYPECHECK_UINT8 20 %enddef -%define SWIG_TYPECHECK_INT8 25 %enddef -%define SWIG_TYPECHECK_UINT16 30 %enddef -%define SWIG_TYPECHECK_INT16 35 %enddef -%define SWIG_TYPECHECK_UINT32 40 %enddef -%define SWIG_TYPECHECK_INT32 45 %enddef -%define SWIG_TYPECHECK_SIZE 47 %enddef -%define SWIG_TYPECHECK_PTRDIFF 48 %enddef -%define SWIG_TYPECHECK_UINT64 50 %enddef -%define SWIG_TYPECHECK_INT64 55 %enddef -%define SWIG_TYPECHECK_UINT128 60 %enddef -%define SWIG_TYPECHECK_INT128 65 %enddef -%define SWIG_TYPECHECK_INTEGER 70 %enddef -%define SWIG_TYPECHECK_FLOAT 80 %enddef -%define SWIG_TYPECHECK_DOUBLE 90 %enddef -%define SWIG_TYPECHECK_CPLXFLT 95 %enddef -%define SWIG_TYPECHECK_CPLXDBL 100 %enddef -%define SWIG_TYPECHECK_COMPLEX 105 %enddef -%define SWIG_TYPECHECK_UNICHAR 110 %enddef -%define SWIG_TYPECHECK_STDUNISTRING 115 %enddef -%define SWIG_TYPECHECK_UNISTRING 120 %enddef -%define SWIG_TYPECHECK_CHAR 130 %enddef -%define SWIG_TYPECHECK_STDSTRING 135 %enddef -%define SWIG_TYPECHECK_STRING 140 %enddef -%define SWIG_TYPECHECK_PAIR 150 %enddef -%define SWIG_TYPECHECK_VECTOR 160 %enddef -%define SWIG_TYPECHECK_DEQUE 170 %enddef -%define SWIG_TYPECHECK_LIST 180 %enddef -%define SWIG_TYPECHECK_SET 190 %enddef -%define SWIG_TYPECHECK_MULTISET 200 %enddef -%define SWIG_TYPECHECK_MAP 210 %enddef -%define SWIG_TYPECHECK_MULTIMAP 220 %enddef -%define SWIG_TYPECHECK_STACK 230 %enddef -%define SWIG_TYPECHECK_QUEUE 240 %enddef - -%define SWIG_TYPECHECK_BOOL_ARRAY 1015 %enddef -%define SWIG_TYPECHECK_INT8_ARRAY 1025 %enddef -%define SWIG_TYPECHECK_INT16_ARRAY 1035 %enddef -%define SWIG_TYPECHECK_INT32_ARRAY 1045 %enddef -%define SWIG_TYPECHECK_INT64_ARRAY 1055 %enddef -%define SWIG_TYPECHECK_INT128_ARRAY 1065 %enddef -%define SWIG_TYPECHECK_FLOAT_ARRAY 1080 %enddef -%define SWIG_TYPECHECK_DOUBLE_ARRAY 1090 %enddef -%define SWIG_TYPECHECK_CHAR_ARRAY 1130 %enddef -%define SWIG_TYPECHECK_STRING_ARRAY 1140 %enddef -%define SWIG_TYPECHECK_OBJECT_ARRAY 1150 %enddef - -%define SWIG_TYPECHECK_BOOL_PTR 2015 %enddef -%define SWIG_TYPECHECK_UINT8_PTR 2020 %enddef -%define SWIG_TYPECHECK_INT8_PTR 2025 %enddef -%define SWIG_TYPECHECK_UINT16_PTR 2030 %enddef -%define SWIG_TYPECHECK_INT16_PTR 2035 %enddef -%define SWIG_TYPECHECK_UINT32_PTR 2040 %enddef -%define SWIG_TYPECHECK_INT32_PTR 2045 %enddef -%define SWIG_TYPECHECK_UINT64_PTR 2050 %enddef -%define SWIG_TYPECHECK_INT64_PTR 2055 %enddef -%define SWIG_TYPECHECK_FLOAT_PTR 2080 %enddef -%define SWIG_TYPECHECK_DOUBLE_PTR 2090 %enddef -%define SWIG_TYPECHECK_CHAR_PTR 2130 %enddef - - -%define SWIG_TYPECHECK_SWIGOBJECT 5000 %enddef - - /* ----------------------------------------------------------------------------- * Runtime code * ----------------------------------------------------------------------------- */ diff --git a/Lib/swigwarnings.swg b/Lib/swigwarnings.swg index 21498ebd3..34c98fbda 100644 --- a/Lib/swigwarnings.swg +++ b/Lib/swigwarnings.swg @@ -54,6 +54,7 @@ %define SWIGWARN_TYPEMAP_SWIGTYPELEAK_MSG "454:Setting a pointer/reference variable may leak memory." %enddef %define SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG "470:Thread/reentrant unsafe wrapping, consider returning by value instead." %enddef %define SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG "473:Returning a pointer or reference in a director method is not recommended." %enddef +%define SWIGWARN_TYPEMAP_INITIALIZER_LIST_MSG "476:Initialization using std::initializer_list." %enddef /* ----------------------------------------------------------------------------- * Operator related warning messages diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index b3eb72493..8ce5ed4dd 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -4635,27 +4635,21 @@ cpp_member : c_declaration { $$ = $1; } cpp_constructor_decl : storage_class type LPAREN parms RPAREN ctor_end { if (Classprefix) { - if ($4 && Getattr($4,"type") && strstr(Char(Getattr($4,"type")), "initializer_list<")) { - /* Ignore constructors containing initializer_list<> introduced in C++0x */ - Swig_warning(WARN_LANG_INITIALIZER_LIST, cparse_file, cparse_line, "Constructor with std::initializer_list<> argument ignored.\n"); - $$ = 0; - } else { - SwigType *decl = NewStringEmpty(); - $$ = new_node("constructor"); - Setattr($$,"storage",$1); - Setattr($$,"name",$2); - Setattr($$,"parms",$4); - SwigType_add_function(decl,$4); - Setattr($$,"decl",decl); - Setattr($$,"throws",$6.throws); - Setattr($$,"throw",$6.throwf); - if (Len(scanner_ccode)) { - String *code = Copy(scanner_ccode); - Setattr($$,"code",code); - Delete(code); - } - SetFlag($$,"feature:new"); - } + SwigType *decl = NewStringEmpty(); + $$ = new_node("constructor"); + Setattr($$,"storage",$1); + Setattr($$,"name",$2); + Setattr($$,"parms",$4); + SwigType_add_function(decl,$4); + Setattr($$,"decl",decl); + Setattr($$,"throws",$6.throws); + Setattr($$,"throw",$6.throwf); + if (Len(scanner_ccode)) { + String *code = Copy(scanner_ccode); + Setattr($$,"code",code); + Delete(code); + } + SetFlag($$,"feature:new"); } else { $$ = 0; } diff --git a/Source/Include/swigwarn.h b/Source/Include/swigwarn.h index ad8d1211d..218cc6f10 100644 --- a/Source/Include/swigwarn.h +++ b/Source/Include/swigwarn.h @@ -174,6 +174,7 @@ #define WARN_TYPEMAP_DIRECTOROUT_PTR 473 #define WARN_TYPEMAP_OUT_OPTIMAL_IGNORED 474 #define WARN_TYPEMAP_OUT_OPTIMAL_MULTIPLE 475 +#define WARN_TYPEMAP_INITIALIZER_LIST 476 /* -- Fragments -- */ #define WARN_FRAGMENT_NOT_FOUND 490 @@ -201,7 +202,6 @@ #define WARN_LANG_TEMPLATE_METHOD_IGNORE 519 #define WARN_LANG_SMARTPTR_MISSING 520 #define WARN_LANG_ILLEGAL_DESTRUCTOR 521 -#define WARN_LANG_INITIALIZER_LIST 522 /* -- Reserved (600-799) -- */ From 6399428a62ed932e593724f4ebb7041b17e7093c Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 4 Feb 2013 20:05:34 +0000 Subject: [PATCH 107/481] Add lambda functions to the symbol tables and add ability to suppress lambda warnings. --- Doc/Manual/Cpp0x.html | 2 +- Examples/test-suite/cpp0x_lambda_functions.i | 28 +++++++++++++++++++- Source/CParse/parser.y | 19 ++++++++++--- Source/Modules/browser.cxx | 6 +++++ Source/Modules/lang.cxx | 5 ++++ Source/Modules/swigmod.h | 1 + Source/Modules/typepass.cxx | 10 ++++++- 7 files changed, 64 insertions(+), 7 deletions(-) diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html index 30a70e75e..b85df1b09 100644 --- a/Doc/Manual/Cpp0x.html +++ b/Doc/Manual/Cpp0x.html @@ -320,7 +320,7 @@ auto sum = [](int x, int y) { return x+y; }; auto sum = [](int x, int y) -> int { return x+y; };
  • -

    The lambda functions are removed from the wrapper class for now, because of the lack of support +

    The lambda functions are removed from the wrappers for now, because of the lack of support for closures (scope of the lambda functions) in the target languages.

    diff --git a/Examples/test-suite/cpp0x_lambda_functions.i b/Examples/test-suite/cpp0x_lambda_functions.i index 0f11f9e63..312414a49 100644 --- a/Examples/test-suite/cpp0x_lambda_functions.i +++ b/Examples/test-suite/cpp0x_lambda_functions.i @@ -5,7 +5,26 @@ */ %module cpp0x_lambda_functions -#pragma SWIG nowarn=SWIGWARN_LANG_NATIVE_UNIMPL +%warnfilter(SWIGWARN_CPP11_LAMBDA) lambda1; +%warnfilter(SWIGWARN_CPP11_LAMBDA) lambda2; +%warnfilter(SWIGWARN_CPP11_LAMBDA) lambda3; +%warnfilter(SWIGWARN_CPP11_LAMBDA) lambda4; +%warnfilter(SWIGWARN_CPP11_LAMBDA) lambda5; +%warnfilter(SWIGWARN_CPP11_LAMBDA) lambda6; +%warnfilter(SWIGWARN_CPP11_LAMBDA) lambda7; +%warnfilter(SWIGWARN_CPP11_LAMBDA) lambda8; +%warnfilter(SWIGWARN_CPP11_LAMBDA) lambda9; +%warnfilter(SWIGWARN_CPP11_LAMBDA) lambda10; +%warnfilter(SWIGWARN_CPP11_LAMBDA) lambda11; +%warnfilter(SWIGWARN_CPP11_LAMBDA) lambda12; +%warnfilter(SWIGWARN_CPP11_LAMBDA) lambda13; +%warnfilter(SWIGWARN_CPP11_LAMBDA) lambda14; +%warnfilter(SWIGWARN_CPP11_LAMBDA) lambda15; +%warnfilter(SWIGWARN_CPP11_LAMBDA) lambda16; +%warnfilter(SWIGWARN_CPP11_LAMBDA) lambda17; +%warnfilter(SWIGWARN_CPP11_LAMBDA) lambda18; +%warnfilter(SWIGWARN_CPP11_LAMBDA) Space1::lambda19; +%warnfilter(SWIGWARN_CPP11_LAMBDA) Space1::Space2::lambda20; %inline %{ /* Defined lambda function with return value. */ @@ -44,6 +63,13 @@ auto lambda16 = [] { return thing; }; auto lambda17 = [] { return thing; }(); constexpr auto lambda18 = [] (int x, int y) mutable throw(int) { return x+y; }; +namespace Space1 { + constexpr auto lambda19 = [] (int x, int y) mutable throw(int) { return x+y; }; + namespace Space2 { + constexpr auto lambda20 = [] (int x, int y) mutable throw(int) { return x+y; }; + } +} + int runLambda1() { return lambda1(5,6); } diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 8ce5ed4dd..b9c51571a 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -3165,7 +3165,12 @@ c_declaration : c_decl { appendChild($$,firstChild($5)); } } - | cpp_lambda_decl { Swig_warning(WARN_CPP11_LAMBDA, cparse_file, cparse_line,"Lambda expressions and closures are not fully supported yet.\n"); $$ = $1; } + | cpp_lambda_decl { + $$ = $1; + SWIG_WARN_NODE_BEGIN($$); + Swig_warning(WARN_CPP11_LAMBDA, cparse_file, cparse_line, "Lambda expressions and closures are not fully supported yet.\n"); + SWIG_WARN_NODE_END($$); + } | USING idcolon EQUAL { skip_decl(); Swig_warning(WARN_CPP11_ALIAS_DECLARATION, cparse_file, cparse_line,"The 'using' keyword in type aliasing is not fully supported yet.\n"); $$ = 0; } | TEMPLATE LESSTHAN template_parms GREATERTHAN USING idcolon EQUAL { skip_decl(); Swig_warning(WARN_CPP11_ALIAS_TEMPLATE, cparse_file, cparse_line,"The 'using' keyword in template aliasing is not fully supported yet.\n"); $$ = 0; } ; @@ -3366,13 +3371,19 @@ cpp_alternate_rettype : primitive_type { $$ = $1; } auto six = [](int x, int y) { return x+y; }(4, 2); ------------------------------------------------------------ */ cpp_lambda_decl : storage_class AUTO idcolon EQUAL lambda_introducer LPAREN parms RPAREN cpp_const lambda_body lambda_tail { - $$ = 0; + $$ = new_node("lambda"); + Setattr($$,"name",$3); + add_symbols($$); } | storage_class AUTO idcolon EQUAL lambda_introducer LPAREN parms RPAREN cpp_const ARROW type lambda_body lambda_tail { - $$ = 0; + $$ = new_node("lambda"); + Setattr($$,"name",$3); + add_symbols($$); } | storage_class AUTO idcolon EQUAL lambda_introducer lambda_body lambda_tail { - $$ = 0; + $$ = new_node("lambda"); + Setattr($$,"name",$3); + add_symbols($$); } ; diff --git a/Source/Modules/browser.cxx b/Source/Modules/browser.cxx index f5ceae5b1..217b40a7e 100644 --- a/Source/Modules/browser.cxx +++ b/Source/Modules/browser.cxx @@ -136,6 +136,12 @@ public: return SWIG_OK; } + virtual int lambdaDeclaration(Node *n) { + show_attributes(n); + emit_children(n); + return SWIG_OK; + } + virtual int enumDeclaration(Node *n) { show_attributes(n); emit_children(n); diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 4f1657825..1890add23 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -139,6 +139,8 @@ int Dispatcher::emit_one(Node *n) { ret = namespaceDeclaration(n); } else if (strcmp(tag, "template") == 0) { ret = templateDeclaration(n); + } else if (strcmp(tag, "lambda") == 0) { + ret = lambdaDeclaration(n); } /* =============================================================== @@ -285,6 +287,9 @@ int Dispatcher::classDeclaration(Node *n) { int Dispatcher::templateDeclaration(Node *n) { return defaultHandler(n); } +int Dispatcher::lambdaDeclaration(Node *n) { + return defaultHandler(n); +} int Dispatcher::classforwardDeclaration(Node *n) { return defaultHandler(n); } diff --git a/Source/Modules/swigmod.h b/Source/Modules/swigmod.h index b3722af40..32fd06339 100644 --- a/Source/Modules/swigmod.h +++ b/Source/Modules/swigmod.h @@ -99,6 +99,7 @@ public: virtual int usingDeclaration(Node *n); virtual int namespaceDeclaration(Node *n); virtual int templateDeclaration(Node *n); + virtual int lambdaDeclaration(Node *n); enum AccessMode { PUBLIC, PRIVATE, PROTECTED }; diff --git a/Source/Modules/typepass.cxx b/Source/Modules/typepass.cxx index bdd64e3a5..af16afb21 100644 --- a/Source/Modules/typepass.cxx +++ b/Source/Modules/typepass.cxx @@ -524,7 +524,7 @@ class TypePass:private Dispatcher { } /* ------------------------------------------------------------ - * namespaceDeclaration() + * templateDeclaration() * ------------------------------------------------------------ */ virtual int templateDeclaration(Node *n) { @@ -543,6 +543,14 @@ class TypePass:private Dispatcher { return SWIG_OK; } + /* ------------------------------------------------------------ + * lambdaDeclaration() + * ------------------------------------------------------------ */ + + virtual int lambdaDeclaration(Node *) { + return SWIG_OK; + } + /* ------------------------------------------------------------ * classforwardDeclaration() * ------------------------------------------------------------ */ From 3020bc328c5f832504882819723ac80ecf7e66eb Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 4 Feb 2013 20:26:52 +0000 Subject: [PATCH 108/481] Add template aliasing and type aliasing into symbol table and enable explicit warning suppression for these. They still need to be added into the parse tree and dealt with. --- Examples/test-suite/cpp0x_template_typedefs.i | 4 ++++ Source/CParse/parser.y | 24 +++++++++++++++++-- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/Examples/test-suite/cpp0x_template_typedefs.i b/Examples/test-suite/cpp0x_template_typedefs.i index bd7e2b220..aeffde11a 100644 --- a/Examples/test-suite/cpp0x_template_typedefs.i +++ b/Examples/test-suite/cpp0x_template_typedefs.i @@ -1,6 +1,9 @@ /* This testcase checks whether SWIG correctly parses alias templates. */ %module cpp0x_template_typedefs +%warnfilter(SWIGWARN_CPP11_ALIAS_TEMPLATE) TypedefName; +%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) PF; + %inline %{ template< typename T1, typename T2, int > class SomeType { @@ -9,6 +12,7 @@ class SomeType { int c; }; +// template aliasing template< typename T2 > using TypedefName = SomeType; diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index b9c51571a..5bbb63846 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -3171,8 +3171,28 @@ c_declaration : c_decl { Swig_warning(WARN_CPP11_LAMBDA, cparse_file, cparse_line, "Lambda expressions and closures are not fully supported yet.\n"); SWIG_WARN_NODE_END($$); } - | USING idcolon EQUAL { skip_decl(); Swig_warning(WARN_CPP11_ALIAS_DECLARATION, cparse_file, cparse_line,"The 'using' keyword in type aliasing is not fully supported yet.\n"); $$ = 0; } - | TEMPLATE LESSTHAN template_parms GREATERTHAN USING idcolon EQUAL { skip_decl(); Swig_warning(WARN_CPP11_ALIAS_TEMPLATE, cparse_file, cparse_line,"The 'using' keyword in template aliasing is not fully supported yet.\n"); $$ = 0; } + | USING idcolon EQUAL { + skip_decl(); + $$ = new_node("using"); + Setattr($$,"name",$2); + add_symbols($$); + SWIG_WARN_NODE_BEGIN($$); + Swig_warning(WARN_CPP11_ALIAS_DECLARATION, cparse_file, cparse_line, "The 'using' keyword in type aliasing is not fully supported yet.\n"); + SWIG_WARN_NODE_END($$); + + $$ = 0; /* TODO - ignored for now */ + } + | TEMPLATE LESSTHAN template_parms GREATERTHAN USING idcolon EQUAL { + skip_decl(); + $$ = new_node("using"); + Setattr($$,"name",$6); + add_symbols($$); + SWIG_WARN_NODE_BEGIN($$); + Swig_warning(WARN_CPP11_ALIAS_TEMPLATE, cparse_file, cparse_line, "The 'using' keyword in template aliasing is not fully supported yet.\n"); + SWIG_WARN_NODE_END($$); + + $$ = 0; /* TODO - ignored for now */ + } ; /* ------------------------------------------------------------ From dbf4821b18e0811564ae221619efaee3a3fd5ba2 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 5 Feb 2013 07:17:54 +0000 Subject: [PATCH 109/481] Add ability to suppress variadic template first argumnet warning --- Source/CParse/parser.y | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 5bbb63846..f1973a05c 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -2967,7 +2967,9 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va p = tp; def_supplied = 1; } else if (p && !tp) { /* Variadic template - tp < p */ + SWIG_WARN_NODE_BEGIN(nn); Swig_warning(WARN_CPP11_VARIADIC_TEMPLATE,cparse_file, cparse_line,"Only the first variadic template argument is currently supported.\n"); + SWIG_WARN_NODE_END(nn); break; } } From c1b99d427987524349e0c9ae427b7c694231d266 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 5 Feb 2013 23:08:08 +0000 Subject: [PATCH 110/481] User defined literals: fix for %rename and update docs --- Doc/Manual/Cpp0x.html | 28 ++++++++++++++++--- .../test-suite/cpp0x_userdefined_literals.i | 27 ++++++++++++++++++ Source/CParse/parser.y | 3 +- 3 files changed, 53 insertions(+), 5 deletions(-) diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html index b85df1b09..e9576ec84 100644 --- a/Doc/Manual/Cpp0x.html +++ b/Doc/Manual/Cpp0x.html @@ -631,7 +631,7 @@ In the above example SIZE is of course wrapped as a constant.

    7.2.18 New string literals

    -

    SWIG fully supports unicode string constants and raw string literals.

    +

    SWIG supports unicode string constants and raw string literals.

     // New string literals
    @@ -685,12 +685,32 @@ OutputType operator "" _mySuffix(const char32_t * string_values, size_t num_char
     

    -Note that the %rename directive currently does not parse the double quotes, so these can't be easily accessed from -target languages. +Like other operators that SWIG parses, a warning is given about renaming the operator in order for it to be wrapped:

    +
    +example.i:27: Warning 503: Can't wrap 'operator "" _myRawLiteral' unless renamed to a valid identifier.
    +
    +

    -Use of user-defined literals such as the following still give a syntax error: +If %rename is used, then it can be called like any other wrapped method. +Currently you need to specify the full declaration including parameters for %rename: +

    + +
    +%rename(MyRawLiteral)  operator"" _myRawLiteral(const char * value);
    +
    + +

    +Or if you just wish to ignore it altogether: +

    + +
    +%ignore operator "" _myRawLiteral(const char * value);
    +
    + +

    +Note that use of user-defined literals such as the following still give a syntax error:

    diff --git a/Examples/test-suite/cpp0x_userdefined_literals.i b/Examples/test-suite/cpp0x_userdefined_literals.i
    index b21ff762d..d20345fed 100644
    --- a/Examples/test-suite/cpp0x_userdefined_literals.i
    +++ b/Examples/test-suite/cpp0x_userdefined_literals.i
    @@ -2,6 +2,17 @@
        introduced in C++0x. */
     %module cpp0x_userdefined_literals
     
    +// Unfortunately full declaration is needed for %rename atm, the parameter list cannot be omitted.
    +%rename(MyRawLiteral)  operator"" _myRawLiteral(const char * value);
    +%rename(MySuffixIntegral) operator "" _mySuffixIntegral(unsigned long long);
    +%rename(MySuffixFloat) operator "" _mySuffixFloat(long double);
    +%rename(MySuffix1) operator "" _mySuffix1(const char * string_values, size_t num_chars);
    +%rename(MySuffix2) operator "" _mySuffix2(const wchar_t * string_values, size_t num_chars);
    +%rename(MySuffix3) operator "" _mySuffix3(const char16_t * string_values, size_t num_chars);
    +%rename(MySuffix4) operator "" _mySuffix4(const char32_t * string_values, size_t num_chars);
    +
    +%ignore operator "" _myRawLiteralIgnored(const char * value);
    +
     %inline %{
     #include 
     
    @@ -23,4 +34,20 @@ OutputType operator "" _mySuffix2(const wchar_t * string_values, size_t num_char
     OutputType operator "" _mySuffix3(const char16_t * string_values, size_t num_chars) { return OutputType(300); }
     OutputType operator "" _mySuffix4(const char32_t * string_values, size_t num_chars) { return OutputType(400); }
     
    +OutputType operator"" _myRawLiteralIgnored(const char * value) { return OutputType(15); }
     %}
    +
    +%{
    +// TODO: SWIG cannot parse these
    +OutputType some_variable_a = 1234_myRawLiteral;
    +
    +OutputType some_variable_b = 1234_mySuffixIntegral;
    +OutputType some_variable_c = 3.1416_mySuffixFloat;
    +
    +OutputType some_variable_d =   "1234"_mySuffix1;
    +OutputType some_variable_e = u8"1234"_mySuffix1;
    +OutputType some_variable_f =  L"1234"_mySuffix2;
    +OutputType some_variable_g =  u"1234"_mySuffix3;
    +OutputType some_variable_h =  U"1234"_mySuffix4;
    +%}
    +
    diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y
    index f1973a05c..dfa2f8de2 100644
    --- a/Source/CParse/parser.y
    +++ b/Source/CParse/parser.y
    @@ -5677,10 +5677,11 @@ direct_declarator : idcolon {
     		    }
                      }
                      /* User-defined string literals. eg.
    -                    int operator""_mySuffix(const char* val, int length) {...} */
    +                    int operator"" _mySuffix(const char* val, int length) {...} */
     		 /* This produces one S/R conflict. */
                      | OPERATOR ID LPAREN parms RPAREN {
     		    SwigType *t;
    +                    Append($1, " "); /* intervening space is mandatory */
                         Append($1, Char($2));
     		    $$.id = Char($1);
     		    t = NewStringEmpty();
    
    From c6bc7b881f0b8f7fa26cddbc8a997b7be877b6e1 Mon Sep 17 00:00:00 2001
    From: William S Fulton 
    Date: Tue, 5 Feb 2013 23:09:21 +0000
    Subject: [PATCH 111/481] Remove test tokens
    
    ---
     Source/CParse/parser.y | 1 -
     1 file changed, 1 deletion(-)
    
    diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y
    index dfa2f8de2..45b691689 100644
    --- a/Source/CParse/parser.y
    +++ b/Source/CParse/parser.y
    @@ -1725,7 +1725,6 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) {
     %token  OPERATOR
     %token  COPERATOR
     %token PARSETYPE PARSEPARM PARSEPARMS
    -%token TEST1 TEST2 TEST3
     
     %left  CAST
     %left  QUESTIONMARK
    
    From b725625e6fc29fc38e561f1c8455f4559add4d5e Mon Sep 17 00:00:00 2001
    From: William S Fulton 
    Date: Fri, 8 Feb 2013 06:34:35 +0000
    Subject: [PATCH 112/481] Add support for thread_local when specified with
     other legitimate storage class specifiers - extern and static
    
    ---
     Doc/Manual/Cpp0x.html                         | 13 ++++--
     Examples/test-suite/cpp0x_thread_local.i      | 26 +++++++++--
     .../java/cpp0x_thread_local_runme.java        | 43 +++++++++++++++++++
     .../python/cpp0x_thread_local_runme.py        | 30 +++++++++++++
     Source/CParse/parser.y                        |  4 ++
     Source/Modules/allocate.cxx                   |  2 +-
     Source/Modules/contract.cxx                   |  2 +-
     Source/Modules/directors.cxx                  |  4 +-
     Source/Modules/go.cxx                         |  4 +-
     Source/Modules/lang.cxx                       |  7 ++-
     Source/Modules/typepass.cxx                   |  2 +-
     Source/Swig/cwrap.c                           |  6 +--
     Source/Swig/misc.c                            | 21 +++++++++
     Source/Swig/naming.c                          |  3 +-
     Source/Swig/swig.h                            |  2 +
     15 files changed, 145 insertions(+), 24 deletions(-)
     create mode 100644 Examples/test-suite/java/cpp0x_thread_local_runme.java
     create mode 100644 Examples/test-suite/python/cpp0x_thread_local_runme.py
    
    diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/Cpp0x.html
    index e9576ec84..457a7e41d 100644
    --- a/Doc/Manual/Cpp0x.html
    +++ b/Doc/Manual/Cpp0x.html
    @@ -722,17 +722,22 @@ OutputType var3 = 3.1416_suffix;
     

    7.2.20 Thread-local storage

    -

    SWIG correctly parses the thread_local keyword. For example, a variable +

    SWIG correctly parses the thread_local keyword. For example, variable reachable by the current thread can be defined as:

     struct A {
    -   thread_local int val;
    +   static thread_local int val;
     };
    +thread_local int global_val;
     
    -

    The new C++0x threading libraries are ignored because each SWIG target language offers -its own threading facilities.

    +

    +The use of the thread_local storage specifier does not affect the wrapping process; it does not modify +the wrapper code compared to when it is not specified. +A variable will be thread local if accessed from different threads from the target language in the +same way that it will be thread local if accessed from C++ code. +

    7.2.21 Defaulting/deleting of standard functions on C++ objects

    diff --git a/Examples/test-suite/cpp0x_thread_local.i b/Examples/test-suite/cpp0x_thread_local.i index 2ec633319..5ba01ea58 100644 --- a/Examples/test-suite/cpp0x_thread_local.i +++ b/Examples/test-suite/cpp0x_thread_local.i @@ -1,11 +1,29 @@ -/* This testcase checks whether SWIG correctly parses the 'thread_local' - keyword before the member type and name. */ +/* This testcase checks whether SWIG correctly parses the 'thread_local' storage specifier */ %module cpp0x_thread_local %inline %{ -struct A { - thread_local int val; +struct ThreadLocals { +// thread_local int tval; // members must also be declared static + static thread_local int stval; + thread_local static int tsval; + static thread_local const int stcval88 = 88; + thread_local static const int tscval99 = 99; }; +thread_local int tval; +static thread_local int stval; +thread_local static int tsval; +extern thread_local int etval; +thread_local extern int teval; + +thread_local int ThreadLocals::stval = 11; +thread_local int ThreadLocals::tsval = 22; +thread_local const int ThreadLocals::stcval88; +thread_local const int ThreadLocals::tscval99; %} +%{ +// externs +thread_local int etval = 33; +thread_local int teval = 44; +%} diff --git a/Examples/test-suite/java/cpp0x_thread_local_runme.java b/Examples/test-suite/java/cpp0x_thread_local_runme.java new file mode 100644 index 000000000..adc88a903 --- /dev/null +++ b/Examples/test-suite/java/cpp0x_thread_local_runme.java @@ -0,0 +1,43 @@ +import cpp0x_thread_local.*; + +public class cpp0x_thread_local_runme { + + static { + try { + System.loadLibrary("cpp0x_thread_local"); + } 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[]) + { + if (ThreadLocals.getStval() != 11) + throw new RuntimeException(); + if (ThreadLocals.getTsval() != 22) + throw new RuntimeException(); + if (ThreadLocals.tscval99 != 99) + throw new RuntimeException(); + + cpp0x_thread_local.setEtval(-11); + if (cpp0x_thread_local.getEtval() != -11) + throw new RuntimeException(); + + cpp0x_thread_local.setStval(-22); + if (cpp0x_thread_local.getStval() != -22) + throw new RuntimeException(); + + cpp0x_thread_local.setTsval(-33); + if (cpp0x_thread_local.getTsval() != -33) + throw new RuntimeException(); + + cpp0x_thread_local.setEtval(-44); + if (cpp0x_thread_local.getEtval() != -44) + throw new RuntimeException(); + + cpp0x_thread_local.setTeval(-55); + if (cpp0x_thread_local.getTeval() != -55) + throw new RuntimeException(); + } +} diff --git a/Examples/test-suite/python/cpp0x_thread_local_runme.py b/Examples/test-suite/python/cpp0x_thread_local_runme.py new file mode 100644 index 000000000..b4aa177f6 --- /dev/null +++ b/Examples/test-suite/python/cpp0x_thread_local_runme.py @@ -0,0 +1,30 @@ +from cpp0x_thread_local import * + +t = ThreadLocals() +if t.stval != 11: + raise RuntimeError +if t.tsval != 22: + raise RuntimeError +if t.tscval99 != 99: + raise RuntimeError + +cvar.etval = -11 +if cvar.etval != -11: + raise RuntimeError + +cvar.stval = -22 +if cvar.stval != -22: + raise RuntimeError + +cvar.tsval = -33 +if cvar.tsval != -33: + raise RuntimeError + +cvar.etval = -44 +if cvar.etval != -44: + raise RuntimeError + +cvar.teval = -55 +if cvar.teval != -55: + raise RuntimeError + diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 45b691689..33f11958e 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -5041,6 +5041,10 @@ storage_class : EXTERN { $$ = "extern"; } | EXPLICIT { $$ = "explicit"; } | CONSTEXPR { $$ = "constexpr"; } | THREAD_LOCAL { $$ = "thread_local"; } + | THREAD_LOCAL STATIC { $$ = "static thread_local"; } + | STATIC THREAD_LOCAL { $$ = "static thread_local"; } + | EXTERN THREAD_LOCAL { $$ = "extern thread_local"; } + | THREAD_LOCAL EXTERN { $$ = "extern thread_local"; } | empty { $$ = 0; } ; diff --git a/Source/Modules/allocate.cxx b/Source/Modules/allocate.cxx index 5320d9689..dee044bf3 100644 --- a/Source/Modules/allocate.cxx +++ b/Source/Modules/allocate.cxx @@ -771,7 +771,7 @@ Allocate(): /* Check to see if this is a static member or not. If so, we add an attribute cplus:staticbase that saves the current class */ - if (checkAttribute(n, "storage", "static")) { + if (Swig_storage_isstatic(n)) { Setattr(n, "cplus:staticbase", inclass); } diff --git a/Source/Modules/contract.cxx b/Source/Modules/contract.cxx index 5fa5bcad5..ffd799cfd 100644 --- a/Source/Modules/contract.cxx +++ b/Source/Modules/contract.cxx @@ -307,7 +307,7 @@ int Contracts::cDeclaration(Node *n) { return SWIG_OK; if (Getattr(n, "feature:contract")) - ret = emit_contract(n, (InClass && !checkAttribute(n, "storage", "static"))); + ret = emit_contract(n, InClass && !Swig_storage_isstatic(n)); return ret; } diff --git a/Source/Modules/directors.cxx b/Source/Modules/directors.cxx index 4cb38d0aa..2fdda5a12 100644 --- a/Source/Modules/directors.cxx +++ b/Source/Modules/directors.cxx @@ -275,8 +275,8 @@ String *Swig_method_decl(SwigType *rettype, SwigType *decl, const_String_or_char void Swig_director_emit_dynamic_cast(Node *n, Wrapper *f) { // TODO: why is the storage element removed in staticmemberfunctionHandler ?? if ((!is_public(n) && (is_member_director(n) || GetFlag(n, "explicitcall"))) || - (is_non_virtual_protected_access(n) && !(checkAttribute(n, "staticmemberfunctionHandler:storage", "static") || - checkAttribute(n, "storage", "static")) + (is_non_virtual_protected_access(n) && !(Swig_storage_isstatic_custom(n, "staticmemberfunctionHandler:storage") || + Swig_storage_isstatic(n)) && !Equal(nodeType(n), "constructor"))) { Node *parent = Getattr(n, "parentNode"); String *dirname; diff --git a/Source/Modules/go.cxx b/Source/Modules/go.cxx index fa706cb62..52e2459b7 100644 --- a/Source/Modules/go.cxx +++ b/Source/Modules/go.cxx @@ -1611,7 +1611,7 @@ private: return goComplexConstant(n, type); } - if (Getattr(n, "storage") && Strcmp(Getattr(n, "storage"), "static") == 0) { + if (Swig_storage_isstatic(n)) { return goComplexConstant(n, type); } @@ -4860,7 +4860,7 @@ private: bool isStatic(Node *n) { String *storage = Getattr(n, "storage"); - return (storage && (Strcmp(storage, "static") == 0 || Strcmp(storage, "friend") == 0) && (!SmartPointer || !Getattr(n, "allocate:smartpointeraccess"))); + return (storage && (Swig_storage_isstatic(n) || Strcmp(storage, "friend") == 0) && (!SmartPointer || !Getattr(n, "allocate:smartpointeraccess"))); } /* ---------------------------------------------------------------------- diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 1890add23..b4ad9c879 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -1058,7 +1058,7 @@ int Language::cDeclaration(Node *n) { int Language::functionHandler(Node *n) { String *storage = Getattr(n, "storage"); int isfriend = CurrentClass && Cmp(storage, "friend") == 0; - int isstatic = CurrentClass && Cmp(storage, "static") == 0 && !(SmartPointer && Getattr(n, "allocate:smartpointeraccess")); + int isstatic = CurrentClass && Swig_storage_isstatic(n) && !(SmartPointer && Getattr(n, "allocate:smartpointeraccess")); Parm *p = Getattr(n, "parms"); if (GetFlag(n, "feature:del")) { /* the method acts like a delete operator, ie, we need to disown the parameter */ @@ -1366,7 +1366,6 @@ int Language::variableHandler(Node *n) { if (!CurrentClass) { globalvariableHandler(n); } else { - String *storage = Getattr(n, "storage"); Swig_save("variableHandler", n, "feature:immutable", NIL); if (SmartPointer) { /* If a smart-pointer and it's a constant access, we have to set immutable */ @@ -1374,7 +1373,7 @@ int Language::variableHandler(Node *n) { SetFlag(n, "feature:immutable"); } } - if ((Cmp(storage, "static") == 0) && !(SmartPointer && Getattr(n, "allocate:smartpointeraccess"))) { + if (Swig_storage_isstatic(n) && !(SmartPointer && Getattr(n, "allocate:smartpointeraccess"))) { staticmembervariableHandler(n); } else { membervariableHandler(n); @@ -1428,7 +1427,7 @@ int Language::membervariableHandler(Node *n) { String *target = 0; if (!Extend) { if (SmartPointer) { - if (checkAttribute(n, "storage", "static")) { + if (Swig_storage_isstatic(n)) { Node *sn = Getattr(n, "cplus:staticbase"); String *base = Getattr(sn, "name"); target = NewStringf("%s::%s", base, name); diff --git a/Source/Modules/typepass.cxx b/Source/Modules/typepass.cxx index af16afb21..7eebfe80b 100644 --- a/Source/Modules/typepass.cxx +++ b/Source/Modules/typepass.cxx @@ -995,7 +995,7 @@ class TypePass:private Dispatcher { String *symname = Getattr(n, "sym:name"); while (c) { if (Strcmp(nodeType(c), "cdecl") == 0) { - if (!(checkAttribute(c, "storage", "static") + if (!(Swig_storage_isstatic(c) || checkAttribute(c, "storage", "typedef") || checkAttribute(c, "storage", "friend") || (Getattr(c, "feature:extend") && !Getattr(c, "code")) diff --git a/Source/Swig/cwrap.c b/Source/Swig/cwrap.c index de93d84c0..f48108e15 100644 --- a/Source/Swig/cwrap.c +++ b/Source/Swig/cwrap.c @@ -922,7 +922,7 @@ int Swig_MethodToFunction(Node *n, const_String_or_char_ptr nspace, String *clas self = NewString("(*(this))->"); is_smart_pointer_overload = 1; } - else if (Cmp(Getattr(n, "storage"), "static") == 0) { + else if (Swig_storage_isstatic(n)) { String *cname = Getattr(n, "classname") ? Getattr(n, "classname") : classname; String *ctname = SwigType_namestr(cname); self = NewStringf("(*(%s const *)this)->", ctname); @@ -1064,7 +1064,7 @@ int Swig_MethodToFunction(Node *n, const_String_or_char_ptr nspace, String *clas String *func = NewStringf("%s(", mangled); String *cres; - if (Cmp(Getattr(n, "storage"), "static") != 0) { + if (!Swig_storage_isstatic(n)) { String *pname = Swig_cparm_name(pp, i); String *ctname = SwigType_namestr(cname); String *fadd = 0; @@ -1467,7 +1467,7 @@ int Swig_MembergetToFunction(Node *n, String *classname, int flags) { int varcref = flags & CWRAP_NATURAL_VAR; if (flags & CWRAP_SMART_POINTER) { - if (checkAttribute(n, "storage", "static")) { + if (Swig_storage_isstatic(n)) { Node *sn = Getattr(n, "cplus:staticbase"); String *base = Getattr(sn, "name"); self = NewStringf("%s::", base); diff --git a/Source/Swig/misc.c b/Source/Swig/misc.c index 05dd0c480..1b8d79daf 100644 --- a/Source/Swig/misc.c +++ b/Source/Swig/misc.c @@ -262,6 +262,27 @@ void Swig_filename_unescape(String *filename) { #endif } +/* ----------------------------------------------------------------------------- + * Swig_storage_isstatic_custom() + * + * Determine if the storage class specifier is static + * ----------------------------------------------------------------------------- */ + +int Swig_storage_isstatic_custom(Node *n, const_String_or_char_ptr storage_name) { + const String *storage = Getattr(n, storage_name); + return storage ? Strncmp(storage, "static", 6) == 0 : 0; +} + +/* ----------------------------------------------------------------------------- + * Swig_storage_isstatic() + * + * Determine if the storage class specifier is static + * ----------------------------------------------------------------------------- */ + +int Swig_storage_isstatic(Node *n) { + return Swig_storage_isstatic_custom(n, "storage"); +} + /* ----------------------------------------------------------------------------- * Swig_string_escape() * diff --git a/Source/Swig/naming.c b/Source/Swig/naming.c index a4bff35af..119f816dc 100644 --- a/Source/Swig/naming.c +++ b/Source/Swig/naming.c @@ -938,8 +938,7 @@ static int nodes_are_equivalent(Node *a, Node *b, int a_inclass) { } /* static functions */ - if ((Cmp(a_storage, "static") == 0) - || (Cmp(b_storage, "static") == 0)) { + if (Swig_storage_isstatic(a) || Swig_storage_isstatic(b)) { if (Cmp(a_storage, b_storage) != 0) return 0; } diff --git a/Source/Swig/swig.h b/Source/Swig/swig.h index 2dd027155..eccc18308 100644 --- a/Source/Swig/swig.h +++ b/Source/Swig/swig.h @@ -315,6 +315,8 @@ extern int ParmList_is_compactdefargs(ParmList *p); extern void Swig_filename_correct(String *filename); extern String *Swig_filename_escape(String *filename); extern void Swig_filename_unescape(String *filename); + extern int Swig_storage_isstatic_custom(Node *n, const_String_or_char_ptr storage); + extern int Swig_storage_isstatic(Node *n); extern String *Swig_string_escape(String *s); extern String *Swig_string_mangle(const String *s); extern void Swig_scopename_split(const String *s, String **prefix, String **last); From 7fcfdeee0837fb240fb30c521a9471de6e0e7bfa Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 8 Feb 2013 07:38:10 +0000 Subject: [PATCH 113/481] Fixes detecting if a variable is extern when using 'extern thread_local' --- Source/Modules/cffi.cxx | 11 ----------- Source/Modules/clisp.cxx | 4 ++-- Source/Modules/lang.cxx | 8 ++++---- Source/Swig/misc.c | 11 +++++++++++ Source/Swig/swig.h | 1 + 5 files changed, 18 insertions(+), 17 deletions(-) diff --git a/Source/Modules/cffi.cxx b/Source/Modules/cffi.cxx index 29de9f9ed..0b1153d61 100644 --- a/Source/Modules/cffi.cxx +++ b/Source/Modules/cffi.cxx @@ -506,11 +506,6 @@ int CFFI::functionWrapper(Node *n) { void CFFI::emit_defun(Node *n, String *name) { - - // String *storage=Getattr(n,"storage"); - // if(!storage || (Strcmp(storage,"extern") && Strcmp(storage,"externc"))) - // return SWIG_OK; - String *func_name = Getattr(n, "sym:name"); ParmList *pl = Getattr(n, "parms"); @@ -583,12 +578,6 @@ int CFFI::constantWrapper(Node *n) { } int CFFI::variableWrapper(Node *n) { - // String *storage=Getattr(n,"storage"); - // Printf(stdout,"\"%s\" %s)\n",storage,Getattr(n, "sym:name")); - - // if(!storage || (Strcmp(storage,"extern") && Strcmp(storage,"externc"))) - // return SWIG_OK; - String *var_name = Getattr(n, "sym:name"); String *lisp_type = Swig_typemap_lookup("cin", n, "", 0); String *lisp_name = lispify_name(n, var_name, "'variable"); diff --git a/Source/Modules/clisp.cxx b/Source/Modules/clisp.cxx index 4290b5452..7dfa74539 100644 --- a/Source/Modules/clisp.cxx +++ b/Source/Modules/clisp.cxx @@ -148,7 +148,7 @@ int CLISP::top(Node *n) { int CLISP::functionWrapper(Node *n) { is_function = 1; String *storage = Getattr(n, "storage"); - if (!extern_all_flag && (!storage || (Strcmp(storage, "extern") && Strcmp(storage, "externc")))) + if (!extern_all_flag && (!storage || (!Swig_storage_isextern(n) && Strcmp(storage, "externc")))) return SWIG_OK; String *func_name = Getattr(n, "sym:name"); @@ -220,7 +220,7 @@ int CLISP::variableWrapper(Node *n) { // SwigType *type=; String *storage = Getattr(n, "storage"); - if (!extern_all_flag && (!storage || (Strcmp(storage, "extern") && Strcmp(storage, "externc")))) + if (!extern_all_flag && (!storage || (!Swig_storage_isextern(n) && Strcmp(storage, "externc")))) return SWIG_OK; String *var_name = Getattr(n, "sym:name"); diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index b4ad9c879..5aa18a251 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -955,7 +955,7 @@ int Language::cDeclaration(Node *n) { if (AddExtern) { if (f_header) { - if ((Cmp(storage, "extern") == 0) || (ForceExtern && !storage)) { + if (Swig_storage_isextern(n) || (ForceExtern && !storage)) { /* we don't need the 'extern' part in the C/C++ declaration, and it produces some problems when namespace and SUN Studio is used. @@ -1017,12 +1017,12 @@ int Language::cDeclaration(Node *n) { if (Getattr(n, "nested")) SetFlag(n, "feature:immutable"); if (!CurrentClass) { - if ((Cmp(storage, "extern") == 0) || ForceExtern) { - f_header = Swig_filebyname("header"); + if (Swig_storage_isextern(n) || ForceExtern) { if (AddExtern) { + f_header = Swig_filebyname("header"); if (f_header) { String *str = SwigType_str(ty, name); - Printf(f_header, "extern %s;\n", str); + Printf(f_header, "%s %s;\n", Getattr(n, "storage"), str); Delete(str); } } diff --git a/Source/Swig/misc.c b/Source/Swig/misc.c index 1b8d79daf..297d1ccdc 100644 --- a/Source/Swig/misc.c +++ b/Source/Swig/misc.c @@ -262,6 +262,17 @@ void Swig_filename_unescape(String *filename) { #endif } +/* ----------------------------------------------------------------------------- + * Swig_storage_isextern() + * + * Determine if the storage class specifier is extern (but not externc) + * ----------------------------------------------------------------------------- */ + +int Swig_storage_isextern(Node *n) { + const String *storage = Getattr(n, "storage"); + return storage ? Strcmp(storage, "extern") == 0 || Strncmp(storage, "extern ", 7) == 0 : 0; +} + /* ----------------------------------------------------------------------------- * Swig_storage_isstatic_custom() * diff --git a/Source/Swig/swig.h b/Source/Swig/swig.h index eccc18308..85d8c0b3e 100644 --- a/Source/Swig/swig.h +++ b/Source/Swig/swig.h @@ -315,6 +315,7 @@ extern int ParmList_is_compactdefargs(ParmList *p); extern void Swig_filename_correct(String *filename); extern String *Swig_filename_escape(String *filename); extern void Swig_filename_unescape(String *filename); + extern int Swig_storage_isextern(Node *n); extern int Swig_storage_isstatic_custom(Node *n, const_String_or_char_ptr storage); extern int Swig_storage_isstatic(Node *n); extern String *Swig_string_escape(String *s); From e44656cfe5b1d79643a1b972736a5ab485a6e948 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 8 Feb 2013 18:45:29 +0000 Subject: [PATCH 114/481] Add support for extern "C" thread_local --- Examples/test-suite/cpp0x_thread_local.i | 2 ++ .../test-suite/java/cpp0x_thread_local_runme.java | 4 ++++ .../test-suite/python/cpp0x_thread_local_runme.py | 4 ++++ Source/CParse/parser.y | 13 +++++++++++-- Source/Modules/clisp.cxx | 5 ++--- Source/Modules/lang.cxx | 2 +- Source/Swig/misc.c | 11 +++++++++++ Source/Swig/swig.h | 1 + 8 files changed, 36 insertions(+), 6 deletions(-) diff --git a/Examples/test-suite/cpp0x_thread_local.i b/Examples/test-suite/cpp0x_thread_local.i index 5ba01ea58..96faaaec4 100644 --- a/Examples/test-suite/cpp0x_thread_local.i +++ b/Examples/test-suite/cpp0x_thread_local.i @@ -15,6 +15,7 @@ static thread_local int stval; thread_local static int tsval; extern thread_local int etval; thread_local extern int teval; +extern "C" thread_local int ectval; thread_local int ThreadLocals::stval = 11; thread_local int ThreadLocals::tsval = 22; @@ -26,4 +27,5 @@ thread_local const int ThreadLocals::tscval99; // externs thread_local int etval = 33; thread_local int teval = 44; +thread_local int ectval = 55; %} diff --git a/Examples/test-suite/java/cpp0x_thread_local_runme.java b/Examples/test-suite/java/cpp0x_thread_local_runme.java index adc88a903..d660f77db 100644 --- a/Examples/test-suite/java/cpp0x_thread_local_runme.java +++ b/Examples/test-suite/java/cpp0x_thread_local_runme.java @@ -39,5 +39,9 @@ public class cpp0x_thread_local_runme { cpp0x_thread_local.setTeval(-55); if (cpp0x_thread_local.getTeval() != -55) throw new RuntimeException(); + + cpp0x_thread_local.setEctval(-55); + if (cpp0x_thread_local.getEctval() != -55) + throw new RuntimeException(); } } diff --git a/Examples/test-suite/python/cpp0x_thread_local_runme.py b/Examples/test-suite/python/cpp0x_thread_local_runme.py index b4aa177f6..a4d9852f7 100644 --- a/Examples/test-suite/python/cpp0x_thread_local_runme.py +++ b/Examples/test-suite/python/cpp0x_thread_local_runme.py @@ -28,3 +28,7 @@ cvar.teval = -55 if cvar.teval != -55: raise RuntimeError +cvar.ectval = -66 +if cvar.ectval != -66: + raise RuntimeError + diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 33f11958e..35e600d5e 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1491,8 +1491,9 @@ static void new_feature(const char *featurename, String *val, Hash *featureattri /* check if a function declaration is a plain C object */ static int is_cfunction(Node *n) { - if (!cparse_cplusplus || cparse_externc) return 1; - if (Cmp(Getattr(n,"storage"),"externc") == 0) { + if (!cparse_cplusplus || cparse_externc) + return 1; + if (Swig_storage_isexternc(n)) { return 1; } return 0; @@ -5034,6 +5035,14 @@ storage_class : EXTERN { $$ = "extern"; } $$ = 0; } } + | EXTERN string THREAD_LOCAL { + if (strcmp($2,"C") == 0) { + $$ = "externc thread_local"; + } else { + Swig_warning(WARN_PARSE_UNDEFINED_EXTERN,cparse_file, cparse_line,"Unrecognized extern type \"%s\".\n", $2); + $$ = 0; + } + } | STATIC { $$ = "static"; } | TYPEDEF { $$ = "typedef"; } | VIRTUAL { $$ = "virtual"; } diff --git a/Source/Modules/clisp.cxx b/Source/Modules/clisp.cxx index 7dfa74539..e7d971faa 100644 --- a/Source/Modules/clisp.cxx +++ b/Source/Modules/clisp.cxx @@ -148,7 +148,7 @@ int CLISP::top(Node *n) { int CLISP::functionWrapper(Node *n) { is_function = 1; String *storage = Getattr(n, "storage"); - if (!extern_all_flag && (!storage || (!Swig_storage_isextern(n) && Strcmp(storage, "externc")))) + if (!extern_all_flag && (!storage || (!Swig_storage_isextern(n) && !Swig_storage_isexternc(n)))) return SWIG_OK; String *func_name = Getattr(n, "sym:name"); @@ -217,10 +217,9 @@ int CLISP::constantWrapper(Node *n) { int CLISP::variableWrapper(Node *n) { is_function = 0; - // SwigType *type=; String *storage = Getattr(n, "storage"); - if (!extern_all_flag && (!storage || (!Swig_storage_isextern(n) && Strcmp(storage, "externc")))) + if (!extern_all_flag && (!storage || (!Swig_storage_isextern(n) && !Swig_storage_isexternc(n)))) return SWIG_OK; String *var_name = Getattr(n, "sym:name"); diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 5aa18a251..6c2ea8271 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -985,7 +985,7 @@ int Language::cDeclaration(Node *n) { } } Printf(f_header, ";\n"); - } else if (Cmp(storage, "externc") == 0) { + } else if (Swig_storage_isexternc(n)) { /* here 'extern "C"' is needed */ String *str = SwigType_str(ty, name); Printf(f_header, "extern \"C\" %s;\n", str); diff --git a/Source/Swig/misc.c b/Source/Swig/misc.c index 297d1ccdc..229633bab 100644 --- a/Source/Swig/misc.c +++ b/Source/Swig/misc.c @@ -273,6 +273,17 @@ int Swig_storage_isextern(Node *n) { return storage ? Strcmp(storage, "extern") == 0 || Strncmp(storage, "extern ", 7) == 0 : 0; } +/* ----------------------------------------------------------------------------- + * Swig_storage_isexternc() + * + * Determine if the storage class specifier is externc (but not plain extern) + * ----------------------------------------------------------------------------- */ + +int Swig_storage_isexternc(Node *n) { + const String *storage = Getattr(n, "storage"); + return storage ? Strcmp(storage, "externc") == 0 || Strncmp(storage, "externc ", 8) == 0 : 0; +} + /* ----------------------------------------------------------------------------- * Swig_storage_isstatic_custom() * diff --git a/Source/Swig/swig.h b/Source/Swig/swig.h index 85d8c0b3e..b730ab04d 100644 --- a/Source/Swig/swig.h +++ b/Source/Swig/swig.h @@ -316,6 +316,7 @@ extern int ParmList_is_compactdefargs(ParmList *p); extern String *Swig_filename_escape(String *filename); extern void Swig_filename_unescape(String *filename); extern int Swig_storage_isextern(Node *n); + extern int Swig_storage_isexternc(Node *n); extern int Swig_storage_isstatic_custom(Node *n, const_String_or_char_ptr storage); extern int Swig_storage_isstatic(Node *n); extern String *Swig_string_escape(String *s); From 8778724768e284e584b065063a1957fdd1fa9428 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 8 Feb 2013 18:55:16 +0000 Subject: [PATCH 115/481] Add support for extern "C++" - no warning should be issued as was previously occurring --- Examples/test-suite/common.mk | 2 +- Examples/test-suite/cpp0x_thread_local.i | 2 ++ Examples/test-suite/java/cpp0x_thread_local_runme.java | 4 ++++ Examples/test-suite/python/cpp0x_thread_local_runme.py | 4 ++++ Source/CParse/parser.y | 6 +++++- 5 files changed, 16 insertions(+), 2 deletions(-) diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 4b4228db8..c0f642212 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -507,7 +507,7 @@ CPP0X_TEST_CASES = \ # cpp0x_inheriting_constructors \ # not supported by gcc-4.7 # cpp0x_hash_tables \ # not fully implemented yet # cpp0x_result_of \ # SWIG does not support -# cpp0x_thread_local \ # not supported by any compiler yet +# cpp0x_thread_local \ # needs gcc-4.8 # Broken C++0x test cases. CPP0X_TEST_BROKEN = diff --git a/Examples/test-suite/cpp0x_thread_local.i b/Examples/test-suite/cpp0x_thread_local.i index 96faaaec4..00f12dff9 100644 --- a/Examples/test-suite/cpp0x_thread_local.i +++ b/Examples/test-suite/cpp0x_thread_local.i @@ -16,6 +16,7 @@ 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 ecpptval; thread_local int ThreadLocals::stval = 11; thread_local int ThreadLocals::tsval = 22; @@ -28,4 +29,5 @@ thread_local const int ThreadLocals::tscval99; thread_local int etval = 33; thread_local int teval = 44; thread_local int ectval = 55; +thread_local int ecpptval = 66; %} diff --git a/Examples/test-suite/java/cpp0x_thread_local_runme.java b/Examples/test-suite/java/cpp0x_thread_local_runme.java index d660f77db..dc7cafafe 100644 --- a/Examples/test-suite/java/cpp0x_thread_local_runme.java +++ b/Examples/test-suite/java/cpp0x_thread_local_runme.java @@ -43,5 +43,9 @@ public class cpp0x_thread_local_runme { cpp0x_thread_local.setEctval(-55); if (cpp0x_thread_local.getEctval() != -55) throw new RuntimeException(); + + cpp0x_thread_local.setEcpptval(-66); + if (cpp0x_thread_local.getEcpptval() != -66) + throw new RuntimeException(); } } diff --git a/Examples/test-suite/python/cpp0x_thread_local_runme.py b/Examples/test-suite/python/cpp0x_thread_local_runme.py index a4d9852f7..ff27b7785 100644 --- a/Examples/test-suite/python/cpp0x_thread_local_runme.py +++ b/Examples/test-suite/python/cpp0x_thread_local_runme.py @@ -32,3 +32,7 @@ cvar.ectval = -66 if cvar.ectval != -66: raise RuntimeError +cvar.ecpptval = -66 +if cvar.ecpptval != -66: + raise RuntimeError + diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 35e600d5e..dc033ed7b 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -5027,9 +5027,11 @@ anon_bitfield_type : primitive_type { $$ = $1; * ====================================================================== */ storage_class : EXTERN { $$ = "extern"; } - | EXTERN string { + | EXTERN string { if (strcmp($2,"C") == 0) { $$ = "externc"; + } else if (strcmp($2,"C++") == 0) { + $$ = "extern"; } else { Swig_warning(WARN_PARSE_UNDEFINED_EXTERN,cparse_file, cparse_line,"Unrecognized extern type \"%s\".\n", $2); $$ = 0; @@ -5038,6 +5040,8 @@ storage_class : EXTERN { $$ = "extern"; } | EXTERN string THREAD_LOCAL { if (strcmp($2,"C") == 0) { $$ = "externc thread_local"; + } else if (strcmp($2,"C++") == 0) { + $$ = "extern thread_local"; } else { Swig_warning(WARN_PARSE_UNDEFINED_EXTERN,cparse_file, cparse_line,"Unrecognized extern type \"%s\".\n", $2); $$ = 0; From f17700aa1dc399dca66a45323eff81982856b250 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 8 Feb 2013 21:53:11 +0000 Subject: [PATCH 116/481] Suppress leaking memory warnings in rvalue reference tests --- Examples/test-suite/cpp0x_rvalue_reference2.i | 2 ++ Examples/test-suite/cpp0x_rvalue_reference3.i | 2 ++ 2 files changed, 4 insertions(+) diff --git a/Examples/test-suite/cpp0x_rvalue_reference2.i b/Examples/test-suite/cpp0x_rvalue_reference2.i index b7f58afee..dbeaa78fa 100644 --- a/Examples/test-suite/cpp0x_rvalue_reference2.i +++ b/Examples/test-suite/cpp0x_rvalue_reference2.i @@ -1,5 +1,7 @@ %module cpp0x_rvalue_reference2 +%warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK) globalrrval; + // This testcase tests lots of different places that rvalue reference syntax can be used %typemap(in) Something && "/*in Something && typemap*/" diff --git a/Examples/test-suite/cpp0x_rvalue_reference3.i b/Examples/test-suite/cpp0x_rvalue_reference3.i index c6fe60068..2da1bf741 100644 --- a/Examples/test-suite/cpp0x_rvalue_reference3.i +++ b/Examples/test-suite/cpp0x_rvalue_reference3.i @@ -1,5 +1,7 @@ %module cpp0x_rvalue_reference3 +%warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK); + %inline %{ #include struct Thing {}; From 67659773ccfd927ca86b35c31c7bb338532c2729 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 2 Sep 2013 19:14:20 +0100 Subject: [PATCH 117/481] Remove some Java references from C# module --- Source/Modules/csharp.cxx | 6 +++--- Source/Modules/java.cxx | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Source/Modules/csharp.cxx b/Source/Modules/csharp.cxx index 44db84264..d30f278fc 100644 --- a/Source/Modules/csharp.cxx +++ b/Source/Modules/csharp.cxx @@ -4028,7 +4028,7 @@ public: Delete(director_ctor_code); director_ctor_code = NewString("$director_new"); - Java_director_declaration(n); + directorDeclaration(n); Printf(f_directors_h, "%s {\n", Getattr(n, "director:decl")); Printf(f_directors_h, "\npublic:\n"); @@ -4148,13 +4148,13 @@ public: } /*---------------------------------------------------------------------- - * Java_director_declaration() + * directorDeclaration() * * Generate the director class's declaration * e.g. "class SwigDirector_myclass : public myclass, public Swig::Director {" *--------------------------------------------------------------------*/ - void Java_director_declaration(Node *n) { + void directorDeclaration(Node *n) { String *base = Getattr(n, "classtype"); String *class_ctor = NewString("Swig::Director()"); diff --git a/Source/Modules/java.cxx b/Source/Modules/java.cxx index b99bbb4ee..24435ac30 100644 --- a/Source/Modules/java.cxx +++ b/Source/Modules/java.cxx @@ -4221,7 +4221,7 @@ public: Delete(director_ctor_code); director_ctor_code = NewString("$director_new"); - Java_director_declaration(n); + directorDeclaration(n); Printf(f_directors_h, "%s {\n", Getattr(n, "director:decl")); Printf(f_directors_h, "\npublic:\n"); @@ -4405,13 +4405,13 @@ public: } /*---------------------------------------------------------------------- - * Java_director_declaration() + * directorDeclaration() * * Generate the director class's declaration * e.g. "class SwigDirector_myclass : public myclass, public Swig::Director {" *--------------------------------------------------------------------*/ - void Java_director_declaration(Node *n) { + void directorDeclaration(Node *n) { String *base = Getattr(n, "classtype"); String *class_ctor = NewString("Swig::Director(jenv)"); From f47075ec991716733d7e3588aea5e58673c004ff Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 3 Sep 2013 23:58:05 +0100 Subject: [PATCH 118/481] Smart pointer documentation improvement --- Doc/Manual/SWIGPlus.html | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Doc/Manual/SWIGPlus.html b/Doc/Manual/SWIGPlus.html index 716882f53..2713725d7 100644 --- a/Doc/Manual/SWIGPlus.html +++ b/Doc/Manual/SWIGPlus.html @@ -4433,7 +4433,7 @@ around some other class. For example: template<class T> class SmartPtr { T *pointee; public: - ... + SmartPtr(T *p) : pointee(p) { ... } T *operator->() { return pointee; } @@ -4453,7 +4453,7 @@ typedef SmartPtr<Foo_Impl> Foo; // Create smart pointer Foo Foo make_Foo() { - return SmartPtr(new Foo_Impl()); + return SmartPtr<Foo_Impl>(new Foo_Impl()); } // Do something with smart pointer Foo @@ -4461,6 +4461,9 @@ void do_something(Foo f) { printf("x = %d\n", f->x); f->bar(); } + +// Call the wrapped smart pointer proxy class in the target language 'Foo' +%template(Foo) SmartPtr<Foo_Impl>;
    From a91cd0bc5c1550bfa2c922c7434323c30ca1fb87 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 12 Sep 2013 07:23:54 +0100 Subject: [PATCH 119/481] Infinity is now by default an acceptable value for type 'float'. This fix makes the handling of type 'float' and 'double' the same. The implementation requires the C99 isfinite() macro, or otherwise some platform dependent equivalents, to be available. --- CHANGES.current | 16 ++++++ Examples/test-suite/common.mk | 3 +- Examples/test-suite/overload_numeric.i | 51 +++++++++++++++++++ .../python/overload_numeric_runme.py | 43 ++++++++++++++++ Lib/typemaps/fragments.swg | 32 +++++++++++- Lib/typemaps/primtypes.swg | 2 +- 6 files changed, 144 insertions(+), 3 deletions(-) create mode 100644 Examples/test-suite/overload_numeric.i create mode 100644 Examples/test-suite/python/overload_numeric_runme.py diff --git a/CHANGES.current b/CHANGES.current index ffb805ccd..77d2df753 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,22 @@ See the RELEASENOTES file for a summary of changes in each release. Version 2.0.11 (in progress) ============================ +2013-09-12: wsfulton + [UTL] Infinity is now by default an acceptable value for type 'float'. This fix makes + the handling of type 'float' and 'double' the same. The implementation requires the + C99 isfinite() macro, or otherwise some platform dependent equivalents, to be available. + + Users requiring the old behaviour of not accepting infinity, can define a 'check' typemap + wherever a float is used, such as: + + %typemap(check,fragment="") float, const float & %{ + if ($1 < -FLT_MAX || $1 > FLT_MAX) { + SWIG_exception_fail(SWIG_TypeError, "Overflow in type float"); + } + %} + + *** POTENTIAL INCOMPATIBILITY *** + 2013-08-30: wsfulton [Lua] Pull Git patch #81: Include Lua error locus in SWIG error messages. This is standard information in Lua error messages, and makes it much diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 5d6a4730a..997f8e715 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -285,8 +285,9 @@ CPP_TEST_CASES += \ operbool \ ordering \ overload_copy \ - overload_method \ overload_extend \ + overload_method \ + overload_numeric \ overload_rename \ overload_return_type \ overload_simple \ diff --git a/Examples/test-suite/overload_numeric.i b/Examples/test-suite/overload_numeric.i new file mode 100644 index 000000000..44c3b811c --- /dev/null +++ b/Examples/test-suite/overload_numeric.i @@ -0,0 +1,51 @@ +%module overload_numeric + +// Tests overloading of integral and floating point types to verify the range checking required +// for dispatch to the correct overloaded method + +#ifdef SWIGLUA +// lua only has one numeric type, so most of the overloads shadow each other creating warnings +%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) Nums::over; +#endif + +%{ +#include +%} + +%inline %{ +#include +#include +struct Limits { + signed char schar_min() { return SCHAR_MIN; } + signed char schar_max() { return SCHAR_MAX; } + short shrt_min() { return SHRT_MIN; } + short shrt_max() { return SHRT_MAX; } + int int_min() { return INT_MIN; } + int int_max() { return INT_MAX; } + float flt_min() { return FLT_MIN; } + float flt_max() { return FLT_MAX; } + double dbl_max() { return DBL_MAX; } +}; + +struct Nums { + const char * over(signed char v) { + return "signed char"; + } + const char * over(short v) { + return "short"; + } + const char * over(int v) { + return "int"; + } + const char * over(float v) { + return "float"; + } + const char * over(double v) { + return "double"; + } + double doublebounce(double v) { + return v; + } +}; +%} + diff --git a/Examples/test-suite/python/overload_numeric_runme.py b/Examples/test-suite/python/overload_numeric_runme.py new file mode 100644 index 000000000..639fb5e5d --- /dev/null +++ b/Examples/test-suite/python/overload_numeric_runme.py @@ -0,0 +1,43 @@ + +from overload_numeric import * +import math + +nums = Nums() +limits = Limits() + +def check(got, expected): + if got != expected: + raise RuntimeError("got: " + got + " expected: " + expected) + +check(nums.over(0), "signed char") +check(nums.over(0.0), "float") + +check(nums.over(limits.schar_min()), "signed char") +check(nums.over(limits.schar_max()), "signed char") + +check(nums.over(limits.schar_min()-1), "short") +check(nums.over(limits.schar_max()+1), "short") +check(nums.over(limits.shrt_min()), "short") +check(nums.over(limits.shrt_max()), "short") + +check(nums.over(limits.shrt_min()-1), "int") +check(nums.over(limits.shrt_max()+1), "int") +check(nums.over(limits.int_min()), "int") +check(nums.over(limits.int_max()), "int") + +check(nums.over(limits.flt_min()), "float") +check(nums.over(limits.flt_max()), "float") + +check(nums.over(limits.flt_max()*10), "double") +check(nums.over(-limits.flt_max()*10), "double") +check(nums.over(limits.dbl_max()), "double") +check(nums.over(-limits.dbl_max()), "double") + +check(nums.over(float("inf")), "float") +check(nums.over(float("-inf")), "float") +check(nums.over(float("nan")), "float") + +# Just check if the following are accepted without exceptions being thrown +nums.doublebounce(float("inf")) +nums.doublebounce(float("-inf")) +nums.doublebounce(float("nan")) diff --git a/Lib/typemaps/fragments.swg b/Lib/typemaps/fragments.swg index 4dbc1f20d..8f887e34e 100644 --- a/Lib/typemaps/fragments.swg +++ b/Lib/typemaps/fragments.swg @@ -153,6 +153,29 @@ #include %} +%fragment("SWIG_isfinite","header",fragment=",") %{ +/* Getting isfinite working pre C99 across multiple platforms is non-trivial. Users can provide SWIG_isfinite on older platforms. */ +#ifndef SWIG_isfinite +# if defined(isfinite) +# define SWIG_isfinite(X) (isfinite(X)) +# elif defined(_MSC_VER) +# define SWIG_isfinite(X) (_finite(X)) +# elif defined(__sun) && defined(__SVR4) +# include +# define SWIG_isfinite(X) (finite(X)) +# endif +#endif +%} + +%fragment("SWIG_Float_Overflow_Check","header",fragment=",SWIG_isfinite") %{ +/* Accept infinite as a valid float value unless we are unable to check if a value is finite */ +#ifdef SWIG_isfinite +# define SWIG_Float_Overflow_Check(X) ((X < -FLT_MAX || X > FLT_MAX) && SWIG_isfinite(X)) +#else +# define SWIG_Float_Overflow_Check(X) ((X < -FLT_MAX || X > FLT_MAX)) +#endif +%} + /* ----------------------------------------------------------------------------- * special macros for fragments * ----------------------------------------------------------------------------- */ @@ -213,13 +236,20 @@ SWIG_AsVal_dec(Type)(SWIG_Object obj, Type *val) %enddef -/* Macro for 'double' derived types */ +/* Macro for floating point derived types (original macro) */ %define %numeric_double(Type, Frag, Min, Max) %numeric_type_from(Type, double) %numeric_signed_type_asval(Type, double, Frag , Min, Max) %enddef +/* Macro for floating point derived types */ + +%define %numeric_float(Type, Frag, OverflowCond) +%numeric_type_from(Type, double) +%numeric_type_asval(Type, double, Frag, OverflowCond) +%enddef + /* Macros for missing fragments */ diff --git a/Lib/typemaps/primtypes.swg b/Lib/typemaps/primtypes.swg index cc8a55e6e..45632c31f 100644 --- a/Lib/typemaps/primtypes.swg +++ b/Lib/typemaps/primtypes.swg @@ -139,7 +139,7 @@ SWIG_AsVal_dec(bool)(SWIG_Object obj, bool *val) /* float */ -%numeric_double(float, "", -FLT_MAX, FLT_MAX) +%numeric_float(float, "SWIG_Float_Overflow_Check", SWIG_Float_Overflow_Check(v)) /* long/unsigned long */ From c3f3880d0c55f55d9f83dd2d84be685b6b361cc7 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Thu, 12 Sep 2013 19:49:51 +0100 Subject: [PATCH 120/481] Lua static member access improvements. 1) Static members and static functions inside class can be accessed as ModuleName.ClassName.FunctionName (MemberName respectively). Old way aka ModuleName.ClassName_FunctionName still works. 2) Same goes for enums inside classes: ModuleName.ClassName.EnumValue1 etc. 3) More 'runme' tests for lua + modifications to existing tests to test new changes. Code is loosely based upon python implemenation of the same thing. Patch #62. --- CHANGES.current | 7 + Examples/test-suite/lua/cpp_basic_runme.lua | 6 + Lib/lua/luarun.swg | 206 +++++++++++++++++++- Source/Modules/lua.cxx | 129 +++++++++++- 4 files changed, 335 insertions(+), 13 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index 77d2df753..b2f007a92 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,13 @@ See the RELEASENOTES file for a summary of changes in each release. Version 2.0.11 (in progress) ============================ +2013-09-12: wsfulton + [Lua] Pull Git patch #62. + 1) Static members and static functions inside class can be accessed as + ModuleName.ClassName.FunctionName (MemberName respectively). Old way such as + ModuleName.ClassName_FunctionName still works. + 2) Same goes for enums inside classes: ModuleName.ClassName.EnumValue1 etc. + 2013-09-12: wsfulton [UTL] Infinity is now by default an acceptable value for type 'float'. This fix makes the handling of type 'float' and 'double' the same. The implementation requires the diff --git a/Examples/test-suite/lua/cpp_basic_runme.lua b/Examples/test-suite/lua/cpp_basic_runme.lua index 02f88479b..3d5ccaadf 100644 --- a/Examples/test-suite/lua/cpp_basic_runme.lua +++ b/Examples/test-suite/lua/cpp_basic_runme.lua @@ -42,16 +42,22 @@ assert(f3.num==32) f4=cb.Foo(6) cb.Bar_global_fptr=f4 assert(cb.Bar_global_fptr.num==6) +assert(cb.Bar.global_fptr.num==6) f4.num=8 assert(cb.Bar_global_fptr.num==8) +assert(cb.Bar.global_fptr.num==8) assert(cb.Bar_global_fref.num==23) +assert(cb.Bar.global_fref.num==23) cb.Bar_global_fref=cb.Foo(-7) -- this will set the value assert(cb.Bar_global_fref.num==-7) +assert(cb.Bar.global_fref.num==-7) assert(cb.Bar_global_fval.num==3) +assert(cb.Bar.global_fval.num==3) cb.Bar_global_fval=cb.Foo(-34) assert(cb.Bar_global_fval.num==-34) +assert(cb.Bar.global_fval.num==-34) -- Now test member function pointers func1_ptr=cb.get_func1_ptr() diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index c705e38e5..4d851bdb1 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -140,6 +140,15 @@ typedef struct { lua_CFunction setmethod; } swig_lua_attribute; +// Can be used to create namespaces. Currently used to +// wrap class static methods/variables/constants +typedef struct { + const char *name; + swig_lua_method *ns_methods; + swig_lua_attribute *ns_attributes; + swig_lua_const_info *ns_constants; +} swig_lua_namespace; + typedef struct swig_lua_class { const char *name; swig_type_info **type; @@ -147,6 +156,7 @@ typedef struct swig_lua_class { void (*destructor)(void *); swig_lua_method *methods; swig_lua_attribute *attributes; + swig_lua_namespace cls_static; struct swig_lua_class **bases; const char **base_names; } swig_lua_class; @@ -415,6 +425,137 @@ SWIGINTERN void SWIG_Lua_module_add_function(lua_State* L,const char* name,lua_ SWIG_Lua_add_function(L,name,fn); } +/* ----------------------------------------------------------------------------- + * global variable support code: namespaces + * ----------------------------------------------------------------------------- */ + +SWIGINTERN int SWIG_Lua_namespace_get(lua_State* L) +{ +/* there should be 2 params passed in + (1) table (not the meta table) + (2) string name of the attribute +*/ + assert(lua_istable(L,-2)); /* just in case */ + lua_getmetatable(L,-2); + assert(lua_istable(L,-1)); + SWIG_Lua_get_table(L,".get"); /* find the .get table */ + assert(lua_istable(L,-1)); + /* look for the key in the .get table */ + lua_pushvalue(L,2); /* key */ + lua_rawget(L,-2); + lua_remove(L,-2); /* stack tidy, remove .get table */ + if (lua_iscfunction(L,-1)) + { /* found it so call the fn & return its value */ + lua_call(L,0,1); /* 1 value in (userdata),1 out (result) */ + lua_remove(L,-2); /* stack tidy, remove metatable */ + return 1; + } + lua_pop(L,1); /* remove whatever was there */ + /* ok, so try the .fn table */ + SWIG_Lua_get_table(L,".fn"); /* find the .get table */ + assert(lua_istable(L,-1)); /* just in case */ + lua_pushvalue(L,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: whether 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 */ + return 1; + } + lua_pop(L,1); /* remove whatever was there */ + return 0; +} + +SWIGINTERN int SWIG_Lua_namespace_set(lua_State* L) +{ +/* there should be 3 params passed in + (1) table (not the meta table) + (2) string name of the attribute + (3) any for the new value +*/ + + assert(lua_istable(L,1)); + lua_getmetatable(L,1); /* get the meta table */ + assert(lua_istable(L,-1)); + + SWIG_Lua_get_table(L,".set"); /* find the .set table */ + if (lua_istable(L,-1)) + { + /* look for the key in the .set table */ + lua_pushvalue(L,2); /* key */ + lua_rawget(L,-2); + if (lua_iscfunction(L,-1)) + { /* found it so call the fn & return its value */ + lua_pushvalue(L,3); /* value */ + lua_call(L,1,0); + return 0; + } + lua_pop(L,1); /* remove the value */ + } + lua_pop(L,1); /* remove the value .set table */ + return 0; +} + +SWIGINTERN void SWIG_Lua_InstallConstants(lua_State* L, swig_lua_const_info constants[]); // forward declaration +SWIGINTERN void SWIG_Lua_add_class_variable(lua_State* L,const char* name,lua_CFunction getFn,lua_CFunction setFn); // forward declaration + +/* helper function - register namespace methods and attributes into namespace */ +SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State* L, swig_lua_namespace* ns) +{ + int i = 0; + assert(lua_istable(L,-1)); + /* There must be table at the top of the stack */ + SWIG_Lua_InstallConstants(L, ns->ns_constants); + + lua_getmetatable(L,-1); + + /* add fns */ + for(i=0;ns->ns_attributes[i].name;i++){ + SWIG_Lua_add_class_variable(L,ns->ns_attributes[i].name,ns->ns_attributes[i].getmethod,ns->ns_attributes[i].setmethod); + } + + /* add methods to the metatable */ + SWIG_Lua_get_table(L,".fn"); /* find the .fn table */ + assert(lua_istable(L,-1)); /* just in case */ + for(i=0;ns->ns_methods[i].name;i++){ + SWIG_Lua_add_function(L,ns->ns_methods[i].name,ns->ns_methods[i].method); + } + lua_pop(L,1); + + /* clear stack - remove metatble */ + lua_pop(L,1); + +} + +/* helper function. creates namespace table and add it to module table */ +SWIGINTERN int SWIG_Lua_namespace_register(lua_State* L, swig_lua_namespace* ns) +{ + assert(lua_istable(L,-1)); /* just in case. This is supposed to be module table */ + lua_checkstack(L,5); + lua_pushstring(L, ns->name); + lua_newtable(L); /* namespace itself */ + lua_newtable(L); /* metatable for namespace */ + + /* add a table called ".get" */ + lua_pushstring(L,".get"); + lua_newtable(L); + lua_rawset(L,-3); + /* add a table called ".set" */ + lua_pushstring(L,".set"); + lua_newtable(L); + lua_rawset(L,-3); + /* add a table called ".fn" */ + lua_pushstring(L,".fn"); + lua_newtable(L); + lua_rawset(L,-3); + + /* add accessor fns for using the .get,.set&.fn */ + SWIG_Lua_add_function(L,"__index",SWIG_Lua_namespace_get); + SWIG_Lua_add_function(L,"__newindex",SWIG_Lua_namespace_set); + + lua_setmetatable(L,-2); /* set metatable */ + lua_rawset(L,-3); /* add namespace to module table */ +} /* ----------------------------------------------------------------------------- * global variable support code: classes * ----------------------------------------------------------------------------- */ @@ -570,6 +711,23 @@ SWIGINTERN int SWIG_Lua_class_disown(lua_State* L) return 0; } +/* Constructor proxy. Used when class name entry in module is not class constructor, +but special table instead. */ +SWIGINTERN int SWIG_Lua_constructor_proxy(lua_State* L) +{ + /* unlimited number of parameters + First one is our proxy table and we should remove it + Other we should pass to real constructor + */ + assert(lua_istable(L,1)); + lua_pushstring(L,".constructor"); + lua_rawget(L,1); + assert(!lua_isnil(L,-1)); + lua_replace(L,1); /* replace our table with real constructor */ + lua_call(L,lua_gettop(L)-1,1); + return 1; +} + /* gets the swig class registry (or creates it) */ SWIGINTERN void SWIG_Lua_get_class_registry(lua_State* L) { @@ -614,6 +772,21 @@ SWIGINTERN void SWIG_Lua_add_class_variable(lua_State* L,const char* name,lua_C } } +/* helper to recursively add class static details (static attributes, operations and constants) */ +SWIGINTERN void SWIG_Lua_add_class_static_details(lua_State* L, swig_lua_class* clss) +{ + int i = 0; + /* The class namespace table must be on the top of the stack */ + assert(lua_istable(L,-1)); + /* call all the base classes first: we can then override these later: */ + for(i=0;clss->bases[i];i++) + { + SWIG_Lua_add_class_static_details(L,clss->bases[i]); + } + + SWIG_Lua_add_namespace_details(L, &clss->cls_static); +} + /* helper to recursively add class details (attributes & operations) */ SWIGINTERN void SWIG_Lua_add_class_details(lua_State* L,swig_lua_class* clss) { @@ -667,15 +840,42 @@ SWIGINTERN void SWIG_Lua_init_base_class(lua_State* L,swig_lua_class* clss) } } -/* performs the entire class registration process */ -SWIGINTERN void SWIG_Lua_class_register(lua_State* L,swig_lua_class* clss) +/* Register class static methods,attributes etc as well as constructor proxy */ +SWIGINTERN void SWIG_Lua_class_register_static(lua_State* L, swig_lua_class* clss) { + lua_checkstack(L,5); /* just in case */ + assert(lua_istable(L,-1)); /* just in case */ + assert(strcmp(clss->name, clss->cls_static.name) == 0); /* in class those 2 must be equal */ + + SWIG_Lua_namespace_register(L,&clss->cls_static); + + SWIG_Lua_get_table(L,clss->name); // Get namespace table back + assert(lua_istable(L,-1)); /* just in case */ + /* add its constructor to module with the name of the class so you can do MyClass(...) as well as new_MyClass(...) BUT only if a constructor is defined (this overcomes the problem of pure virtual classes without constructors)*/ if (clss->constructor) - SWIG_Lua_add_function(L,clss->name,clss->constructor); + { + SWIG_Lua_add_function(L,".constructor", clss->constructor); + lua_getmetatable(L,-1); + assert(lua_istable(L,-1)); /* just in case */ + SWIG_Lua_add_function(L,"__call", SWIG_Lua_constructor_proxy); + lua_pop(L,1); + } + + assert(lua_istable(L,-1)); /* just in case */ + SWIG_Lua_add_class_static_details(L, clss); + + /* clear stack */ + lua_pop(L,1); +} + +/* performs the entire class registration process */ +SWIGINTERN void SWIG_Lua_class_register(lua_State* L,swig_lua_class* clss) +{ + SWIG_Lua_class_register_static(L,clss); SWIG_Lua_get_class_registry(L); /* get the registry */ lua_pushstring(L,clss->name); /* get the name */ diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index cff3107db..b76945b95 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -45,6 +45,7 @@ */ #include "swigmod.h" +#include "cparse.h" /**** Diagnostics: With the #define REPORT(), you can change the amount of diagnostics given @@ -111,6 +112,9 @@ private: String *s_const_tab; // table of global constants String *s_methods_tab; // table of class methods String *s_attr_tab; // table of class attributes + String *s_cls_attr_tab; // table of class static attributes + String *s_cls_methods_tab; // table of class static methods + String *s_cls_const_tab; // tables of class constants(including enums) String *s_luacode; // luacode to be called during init String *s_dot_get; // table of variable 'get' functions String *s_dot_set; // table of variable 'set' functions @@ -154,6 +158,9 @@ public: s_const_tab(0), s_methods_tab(0), s_attr_tab(0), + s_cls_attr_tab(0), + s_cls_methods_tab(0), + s_cls_const_tab(0), s_luacode(0), s_dot_get(0), s_dot_set(0), @@ -736,13 +743,18 @@ public: NEW LANGUAGE NOTE:END ************************************************/ /* Now register the function with the interpreter. */ if (!Getattr(n, "sym:overloaded")) { + //REPORT("dispatchFunction", n); // add_method(n, iname, wname, description); if (current==NO_CPP || current==STATIC_FUNC) { // emit normal fns & static fns + String *wrapname = Swig_name_wrapper(iname); if(elua_ltr || eluac_ltr) Printv(s_cmd_tab, tab4, "{LSTRKEY(\"", iname, "\")", ", LFUNCVAL(", Swig_name_wrapper(iname), ")", "},\n", NIL); else Printv(s_cmd_tab, tab4, "{ \"", iname, "\", ", Swig_name_wrapper(iname), "},\n", NIL); // Printv(s_cmd_tab, tab4, "{ SWIG_prefix \"", iname, "\", (swig_wrapper_func) ", Swig_name_wrapper(iname), "},\n", NIL); + if (getCurrentClass()) { + Setattr(n,"luaclassobj:wrap:name", wrapname); + } } } else { if (!Getattr(n, "sym:nextSibling")) { @@ -775,6 +787,7 @@ public: look for %typecheck(SWIG_TYPECHECK_*) in the .swg file NEW LANGUAGE NOTE:END ************************************************/ void dispatchFunction(Node *n) { + //REPORT("dispatchFunction", n); /* Last node in overloaded chain */ int maxargs; @@ -822,10 +835,14 @@ public: if (current==NO_CPP || current==STATIC_FUNC) // emit normal fns & static fns Printv(s_cmd_tab, tab4, "{ \"", symname, "\",", wname, "},\n", NIL); + if (getCurrentClass()) + Setattr(n,"luaclassobj:wrap:name", wname); + else + Delete(wname); + DelWrapper(f); Delete(dispatch); Delete(tmp); - Delete(wname); } @@ -878,8 +895,13 @@ public: } else { Printf(s_var_tab, "%s{ \"%s\", %s, %s },\n", tab4, iname, getName, setName); } - Delete(getName); - Delete(setName); + if (getCurrentClass()) { + Setattr(n, "luaclassobj:wrap:get", getName); + Setattr(n, "luaclassobj:wrap:set", setName); + } else { + Delete(getName); + Delete(setName); + } return result; } @@ -887,7 +909,7 @@ public: * constantWrapper() * ------------------------------------------------------------ */ virtual int constantWrapper(Node *n) { - // REPORT("constantWrapper", n); + REPORT("constantWrapper", n); String *name = Getattr(n, "name"); String *iname = Getattr(n, "sym:name"); String *nsname = Copy(iname); @@ -923,6 +945,20 @@ public: Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value.\n"); return SWIG_NOWRAP; } + if (cparse_cplusplus && getCurrentClass()) { + // Additionally add to class constants + Swig_require("luaclassobj_constantWrapper", n, "*sym:name", "luaclassobj:symname", NIL); + Setattr(n, "sym:name", Getattr(n, "luaclassobj:symname")); + String *cls_nsname = Getattr(n, "sym:name"); + if ((tm = Swig_typemap_lookup("consttab", n, name, 0))) { + Replaceall(tm, "$source", value); + Replaceall(tm, "$target", name); + Replaceall(tm, "$value", value); + Replaceall(tm, "$nsname", cls_nsname); + Printf(s_cls_const_tab, " %s,\n", tm); + } + Swig_restore(n); + } Delete(nsname); return SWIG_OK; } @@ -1009,6 +1045,19 @@ public: Printf(s_methods_tab, "static swig_lua_method swig_"); Printv(s_methods_tab, mangled_classname, "_methods[] = {\n", NIL); + s_cls_methods_tab = NewString(""); + Printf(s_cls_methods_tab, "static swig_lua_method swig_"); + Printv(s_cls_methods_tab, mangled_classname, "_cls_methods[] = {\n", NIL); + + s_cls_attr_tab = NewString(""); + Printf(s_cls_attr_tab, "static swig_lua_attribute swig_"); + Printv(s_cls_attr_tab, mangled_classname, "_cls_attributes[] = {\n", NIL); + + s_cls_const_tab = NewString(""); + Printf(s_cls_const_tab, "static swig_lua_const_info swig_"); + Printv(s_cls_const_tab, mangled_classname, "_cls_constants[] = {\n", NIL); + + // Generate normal wrappers Language::classHandler(n); @@ -1047,8 +1096,21 @@ public: Printf(s_attr_tab, " {0,0,0}\n};\n"); Printv(f_wrappers, s_attr_tab, NIL); + Printf(s_cls_attr_tab, " {0,0,0}\n};\n"); + Printv(f_wrappers, s_cls_attr_tab, NIL); + + Printf(s_cls_methods_tab, " {0,0}\n};\n"); + Printv(f_wrappers, s_cls_methods_tab, NIL); + + Printf(s_cls_const_tab, " {0,0,0,0,0,0}\n};\n"); + Printv(f_wrappers, s_cls_const_tab, NIL); + + Delete(s_methods_tab); Delete(s_attr_tab); + Delete(s_cls_methods_tab); + Delete(s_cls_attr_tab); + Delete(s_cls_const_tab); // Handle inheritance // note: with the idea of class hierarchies spread over multiple modules @@ -1122,7 +1184,10 @@ public: } else { Printf(f_wrappers, ",0"); } - Printf(f_wrappers, ", swig_%s_methods, swig_%s_attributes, swig_%s_bases, swig_%s_base_names };\n\n", mangled_classname, mangled_classname, mangled_classname, mangled_classname); + Printf(f_wrappers, ", swig_%s_methods, swig_%s_attributes, { \"%s\", swig_%s_cls_methods, swig_%s_cls_attributes, swig_%s_cls_constants }, swig_%s_bases, swig_%s_base_names };\n\n", + mangled_classname, mangled_classname, + class_name, mangled_classname, mangled_classname, mangled_classname, + mangled_classname, mangled_classname); // Printv(f_wrappers, ", swig_", mangled_classname, "_methods, swig_", mangled_classname, "_attributes, swig_", mangled_classname, "_bases };\n\n", NIL); // Printv(s_cmd_tab, tab4, "{ SWIG_prefix \"", class_name, "\", (swig_wrapper_func) SWIG_ObjectConstructor, &_wrap_class_", mangled_classname, "},\n", NIL); @@ -1232,8 +1297,30 @@ public: * ---------------------------------------------------------------------- */ virtual int staticmemberfunctionHandler(Node *n) { + REPORT("staticmemberfunctionHandler", n); current = STATIC_FUNC; - return Language::staticmemberfunctionHandler(n); + String *symname = Getattr(n, "sym:name"); + int result = Language::staticmemberfunctionHandler(n); + + if (cparse_cplusplus && getCurrentClass()) { + Swig_restore(n); + } + current = NO_CPP; + if (result != SWIG_OK) + return result; + + if (Getattr(n, "sym:nextSibling")) + return SWIG_OK; + + Swig_require("luaclassobj_staticmemberfunctionHandler", n, "luaclassobj:wrap:name", NIL); + String *name = Getattr(n, "name"); + String *rname, *realname; + realname = symname ? symname : name; + rname = Getattr(n, "luaclassobj:wrap:name"); + Printv(s_cls_methods_tab, tab4, "{\"", realname, "\", ", rname, "}, \n", NIL); + Swig_restore(n); + + return SWIG_OK; } /* ------------------------------------------------------------ @@ -1243,8 +1330,17 @@ public: * ------------------------------------------------------------ */ virtual int memberconstantHandler(Node *n) { - // REPORT("memberconstantHandler",n); - return Language::memberconstantHandler(n); + REPORT("memberconstantHandler",n); + String *symname = Getattr(n, "sym:name"); + if (cparse_cplusplus && getCurrentClass()) { + Swig_save("luaclassobj_memberconstantHandler", n, "luaclassobj:symname", NIL); + Setattr(n, "luaclassobj:symname", symname); + } + int result = Language::memberconstantHandler(n); + if (cparse_cplusplus && getCurrentClass()) + Swig_restore(n); + + return result; } /* --------------------------------------------------------------------- @@ -1252,9 +1348,22 @@ public: * --------------------------------------------------------------------- */ virtual int staticmembervariableHandler(Node *n) { - // REPORT("staticmembervariableHandler",n); + REPORT("staticmembervariableHandler",n); current = STATIC_VAR; - return Language::staticmembervariableHandler(n); + String *symname = Getattr(n, "sym:name"); + int result = Language::staticmembervariableHandler(n); + + if (result != SWIG_OK) + return result; + + + if (Getattr(n, "wrappedasconstant")) + return SWIG_OK; + + Swig_require("luaclassobj_staticmembervariableHandler", n, "luaclassobj:wrap:get", "luaclassobj:wrap:set", NIL); + Printf(s_cls_attr_tab,"%s{ \"%s\", %s, %s},\n",tab4,symname,Getattr(n,"luaclassobj:wrap:get"), Getattr(n,"luaclassobj:wrap:set")); + Swig_restore(n); + return SWIG_OK; } /* --------------------------------------------------------------------- From 7a88729c87487c13163748c24b95196674f8ed21 Mon Sep 17 00:00:00 2001 From: Sylvestre Ledru Date: Fri, 13 Sep 2013 09:36:26 +0200 Subject: [PATCH 121/481] Remove trailing spaces in the generated code. No functional changes --- Lib/swigerrors.swg | 20 ++++---- Lib/swiginit.swg | 24 +++++----- Lib/swiglabels.swg | 12 ++--- Lib/swigrun.swg | 96 ++++++++++++++++++------------------- Lib/typemaps/swigmacros.swg | 58 +++++++++++----------- Source/Swig/misc.c | 8 ++-- 6 files changed, 109 insertions(+), 109 deletions(-) diff --git a/Lib/swigerrors.swg b/Lib/swigerrors.swg index 32857c498..1a6d20366 100644 --- a/Lib/swigerrors.swg +++ b/Lib/swigerrors.swg @@ -1,16 +1,16 @@ /* Errors in SWIG */ -#define SWIG_UnknownError -1 -#define SWIG_IOError -2 -#define SWIG_RuntimeError -3 -#define SWIG_IndexError -4 -#define SWIG_TypeError -5 -#define SWIG_DivisionByZero -6 -#define SWIG_OverflowError -7 -#define SWIG_SyntaxError -8 -#define SWIG_ValueError -9 +#define SWIG_UnknownError -1 +#define SWIG_IOError -2 +#define SWIG_RuntimeError -3 +#define SWIG_IndexError -4 +#define SWIG_TypeError -5 +#define SWIG_DivisionByZero -6 +#define SWIG_OverflowError -7 +#define SWIG_SyntaxError -8 +#define SWIG_ValueError -9 #define SWIG_SystemError -10 #define SWIG_AttributeError -11 -#define SWIG_MemoryError -12 +#define SWIG_MemoryError -12 #define SWIG_NullReferenceError -13 diff --git a/Lib/swiginit.swg b/Lib/swiginit.swg index 6fe58d296..f321181eb 100644 --- a/Lib/swiginit.swg +++ b/Lib/swiginit.swg @@ -1,17 +1,17 @@ /* ----------------------------------------------------------------------------- * Type initialization: - * This problem is tough by the requirement that no dynamic - * memory is used. Also, since swig_type_info structures store pointers to + * This problem is tough by the requirement that no dynamic + * memory is used. Also, since swig_type_info structures store pointers to * swig_cast_info structures and swig_cast_info structures store pointers back - * to swig_type_info structures, we need some lookup code at initialization. - * The idea is that swig generates all the structures that are needed. - * The runtime then collects these partially filled structures. - * The SWIG_InitializeModule function takes these initial arrays out of + * to swig_type_info structures, we need some lookup code at initialization. + * The idea is that swig generates all the structures that are needed. + * The runtime then collects these partially filled structures. + * The SWIG_InitializeModule function takes these initial arrays out of * swig_module, and does all the lookup, filling in the swig_module.types * array with the correct data and linking the correct swig_cast_info * structures together. * - * The generated swig_type_info structures are assigned staticly to an initial + * The generated swig_type_info structures are assigned staticly to an initial * array. We just loop through that array, and handle each type individually. * First we lookup if this type has been already loaded, and if so, use the * loaded structure instead of the generated one. Then we have to fill in the @@ -21,17 +21,17 @@ * a column is one of the swig_cast_info structures for that type. * The cast_initial array is actually an array of arrays, because each row has * a variable number of columns. So to actually build the cast linked list, - * we find the array of casts associated with the type, and loop through it + * we find the array of casts associated with the type, and loop through it * adding the casts to the list. The one last trick we need to do is making * sure the type pointer in the swig_cast_info struct is correct. * - * First off, we lookup the cast->type name to see if it is already loaded. + * First off, we lookup the cast->type name to see if it is already loaded. * There are three cases to handle: * 1) If the cast->type has already been loaded AND the type we are adding * casting info to has not been loaded (it is in this module), THEN we * replace the cast->type pointer with the type pointer that has already * been loaded. - * 2) If BOTH types (the one we are adding casting info to, and the + * 2) If BOTH types (the one we are adding casting info to, and the * cast->type) are loaded, THEN the cast info has already been loaded by * the previous module so we just ignore it. * 3) Finally, if cast->type has not already been loaded, then we add that @@ -108,7 +108,7 @@ SWIG_InitializeModule(void *clientdata) { swig_type_info *type = 0; swig_type_info *ret; swig_cast_info *cast; - + #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); #endif @@ -135,7 +135,7 @@ SWIG_InitializeModule(void *clientdata) { /* Insert casting types */ cast = swig_module.cast_initial[i]; while (cast->type) { - + /* Don't need to add information already in the list */ ret = 0; #ifdef SWIGRUNTIME_DEBUG diff --git a/Lib/swiglabels.swg b/Lib/swiglabels.swg index b943afb47..d428ac33d 100644 --- a/Lib/swiglabels.swg +++ b/Lib/swiglabels.swg @@ -29,28 +29,28 @@ #ifndef SWIGUNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) -# define SWIGUNUSED __attribute__ ((__unused__)) +# define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif # elif defined(__ICC) -# define SWIGUNUSED __attribute__ ((__unused__)) +# define SWIGUNUSED __attribute__ ((__unused__)) # else -# define SWIGUNUSED +# define SWIGUNUSED # endif #endif #ifndef SWIG_MSC_UNSUPPRESS_4505 # if defined(_MSC_VER) # pragma warning(disable : 4505) /* unreferenced local function has been removed */ -# endif +# endif #endif #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) # else -# define SWIGUNUSEDPARM(p) p SWIGUNUSED +# define SWIGUNUSEDPARM(p) p SWIGUNUSED # endif #endif @@ -93,7 +93,7 @@ # define SWIGSTDCALL __stdcall # else # define SWIGSTDCALL -# endif +# endif #endif /* Deal with Microsoft's attempt at deprecating C standard runtime functions */ diff --git a/Lib/swigrun.swg b/Lib/swigrun.swg index 21f0a5c14..7066e670e 100644 --- a/Lib/swigrun.swg +++ b/Lib/swigrun.swg @@ -22,7 +22,7 @@ You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for creating a static or dynamic library from the SWIG runtime code. In 99.9% of the cases, SWIG just needs to declare them as 'static'. - + But only do this if strictly necessary, ie, if you have problems with your compiler or suchlike. */ @@ -48,16 +48,16 @@ #define SWIG_POINTER_OWN 0x1 -/* +/* Flags/methods for returning states. - - The SWIG conversion methods, as ConvertPtr, return an integer + + The SWIG conversion methods, as ConvertPtr, return an integer that tells if the conversion was successful or not. And if not, an error code can be returned (see swigerrors.swg for the codes). - + Use the following macros/flags to set or process the returning states. - + In old versions of SWIG, code such as the following was usually written: if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) { @@ -90,23 +90,23 @@ } else { // fail code } - + I.e., now SWIG_ConvertPtr can return new objects and you can identify the case and take care of the deallocation. Of course that also requires SWIG_ConvertPtr to return new result values, such as - int SWIG_ConvertPtr(obj, ptr,...) { - if () { - if () { - *ptr = ; - return SWIG_NEWOBJ; - } else { - *ptr = ; - return SWIG_OLDOBJ; - } - } else { - return SWIG_BADOBJ; - } + int SWIG_ConvertPtr(obj, ptr,...) { + if () { + if () { + *ptr = ; + return SWIG_NEWOBJ; + } else { + *ptr = ; + return SWIG_OLDOBJ; + } + } else { + return SWIG_BADOBJ; + } } Of course, returning the plain '0(success)/-1(fail)' still works, but you can be @@ -120,17 +120,17 @@ int fooi(int); and you call - + food(1) // cast rank '1' (1 -> 1.0) fooi(1) // cast rank '0' just use the SWIG_AddCast()/SWIG_CheckState() */ -#define SWIG_OK (0) +#define SWIG_OK (0) #define SWIG_ERROR (-1) #define SWIG_IsOK(r) (r >= 0) -#define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) +#define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) /* The CastRankLimit says how many bits are used for the cast rank */ #define SWIG_CASTRANKLIMIT (1 << 8) @@ -161,11 +161,11 @@ # endif # define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) # define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) -SWIGINTERNINLINE int SWIG_AddCast(int r) { +SWIGINTERNINLINE int SWIG_AddCast(int r) { return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; } -SWIGINTERNINLINE int SWIG_CheckState(int r) { - return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; +SWIGINTERNINLINE int SWIG_CheckState(int r) { + return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; } #else /* no cast-rank mode */ # define SWIG_AddCast(r) (r) @@ -212,7 +212,7 @@ typedef struct swig_module_info { void *clientdata; /* Language specific module data */ } swig_module_info; -/* +/* Compare two type names skipping the space characters, therefore "char*" == "char *" and "Class" == "Class", etc. @@ -285,7 +285,7 @@ SWIG_TypeCheck(const char *c, swig_type_info *ty) { return 0; } -/* +/* Identical to SWIG_TypeCheck, except strcmp is replaced with a pointer comparison */ SWIGRUNTIME swig_cast_info * @@ -320,7 +320,7 @@ SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); } -/* +/* Dynamic pointer casting. Down an inheritance hierarchy */ SWIGRUNTIME swig_type_info * @@ -364,7 +364,7 @@ SWIG_TypePrettyName(const swig_type_info *type) { return type->name; } -/* +/* Set the clientdata field for a type */ SWIGRUNTIME void @@ -372,14 +372,14 @@ SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { swig_cast_info *cast = ti->cast; /* if (ti->clientdata == clientdata) return; */ ti->clientdata = clientdata; - + while (cast) { if (!cast->converter) { swig_type_info *tc = cast->type; if (!tc->clientdata) { SWIG_TypeClientData(tc, clientdata); } - } + } cast = cast->next; } } @@ -388,18 +388,18 @@ SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { SWIG_TypeClientData(ti, clientdata); ti->owndata = 1; } - + /* Search for a swig_type_info structure only by mangled name Search is a O(log #types) - - We start searching at module start, and finish searching when start == end. + + We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * -SWIG_MangledTypeQueryModule(swig_module_info *start, - swig_module_info *end, +SWIG_MangledTypeQueryModule(swig_module_info *start, + swig_module_info *end, const char *name) { swig_module_info *iter = start; do { @@ -408,11 +408,11 @@ SWIG_MangledTypeQueryModule(swig_module_info *start, register size_t r = iter->size - 1; do { /* since l+r >= 0, we can (>> 1) instead (/ 2) */ - register size_t i = (l + r) >> 1; + register size_t i = (l + r) >> 1; const char *iname = iter->types[i]->name; if (iname) { register int compare = strcmp(name, iname); - if (compare == 0) { + if (compare == 0) { return iter->types[i]; } else if (compare < 0) { if (i) { @@ -437,14 +437,14 @@ SWIG_MangledTypeQueryModule(swig_module_info *start, Search for a swig_type_info structure for either a mangled name or a human readable name. It first searches the mangled names of the types, which is a O(log #types) If a type is not found it then searches the human readable names, which is O(#types). - - We start searching at module start, and finish searching when start == end. + + We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * -SWIG_TypeQueryModule(swig_module_info *start, - swig_module_info *end, +SWIG_TypeQueryModule(swig_module_info *start, + swig_module_info *end, const char *name) { /* STEP 1: Search the name field using binary search */ swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); @@ -463,12 +463,12 @@ SWIG_TypeQueryModule(swig_module_info *start, iter = iter->next; } while (iter != end); } - + /* neither found a match */ return 0; } -/* +/* Pack binary data into a string */ SWIGRUNTIME char * @@ -484,7 +484,7 @@ SWIG_PackData(char *c, void *ptr, size_t sz) { return c; } -/* +/* Unpack binary data from a string */ SWIGRUNTIME const char * @@ -498,21 +498,21 @@ SWIG_UnpackData(const char *c, void *ptr, size_t sz) { uu = ((d - '0') << 4); else if ((d >= 'a') && (d <= 'f')) uu = ((d - ('a'-10)) << 4); - else + else return (char *) 0; d = *(c++); if ((d >= '0') && (d <= '9')) uu |= (d - '0'); else if ((d >= 'a') && (d <= 'f')) uu |= (d - ('a'-10)); - else + else return (char *) 0; *u = uu; } return c; } -/* +/* Pack 'void *' into a string buffer. */ SWIGRUNTIME char * diff --git a/Lib/typemaps/swigmacros.swg b/Lib/typemaps/swigmacros.swg index e95e7af92..c9b42facf 100644 --- a/Lib/typemaps/swigmacros.swg +++ b/Lib/typemaps/swigmacros.swg @@ -9,9 +9,9 @@ -------------------------- %arg(Arg) Safe argument wrap - %str(Arg) Stringtify the argument - %begin_block Begin a execution block - %end_block End a execution block + %str(Arg) Stringtify the argument + %begin_block Begin a execution block + %end_block End a execution block %block(Block) Execute Block as a excecution block %define_as(Def, Val) Define 'Def' as 'Val', expanding Def and Val first %ifcplusplus(V1, V2) if C++ Mode; then V1; else V2; fi @@ -19,33 +19,33 @@ Casting Operations: ------------------- - + SWIG provides the following casting macros, which implement the corresponding C++ casting operations: - %const_cast(a, Type) const_cast(a) - %static_cast(a, Type) static_cast(a) - %reinterpret_cast(a, Type) reinterpret_cast(a) - %numeric_cast(a, Type) static_cast(a) - %as_voidptr(a) const_cast(static_cast(a)) - %as_voidptrptr(a) reinterpret_cast(a) - + %const_cast(a, Type) const_cast(a) + %static_cast(a, Type) static_cast(a) + %reinterpret_cast(a, Type) reinterpret_cast(a) + %numeric_cast(a, Type) static_cast(a) + %as_voidptr(a) const_cast(static_cast(a)) + %as_voidptrptr(a) reinterpret_cast(a) + or their C unsafe versions. In C++ we use the safe version unless SWIG_NO_CPLUSPLUS_CAST is defined (usually via the -nocppcast swig flag). Memory allocation: ------------------ - + These allocation/freeing macros are safe to use in C or C++ and dispatch the proper new/delete/delete[] or free/malloc calls as needed. - + %new_instance(Type) Allocate a new instance of given Type %new_copy(value,Type) Allocate and initialize a new instance with 'value' %new_array(size,Type) Allocate a new array with given size and Type %new_copy_array(cptr,size,Type) Allocate and initialize a new array from 'cptr' - %delete(cptr) Delete an instance + %delete(cptr) Delete an instance %delete_array(cptr) Delete an array @@ -54,13 +54,13 @@ %formacro(Macro, Args...) or %formacro_1(Macro, Args...) for i in Args - do + do Macro($i) done %formacro_2(Macro2, Args...) for i,j in Args - do + do Macro2($i, $j) done @@ -71,12 +71,12 @@ %mark_flag(flag) flag := True - %evalif(flag,expr) + %evalif(flag,expr) if flag; then expr fi - %evalif_2(flag1 flag2,expr) + %evalif_2(flag1 flag2,expr) if flag1 and flag2; then expr fi @@ -84,7 +84,7 @@ */ /* ----------------------------------------------------------------------------- - * Basic preprocessor macros + * Basic preprocessor macros * ----------------------------------------------------------------------------- */ #define %arg(Arg...) Arg @@ -115,7 +115,7 @@ nocppval %define_as(SWIGVERSION, SWIG_VERSION) %#define SWIG_VERSION SWIGVERSION } -#endif +#endif @@ -153,10 +153,10 @@ nocppval /* ----------------------------------------------------------------------------- - * Allocating/freeing elements + * Allocating/freeing elements * ----------------------------------------------------------------------------- */ -#if defined(__cplusplus) +#if defined(__cplusplus) # define %new_instance(Type...) (new Type) # define %new_copy(val,Type...) (new Type(%static_cast(val, const Type&))) # define %new_array(size,Type...) (new Type[size]) @@ -184,7 +184,7 @@ nocppval /* ----------------------------------------------------------------------------- - * Auxiliary loop macros + * Auxiliary loop macros * ----------------------------------------------------------------------------- */ @@ -213,10 +213,10 @@ nocppval * SWIG flags * ----------------------------------------------------------------------------- */ -/* +/* mark a flag, ie, define a macro name but ignore it in - the interface. - + the interface. + the flag can be later used with %evalif */ @@ -224,16 +224,16 @@ nocppval /* - %evalif and %evalif_2 are use to evaluate or process + %evalif and %evalif_2 are use to evaluate or process an expression if the given predicate is 'true' (1). */ -%define %_evalif(_x,_expr) +%define %_evalif(_x,_expr) #if _x == 1 _expr #endif %enddef -%define %_evalif_2(_x,_y,_expr) +%define %_evalif_2(_x,_y,_expr) #if _x == 1 && _y == 1 _expr #endif diff --git a/Source/Swig/misc.c b/Source/Swig/misc.c index efa397878..651b94cf1 100644 --- a/Source/Swig/misc.c +++ b/Source/Swig/misc.c @@ -72,11 +72,11 @@ void Swig_banner(File *f) { Printf(f, "/* ----------------------------------------------------------------------------\n\ * This file was automatically generated by SWIG (http://www.swig.org).\n\ * Version %s\n\ - * \n\ - * This file is not intended to be easily readable and contains a number of \n\ + *\n\ + * This file is not intended to be easily readable and contains a number of\n\ * coding conventions designed to improve portability and efficiency. Do not make\n\ - * changes to this file unless you know what you are doing--modify the SWIG \n\ - * interface file instead. \n", Swig_package_version()); + * changes to this file unless you know what you are doing--modify the SWIG\n\ + * interface file instead.\n", Swig_package_version()); /* String too long for ISO compliance */ Printf(f, " * ----------------------------------------------------------------------------- */\n"); From ba9baefdd93922a585757e18f10e5723a0105202 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 14 Sep 2013 12:53:45 +0100 Subject: [PATCH 122/481] sed portability fix creating swigwarn.swg --- Makefile.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile.in b/Makefile.in index 0ac8c88f9..c7972832c 100644 --- a/Makefile.in +++ b/Makefile.in @@ -433,7 +433,7 @@ maintainer-clean: $(srcdir)/Lib/swigwarn.swg: $(srcdir)/Source/Include/swigwarn.h mkdir -p Lib echo "/* SWIG warning codes */" > $@ - cat $? | grep "^#define WARN\|/\*.*\*/\|^[ \t]*$$" | sed 's/^#define \(WARN.*[0-9]\+\)\(.*\)$$/%define SWIG\1 %enddef\2/' >> $@ + cat $? | grep "^#define WARN\|/\*.*\*/\|^[ \t]*$$" | sed 's/^#define \(WARN.*[0-9][0-9]*\)\(.*\)$$/%define SWIG\1 %enddef\2/' >> $@ ##################################################################### # TARGETS: install & friends From c4e29fb686b860584ac1def0dd36a7a3d46310c6 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 14 Sep 2013 15:51:50 -0700 Subject: [PATCH 123/481] Remove mkstemp replacement for ccache-swig on Cygwin Cygwin 1.7.0 as well as Cygwin 1.7.24 seem to be working okay Cygwin 1.7.24 gives gcc warning about dangerous use of mktemp --- CCache/ccache.h | 2 ++ CCache/util.c | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CCache/ccache.h b/CCache/ccache.h index 3c3e22311..dcbb03f0c 100644 --- a/CCache/ccache.h +++ b/CCache/ccache.h @@ -200,6 +200,8 @@ typedef int (*COMPAR_FN_T)(const void *, const void *); /* mkstemp() on some versions of cygwin don't handle binary files, so override */ +/* Seems okay in Cygwin 1.7.0 #ifdef __CYGWIN__ #undef HAVE_MKSTEMP #endif +*/ diff --git a/CCache/util.c b/CCache/util.c index bba232492..66f9823b9 100644 --- a/CCache/util.c +++ b/CCache/util.c @@ -82,7 +82,7 @@ void copy_fd(int fd_in, int fd_out) #ifndef HAVE_MKSTEMP /* cheap and nasty mkstemp replacement */ -static int mkstemp(char *template) +int mkstemp(char *template) { mktemp(template); return open(template, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600); From cb4a23b2df066b316bc8c427e1849826e4341e95 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 14 Sep 2013 15:52:42 -0700 Subject: [PATCH 124/481] Cygwin test-suite fix for tcl 8.5 on Cygwin --- Examples/test-suite/li_windows.i | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Examples/test-suite/li_windows.i b/Examples/test-suite/li_windows.i index 26f96cc3b..c99ffe4ca 100644 --- a/Examples/test-suite/li_windows.i +++ b/Examples/test-suite/li_windows.i @@ -4,6 +4,12 @@ %{ #if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) + // Fix Tcl.h and Windows.h cat and mouse over definition of VOID + #if defined(_TCL) && defined(__CYGWIN__) + #ifdef VOID + #undef VOID + #endif + #endif #include #else // Use equivalent types for non-windows systems From f618a6999041614181272cc95afd290f19e30c6c Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 14 Sep 2013 17:32:54 -0700 Subject: [PATCH 125/481] Better detection of Ruby shared library extension Use Config to detect dll extension (needs to be .so for Ruby 1.9 on Cygwin) --- Examples/Makefile.in | 5 +++-- configure.ac | 2 ++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index df754427c..5607feb9e 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -913,6 +913,7 @@ RUBY_INCLUDE= @RUBYINCLUDE@ RUBY_LIB = @RUBYLIB@ RUBY_DLNK = @RUBYDYNAMICLINKING@ RUBY_LIBOPTS = @RUBYLINK@ @LIBS@ $(SYSLIBS) +RUBY_SO = @RUBYSO@ RUBY = @RUBY@ RUBY_SCRIPT = $(RUNME).rb @@ -924,7 +925,7 @@ RUBY_SCRIPT = $(RUNME).rb ruby: $(SRCS) $(SWIG) -ruby $(SWIGOPT) $(INTERFACEPATH) $(CC) -c $(CCSHARED) $(CFLAGS) $(RUBY_CFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) $(RUBY_INCLUDE) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(RUBY_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(RUBY_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(RUBY_SO) # ----------------------------------------------------------------- # Build a C++ dynamically loadable module @@ -933,7 +934,7 @@ ruby: $(SRCS) ruby_cpp: $(SRCS) $(SWIG) -c++ -ruby $(SWIGOPT) $(INTERFACEPATH) $(CXX) -c $(CCSHARED) $(CFLAGS) $(RUBY_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(RUBY_INCLUDE) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(RUBY_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(RUBY_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(RUBY_SO) # ----------------------------------------------------------------- # Build statically linked Ruby interpreter diff --git a/configure.ac b/configure.ac index 5b6441b86..c4db3ce98 100644 --- a/configure.ac +++ b/configure.ac @@ -1399,6 +1399,7 @@ if test -n "$RUBY"; then esac RUBYCCDLFLAGS=`($RUBY -rrbconfig -e 'print Config::CONFIG[["CCDLFLAGS"]]') 2>/dev/null` + RUBYSO=.`($RUBY -rrbconfig -e 'print Config::CONFIG[["DLEXT"]]') 2>/dev/null` else AC_MSG_RESULT(could not figure out how to run ruby) RUBYINCLUDE="-I/usr/local/lib/ruby/1.4/arch" @@ -1416,6 +1417,7 @@ AC_SUBST(RUBYINCLUDE) AC_SUBST(RUBYLIB) AC_SUBST(RUBYLINK) AC_SUBST(RUBYCCDLFLAGS) +AC_SUBST(RUBYSO) AC_SUBST(RUBYDYNAMICLINKING) #------------------------------------------------------------------------- From f01b52c44cbab9205a4fd4c2bcac5ba2d12ef460 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 13 Sep 2013 07:15:34 +0100 Subject: [PATCH 126/481] Tweak 'make beautify-file' unix2dos and dos2unix were renamed to todos and fromdos - they aren't really needed (on Linux anyway), so removed. --- Source/Makefile.am | 2 -- 1 file changed, 2 deletions(-) diff --git a/Source/Makefile.am b/Source/Makefile.am index 984b9c268..40fa4d9f2 100644 --- a/Source/Makefile.am +++ b/Source/Makefile.am @@ -140,8 +140,6 @@ beautify-file: test -n "$(INDENTFILE)" || (echo INDENTFILE not defined && exit 1;) test -e $(INDENTFILE) || (echo File does not exist: $(INDENTFILE) && exit 1;) cp $(INDENTFILE) $(INDENTBAKSDIR)/$(INDENTFILE); - unix2dos $(INDENTFILE) - dos2unix $(INDENTFILE) indent -kr --honour-newlines --line-length160 --indent-level2 --braces-on-func-def-line --leave-optional-blank-lines $(SWIGTYPEDEFS) $(INDENTFILE) -o $(INDENTFILE).tmp; cat $(INDENTFILE).tmp | sed -e 's/const const /const /' > $(INDENTFILE); rm $(INDENTFILE).tmp; From 0431664b18f17774344c79962518acfa4c738746 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 15 Sep 2013 10:43:49 +0100 Subject: [PATCH 127/481] Guile OUTPUT typemap fix Fixes 'attempt to free a non-heap object' in some OUTPUT typemaps. --- CHANGES.current | 9 +++++++++ Examples/test-suite/typemap_qualifier_strip.i | 4 ++++ Lib/r/r.swg | 9 ++++++++- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/CHANGES.current b/CHANGES.current index b2f007a92..7e756e912 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,15 @@ See the RELEASENOTES file for a summary of changes in each release. Version 2.0.11 (in progress) ============================ +2013-09-15: wsfulton + [R] Fix attempt to free a non-heap object in OUTPUT typemaps for: + unsigned short *OUTPUT + unsigned long *OUTPUT + signed long long *OUTPUT + char *OUTPUT + signed char*OUTPUT + unsigned char*OUTPUT + 2013-09-12: wsfulton [Lua] Pull Git patch #62. 1) Static members and static functions inside class can be accessed as diff --git a/Examples/test-suite/typemap_qualifier_strip.i b/Examples/test-suite/typemap_qualifier_strip.i index d91a7b109..9b9f24cd8 100644 --- a/Examples/test-suite/typemap_qualifier_strip.i +++ b/Examples/test-suite/typemap_qualifier_strip.i @@ -1,5 +1,9 @@ %module typemap_qualifier_strip +%typemap(freearg) int *ptr "" +%typemap(freearg) int *const ptrConst "" +%typemap(freearg) int const* constPtr "" + %typemap(in) int *ptr { int temp = 1234; $1 = &temp; diff --git a/Lib/r/r.swg b/Lib/r/r.swg index be42ff3a1..126611d61 100644 --- a/Lib/r/r.swg +++ b/Lib/r/r.swg @@ -114,12 +114,19 @@ signed int *OUTPUT, unsigned int *OUTPUT, short *OUTPUT, signed short *OUTPUT, +unsigned short *OUTPUT, long *OUTPUT, signed long *OUTPUT, +unsigned long *OUTPUT, long long *OUTPUT, +signed long long *OUTPUT, unsigned long long *OUTPUT, float *OUTPUT, -double *OUTPUT {} +double *OUTPUT, +char *OUTPUT, +signed char *OUTPUT, +unsigned char *OUTPUT +{} From 80b108eb70229680ad63daa7267d74ccc342dd2c Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 15 Sep 2013 15:11:43 +0100 Subject: [PATCH 128/481] Add swig-2.0.11 release info and date --- ANNOUNCE | 8 ++++---- CHANGES.current | 2 +- Doc/Manual/Sections.html | 2 +- README | 2 +- RELEASENOTES | 4 ++++ 5 files changed, 11 insertions(+), 7 deletions(-) diff --git a/ANNOUNCE b/ANNOUNCE index 1c3297a5c..caaa55d8c 100644 --- a/ANNOUNCE +++ b/ANNOUNCE @@ -1,8 +1,8 @@ -*** ANNOUNCE: SWIG 2.0.10 (in progress) *** +*** ANNOUNCE: SWIG 2.0.11 (15 Sep 2013) *** http://www.swig.org -We're pleased to announce SWIG-2.0.10, the latest SWIG release. +We're pleased to announce SWIG-2.0.11, the latest SWIG release. What is SWIG? ============= @@ -21,11 +21,11 @@ Availability ============ The release is available for download on Sourceforge at - http://prdownloads.sourceforge.net/swig/swig-2.0.10.tar.gz + http://prdownloads.sourceforge.net/swig/swig-2.0.11.tar.gz A Windows version is also available at - http://prdownloads.sourceforge.net/swig/swigwin-2.0.10.zip + http://prdownloads.sourceforge.net/swig/swigwin-2.0.11.zip Please report problems with this release to the swig-devel mailing list, details at http://www.swig.org/mail.html. diff --git a/CHANGES.current b/CHANGES.current index 7e756e912..1727ecb2c 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -2,7 +2,7 @@ Below are the changes for the current release. See the CHANGES file for changes in older releases. See the RELEASENOTES file for a summary of changes in each release. -Version 2.0.11 (in progress) +Version 2.0.11 (15 Sep 2013) ============================ 2013-09-15: wsfulton diff --git a/Doc/Manual/Sections.html b/Doc/Manual/Sections.html index 9e4a3dd17..2dfb438f8 100644 --- a/Doc/Manual/Sections.html +++ b/Doc/Manual/Sections.html @@ -6,7 +6,7 @@

    SWIG-2.0 Documentation

    -Last update : SWIG-2.0.10 (in progress) +Last update : SWIG-2.0.11 (15 Sep 2013)

    Sections

    diff --git a/README b/README index 444643a0d..946bd9a8f 100644 --- a/README +++ b/README @@ -1,6 +1,6 @@ SWIG (Simplified Wrapper and Interface Generator) -Version: 2.0.10 (in progress) +Version: 2.0.11 (15 Sep 2013) Tagline: SWIG is a compiler that integrates C and C++ with languages including Perl, Python, Tcl, Ruby, PHP, Java, C#, D, Go, Lua, diff --git a/RELEASENOTES b/RELEASENOTES index 49eacf28a..720dc9d34 100644 --- a/RELEASENOTES +++ b/RELEASENOTES @@ -4,6 +4,10 @@ and CHANGES files. Release Notes ============= +SWIG-2.0.11 summary: +- Minor bug fixes and enhancements mostly in Python, but also + C#, Lua, Ocaml, Octave, Perl, PHP, Python, R, Ruby, Tcl. + SWIG-2.0.10 summary: - Ruby 1.9 support is now complete. - Add support for Guile 2.0 and Guile 1.6 support (GH interface) has From b0b8d4c87e0077baccf770441768f5ad3b15dcd3 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 15 Sep 2013 22:39:08 +0100 Subject: [PATCH 129/481] Add hint about pushing tags post release [ci skip] --- Tools/mkrelease.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tools/mkrelease.py b/Tools/mkrelease.py index 9eceba07e..0623fe786 100755 --- a/Tools/mkrelease.py +++ b/Tools/mkrelease.py @@ -45,4 +45,4 @@ os.system("rsync --archive --verbose -P --times -e ssh " + "swigwin-" + version print "Finished" -print "Now log in to SourceForge and set the operating systems applicable to the newly uploaded tarball and zip file. Also remember to do a 'git push'." +print "Now log in to SourceForge and set the operating systems applicable to the newly uploaded tarball and zip file. Also remember to do a 'git push --tags'." From 37bccfd517dfebb4d191a144975d04c7ebfdea12 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 17 Sep 2013 23:43:30 +0100 Subject: [PATCH 130/481] Bump version to 3.0.0 SWIG 3 is open for business - looks go crazy! --- ANNOUNCE | 8 +-- CHANGES | 138 +++++++++++++++++++++++++++++++++++++++ CHANGES.current | 136 +------------------------------------- Doc/Manual/Sections.html | 6 +- README | 2 +- configure.ac | 2 +- 6 files changed, 148 insertions(+), 144 deletions(-) diff --git a/ANNOUNCE b/ANNOUNCE index caaa55d8c..90cc9ba24 100644 --- a/ANNOUNCE +++ b/ANNOUNCE @@ -1,8 +1,8 @@ -*** ANNOUNCE: SWIG 2.0.11 (15 Sep 2013) *** +*** ANNOUNCE: SWIG 3.0.0 (in progress) *** http://www.swig.org -We're pleased to announce SWIG-2.0.11, the latest SWIG release. +We're pleased to announce SWIG-3.0.0, the latest SWIG release. What is SWIG? ============= @@ -21,11 +21,11 @@ Availability ============ The release is available for download on Sourceforge at - http://prdownloads.sourceforge.net/swig/swig-2.0.11.tar.gz + http://prdownloads.sourceforge.net/swig/swig-3.0.0.tar.gz A Windows version is also available at - http://prdownloads.sourceforge.net/swig/swigwin-2.0.11.zip + http://prdownloads.sourceforge.net/swig/swigwin-3.0.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/CHANGES b/CHANGES index 488bf7286..c70765cf1 100644 --- a/CHANGES +++ b/CHANGES @@ -3,6 +3,144 @@ SWIG (Simplified Wrapper and Interface Generator) See the CHANGES.current file for changes in the current version. See the RELEASENOTES file for a summary of changes in each release. + +Version 2.0.11 (15 Sep 2013) +============================ + +2013-09-15: wsfulton + [R] Fix attempt to free a non-heap object in OUTPUT typemaps for: + unsigned short *OUTPUT + unsigned long *OUTPUT + signed long long *OUTPUT + char *OUTPUT + signed char*OUTPUT + unsigned char*OUTPUT + +2013-09-12: wsfulton + [Lua] Pull Git patch #62. + 1) Static members and static functions inside class can be accessed as + ModuleName.ClassName.FunctionName (MemberName respectively). Old way such as + ModuleName.ClassName_FunctionName still works. + 2) Same goes for enums inside classes: ModuleName.ClassName.EnumValue1 etc. + +2013-09-12: wsfulton + [UTL] Infinity is now by default an acceptable value for type 'float'. This fix makes + the handling of type 'float' and 'double' the same. The implementation requires the + C99 isfinite() macro, or otherwise some platform dependent equivalents, to be available. + + Users requiring the old behaviour of not accepting infinity, can define a 'check' typemap + wherever a float is used, such as: + + %typemap(check,fragment="") float, const float & %{ + if ($1 < -FLT_MAX || $1 > FLT_MAX) { + SWIG_exception_fail(SWIG_TypeError, "Overflow in type float"); + } + %} + + *** POTENTIAL INCOMPATIBILITY *** + +2013-08-30: wsfulton + [Lua] Pull Git patch #81: Include Lua error locus in SWIG error messages. + This is standard information in Lua error messages, and makes it much + easier to find bugs. + +2013-08-29: wsfulton + Pull Git patch #75: Handle UTF-8 files with BOM at beginning of file. Was giving an + 'Illegal token' syntax error. + +2013-08-29: wsfulton + [C#] Pull Git patch #77: Allow exporting std::map using non-default comparison function. + +2013-08-28: wsfulton + [Python] %implicitconv is improved for overloaded functions. Like in C++, the methods + with the actual types are considered before trying implicit conversions. Example: + + %implicitconv A; + struct A { + A(int i); + }; + class CCC { + public: + int xx(int i) { return 11; } + int xx(const A& i) { return 22; } + }; + + The following python code: + + CCC().xx(-1) + + will now return 11 instead of 22 - the implicit conversion is not done. + +2013-08-23: olly + [Python] Fix clang++ warning in generated wrapper code. + +2013-08-16: wsfulton + [Python] %implicitconv will now accept None where the implicit conversion takes a C/C++ pointer. + Problem highlighted by Bo Peng. Closes SF patch #230. + +2013-08-07: wsfulton + [Python] SF Patch #326 from Kris Thielemans - Remove SwigPyObject_print and SwigPyObject_str and + make the generated wrapper use the default python implementations, which will fall back to repr + (for -builtin option). + + Advantages: + - it avoids the swig user having to jump through hoops to get print to work as expected when + redefining repr/str slots. + - typing the name of a variable on the python prompt now prints the result of a (possibly redefined) + repr, without the swig user having to do any extra work. + - when redefining repr, the swig user doesn't necessarily have to redefine str as it will call the + redefined repr + - the behaviour is exactly the same as without the -builtin option while requiring no extra work + by the user (aside from adding the %feature("python:slot...) statements of course) + + Disadvantage: + - default str() will give different (but clearer?) output on swigged classes + +2013-07-30: wsfulton + [Python, Ruby] Fix #64 #65: Missing code in std::multimap wrappers. Previously an instantiation + of a std::map was erroneously required in addition to an instantiation of std::multimap with the + same template parameters to prevent compilation errors for the wrappers of a std::multimap. + +2013-07-14: joequant + [R] Change types file to allow for SEXP return values + +2013-07-05: wsfulton + [Python] Add %pythonbegin directive which works like %pythoncode, except the specified code is + added at the beginning of the generated .py file. This is primarily needed for importing from + __future__ statements required to be at the very beginning of the file. Example: + + %pythonbegin %{ + from __future__ import print_function + print("Loading", "Whizz", "Bang", sep=' ... ') + %} + +2013-07-01: wsfulton + [Python] Apply SF patch #340 - Uninitialized variable fix in SWIG_Python_NonDynamicSetAttr + when using -builtin. + +2013-07-01: wsfulton + [Python, Ruby, Ocaml] Apply SF patch #341 - fix a const_cast in generated code that was generating + a <:: digraph when using the unary scope operator (::) (global scope) in a template type. + +2013-07-01: wsfulton + [Python] Add SF patch #342 from Christian Delbaere to fix some director classes crashing on + object deletion when using -builtin. Fixes SF bug #1301. + +2013-06-11: wsfulton + [Python] Add SWIG_PYTHON_INTERPRETER_NO_DEBUG macro which can be defined to use the Release version + of the Python interpreter in Debug builds of the wrappers. The Visual Studio .dsp example + files have been modified to use this so that Debug builds will now work without having + to install or build a Debug build of the interpreter. + +2013-06-07: wsfulton + [Ruby] Git issue #52. Fix regression with missing rb_complex_new function for Ruby + versions prior to 1.9 using std::complex wrappers if just using std::complex as an output type. + Also fix the Complex helper functions external visibility (to static by default). + +2013-06-04: olly + [PHP] Fix SWIG_ZTS_ConvertResourcePtr() not to dereference NULL + if the type lookup fails. + Version 2.0.10 (27 May 2013) ============================ diff --git a/CHANGES.current b/CHANGES.current index 1727ecb2c..ddf123364 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -2,140 +2,6 @@ Below are the changes for the current release. See the CHANGES file for changes in older releases. See the RELEASENOTES file for a summary of changes in each release. -Version 2.0.11 (15 Sep 2013) +Version 3.0.0 (in progress) ============================ -2013-09-15: wsfulton - [R] Fix attempt to free a non-heap object in OUTPUT typemaps for: - unsigned short *OUTPUT - unsigned long *OUTPUT - signed long long *OUTPUT - char *OUTPUT - signed char*OUTPUT - unsigned char*OUTPUT - -2013-09-12: wsfulton - [Lua] Pull Git patch #62. - 1) Static members and static functions inside class can be accessed as - ModuleName.ClassName.FunctionName (MemberName respectively). Old way such as - ModuleName.ClassName_FunctionName still works. - 2) Same goes for enums inside classes: ModuleName.ClassName.EnumValue1 etc. - -2013-09-12: wsfulton - [UTL] Infinity is now by default an acceptable value for type 'float'. This fix makes - the handling of type 'float' and 'double' the same. The implementation requires the - C99 isfinite() macro, or otherwise some platform dependent equivalents, to be available. - - Users requiring the old behaviour of not accepting infinity, can define a 'check' typemap - wherever a float is used, such as: - - %typemap(check,fragment="") float, const float & %{ - if ($1 < -FLT_MAX || $1 > FLT_MAX) { - SWIG_exception_fail(SWIG_TypeError, "Overflow in type float"); - } - %} - - *** POTENTIAL INCOMPATIBILITY *** - -2013-08-30: wsfulton - [Lua] Pull Git patch #81: Include Lua error locus in SWIG error messages. - This is standard information in Lua error messages, and makes it much - easier to find bugs. - -2013-08-29: wsfulton - Pull Git patch #75: Handle UTF-8 files with BOM at beginning of file. Was giving an - 'Illegal token' syntax error. - -2013-08-29: wsfulton - [C#] Pull Git patch #77: Allow exporting std::map using non-default comparison function. - -2013-08-28: wsfulton - [Python] %implicitconv is improved for overloaded functions. Like in C++, the methods - with the actual types are considered before trying implicit conversions. Example: - - %implicitconv A; - struct A { - A(int i); - }; - class CCC { - public: - int xx(int i) { return 11; } - int xx(const A& i) { return 22; } - }; - - The following python code: - - CCC().xx(-1) - - will now return 11 instead of 22 - the implicit conversion is not done. - -2013-08-23: olly - [Python] Fix clang++ warning in generated wrapper code. - -2013-08-16: wsfulton - [Python] %implicitconv will now accept None where the implicit conversion takes a C/C++ pointer. - Problem highlighted by Bo Peng. Closes SF patch #230. - -2013-08-07: wsfulton - [Python] SF Patch #326 from Kris Thielemans - Remove SwigPyObject_print and SwigPyObject_str and - make the generated wrapper use the default python implementations, which will fall back to repr - (for -builtin option). - - Advantages: - - it avoids the swig user having to jump through hoops to get print to work as expected when - redefining repr/str slots. - - typing the name of a variable on the python prompt now prints the result of a (possibly redefined) - repr, without the swig user having to do any extra work. - - when redefining repr, the swig user doesn't necessarily have to redefine str as it will call the - redefined repr - - the behaviour is exactly the same as without the -builtin option while requiring no extra work - by the user (aside from adding the %feature("python:slot...) statements of course) - - Disadvantage: - - default str() will give different (but clearer?) output on swigged classes - -2013-07-30: wsfulton - [Python, Ruby] Fix #64 #65: Missing code in std::multimap wrappers. Previously an instantiation - of a std::map was erroneously required in addition to an instantiation of std::multimap with the - same template parameters to prevent compilation errors for the wrappers of a std::multimap. - -2013-07-14: joequant - [R] Change types file to allow for SEXP return values - -2013-07-05: wsfulton - [Python] Add %pythonbegin directive which works like %pythoncode, except the specified code is - added at the beginning of the generated .py file. This is primarily needed for importing from - __future__ statements required to be at the very beginning of the file. Example: - - %pythonbegin %{ - from __future__ import print_function - print("Loading", "Whizz", "Bang", sep=' ... ') - %} - -2013-07-01: wsfulton - [Python] Apply SF patch #340 - Uninitialized variable fix in SWIG_Python_NonDynamicSetAttr - when using -builtin. - -2013-07-01: wsfulton - [Python, Ruby, Ocaml] Apply SF patch #341 - fix a const_cast in generated code that was generating - a <:: digraph when using the unary scope operator (::) (global scope) in a template type. - -2013-07-01: wsfulton - [Python] Add SF patch #342 from Christian Delbaere to fix some director classes crashing on - object deletion when using -builtin. Fixes SF bug #1301. - -2013-06-11: wsfulton - [Python] Add SWIG_PYTHON_INTERPRETER_NO_DEBUG macro which can be defined to use the Release version - of the Python interpreter in Debug builds of the wrappers. The Visual Studio .dsp example - files have been modified to use this so that Debug builds will now work without having - to install or build a Debug build of the interpreter. - -2013-06-07: wsfulton - [Ruby] Git issue #52. Fix regression with missing rb_complex_new function for Ruby - versions prior to 1.9 using std::complex wrappers if just using std::complex as an output type. - Also fix the Complex helper functions external visibility (to static by default). - -2013-06-04: olly - [PHP] Fix SWIG_ZTS_ConvertResourcePtr() not to dereference NULL - if the type lookup fails. - diff --git a/Doc/Manual/Sections.html b/Doc/Manual/Sections.html index 2dfb438f8..195111424 100644 --- a/Doc/Manual/Sections.html +++ b/Doc/Manual/Sections.html @@ -1,12 +1,12 @@ -SWIG-2.0 Documentation +SWIG-3.0 Documentation -

    SWIG-2.0 Documentation

    +

    SWIG-3.0 Documentation

    -Last update : SWIG-2.0.11 (15 Sep 2013) +Last update : SWIG-3.0.0 (in progress)

    Sections

    diff --git a/README b/README index 946bd9a8f..b6080a4fd 100644 --- a/README +++ b/README @@ -1,6 +1,6 @@ SWIG (Simplified Wrapper and Interface Generator) -Version: 2.0.11 (15 Sep 2013) +Version: 3.0.0 (in progress) Tagline: SWIG is a compiler that integrates C and C++ with languages including Perl, Python, Tcl, Ruby, PHP, Java, C#, D, Go, Lua, diff --git a/configure.ac b/configure.ac index c4db3ce98..47d1e13ae 100644 --- a/configure.ac +++ b/configure.ac @@ -2,7 +2,7 @@ dnl Process this file with autoconf to produce a configure script. dnl The macros which aren't shipped with the autotools are stored in the dnl Tools/config directory in .m4 files. -AC_INIT([swig],[2.0.11],[http://www.swig.org]) +AC_INIT([swig],[3.0.0],[http://www.swig.org]) dnl NB: When this requirement is increased to 2.60 or later, AC_PROG_SED dnl definition below can be removed From d0cb2b73dbd04a20f977db818056b0de5ac2605e Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Wed, 18 Sep 2013 00:38:39 +0100 Subject: [PATCH 131/481] Remove X11 detection during configure X11 is not used anywhere. --- Examples/Makefile.in | 21 ------------ Lib/perl5/Makefile.in | 18 ++--------- Lib/python/Makefile.in | 18 ++--------- Lib/tcl/Makefile.in | 19 ++++------- configure.ac | 73 +----------------------------------------- 5 files changed, 13 insertions(+), 136 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 5607feb9e..e9b70f961 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -51,11 +51,6 @@ RUNPIPE= RUNME = runme -# X11 options - -XLIB = @XLIBSW@ -XINCLUDE = @XINCLUDES@ - IWRAP = $(INTERFACE:.i=_wrap.i) ISRCS = $(IWRAP:.i=.c) ICXXSRCS = $(IWRAP:.i=.cxx) @@ -136,7 +131,6 @@ TCL_SCRIPT = $(RUNME).tcl # Build a new version of the tclsh shell # ----------------------------------------------------------- - tclsh: $(SRCS) $(SWIG) -tcl8 $(SWIGOPT) $(TCL_SWIGOPTS) -ltclsh.i $(INTERFACEPATH) $(CC) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(TCL_INCLUDE) \ @@ -147,21 +141,6 @@ tclsh_cpp: $(SRCS) $(CXX) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) \ $(TCL_LIB) $(TCL_OPTS) $(LIBS) $(SYSLIBS) -o $(TARGET) -# ----------------------------------------------------------- -# Build a new copy of wish -# ----------------------------------------------------------- - -wish: $(SRCS) - $(SWIG) -tcl8 $(SWIGOPT) $(TCL_SWIGOPTS) -lwish.i $(INTERFACEPATH) - $(CC) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(TCL_INCLUDE) \ - $(XINCLUDE) $(TCL_LIB) $(TK_OPTS) $(XLIB) $(LIBS) $(SYSLIBS) -o $(TARGET) - - -wish_cpp: $(SRCS) - $(SWIG) -tcl8 -c++ $(SWIGOPT) $(TCL_SWIGOPTS) -lwish.i $(INTERFACEPATH) - $(CXX) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) \ - $(XINCLUDE) $(TCL_LIB) $(TK_OPTS) $(XLIB) $(LIBS) $(SYSLIBS) -o $(TARGET) - # ----------------------------------------------------------- # Build a Tcl dynamic loadable module (you might need to tweak this) # ----------------------------------------------------------- diff --git a/Lib/perl5/Makefile.in b/Lib/perl5/Makefile.in index dde01894d..f11ad2bdf 100644 --- a/Lib/perl5/Makefile.in +++ b/Lib/perl5/Makefile.in @@ -47,7 +47,7 @@ SWIGOPT = -perl5 SWIGCC = $(CC) # SWIG Library files. Uncomment this to staticly rebuild Perl -#SWIGLIB = -static -lperlmain.i +#SWIGLIBS = -static -lperlmain.i # Rules for creating .o files from source. @@ -69,33 +69,21 @@ BUILD = @LDSHARED@ #DLL_LIBS = -L/usr/local/lib/gcc-lib/sparc-sun-solaris2.5.1/2.7.2 \ -L/usr/local/lib -lg++ -lstdc++ -lgcc -# X11 installation (possibly needed if using Perl-Tk) - -XLIB = @XLIBSW@ -XINCLUDE = @XINCLUDES@ - # Perl installation PERL_INCLUDE = -I@PERL5EXT@ PERL_LIB = -L@PERL5EXT@ -lperl PERL_FLAGS = -Dbool=char -Dexplicit= -# Tcl installation. If using Tk you might need this - -TCL_INCLUDE = @TCLINCLUDE@ -TCL_LIB = @TCLLIB@ - # Build libraries (needed for static builds) LIBM = @LIBM@ LIBC = @LIBC@ SYSLIBS = $(LIBM) $(LIBC) @LIBS@ -# Build options (uncomment only one these) +# Build options -#TK_LIB = $(TCL_LIB) -ltcl -ltk $(XLIB) BUILD_LIBS = $(LIBS) # Dynamic loading -#BUILD_LIBS = $(PERL_LIB) $(TK_LIB) $(LIBS) $(SYSLIBS) # Static linking # Compilation rules for non-SWIG components @@ -123,7 +111,7 @@ $(WRAPOBJ) : $(WRAPFILE) $(SWIGCC) -c $(CCSHARED) $(CFLAGS) $(INCLUDES) $(PERL_INCLUDE) $(PERL_FLAGS) $(WRAPFILE) $(WRAPFILE) : $(INTERFACE) - $(SWIG) $(SWIGOPT) -o $(WRAPFILE) $(SWIGLIB) $(INTERFACE) + $(SWIG) $(SWIGOPT) -o $(WRAPFILE) $(SWIGLIBS) $(INTERFACE) $(TARGET): $(WRAPOBJ) $(ALLOBJS) $(BUILD) $(WRAPOBJ) $(ALLOBJS) $(BUILD_LIBS) -o $(TARGET) diff --git a/Lib/python/Makefile.in b/Lib/python/Makefile.in index 3243b3df4..71effea70 100644 --- a/Lib/python/Makefile.in +++ b/Lib/python/Makefile.in @@ -47,7 +47,7 @@ SWIGOPT = -python SWIGCC = $(CC) # SWIG Library files. Uncomment if rebuilding the Python interpreter -#SWIGLIB = -lembed.i +#SWIGLIBS = -lembed.i # Rules for creating .o files from source. @@ -69,32 +69,20 @@ BUILD = @LDSHARED@ #DLL_LIBS = -L/usr/local/lib/gcc-lib/sparc-sun-solaris2.5.1/2.7.2 \ -L/usr/local/lib -lg++ -lstdc++ -lgcc -# X11 installation (needed if rebuilding Python + tkinter) - -XLIB = @XLIBSW@ -XINCLUDE = @XINCLUDES@ - # Python installation PY_INCLUDE = -DHAVE_CONFIG_H @PYINCLUDE@ PY_LIB = @PYLIB@ -# Tcl installation. Needed if rebuilding Python with tkinter. - -TCL_INCLUDE = @TCLINCLUDE@ -TCL_LIB = @TCLLIB@ - # Build libraries (needed for static builds) LIBM = @LIBM@ LIBC = @LIBC@ SYSLIBS = $(LIBM) $(LIBC) @LIBS@ -# Build options (uncomment only one these) +# Build options -#TKINTER = $(TCL_LIB) -ltk -ltcl $(XLIB) BUILD_LIBS = $(LIBS) # Dynamic loading -#BUILD_LIBS = $(PY_LIB) @PYLINK@ $(TKINTER) $(LIBS) $(SYSLIBS) # Compilation rules for non-SWIG components @@ -122,7 +110,7 @@ $(WRAPOBJ) : $(WRAPFILE) $(SWIGCC) -c $(CCSHARED) $(CFLAGS) $(WRAPFILE) $(INCLUDES) $(PY_INCLUDE) $(WRAPFILE) : $(INTERFACE) - $(SWIG) $(SWIGOPT) -o $(WRAPFILE) $(SWIGLIB) $(INTERFACE) + $(SWIG) $(SWIGOPT) -o $(WRAPFILE) $(SWIGLIBS) $(INTERFACE) $(TARGET): $(WRAPOBJ) $(ALLOBJS) $(BUILD) $(WRAPOBJ) $(ALLOBJS) $(BUILD_LIBS) -o $(TARGET) diff --git a/Lib/tcl/Makefile.in b/Lib/tcl/Makefile.in index 523349bb5..2ab0f7b01 100644 --- a/Lib/tcl/Makefile.in +++ b/Lib/tcl/Makefile.in @@ -1,5 +1,5 @@ # --------------------------------------------------------------- -# SWIG Tcl/Tk Makefile +# SWIG Tcl Makefile # # This file can be used to build various Tcl extensions with SWIG. # By default this file is set up for dynamic loading, but it can @@ -48,9 +48,8 @@ SWIG = $(exec_prefix)/bin/swig SWIGOPT = -tcl # use -tcl8 for Tcl 8.0 SWIGCC = $(CC) -# SWIG Library files. Uncomment one of these for rebuilding tclsh or wish -#SWIGLIB = -ltclsh.i -#SWIGLIB = -lwish.i +# SWIG Library files. Uncomment if rebuilding tclsh +#SWIGLIBS = -ltclsh.i # Rules for creating .o files from source. @@ -72,12 +71,7 @@ BUILD = @LDSHARED@ #DLL_LIBS = -L/usr/local/lib/gcc-lib/sparc-sun-solaris2.5.1/2.7.2 \ -L/usr/local/lib -lg++ -lstdc++ -lgcc -# X11 installation (needed to rebuild Tk extensions) - -XLIB = @XLIBSW@ -XINCLUDE = @XINCLUDES@ - -# Tcl installation (where is Tcl/Tk located) +# Tcl installation (where is Tcl located) TCL_INCLUDE = @TCLINCLUDE@ TCL_LIB = @TCLLIB@ @@ -88,11 +82,10 @@ LIBM = @LIBM@ LIBC = @LIBC@ SYSLIBS = $(LIBM) $(LIBC) @LIBS@ -# Build options (uncomment only one these) +# Build options (uncomment only one of these) BUILD_LIBS = $(LIBS) # Dynamic loading #BUILD_LIBS = $(TCL_LIB) -ltcl $(LIBS) $(SYSLIBS) # tclsh -#BUILD_LIBS = $(TCL_LIB) -ltk -ltcl $(XLIB) $(LIBS) $(SYSLIBS) # wish # Compilation rules for non-SWIG components @@ -120,7 +113,7 @@ $(WRAPOBJ) : $(WRAPFILE) $(SWIGCC) -c $(CCSHARED) $(CFLAGS) $(WRAPFILE) $(INCLUDES) $(TCL_INCLUDE) $(WRAPFILE) : $(INTERFACE) - $(SWIG) $(SWIGOPT) -o $(WRAPFILE) $(SWIGLIB) $(INTERFACE) + $(SWIG) $(SWIGOPT) -o $(WRAPFILE) $(SWIGLIBS) $(INTERFACE) $(TARGET): $(WRAPOBJ) $(ALLOBJS) $(BUILD) $(WRAPOBJ) $(ALLOBJS) $(BUILD_LIBS) -o $(TARGET) diff --git a/configure.ac b/configure.ac index 47d1e13ae..2d1c4a592 100644 --- a/configure.ac +++ b/configure.ac @@ -418,80 +418,9 @@ else AC_MSG_ERROR([proper usage is --with-libc=STRING]) fi]) #-------------------------------------------------------------------- -# Locate the X11 header files and the X11 library archive. Try -# the ac_path_x macro first, but if it doesn't find the X stuff -# (e.g. because there's no xmkmf program) then check through -# a list of possible directories. Under some conditions the -# autoconf macro will return an include directory that contains -# no include files, so double-check its result just to be safe. +# Target languages #-------------------------------------------------------------------- -AC_PATH_X -not_really_there="" -if test "$no_x" = ""; then - if test "$x_includes" = ""; then - AC_TRY_CPP([#include ], , not_really_there="yes") - else - if test ! -r $x_includes/X11/Intrinsic.h; then - not_really_there="yes" - fi - fi -fi -if test "$no_x" = "yes" -o "$not_really_there" = "yes"; then - AC_MSG_CHECKING(for X11 header files) - XINCLUDES="# no special path needed" - AC_TRY_CPP([#include ], , XINCLUDES="") - if test -z "$XINCLUDES"; then - dirs="/usr/unsupported/include /usr/local/include /usr/X386/include /usr/include/X11R4 /usr/X11R5/include /usr/include/X11R5 /usr/openwin/include /usr/X11/include /usr/sww/include /usr/X11R6/include /usr/include/X11R6" - for i in $dirs ; do - if test -r $i/X11/Intrinsic.h; then - XINCLUDES=" -I$i" - break - fi - done - fi - AC_MSG_RESULT($XINCLUDES) -else - if test "$x_includes" != ""; then - XINCLUDES=-I$x_includes - else - XINCLUDES="# no special path needed" - fi -fi -if test -z "$XINCLUDES"; then - AC_MSG_RESULT(couldn't find any!) - XINCLUDES="# no include files found" -fi - -if test "$no_x" = yes; then - AC_MSG_CHECKING(for X11 libraries) - XLIBSW= - dirs="/usr/unsupported/lib /usr/local/lib /usr/X386/lib /usr/lib/X11R4 /usr/X11R5/lib /usr/lib/X11R5 /usr/X11R6/lib /usr/lib/X11R6 /usr/openwin/lib /usr/X11/lib /usr/sww/X11/lib" - for i in $dirs ; do - if test -r $i/libX11.a -o -r $i/libX11.so -o -r $i/libX11.sl; then - AC_MSG_RESULT($i) - XLIBSW="-L$i -lX11" - break - fi - done -else - if test "$x_libraries" = ""; then - XLIBSW=-lX11 - else - XLIBSW="-L$x_libraries -lX11" - fi -fi -if test -z "$XLIBSW" ; then - AC_CHECK_LIB(Xwindow, XCreateWindow, XLIBSW=-lXwindow) -fi -if test -z "$XLIBSW" ; then - AC_MSG_RESULT(couldn't find any! Using -lX11.) - XLIBSW=-lX11 -fi - -AC_SUBST(XINCLUDES) -AC_SUBST(XLIBSW) - AC_ARG_WITH(alllang, AS_HELP_STRING([--without-alllang], [Disable all languages]), with_alllang="$withval") #-------------------------------------------------------------------- From 43032339d0517cd371b783693fb471a20f887e6d Mon Sep 17 00:00:00 2001 From: Gavin Kinsey Date: Thu, 19 Sep 2013 12:21:57 +0100 Subject: [PATCH 132/481] Fixed a memory leak for java STRING_ARRAY The allocation loop uses size, so the free loop should do the same, not size-1. --- Lib/java/various.i | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/java/various.i b/Lib/java/various.i index f589bf714..7ba7a5eb3 100644 --- a/Lib/java/various.i +++ b/Lib/java/various.i @@ -52,7 +52,7 @@ %typemap(freearg) char **STRING_ARRAY { int i; - for (i=0; i Date: Fri, 20 Sep 2013 18:47:46 +0100 Subject: [PATCH 133/481] Document Java char **STRING_ARRAY typemap fix --- CHANGES.current | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGES.current b/CHANGES.current index ddf123364..fe625d798 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,3 +5,6 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2013-09-20: wsfulton + [Java] Fix a memory leak for the java char **STRING_ARRAY typemaps. + From 173c4b3bbaec6afcb8d01dc59785664c124aa084 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 20 Sep 2013 19:39:30 +0100 Subject: [PATCH 134/481] Grab .travis.yml file from master to turn on Travis testing --- .travis.yml | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000..26758304f --- /dev/null +++ b/.travis.yml @@ -0,0 +1,58 @@ +language: cpp +compiler: + - clang + - gcc +env: + - SWIGLANG= +matrix: + include: + - compiler: gcc + env: SWIGLANG=csharp + - compiler: gcc + env: SWIGLANG=go + - compiler: gcc + env: SWIGLANG=guile + - compiler: gcc + env: SWIGLANG=java + - compiler: gcc + env: SWIGLANG=lua + - compiler: gcc + env: SWIGLANG=octave SWIGJOBS=-j4 + - compiler: gcc + env: SWIGLANG=perl5 + - compiler: gcc + env: SWIGLANG=php + - compiler: gcc + env: SWIGLANG=python + - compiler: gcc + env: SWIGLANG=python PY3=1 + - compiler: gcc + env: SWIGLANG=ruby + - compiler: gcc + env: SWIGLANG=tcl + allow_failures: + # None +before_install: + - lsb_release -a + - uname -a + - sudo apt-get -qq update + - time sudo apt-get -qq install libboost-dev + - if test "$SWIGLANG" = "csharp"; then sudo apt-get -qq install mono-devel; fi + - if test "$SWIGLANG" = "go"; then go env | sed -e 's/^/export /' > goenvsetup && source goenvsetup && rm -f goenvsetup; fi # Until configure.ac is fixed + - if test "$SWIGLANG" = "guile"; then sudo apt-get -qq install guile-2.0-dev; fi + - if test "$SWIGLANG" = "lua"; then sudo apt-get -qq install lua5.1 liblua5.1-dev; fi + - if test "$SWIGLANG" = "octave"; then sudo apt-get -qq install octave3.2 octave3.2-headers; fi + - if test "$SWIGLANG" = "php"; then sudo apt-get install php5-cli php5-dev; fi + - if test "$SWIGLANG" = "python" -a "$PY3"; then sudo apt-get install python3-dev; fi + - if test "$SWIGLANG" = "tcl"; then sudo apt-get -qq install tcl8.4-dev; fi +script: + - ./autogen.sh && ./configure + - make -s $SWIGJOBS + - if test -z "$SWIGLANG"; then make -s check-ccache; fi + - ./swig -version + - if test -n "$SWIGLANG"; then make -s check-$SWIGLANG-version; fi + - if test -n "$SWIGLANG"; then make -k $SWIGJOBS check-$SWIGLANG-examples; fi + - if test -n "$SWIGLANG"; then make -k $SWIGJOBS check-$SWIGLANG-test-suite; fi +branches: + only: + - master From 12708c9241bf9e5ef75a449ff848f2be84a35e72 Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Wed, 25 Sep 2013 17:29:33 +1200 Subject: [PATCH 135/481] Fix typos --- CHANGES | 4 ++-- Doc/Manual/Java.html | 2 +- Doc/Manual/SWIG.html | 2 +- .../android/extend/src/org/swig/extendexample/SwigExtend.java | 2 +- Examples/csharp/extend/runme.cs | 2 +- Examples/d/extend/d1/runme.d | 2 +- Examples/d/extend/d2/runme.d | 2 +- Examples/go/extend/runme.go | 2 +- Examples/java/extend/runme.java | 2 +- Lib/go/go.swg | 2 +- Source/Modules/lang.cxx | 2 +- Source/Modules/python.cxx | 2 +- Tools/config/ac_compile_warnings.m4 | 2 +- 13 files changed, 14 insertions(+), 14 deletions(-) diff --git a/CHANGES b/CHANGES index c70765cf1..4cc222901 100644 --- a/CHANGES +++ b/CHANGES @@ -3303,8 +3303,8 @@ Version 1.3.36 (24 June 2008) Makefile target being generated when generating makefiles with the -M family of options. For example: - $ swig -java -MM -MT overiddenname -c++ example.i - overiddenname: \ + $ swig -java -MM -MT overriddenname -c++ example.i + overriddenname: \ example.i \ example.h diff --git a/Doc/Manual/Java.html b/Doc/Manual/Java.html index 0024d602a..f3d8a1684 100644 --- a/Doc/Manual/Java.html +++ b/Doc/Manual/Java.html @@ -7886,7 +7886,7 @@ where it is possible to step from Java code into a JNI method within one environ

    Alternatively, debugging can involve placing debug printout statements in the JNI layer using the %exception directive. See the special variables for %exception section. -Many of the default typemaps can also be overidden and modified for adding in extra logging/debug display information. +Many of the default typemaps can also be overridden and modified for adding in extra logging/debug display information.

    diff --git a/Doc/Manual/SWIG.html b/Doc/Manual/SWIG.html index 25dc899de..f9ea5b2ef 100644 --- a/Doc/Manual/SWIG.html +++ b/Doc/Manual/SWIG.html @@ -258,7 +258,7 @@ this option the default output directory is the path to the input file. If -o and -outcurrentdir are used together, -outcurrentdir is effectively ignored as the output directory for the language files is the same directory as the -generated C/C++ file if not overidden with -outdir. +generated C/C++ file if not overridden with -outdir.

    5.1.3 Comments

    diff --git a/Examples/android/extend/src/org/swig/extendexample/SwigExtend.java b/Examples/android/extend/src/org/swig/extendexample/SwigExtend.java index a343dfebc..b88d36082 100644 --- a/Examples/android/extend/src/org/swig/extendexample/SwigExtend.java +++ b/Examples/android/extend/src/org/swig/extendexample/SwigExtend.java @@ -96,7 +96,7 @@ public class SwigExtend extends Activity // methods of all these instances are treated the same. For items 0, 1, and // 2, all methods resolve in C++. For item 3, our CEO, getTitle calls // getPosition which resolves in Java. The call to getPosition is - // slightly different, however, because of the overidden getPosition() call, since + // slightly different, however, because of the overridden getPosition() call, since // now the object reference has been "laundered" by passing through // EmployeeList as an Employee*. Previously, Java resolved the call // immediately in CEO, but now Java thinks the object is an instance of diff --git a/Examples/csharp/extend/runme.cs b/Examples/csharp/extend/runme.cs index 825dcdbca..92313aa5e 100644 --- a/Examples/csharp/extend/runme.cs +++ b/Examples/csharp/extend/runme.cs @@ -45,7 +45,7 @@ public class runme // methods of all these instances are treated the same. For items 0, 1, and // 2, all methods resolve in C++. For item 3, our CEO, getTitle calls // getPosition which resolves in C#. The call to getPosition is - // slightly different, however, because of the overidden getPosition() call, since + // slightly different, however, because of the overridden getPosition() call, since // now the object reference has been "laundered" by passing through // EmployeeList as an Employee*. Previously, C# resolved the call // immediately in CEO, but now C# thinks the object is an instance of diff --git a/Examples/d/extend/d1/runme.d b/Examples/d/extend/d1/runme.d index 96501d1a4..058432096 100644 --- a/Examples/d/extend/d1/runme.d +++ b/Examples/d/extend/d1/runme.d @@ -46,7 +46,7 @@ void main() { // methods of all these instances are treated the same. For items 0, 1, and // 2, all methods resolve in C++. For item 3, our CEO, getTitle calls // getPosition which resolves in D. The call to getPosition is - // slightly different, however, because of the overidden getPosition() call, since + // slightly different, however, because of the overridden getPosition() call, since // now the object reference has been "laundered" by passing through // EmployeeList as an Employee*. Previously, D resolved the call // immediately in CEO, but now D thinks the object is an instance of diff --git a/Examples/d/extend/d2/runme.d b/Examples/d/extend/d2/runme.d index 1ea6dfd21..cccdf463b 100644 --- a/Examples/d/extend/d2/runme.d +++ b/Examples/d/extend/d2/runme.d @@ -46,7 +46,7 @@ void main() { // methods of all these instances are treated the same. For items 0, 1, and // 2, all methods resolve in C++. For item 3, our CEO, getTitle calls // getPosition which resolves in D. The call to getPosition is - // slightly different, however, because of the overidden getPosition() call, since + // slightly different, however, because of the overridden getPosition() call, since // now the object reference has been "laundered" by passing through // EmployeeList as an Employee*. Previously, D resolved the call // immediately in CEO, but now D thinks the object is an instance of diff --git a/Examples/go/extend/runme.go b/Examples/go/extend/runme.go index 8fdfd0a6c..770e27802 100644 --- a/Examples/go/extend/runme.go +++ b/Examples/go/extend/runme.go @@ -42,7 +42,7 @@ func main() { // treated the same. For items 0, 1, and 2, all methods // resolve in C++. For item 3, our CEO, GetTitle calls // GetPosition which resolves in Go. The call to GetPosition - // is slightly different, however, because of the overidden + // is slightly different, however, because of the overridden // GetPosition() call, since now the object reference has been // "laundered" by passing through EmployeeList as an // Employee*. Previously, Go resolved the call immediately in diff --git a/Examples/java/extend/runme.java b/Examples/java/extend/runme.java index 629bb14a6..f1ec1ea06 100644 --- a/Examples/java/extend/runme.java +++ b/Examples/java/extend/runme.java @@ -55,7 +55,7 @@ public class runme { // methods of all these instances are treated the same. For items 0, 1, and // 2, all methods resolve in C++. For item 3, our CEO, getTitle calls // getPosition which resolves in Java. The call to getPosition is - // slightly different, however, because of the overidden getPosition() call, since + // slightly different, however, because of the overridden getPosition() call, since // now the object reference has been "laundered" by passing through // EmployeeList as an Employee*. Previously, Java resolved the call // immediately in CEO, but now Java thinks the object is an instance of diff --git a/Lib/go/go.swg b/Lib/go/go.swg index cc3beef7d..b00533fa3 100644 --- a/Lib/go/go.swg +++ b/Lib/go/go.swg @@ -431,7 +431,7 @@ %} /* Typecheck typemaps. The purpose of these is merely to issue a - warning for overloaded C++ functions * that cannot be overloaded in + warning for overloaded C++ functions that cannot be overloaded in Go as more than one C++ type maps to a single Go type. */ %typecheck(SWIG_TYPECHECK_BOOL) /* Go bool */ diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index eb7d49480..6cc6e9fc3 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -2513,7 +2513,7 @@ int Language::classHandler(Node *n) { Setattr(m, "parentNode", n); /* * There is a bug that needs fixing still... - * This area of code is creating methods which have not been overidden in a derived class (director methods that are protected in the base) + * This area of code is creating methods which have not been overridden in a derived class (director methods that are protected in the base) * If the method is overloaded, then Swig_overload_dispatch() incorrectly generates a call to the base wrapper, _wrap_xxx method * See director_protected_overloaded.i - Possibly sym:overname needs correcting here. Printf(stdout, "new method: %s::%s(%s)\n", Getattr(parentNode(m), "name"), Getattr(m, "name"), ParmList_str_defaultargs(Getattr(m, "parms"))); diff --git a/Source/Modules/python.cxx b/Source/Modules/python.cxx index 94802e06d..98f6cac09 100644 --- a/Source/Modules/python.cxx +++ b/Source/Modules/python.cxx @@ -3728,7 +3728,7 @@ public: if (builtin) builtin_pre_decl(n); - /* Overide the shadow file so we can capture its methods */ + /* Override the shadow file so we can capture its methods */ f_shadow = NewString(""); // Set up type check for director class constructor diff --git a/Tools/config/ac_compile_warnings.m4 b/Tools/config/ac_compile_warnings.m4 index 4c030ea59..7e4239a3c 100644 --- a/Tools/config/ac_compile_warnings.m4 +++ b/Tools/config/ac_compile_warnings.m4 @@ -4,7 +4,7 @@ dnl Set the maximum warning verbosity according to C and C++ compiler used. dnl Currently supports g++ and gcc. dnl dnl The compiler options are always added CFLAGS and CXXFLAGS even if -dnl these are overidden at configure time. Removing the maximum warning +dnl these are overridden at configure time. Removing the maximum warning dnl flags can be removed with --without-maximum-compile-warnings. For example: dnl dnl ./configure --without-maximum-compile-warnings CFLAGS= CXXFLAGS= From c4d40c7b64c0a599780f94824ca9d6d00f71264c Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 1 Oct 2013 22:13:57 +0100 Subject: [PATCH 136/481] PHP directors - generate call_user_function on one line --- Source/Modules/php.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Source/Modules/php.cxx b/Source/Modules/php.cxx index 3cae48383..652bd1e63 100644 --- a/Source/Modules/php.cxx +++ b/Source/Modules/php.cxx @@ -2606,8 +2606,8 @@ done: /* wrap complex arguments to zvals */ Printv(w->code, wrap_args, NIL); - Append(w->code, "call_user_function(EG(function_table), (zval**)&swig_self, &funcname,\n"); - Printf(w->code, " %s, %d, args TSRMLS_CC);\n", Swig_cresult_name(), idx); + Append(w->code, "call_user_function(EG(function_table), (zval**)&swig_self, &funcname,"); + Printf(w->code, " %s, %d, args TSRMLS_CC);\n", Swig_cresult_name(), idx); if (tm) { Printv(w->code, Str(tm), "\n", NIL); From e186d2176a527c0e171c8e85e42121a7a1d7d6de Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 4 Oct 2013 23:08:33 +0100 Subject: [PATCH 137/481] Fix %naturalvar and templated methods using enums %naturalvar was not being picked up - use the symbol table instead for looking up the feature. use_naturalvar_mode() has been moved to Language class (not strictly necessary though) --- CHANGES.current | 4 +++ Examples/test-suite/common.mk | 1 + Examples/test-suite/naturalvar_more.i | 46 +++++++++++++++++++++++++++ Source/Modules/lang.cxx | 20 ++++++++---- Source/Modules/swigmod.h | 6 ++-- 5 files changed, 68 insertions(+), 9 deletions(-) create mode 100644 Examples/test-suite/naturalvar_more.i diff --git a/CHANGES.current b/CHANGES.current index fe625d798..edd39af31 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,10 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2013-10-04: wsfulton + Fix %naturalvar not having any affect on templated classes instantiated with an + enum as the template parameter type. Problem reported by Vadim Zeitlin. + 2013-09-20: wsfulton [Java] Fix a memory leak for the java char **STRING_ARRAY typemaps. diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 997f8e715..381a49f7b 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -274,6 +274,7 @@ CPP_TEST_CASES += \ nspace \ nspace_extend \ naturalvar \ + naturalvar_more \ nested_class \ nested_comment \ nested_workaround \ diff --git a/Examples/test-suite/naturalvar_more.i b/Examples/test-suite/naturalvar_more.i new file mode 100644 index 000000000..2cbfb069c --- /dev/null +++ b/Examples/test-suite/naturalvar_more.i @@ -0,0 +1,46 @@ +%module naturalvar_more + +// The instantiation of a template using an enum in the template parameter was not picking up %naturalvar. + +// These typemaps will be used if %naturalvar is not working +%typemap(out) T *te, T *const_te "_should_not_use_this_out_typemap_" +%typemap(varout) T *te, T *const_te "_should_not_use_this_varout_typemap_" +%typemap(out) Hidden *hidden "_should_not_use_this_out_typemap_" +%typemap(varout) Hidden *hidden "_should_not_use_this_varout_typemap_" + +%naturalvar T; +%naturalvar Hidden; + +%inline %{ +template struct T {}; +struct K {}; +struct Hidden; +%} +%{ +struct Hidden {}; +%} + +%inline %{ +namespace Space { + enum E { E1, E2, E3 }; +} +%} + +%template(TE) T; + +%include +%include +%template(VectorString) std::vector; + +%inline { +using namespace Space; +struct S { + T te; + const T const_te; + const std::vector::value_type const_string_member; // check this resolves to std::string which has a naturalvar + std::vector::value_type string_member; // check this resolves to std::string which has a naturalvar + Hidden hidden; + S() : const_te(), const_string_member("initial string value") {} +}; +} + diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 6cc6e9fc3..1e63d4d9c 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -467,9 +467,9 @@ void swig_pragma(char *lang, char *name, char *value) { } /* -------------------------------------------------------------------------- - * use_naturalvar_mode() + * Language::use_naturalvar_mode() * -------------------------------------------------------------------------- */ -int use_naturalvar_mode(Node *n) { +int Language::use_naturalvar_mode(Node *n) const { if (Getattr(n, "unnamed")) return 0; int nvar = naturalvar_mode || GetFlag(n, "feature:naturalvar"); @@ -478,12 +478,17 @@ int use_naturalvar_mode(Node *n) { SwigType *ty = Getattr(n, "type"); SwigType *fullty = SwigType_typedef_resolve_all(ty); if (SwigType_isclass(fullty)) { - Node *m = Copy(n); SwigType *tys = SwigType_strip_qualifiers(fullty); - Swig_features_get(Swig_cparse_features(), 0, tys, 0, m); - nvar = GetFlag(m, "feature:naturalvar"); + if (!CPlusPlus) { + Replaceall(tys, "struct ", ""); + Replaceall(tys, "union ", ""); + Replaceall(tys, "class ", ""); + } + Node *typenode = Swig_symbol_clookup(tys, 0); + assert(typenode); + if (typenode) + nvar = GetFlag(typenode, "feature:naturalvar"); Delete(tys); - Delete(m); } Delete(fullty); } @@ -1441,6 +1446,7 @@ int Language::membervariableHandler(Node *n) { tm = Swig_typemap_lookup("memberin", nin, target, 0); Delete(nin); } + int flags = Extend | SmartPointer | use_naturalvar_mode(n); if (isNonVirtualProtectedAccess(n)) flags = flags | CWRAP_ALL_PROTECTED_ACCESS; @@ -3091,7 +3097,7 @@ Node *Language::symbolLookup(String *s, const_String_or_char_ptr scope) { * Tries to locate a class from a type definition * ----------------------------------------------------------------------------- */ -Node *Language::classLookup(const SwigType *s) { +Node *Language::classLookup(const SwigType *s) const { Node *n = 0; /* Look in hash of cached values */ diff --git a/Source/Modules/swigmod.h b/Source/Modules/swigmod.h index b3722af40..4fcf013eb 100644 --- a/Source/Modules/swigmod.h +++ b/Source/Modules/swigmod.h @@ -215,7 +215,7 @@ public: virtual int addSymbol(const String *s, const Node *n, const_String_or_char_ptr scope = ""); /* Add symbol */ virtual void dumpSymbols(); virtual Node *symbolLookup(String *s, const_String_or_char_ptr scope = ""); /* Symbol lookup */ - virtual Node *classLookup(const SwigType *s); /* Class lookup */ + virtual Node *classLookup(const SwigType *s) const; /* Class lookup */ virtual Node *enumLookup(SwigType *s); /* Enum lookup */ virtual int abstractClassTest(Node *n); /* Is class really abstract? */ virtual int is_assignable(Node *n); /* Is variable assignable? */ @@ -300,6 +300,9 @@ protected: This does not include protected virtual methods as they are turned on with the dirprot option. */ bool isNonVirtualProtectedAccess(Node *n) const; + /* Identify if a wrapped global or member variable n should use the naturalvar feature */ + int use_naturalvar_mode(Node *n) const; + /* Director subclass comparison test */ String *none_comparison; @@ -380,7 +383,6 @@ int is_protected(Node *n); int is_member_director(Node *parentnode, Node *member); int is_member_director(Node *member); int is_non_virtual_protected_access(Node *n); /* Check if the non-virtual protected members are required (for directors) */ -int use_naturalvar_mode(Node *n); void Wrapper_virtual_elimination_mode_set(int); void Wrapper_fast_dispatch_mode_set(int); From 3fcbb40af94f9209c2da4f806db45ef24ad8408b Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 5 Oct 2013 02:16:02 +0100 Subject: [PATCH 138/481] Remove incorrectly and newly introduced assert Was failing in li_boost_shared_ptr.i for some languages. A similar testcase has been added into naturalvar_more.i. --- Examples/test-suite/naturalvar_more.i | 7 +++++++ Source/Modules/lang.cxx | 1 - 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/Examples/test-suite/naturalvar_more.i b/Examples/test-suite/naturalvar_more.i index 2cbfb069c..aebb6b23e 100644 --- a/Examples/test-suite/naturalvar_more.i +++ b/Examples/test-suite/naturalvar_more.i @@ -15,9 +15,15 @@ template struct T {}; struct K {}; struct Hidden; +namespace Ace { + int glob; +} %} %{ struct Hidden {}; +namespace Ace { + template struct NoIdea {}; +} %} %inline %{ @@ -40,6 +46,7 @@ struct S { const std::vector::value_type const_string_member; // check this resolves to std::string which has a naturalvar std::vector::value_type string_member; // check this resolves to std::string which has a naturalvar Hidden hidden; + Ace::NoIdea noidea; S() : const_te(), const_string_member("initial string value") {} }; } diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 1e63d4d9c..a62084499 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -485,7 +485,6 @@ int Language::use_naturalvar_mode(Node *n) const { Replaceall(tys, "class ", ""); } Node *typenode = Swig_symbol_clookup(tys, 0); - assert(typenode); if (typenode) nvar = GetFlag(typenode, "feature:naturalvar"); Delete(tys); From 738cc36aabb80c8a0abbc22147f39cbe3cb13915 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 7 Oct 2013 20:37:00 +0100 Subject: [PATCH 139/481] Rename all C++0x to C++11 and cpp0x to cpp11 --- Doc/Devel/{cpp0x.html => cpp11.html} | 126 +++++++------- Doc/Manual/{Cpp0x.html => CPlusPlus11.html} | 158 +++++++++--------- Doc/Manual/chapters | 2 +- Examples/test-suite/common.mk | 72 ++++---- ...ax.i => cpp11_alternate_function_syntax.i} | 4 +- .../{cpp0x_constexpr.i => cpp11_constexpr.i} | 4 +- .../{cpp0x_decltype.i => cpp11_decltype.i} | 4 +- ...efault_delete.i => cpp11_default_delete.i} | 2 +- ...tors.i => cpp11_delegating_constructors.i} | 2 +- ... => cpp11_explicit_conversion_operators.i} | 4 +- ...ion_objects.i => cpp11_function_objects.i} | 2 +- ...pp0x_hash_tables.i => cpp11_hash_tables.i} | 4 +- ...tors.i => cpp11_inheriting_constructors.i} | 2 +- ...alizer_list.i => cpp11_initializer_list.i} | 4 +- ...tend.i => cpp11_initializer_list_extend.i} | 2 +- ...a_functions.i => cpp11_lambda_functions.i} | 4 +- ...nstant.i => cpp11_null_pointer_constant.i} | 4 +- ...literals.i => cpp11_raw_string_literals.i} | 2 +- .../{cpp0x_result_of.i => cpp11_result_of.i} | 4 +- ...e_reference.i => cpp11_rvalue_reference.i} | 2 +- ...reference2.i => cpp11_rvalue_reference2.i} | 2 +- ...reference3.i => cpp11_rvalue_reference3.i} | 2 +- ..._sizeof_object.i => cpp11_sizeof_object.i} | 4 +- ..._static_assert.i => cpp11_static_assert.i} | 2 +- ....i => cpp11_strongly_typed_enumerations.i} | 10 +- ...ets.i => cpp11_template_double_brackets.i} | 4 +- ...e_explicit.i => cpp11_template_explicit.i} | 4 +- ...e_typedefs.i => cpp11_template_typedefs.i} | 2 +- ...0x_thread_local.i => cpp11_thread_local.i} | 2 +- ...ation.i => cpp11_uniform_initialization.i} | 2 +- ...d_unions.i => cpp11_unrestricted_unions.i} | 2 +- ...iterals.i => cpp11_userdefined_literals.i} | 4 +- ...templates.i => cpp11_variadic_templates.i} | 2 +- ...java => cpp11_lambda_functions_runme.java} | 18 +- ...nme.java => cpp11_thread_local_runme.java} | 34 ++-- .../python/cpp0x_function_objects_runme.py | 12 -- .../cpp0x_initializer_list_extend_runme.py | 4 - .../python/cpp0x_initializer_list_runme.py | 5 - .../cpp0x_null_pointer_constant_runme.py | 15 -- .../python/cpp0x_result_of_runme.py | 3 - ... cpp11_alternate_function_syntax_runme.py} | 4 +- ...ltype_runme.py => cpp11_decltype_runme.py} | 4 +- .../python/cpp11_function_objects_runme.py | 12 ++ .../cpp11_initializer_list_extend_runme.py | 4 + .../python/cpp11_initializer_list_runme.py | 5 + .../cpp11_null_pointer_constant_runme.py | 15 ++ ....py => cpp11_raw_string_literals_runme.py} | 2 +- .../python/cpp11_result_of_runme.py | 3 + ...nme.py => cpp11_rvalue_reference_runme.py} | 4 +- ...l_runme.py => cpp11_thread_local_runme.py} | 2 +- ... => cpp11_uniform_initialization_runme.py} | 8 +- Source/CParse/parser.y | 10 +- 52 files changed, 307 insertions(+), 307 deletions(-) rename Doc/Devel/{cpp0x.html => cpp11.html} (90%) rename Doc/Manual/{Cpp0x.html => CPlusPlus11.html} (78%) rename Examples/test-suite/{cpp0x_alternate_function_syntax.i => cpp11_alternate_function_syntax.i} (77%) rename Examples/test-suite/{cpp0x_constexpr.i => cpp11_constexpr.i} (76%) rename Examples/test-suite/{cpp0x_decltype.i => cpp11_decltype.i} (85%) rename Examples/test-suite/{cpp0x_default_delete.i => cpp11_default_delete.i} (96%) rename Examples/test-suite/{cpp0x_delegating_constructors.i => cpp11_delegating_constructors.i} (88%) rename Examples/test-suite/{cpp0x_explicit_conversion_operators.i => cpp11_explicit_conversion_operators.i} (76%) rename Examples/test-suite/{cpp0x_function_objects.i => cpp11_function_objects.i} (95%) rename Examples/test-suite/{cpp0x_hash_tables.i => cpp11_hash_tables.i} (95%) rename Examples/test-suite/{cpp0x_inheriting_constructors.i => cpp11_inheriting_constructors.i} (89%) rename Examples/test-suite/{cpp0x_initializer_list.i => cpp11_initializer_list.i} (91%) rename Examples/test-suite/{cpp0x_initializer_list_extend.i => cpp11_initializer_list_extend.i} (93%) rename Examples/test-suite/{cpp0x_lambda_functions.i => cpp11_lambda_functions.i} (97%) rename Examples/test-suite/{cpp0x_null_pointer_constant.i => cpp11_null_pointer_constant.i} (85%) rename Examples/test-suite/{cpp0x_raw_string_literals.i => cpp11_raw_string_literals.i} (97%) rename Examples/test-suite/{cpp0x_result_of.i => cpp11_result_of.i} (83%) rename Examples/test-suite/{cpp0x_rvalue_reference.i => cpp11_rvalue_reference.i} (94%) rename Examples/test-suite/{cpp0x_rvalue_reference2.i => cpp11_rvalue_reference2.i} (98%) rename Examples/test-suite/{cpp0x_rvalue_reference3.i => cpp11_rvalue_reference3.i} (98%) rename Examples/test-suite/{cpp0x_sizeof_object.i => cpp11_sizeof_object.i} (71%) rename Examples/test-suite/{cpp0x_static_assert.i => cpp11_static_assert.i} (92%) rename Examples/test-suite/{cpp0x_strongly_typed_enumerations.i => cpp11_strongly_typed_enumerations.i} (84%) rename Examples/test-suite/{cpp0x_template_double_brackets.i => cpp11_template_double_brackets.i} (91%) rename Examples/test-suite/{cpp0x_template_explicit.i => cpp11_template_explicit.i} (81%) rename Examples/test-suite/{cpp0x_template_typedefs.i => cpp11_template_typedefs.i} (94%) rename Examples/test-suite/{cpp0x_thread_local.i => cpp11_thread_local.i} (97%) rename Examples/test-suite/{cpp0x_uniform_initialization.i => cpp11_uniform_initialization.i} (96%) rename Examples/test-suite/{cpp0x_unrestricted_unions.i => cpp11_unrestricted_unions.i} (93%) rename Examples/test-suite/{cpp0x_userdefined_literals.i => cpp11_userdefined_literals.i} (97%) rename Examples/test-suite/{cpp0x_variadic_templates.i => cpp11_variadic_templates.i} (98%) rename Examples/test-suite/java/{cpp0x_lambda_functions_runme.java => cpp11_lambda_functions_runme.java} (52%) rename Examples/test-suite/java/{cpp0x_thread_local_runme.java => cpp11_thread_local_runme.java} (52%) delete mode 100644 Examples/test-suite/python/cpp0x_function_objects_runme.py delete mode 100644 Examples/test-suite/python/cpp0x_initializer_list_extend_runme.py delete mode 100644 Examples/test-suite/python/cpp0x_initializer_list_runme.py delete mode 100644 Examples/test-suite/python/cpp0x_null_pointer_constant_runme.py delete mode 100644 Examples/test-suite/python/cpp0x_result_of_runme.py rename Examples/test-suite/python/{cpp0x_alternate_function_syntax_runme.py => cpp11_alternate_function_syntax_runme.py} (73%) rename Examples/test-suite/python/{cpp0x_decltype_runme.py => cpp11_decltype_runme.py} (86%) create mode 100644 Examples/test-suite/python/cpp11_function_objects_runme.py create mode 100644 Examples/test-suite/python/cpp11_initializer_list_extend_runme.py create mode 100644 Examples/test-suite/python/cpp11_initializer_list_runme.py create mode 100644 Examples/test-suite/python/cpp11_null_pointer_constant_runme.py rename Examples/test-suite/python/{cpp0x_raw_string_literals_runme.py => cpp11_raw_string_literals_runme.py} (95%) create mode 100644 Examples/test-suite/python/cpp11_result_of_runme.py rename Examples/test-suite/python/{cpp0x_rvalue_reference_runme.py => cpp11_rvalue_reference_runme.py} (90%) rename Examples/test-suite/python/{cpp0x_thread_local_runme.py => cpp11_thread_local_runme.py} (94%) rename Examples/test-suite/python/{cpp0x_uniform_initialization_runme.py => cpp11_uniform_initialization_runme.py} (68%) diff --git a/Doc/Devel/cpp0x.html b/Doc/Devel/cpp11.html similarity index 90% rename from Doc/Devel/cpp0x.html rename to Doc/Devel/cpp11.html index 4afc5ffe4..fc35465ae 100644 --- a/Doc/Devel/cpp0x.html +++ b/Doc/Devel/cpp11.html @@ -24,15 +24,15 @@ -

    C++0x support for SWIG

    +

    C++0x/C++11 support for SWIG

    Summary

    -

    This is a technical overview of the C++0x support for the Swig. -This area of Swig is a work in progress. Initial C++0x support for +

    This is a technical overview of the C++0x/C++11 support for the Swig. +This area of Swig is a work in progress. Initial C++0x/C++11 support for Swig was written during the Google Summer of Code 2009 period by Matevž Jekovec.

    SVN branch

    branches/gsoc2009-matevz

    -

    New C++0x features status

    +

    New C++11 features status

    Wikipedia article: http://en.wikipedia.org/wiki/C%2B%2B0x

    Rvalue reference and move semantics [done]

    @@ -63,12 +63,12 @@ operator=(ClassType&&):

    In practice, the Rvalues are used for temporaries (when passing the result of one function as an argument to another).

    Done: Added type&& to Swig parser. Added testcase -cpp0x_rvalue_reference.i. Operator && is treated the same as +cpp11_rvalue_reference.i. Operator && is treated the same as operator &. R11450

    Article: http://www.artima.com/cppsource/rvalue.html

    Generalized constant expressions [done]

    -

    In C++0x you can define functions as constant expressions. +

    In C++11 you can define functions as constant expressions. Functions need to return constant value in form "return expr", where expr is a constant expression.

    @@ -84,7 +84,7 @@ so swig doesn't need to know about the constant values when parsing the header file.

    Done: Added the “constexpr “ keyword to Swig. Added testcase -cpp0x_constexpr. R11322

    +cpp11_constexpr. R11322

    Problem: No compilers were known to support constexpr yet, so the testcase was temporarily commented out in common.mk.

    @@ -94,7 +94,7 @@ template in the translation unit at that time. It's a feature specifically aimed at compilers to speed up the compilation process.

    Done: Added support for 'extern template class -std::vector<MyClass>;'. Added testcase cpp0x_template_explicit. +std::vector<MyClass>;'. Added testcase cpp11_template_explicit. R11385 , R11386

    Initializer lists [done]

    Initializer list is a new type in standard library: @@ -117,11 +117,11 @@ is a simple way to convert an ordinary list or a vector to the initializer_list.

    Done: Ignored the constructor having initializer_list as its argument. Show warning to the user. Added testcase -cpp0x_initializer_list. R11450

    +cpp11_initializer_list. R11450

    Article: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1919.pdf

    Uniform initialization [done]

    -

    The new C++0x standard will allow the following:

    +

    The new C++11 standard will allow the following:

    struct IdString {
       std::string name;
       int identifier;
    @@ -132,7 +132,7 @@ IdString GetString() {
     }

    The feature works exactly as it did now for POD types only (eg. int a[] = {1,2,3};). The following declarations are the same in the new -C++0x:

    +C++11:

    IdString str1 = {„SomeName“, 4};
     IdString str2{„SomeName“, 4};

    The new way of using uniform initialization allows the following:

    @@ -154,12 +154,12 @@ AltStruct var2{2, 4.3}; // calls the constructor

    The new syntax is specific to C++. Java, C# and scripting languages do not support this behaviour, but always need constructors. They support {} brackets for declaration of arrays as C does + they add -support for creation of arrays on-the-fly (what c++0x introduced with +support for creation of arrays on-the-fly (what C++11 introduced with this feature and more).

    Done: Added syntax for {} member initialization in class -constructor. Added testcase cpp0x_uniform_initialization. R11413

    +constructor. Added testcase cpp11_uniform_initialization. R11413

    Type inference [partially done]

    -

    A new keyword 'auto' is introduced in C++0x:

    +

    A new keyword 'auto' is introduced in C++11:

    auto a1 = 100;
     auto a2 = myFunc();

    The type of a1 and a2 is automatically determined according to the @@ -184,7 +184,7 @@ introduce a new SwigType for this.

    only.

    Lambda functions and expressions [done]

    -

    C++0x introduces lambda functions defined as:

    +

    C++11 introduces lambda functions defined as:

    [](int x, int y) -> int { return x + y; }

    If the lambda function contains a single return statement only or the function doesn't return any type, the return type '->' can be @@ -210,14 +210,14 @@ functions still work inside the function block though.

    Article: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2550.pdf

    Done: Added syntax support for the lambda functions. Added -testcase cpp0x_lambda_functions.i. R11491, R11492

    +testcase cpp11_lambda_functions.i. R11491, R11492

    Alternate function syntax [done]

    The problem with decltype() is that the parameters need to be defined before the decltype. The following syntax is not valid, because lhs and rhs hasn't been defined at the time of decltype:

    template< typename LHS, typename RHS> 
    -  decltype(lhs+rhs) AddingFunc(const LHS &lhs, const RHS &rhs) {return lhs + rhs;} //Not legal C++0x

    -The solution C++0x offers is the combination of the 'auto' keyword + decltype(lhs+rhs) AddingFunc(const LHS &lhs, const RHS &rhs) {return lhs + rhs;} //Not legal C++11

    +The solution C++11 offers is the combination of the 'auto' keyword before and '-> rettype' after the function declaration:

    template< typename LHS, typename RHS> 
       auto AddingFunc(const LHS &lhs, const RHS &rhs) -> decltype(lhs+rhs) {return lhs + rhs;}

    @@ -233,13 +233,13 @@ auto SomeStruct::FuncName(int x, int y) -> int { }

    Done: Added support for the 'auto' return type. Added support for the '-> type' after the funtion declaration. Added testcases -cpp0x_alternate_function_syntax.i and -cpp0x_alternate_function_syntax_runme.py. R11414

    +cpp11_alternate_function_syntax.i and +cpp11_alternate_function_syntax_runme.py. R11414

    Concepts, Axioms [ignored]

    In C++ there is a common problem when you use a template in the class which doesn't support all the operations the functions in the class actually do on the type. Compiler errors are usually very long -and unreadable. C++0x adds support for the "concepts". The +and unreadable. C++11 adds support for the "concepts". The idea is to define what operations and attributes should the template have. In contrast to class inheritance and polimorphism, all lookups are done in compile-time. @@ -293,7 +293,7 @@ other constructs commonly associated with classes: T top(const std::vector<T>& v) { return v.back(); } bool empty(const std::vector<T>& v) { return v.empty(); } };

    -Axioms are a facility pertaining to concepts supplied by C++0x to +Axioms are a facility pertaining to concepts supplied by C++11 to express the semantic properties of concepts. For example, the concept Semigroup can be defined with an axiom Associativity as:

    @@ -306,7 +306,7 @@ Semigroup can be defined with an axiom Associativity as: Axioms are more like hints to the compiler to speed-up the process of compilation.

    -

    Ignored: Concepts and axioms were removed from the C++0x standard. +

    Ignored: Concepts and axioms were removed from the C++11 standard.

    Object construction improvement [done]

    This feature allows classes constructors to call other @@ -335,7 +335,7 @@ the inherited class: };

    Swig already correctly parses and produces the correct wrapper for the “using†keyword.

    -

    Done: Added testcase cpp0x_constructors.i which covers both +

    Done: Added testcase cpp11_constructors.i which covers both constructor delegation and constructor inheritance. R11532

    Problem: Constructor delegation and constructor inheritance is not supported by any compiler yet, so it's impossible to try and test @@ -351,11 +351,11 @@ this feature.

    values will work for the C++. And the other way around, nullptr behaves as the ordinary pointer (false, if empty, true, if not empty), so it's ok for swig to compare it.

    -

    Done: Written a testcase cpp0x_null_pointer_constant.i and -cpp0x_null_pointer_constant_runme.py to prove the nullptr +

    Done: Written a testcase cpp11_null_pointer_constant.i and +cpp11_null_pointer_constant_runme.py to prove the nullptr functionality. R11484

    Strongly typed enumerations [partially done]

    -

    C++0x introduces a new syntax for strongly typed enum declaration: +

    C++11 introduces a new syntax for strongly typed enum declaration:

     enum class Enumeration {
       Val1,
    @@ -371,16 +371,16 @@ int etc.:
     
     enum class Enum2 : unsigned int {Val1, Val2};

    And it can be forward declared as well:

    -
     enum Enum1;                   //Illegal in C++ and C++0x; no size is explicitly specified.
    - enum Enum2 : unsigned int;    //Legal in C++0x.
    - enum class Enum3;             //Legal in C++0x, because enum class declarations have a default type of "int".
    - enum class Enum4: unsigned int; //Legal C++0x.
    - enum Enum2 : unsigned short;  //Illegal in C++0x, because Enum2 was previously declared with a different type.

    +

     enum Enum1;                   //Illegal in C++ and C++11; no size is explicitly specified.
    + enum Enum2 : unsigned int;    //Legal in C++11.
    + enum class Enum3;             //Legal in C++11, because enum class declarations have a default type of "int".
    + enum class Enum4: unsigned int; //Legal C++11.
    + enum Enum2 : unsigned short;  //Illegal in C++11, because Enum2 was previously declared with a different type.

    Done: Added syntax 'enum class Name' and forward declarators 'enum Name : inherited type' or 'enum class Name : inherited type' in R11449.

    TODO: Add semantic support for enum elements not clashing with -enum elements in other enum classes. See cpp0x_strongly_typed_enums.i +enum elements in other enum classes. See cpp11_strongly_typed_enums.i warnings.

    Problem: Swig currently doesn't support nested classes. This feature should be implemented using a new nested class when using @@ -396,7 +396,7 @@ following article as a base:

    Done: Added support for angle brackets. Used the preferred "Approach 1". Added a testcase named -cpp0x_template_double_brackets. R11245

    +cpp11_template_double_brackets. R11245

    Explicit conversion operators [done]

    This is used when converting one type to another (eg. if (myObject) {}, where myObject is your custom class converted to @@ -407,9 +407,9 @@ supported in any target language (eg. python, php).

    Done: Swig already supports the keyword "explicit" for function types as well. Added test case -cpp0x_explicit_conversion_operators. R11323

    +cpp11_explicit_conversion_operators. R11323

    Template typedefs [partially done]

    -

    The new C++0x will allow creation of wrapper around the template. +

    The new C++11 will allow creation of wrapper around the template. For example, if we want to do this:

    template< typename first, typename second, int third>
     class SomeType;
    @@ -433,7 +433,7 @@ using PF = void (*)(double);            // New introduced syntax

    Swig supports parsing typedefs for templates as well for example:

    typedef List<int> intList;

    Done: Expanded support for the new 'using' syntax and template -aliasing. Added testcase cpp0x_template_typedefs. R11533

    +aliasing. Added testcase cpp11_template_typedefs. R11533

    TODO: Make Swig aware of the newly defined typedef. The TYPEDEF keyword is part of the storage_class rule and type+declarator (see c_decl rule) is the right part of the definition – for example void @@ -443,7 +443,7 @@ type, type_right rules and declarator, direct_declarator, notso_direct_declarator etc., which is PITA.

    Unrestricted unions [done]

    C++ currently offers usage of unions for types with trivial -constructors only. The new C++0x standard allows usage of types with +constructors only. The new C++11 standard allows usage of types with non-trivial constructors as well:

     struct point {
       point() {}
    @@ -453,14 +453,14 @@ non-trivial constructors as well:

    union P { int z; double w; - point p; // Illegal in C++; point has a non-trivial constructor. However, this is legal in C++0x. + point p; // Illegal in C++; point has a non-trivial constructor. However, this is legal in C++11. } p1;

    Swig already parses the given syntax.

    -

    Done: Added testcase cpp0x_unrestricted_unions. R11435, R11447

    +

    Done: Added testcase cpp11_unrestricted_unions. R11435, R11447

    Problem: GCC doesn't support unrestricted unions yet so there is no way to actually test, if it works.

    Variadic templates [partially done]

    -

    The new C++0x offers the following syntax:

    +

    The new C++11 offers the following syntax:

    template<typename... Values> class tuple;

    This can be used for example:

    class tuple<int, std::vector<int>, std::map<std::string, std::vector<int>>> someInstanceName;

    @@ -502,7 +502,7 @@ A new extension to sizeof is also introduced with this feature. The } // SomeStruct<Type1, Type2>::size is 2 and SomeStruct<>::size is 0

    Done: Added syntax support for 'typename' or 'class' + ... + id. -Added testcase cpp0x_variadic_templates. R11458

    +Added testcase cpp11_variadic_templates. R11458

    Done: Added syntax support for BaseClass + ..., type + ... + id in parameters and baseclass + ... for intializers after constructor. Extended Swig syntax to support sizeof...(Args). R11467

    @@ -510,11 +510,11 @@ Extended Swig syntax to support sizeof...(Args). R11467

    TODO: Only (if present) first variadically defined argument is currently used in %template directive. The next ones are ignored.

    New string literals [partially done]

    -

    Beside the implementation, the new C++0x Unicode and custom +

    Beside the implementation, the new C++11 Unicode and custom delimeter constants can occur in templates in the header file.

    Done: Added symbols 'u', 'u8' and 'U' to mark the beginning of the -UTF string. Also added test case cpp0x_raw_string_literals. R11327

    +UTF string. Also added test case cpp11_raw_string_literals. R11327

    Done: Added R"DELIMITER[, ]DELIMITER" for a custom delimiter for the beginning/end of the string. R11328

    TODO: Fix the Swig's C++ preprocessor bug when parsing an odd @@ -524,7 +524,7 @@ Source/Preprocessor/cpp.c.

    C++ has different suffix literals. eg. 12.5f marks the number 12.5 as float.

    -

    C++0x allows user to define his own suffix for the strings always +

    C++11 allows user to define his own suffix for the strings always starting with the underscore (_). eg. int a = "hello"_mySuffix;

    The syntax is similar to other operator overloading functions: @@ -548,18 +548,18 @@ Another possibility is to use variadic templates: This instantiates the literal processing function as operator""_Suffix<'1', '2', '3', '4'>. In this form, there is no terminating null character to the string. The main -purpose to doing this is to use C++0x's constexpr keyword and the +purpose to doing this is to use C++11's constexpr keyword and the compiler to allow the literal to be transformed entirely at compile time, assuming OutputType is a constexpr-constructable and copyable type, and the literal processing function is a constexpr function.

    Article: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2765.pdf

    Done: Added syntax support for userdefined literals. Added -testcase cpp0x_userdefined_literals.i. R11494

    +testcase cpp11_userdefined_literals.i. R11494

    TODO: %rename doesn't parse operatorâ€â€ yet.

    Thread-local storage [done]

    -

    New C++0x introduces keyword "thread_local" which marks +

    New C++11 introduces keyword "thread_local" which marks the following variable dynamically located depending on the current thread when using the address-of (&) operator.

    @@ -569,7 +569,7 @@ thread when using the address-of (&) operator. thread_local int val; };

    Done: Add "thread_local" keyword to Swig. Added testcase -cpp0x_thread_local. R11393

    +cpp11_thread_local. R11393

    Defaulting/deleting of standard functions on C++ objects [done]

    C++ automatically creates default constructor with empty parameters, copy constructor, operator= and destructor for any class. @@ -600,11 +600,11 @@ the standard functions brought by C++ itself. Ignored: Swig already parses the keywords "= delete" and "= default". These keywords are used for built-in functions (copy constructor, operator= etc.), which are ignored by Swig anyway.

    -

    Done: Added testcase cpp0x_default_delete. R11535

    +

    Done: Added testcase cpp11_default_delete. R11535

    Type long long int [done]

    Type long long int is an integer type that has at least 64 useful bits. C99 added it to its standard, but the C++ didn't adopt it until -C++0x. Most C++ compilers supported it though. +C++11. Most C++ compilers supported it though.

    Done: Swig already parses the C code including the long long type.

    @@ -616,18 +616,18 @@ C++0x. Most C++ compilers supported it though. static_assert(sizeof(int) <= sizeof(T), "not big enough"); };

    Done: Added syntax support for "static_assert()". Added -test case cpp0x_static_assert. R11369

    +test case cpp11_static_assert. R11369

    Allow sizeof to work on members of classes without an explicit object [done]

    -

    C++0x allows calls of sizeof to concrete objects as well: +

    C++11 allows calls of sizeof to concrete objects as well:

     struct A { int member; };
    - sizeof(A::member); //Does not work with C++03. Okay with C++0x

    + sizeof(A::member); //Does not work with C++03. Okay with C++11

    This kind of syntax is already supported by Swig.

    -

    Done: Added testcase cpp0x_sizeof_objects. R11538 +

    Done: Added testcase cpp11_sizeof_objects. R11538

    Threading facilities [ignored]

    -

    C++0x will add the following classes to the standard library: +

    C++11 will add the following classes to the standard library:

     * std::thread
      * std::mutex, std::recursive_mutex
    @@ -637,7 +637,7 @@ This kind of syntax is already supported by Swig.

    Ignored: No changes to the language itself is made.

    Tuple types [TODO]

    -

    Tuple is array of various types. C++0x introduced this feature +

    Tuple is array of various types. C++11 introduced this feature using variadic templates. Tuple is defined as:

    template <class ...Types> class tuple;

    Constructor is automatically generated filling the tuple elements. @@ -655,7 +655,7 @@ t1 = t2 ; // Ok, first two elements can be converted, // the third one can be constructed from a 'const char *'.

    TODO: Implement wrappers for the tuplet<> class.

    Hash tables [TODO]

    -

    C++0x introduces the "unordered" version of existing +

    C++11 introduces the "unordered" version of existing types, which in practice work faster than the linear types:

     - unordered set
    @@ -671,7 +671,7 @@ aliasing unordered classes to ordered ones doesn't work.

    TODO: Implement wrappers for unordered_ types. Initial work is already done in Lib/std/unordered_*.i files.

    Regular expressions [ignored]

    -

    Two new classes are introduced in C++0x: basic_regex and +

    Two new classes are introduced in C++11: basic_regex and match_results. Both are defined in regex header file.

    Ignored: The new feature extends the standardy library only. No @@ -725,9 +725,9 @@ changes to Swig needed. };

    Swig already supports the two.

    Done: Added a runtime testcase for function objects -cpp0x_function_objects. R11419.

    +cpp11_function_objects. R11419.

    Type traits for metaprogramming [ignored]

    -

    C++0x adds a new header file <type_traits> which includes +

    C++11 adds a new header file <type_traits> which includes helper functions to determine the template type while initializing the object at compile time.

    @@ -783,6 +783,6 @@ class calculus_ver2 { Swig correctly parses the result_of class.

    TODO: The return type (the result_of::type member) is not calculated by Swig. This needs a much more complex semantic parser.

    -

    Done: Added testcase cpp0x_result_of. R11534

    +

    Done: Added testcase cpp11_result_of. R11534

    - \ No newline at end of file + diff --git a/Doc/Manual/Cpp0x.html b/Doc/Manual/CPlusPlus11.html similarity index 78% rename from Doc/Manual/Cpp0x.html rename to Doc/Manual/CPlusPlus11.html index 457a7e41d..3caec748e 100644 --- a/Doc/Manual/Cpp0x.html +++ b/Doc/Manual/CPlusPlus11.html @@ -1,54 +1,54 @@ -SWIG and C++0x +SWIG and C++11 -

    7 SWIG and C++0x

    +

    7 SWIG and C++11

    @@ -56,22 +56,22 @@ -

    7.1 Introduction

    +

    7.1 Introduction

    This chapter gives you a brief overview about the SWIG -implementation of the C++0x standard. This part of SWIG is still a work in -progress. Initial C++0x support for SWIG was written during the +implementation of the C++11 standard. This part of SWIG is still a work in +progress. Initial C++11 support for SWIG was written during the Google Summer of Code 2009 period.

    SWIG supports all the new C++ syntax changes with some minor limitations (decltype expressions, variadic templates number). Wrappers for the new STL types (unordered_ containers, result_of, tuples) are not supported yet.

    -

    7.2 Core language changes

    +

    7.2 Core language changes

    -

    7.2.1 Rvalue reference and move semantics

    +

    7.2.1 Rvalue reference and move semantics

    SWIG correctly parses the new operator && the same as the reference operator &.

    @@ -87,7 +87,7 @@ class MyClass { };
    -

    7.2.2 Generalized constant expressions

    +

    7.2.2 Generalized constant expressions

    SWIG correctly parses the keyword constexpr, but ignores its functionality. Constant functions cannot be used as constants.

    @@ -105,7 +105,7 @@ constexpr int myConstFunc() { return MY_CONST; } const int a = MY_CONST; // ok -

    7.2.3 Extern template

    +

    7.2.3 Extern template

    SWIG correctly parses the keywords extern template. However, the explicit template instantiation is not used by SWIG, a %template is still required.

    @@ -123,7 +123,7 @@ public: }; -

    7.2.4 Initializer lists

    +

    7.2.4 Initializer lists

    Initializer lists are very much a C++ compiler construct and are not very accessible from wrappers as @@ -254,7 +254,7 @@ Note that the default typemap for std::initializer_list does nothing bu and hence any user supplied typemaps will override it and suppress the warning.

    -

    7.2.5 Uniform initialization

    +

    7.2.5 Uniform initialization

    The curly brackets {} for member initialization are fully @@ -287,7 +287,7 @@ AltStruct var2{2, 4.3}; // calls the constructor 142.15 -

    7.2.6 Type inference

    +

    7.2.6 Type inference

    SWIG supports decltype() with some limitations. Single @@ -304,13 +304,13 @@ int i; int j; decltype(i+j) k; // syntax error -

    7.2.7 Range-based for-loop

    +

    7.2.7 Range-based for-loop

    This feature is part of the implementation block only. SWIG ignores it.

    -

    7.2.8 Lambda functions and expressions

    +

    7.2.8 Lambda functions and expressions

    SWIG correctly parses most of the Lambda functions syntax. For example:

    @@ -336,7 +336,7 @@ auto six = [](int x, int y) { return x+y; }(4, 2); Better support should be available in a later release.

    -

    7.2.9 Alternate function syntax

    +

    7.2.9 Alternate function syntax

    SWIG fully supports the new definition of functions. For example:

    @@ -346,7 +346,7 @@ struct SomeStruct { }; -

    can now be written as in C++0x:

    +

    can now be written as in C++11:

     struct SomeStruct {
    @@ -371,7 +371,7 @@ auto SomeStruct::FuncName(int x, int y) -> int {
     auto square(float a, float b) -> decltype(a);
     
    -

    7.2.10 Object construction improvement

    +

    7.2.10 Object construction improvement

    @@ -412,12 +412,12 @@ class DerivedClass: public BaseClass { }; -

    7.2.11 Null pointer constant

    +

    7.2.11 Null pointer constant

    The nullptr constant is largely unimportant in wrappers. In the few places it has an effect, it is treated like NULL.

    -

    7.2.12 Strongly typed enumerations

    +

    7.2.12 Strongly typed enumerations

    SWIG parses the new enum class syntax and forward declarator for the enums:

    @@ -468,7 +468,7 @@ class AllColors { }; -

    7.2.13 Double angle brackets

    +

    7.2.13 Double angle brackets

    SWIG correctly parses the symbols >> as closing the @@ -479,7 +479,7 @@ shift operator >> otherwise.

    std::vector<std::vector<int>> myIntTable; -

    7.2.14 Explicit conversion operators

    +

    7.2.14 Explicit conversion operators

    SWIG correctly parses the keyword explicit both for operators and constructors. @@ -515,7 +515,7 @@ SWIG target languages, because all use their own facilities (eg. classes Cloneab to achieve particular copy and compare behaviours.

    -

    7.2.15 Alias templates

    +

    7.2.15 Alias templates

    The following is an example of an alias template: @@ -567,7 +567,7 @@ example.i:17: Warning 341: The 'using' keyword in type aliasing is not fully sup typedef void (*PFD)(double); // The old style -

    7.2.16 Unrestricted unions

    +

    7.2.16 Unrestricted unions

    SWIG fully supports any type inside a union even if it does not @@ -593,7 +593,7 @@ union P { } p1; -

    7.2.17 Variadic templates

    +

    7.2.17 Variadic templates

    SWIG supports the variadic templates syntax (inside the <> @@ -628,7 +628,7 @@ const int SIZE = sizeof...(ClassName<int, int>); In the above example SIZE is of course wrapped as a constant.

    -

    7.2.18 New string literals

    +

    7.2.18 New string literals

    SWIG supports unicode string constants and raw string literals.

    @@ -652,7 +652,7 @@ const char32_t *ii = UR"XXX(I'm a "raw UTF-32" \ string.)XXX";

    Note: SWIG currently incorrectly parses the odd number of double quotes inside the string due to SWIG's C++ preprocessor.

    -

    7.2.19 User-defined literals

    +

    7.2.19 User-defined literals

    @@ -719,7 +719,7 @@ OutputType var2 = 1234_suffix; OutputType var3 = 3.1416_suffix; -

    7.2.20 Thread-local storage

    +

    7.2.20 Thread-local storage

    SWIG correctly parses the thread_local keyword. For example, variable @@ -739,7 +739,7 @@ A variable will be thread local if accessed from different threads from the targ same way that it will be thread local if accessed from C++ code.

    -

    7.2.21 Defaulting/deleting of standard functions on C++ objects

    +

    7.2.21 Defaulting/deleting of standard functions on C++ objects

    SWIG correctly parses the = delete and = default @@ -757,12 +757,12 @@ struct NonCopyable {

    This feature is specific to C++ only. The defaulting/deleting is currently ignored, because SWIG automatically produces wrappers for special constructors and operators specific to the target language.

    -

    7.2.22 Type long long int

    +

    7.2.22 Type long long int

    SWIG correctly parses and uses the new long long type already introduced in C99 some time ago.

    -

    7.2.23 Static assertions

    +

    7.2.23 Static assertions

    SWIG correctly parses and calls the new static_assert function.

    @@ -774,7 +774,7 @@ struct Check { }; -

    7.2.24 Allow sizeof to work on members of classes without an explicit object

    +

    7.2.24 Allow sizeof to work on members of classes without an explicit object

    SWIG correctly calls the sizeof() on types as well as on the @@ -785,7 +785,7 @@ struct A { int member; }; -const int SIZE = sizeof(A::member); // does not work with C++03. Okay with C++0x +const int SIZE = sizeof(A::member); // does not work with C++03. Okay with C++11

    In Python:

    @@ -794,28 +794,28 @@ const int SIZE = sizeof(A::member); // does not work with C++03. Okay with C++0x 8 -

    7.3 Standard library changes

    +

    7.3 Standard library changes

    -

    7.3.1 Threading facilities

    +

    7.3.1 Threading facilities

    SWIG does not currently wrap or use any of the new threading classes introduced (thread, mutex, locks, condition variables, task). The main reason is that SWIG target languages offer their own threading facilities that do not rely on C++.

    -

    7.3.2 Tuple types and hash tables

    +

    7.3.2 Tuple types and hash tables

    SWIG does not wrap the new tuple types and the unordered_ container classes yet. Variadic template support is working so it is possible to include the tuple header file; it is parsed without any problems.

    -

    7.3.3 Regular expressions

    +

    7.3.3 Regular expressions

    -

    SWIG does not wrap the new C++0x regular expressions classes, because the SWIG target languages use their own facilities for this.

    +

    SWIG does not wrap the new C++11 regular expressions classes, because the SWIG target languages use their own facilities for this.

    -

    7.3.4 General-purpose smart pointers

    +

    7.3.4 General-purpose smart pointers

    @@ -823,12 +823,12 @@ SWIG provides special smart pointer handling for std::tr1::shared_ptr i There is no special smart pointer handling available for std::weak_ptr and std::unique_ptr.

    -

    7.3.5 Extensible random number facility

    +

    7.3.5 Extensible random number facility

    This feature extends and standardizes the standard library only and does not effect the C++ language and SWIG.

    -

    7.3.6 Wrapper reference

    +

    7.3.6 Wrapper reference

    The new ref and cref classes are used to instantiate a parameter as a reference of a template function. For example:

    @@ -853,7 +853,7 @@ int main() {

    The ref and cref classes are not wrapped by SWIG because the SWIG target languages do not support referencing.

    -

    7.3.7 Polymorphous wrappers for function objects

    +

    7.3.7 Polymorphous wrappers for function objects

    @@ -884,7 +884,7 @@ t = Test() b = t(1,2) # invoke C++ function object -

    7.3.8 Type traits for metaprogramming

    +

    7.3.8 Type traits for metaprogramming

    The new C++ metaprogramming is useful at compile time and is aimed specifically for C++ development:

    @@ -909,7 +909,7 @@ template< class T1, class T2 > int elaborate( T1 A, T2 B ) {

    SWIG correctly parses the template specialization, template types and values inside the <> block and the new helper functions: is_convertible, is_integral, is_const etc. However, SWIG still explicitly requires concrete types when using the %template directive, so the C++ metaprogramming features are not really of interest at runtime in the target languages.

    -

    7.3.9 Uniform method for computing return type of function objects

    +

    7.3.9 Uniform method for computing return type of function objects

    SWIG does not wrap the new result_of class introduced in the <functional> header and map the result_of::type to the concrete type yet. For example:

    diff --git a/Doc/Manual/chapters b/Doc/Manual/chapters index fd21651e3..45d35e793 100644 --- a/Doc/Manual/chapters +++ b/Doc/Manual/chapters @@ -4,7 +4,7 @@ Windows.html Scripting.html SWIG.html SWIGPlus.html -Cpp0x.html +CPlusPlus11.html Preprocessor.html Library.html Arguments.html diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index c0f642212..be6b4736a 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -87,7 +87,7 @@ CPP_TEST_BROKEN += \ overload_complicated \ template_default_pointer \ template_expr \ - $(CPP0X_TEST_BROKEN) + $(CPP11_TEST_BROKEN) # Broken C test cases. (Can be run individually using: make testcase.ctest) @@ -97,7 +97,7 @@ C_TEST_BROKEN += \ # C++ test cases. (Can be run individually using: make testcase.cpptest) CPP_TEST_CASES += \ - $(CPP0X_TEST_CASES) \ + $(CPP11_TEST_CASES) \ abstract_access \ abstract_inherit \ abstract_inherit_ok \ @@ -476,41 +476,41 @@ CPP_TEST_CASES += \ wallkw \ wrapmacro -# C++0x test cases. -CPP0X_TEST_CASES = \ - cpp0x_alternate_function_syntax \ - cpp0x_constexpr \ - cpp0x_decltype \ - cpp0x_default_delete \ - cpp0x_delegating_constructors \ - cpp0x_explicit_conversion_operators \ - cpp0x_function_objects \ - cpp0x_initializer_list \ - cpp0x_initializer_list_extend \ - cpp0x_lambda_functions \ - cpp0x_null_pointer_constant \ - cpp0x_raw_string_literals \ - cpp0x_rvalue_reference \ - cpp0x_rvalue_reference2 \ - cpp0x_rvalue_reference3 \ - cpp0x_sizeof_object \ - cpp0x_static_assert \ - cpp0x_strongly_typed_enumerations \ - cpp0x_template_double_brackets \ - cpp0x_template_explicit \ - cpp0x_template_typedefs \ - cpp0x_uniform_initialization \ - cpp0x_unrestricted_unions \ - cpp0x_userdefined_literals \ - cpp0x_variadic_templates +# C++11 test cases. +CPP11_TEST_CASES = \ + cpp11_alternate_function_syntax \ + cpp11_constexpr \ + cpp11_decltype \ + cpp11_default_delete \ + cpp11_delegating_constructors \ + cpp11_explicit_conversion_operators \ + cpp11_function_objects \ + cpp11_initializer_list \ + cpp11_initializer_list_extend \ + cpp11_lambda_functions \ + cpp11_null_pointer_constant \ + cpp11_raw_string_literals \ + cpp11_rvalue_reference \ + cpp11_rvalue_reference2 \ + cpp11_rvalue_reference3 \ + cpp11_sizeof_object \ + cpp11_static_assert \ + cpp11_strongly_typed_enumerations \ + cpp11_template_double_brackets \ + cpp11_template_explicit \ + cpp11_template_typedefs \ + cpp11_uniform_initialization \ + cpp11_unrestricted_unions \ + cpp11_userdefined_literals \ + cpp11_variadic_templates -# cpp0x_inheriting_constructors \ # not supported by gcc-4.7 -# cpp0x_hash_tables \ # not fully implemented yet -# cpp0x_result_of \ # SWIG does not support -# cpp0x_thread_local \ # needs gcc-4.8 +# cpp11_inheriting_constructors \ # not supported by gcc-4.7 +# cpp11_hash_tables \ # not fully implemented yet +# cpp11_result_of \ # SWIG does not support +# cpp11_thread_local \ # needs gcc-4.8 -# Broken C++0x test cases. -CPP0X_TEST_BROKEN = +# Broken C++11 test cases. +CPP11_TEST_BROKEN = # # Put all the heavy STD/STL cases here, where they can be skipped if needed @@ -626,7 +626,7 @@ all: $(NOT_BROKEN_TEST_CASES) $(BROKEN_TEST_CASES) check: $(NOT_BROKEN_TEST_CASES) -check-cpp11: $(CPP0X_TEST_CASES:=.cpptest) +check-cpp11: $(CPP11_TEST_CASES:=.cpptest) # partialcheck target runs SWIG only, ie no compilation or running of tests (for a subset of languages) partialcheck: diff --git a/Examples/test-suite/cpp0x_alternate_function_syntax.i b/Examples/test-suite/cpp11_alternate_function_syntax.i similarity index 77% rename from Examples/test-suite/cpp0x_alternate_function_syntax.i rename to Examples/test-suite/cpp11_alternate_function_syntax.i index 6726dad7c..227a1c8c8 100644 --- a/Examples/test-suite/cpp0x_alternate_function_syntax.i +++ b/Examples/test-suite/cpp11_alternate_function_syntax.i @@ -1,6 +1,6 @@ /* This testcase checks whether SWIG correctly uses the new alternate functions - declarations and definitions introduced in C++0x. */ -%module cpp0x_alternate_function_syntax + declarations and definitions introduced in C++11. */ +%module cpp11_alternate_function_syntax %inline %{ struct SomeStruct { diff --git a/Examples/test-suite/cpp0x_constexpr.i b/Examples/test-suite/cpp11_constexpr.i similarity index 76% rename from Examples/test-suite/cpp0x_constexpr.i rename to Examples/test-suite/cpp11_constexpr.i index ae1d292b4..95fe5fa2b 100644 --- a/Examples/test-suite/cpp0x_constexpr.i +++ b/Examples/test-suite/cpp11_constexpr.i @@ -1,7 +1,7 @@ /* This interface tests whether SWIG supports the new "constexpr" keyword - introduced by C++0x. + introduced by C++11. */ -%module cpp0x_constexpr +%module cpp11_constexpr %inline %{ class TestClass { diff --git a/Examples/test-suite/cpp0x_decltype.i b/Examples/test-suite/cpp11_decltype.i similarity index 85% rename from Examples/test-suite/cpp0x_decltype.i rename to Examples/test-suite/cpp11_decltype.i index 5a4292454..deedd5953 100644 --- a/Examples/test-suite/cpp0x_decltype.i +++ b/Examples/test-suite/cpp11_decltype.i @@ -1,7 +1,7 @@ /* This testcase checks whether SWIG correctly uses the new 'decltype()' - introduced in C++0x. + introduced in C++11. */ -%module cpp0x_decltype +%module cpp11_decltype %inline %{ class A { diff --git a/Examples/test-suite/cpp0x_default_delete.i b/Examples/test-suite/cpp11_default_delete.i similarity index 96% rename from Examples/test-suite/cpp0x_default_delete.i rename to Examples/test-suite/cpp11_default_delete.i index bdb74ffb1..be4cc6cc9 100644 --- a/Examples/test-suite/cpp0x_default_delete.i +++ b/Examples/test-suite/cpp11_default_delete.i @@ -1,6 +1,6 @@ /* This testcase checks whether SWIG correctly parses the default and delete keywords which keep or remove default C++ object construction functions. */ -%module cpp0x_default_delete +%module cpp11_default_delete %{ #include diff --git a/Examples/test-suite/cpp0x_delegating_constructors.i b/Examples/test-suite/cpp11_delegating_constructors.i similarity index 88% rename from Examples/test-suite/cpp0x_delegating_constructors.i rename to Examples/test-suite/cpp11_delegating_constructors.i index 679dce242..ca5aa326e 100644 --- a/Examples/test-suite/cpp0x_delegating_constructors.i +++ b/Examples/test-suite/cpp11_delegating_constructors.i @@ -1,7 +1,7 @@ /* This test checks whether SWIG correctly parses the new delegating constructors. */ -%module cpp0x_delegating_constructors +%module cpp11_delegating_constructors %inline %{ class A { diff --git a/Examples/test-suite/cpp0x_explicit_conversion_operators.i b/Examples/test-suite/cpp11_explicit_conversion_operators.i similarity index 76% rename from Examples/test-suite/cpp0x_explicit_conversion_operators.i rename to Examples/test-suite/cpp11_explicit_conversion_operators.i index 313b5e878..5e3ba03df 100644 --- a/Examples/test-suite/cpp0x_explicit_conversion_operators.i +++ b/Examples/test-suite/cpp11_explicit_conversion_operators.i @@ -1,7 +1,7 @@ /* This interface checks whether SWIG correctly compiles the new - explicit conversion operators feature introduced in C++0x. + explicit conversion operators feature introduced in C++11. */ -%module cpp0x_explicit_conversion_operators +%module cpp11_explicit_conversion_operators %inline %{ diff --git a/Examples/test-suite/cpp0x_function_objects.i b/Examples/test-suite/cpp11_function_objects.i similarity index 95% rename from Examples/test-suite/cpp0x_function_objects.i rename to Examples/test-suite/cpp11_function_objects.i index 4b9895ca8..fb75edea6 100644 --- a/Examples/test-suite/cpp0x_function_objects.i +++ b/Examples/test-suite/cpp11_function_objects.i @@ -3,7 +3,7 @@ Function objects are objects which overload the operator() function. The std::function does not provide any seamless support in the target languages yet. */ -%module cpp0x_function_objects +%module cpp11_function_objects %rename(__call__) Test::operator(); diff --git a/Examples/test-suite/cpp0x_hash_tables.i b/Examples/test-suite/cpp11_hash_tables.i similarity index 95% rename from Examples/test-suite/cpp0x_hash_tables.i rename to Examples/test-suite/cpp11_hash_tables.i index fff630ca0..4f68cbac5 100644 --- a/Examples/test-suite/cpp0x_hash_tables.i +++ b/Examples/test-suite/cpp11_hash_tables.i @@ -1,6 +1,6 @@ /* This testcase checks the new wrappers for the new unordered_ STL types - introduced in C++0x. */ -%module cpp0x_hash_tables + introduced in C++11. */ +%module cpp11_hash_tables %inline %{ #include diff --git a/Examples/test-suite/cpp0x_inheriting_constructors.i b/Examples/test-suite/cpp11_inheriting_constructors.i similarity index 89% rename from Examples/test-suite/cpp0x_inheriting_constructors.i rename to Examples/test-suite/cpp11_inheriting_constructors.i index 452598360..e1adb4caa 100644 --- a/Examples/test-suite/cpp0x_inheriting_constructors.i +++ b/Examples/test-suite/cpp11_inheriting_constructors.i @@ -1,7 +1,7 @@ /* This test checks whether SWIG correctly parses the new constructor inheritance. */ -%module cpp0x_inheriting_constructors +%module cpp11_inheriting_constructors %inline %{ class BaseClass { diff --git a/Examples/test-suite/cpp0x_initializer_list.i b/Examples/test-suite/cpp11_initializer_list.i similarity index 91% rename from Examples/test-suite/cpp0x_initializer_list.i rename to Examples/test-suite/cpp11_initializer_list.i index 14833390e..58d2ecc50 100644 --- a/Examples/test-suite/cpp0x_initializer_list.i +++ b/Examples/test-suite/cpp11_initializer_list.i @@ -1,6 +1,6 @@ /* This testcase shows a few simple ways to deal with the new initializer_list - introduced in C++0x. */ -%module cpp0x_initializer_list + introduced in C++11. */ +%module cpp11_initializer_list %warnfilter(SWIGWARN_TYPEMAP_INITIALIZER_LIST) B::B; %ignore A::A(std::initializer_list); diff --git a/Examples/test-suite/cpp0x_initializer_list_extend.i b/Examples/test-suite/cpp11_initializer_list_extend.i similarity index 93% rename from Examples/test-suite/cpp0x_initializer_list_extend.i rename to Examples/test-suite/cpp11_initializer_list_extend.i index d8443e622..02ad1312e 100644 --- a/Examples/test-suite/cpp0x_initializer_list_extend.i +++ b/Examples/test-suite/cpp11_initializer_list_extend.i @@ -1,6 +1,6 @@ /* This testcase shows how to replace std_initializer_list with std_vector. */ -%module cpp0x_initializer_list_extend +%module cpp11_initializer_list_extend %ignore Container::Container(std::initializer_list); %include diff --git a/Examples/test-suite/cpp0x_lambda_functions.i b/Examples/test-suite/cpp11_lambda_functions.i similarity index 97% rename from Examples/test-suite/cpp0x_lambda_functions.i rename to Examples/test-suite/cpp11_lambda_functions.i index 312414a49..87c7196d8 100644 --- a/Examples/test-suite/cpp0x_lambda_functions.i +++ b/Examples/test-suite/cpp11_lambda_functions.i @@ -1,9 +1,9 @@ /* This testcase checks whether SWIG correctly parses the lambda expressions - and closure syntax introduced in C++0x. + and closure syntax introduced in C++11. SWIG supports only lambda syntax and doesn't produce any wrapper code for this. */ -%module cpp0x_lambda_functions +%module cpp11_lambda_functions %warnfilter(SWIGWARN_CPP11_LAMBDA) lambda1; %warnfilter(SWIGWARN_CPP11_LAMBDA) lambda2; diff --git a/Examples/test-suite/cpp0x_null_pointer_constant.i b/Examples/test-suite/cpp11_null_pointer_constant.i similarity index 85% rename from Examples/test-suite/cpp0x_null_pointer_constant.i rename to Examples/test-suite/cpp11_null_pointer_constant.i index dcb5e61bd..0b3276a44 100644 --- a/Examples/test-suite/cpp0x_null_pointer_constant.i +++ b/Examples/test-suite/cpp11_null_pointer_constant.i @@ -1,8 +1,8 @@ /* This testcase checks whether SWIG correctly treats the new nullptr_t - constant introduced in C++0x. + constant introduced in C++11. */ -%module cpp0x_null_pointer_constant +%module cpp11_null_pointer_constant %feature("autodoc") A::NullPtrMethod; // Triggers conversion of nullptr to None, nil etc in target language %feature("compactdefaultargs") A::NullPtrMethod; diff --git a/Examples/test-suite/cpp0x_raw_string_literals.i b/Examples/test-suite/cpp11_raw_string_literals.i similarity index 97% rename from Examples/test-suite/cpp0x_raw_string_literals.i rename to Examples/test-suite/cpp11_raw_string_literals.i index 39a8bb641..6fd13a0d0 100644 --- a/Examples/test-suite/cpp0x_raw_string_literals.i +++ b/Examples/test-suite/cpp11_raw_string_literals.i @@ -7,7 +7,7 @@ This module also tests whether SWIG correctly parses custom string delimiters. */ -%module cpp0x_raw_string_literals +%module cpp11_raw_string_literals %warnfilter(SWIGWARN_TYPEMAP_CHARLEAK_MSG) bb; %warnfilter(SWIGWARN_TYPEMAP_CHARLEAK_MSG) ee; %warnfilter(SWIGWARN_TYPEMAP_CHARLEAK_MSG) gg; diff --git a/Examples/test-suite/cpp0x_result_of.i b/Examples/test-suite/cpp11_result_of.i similarity index 83% rename from Examples/test-suite/cpp0x_result_of.i rename to Examples/test-suite/cpp11_result_of.i index 42ff6c068..6d98ec0c0 100644 --- a/Examples/test-suite/cpp0x_result_of.i +++ b/Examples/test-suite/cpp11_result_of.i @@ -1,6 +1,6 @@ /* This testcase checks whether SWIG correctly uses the new result_of class - and its templating capabilities introduced in C++0x. */ -%module cpp0x_result_of + and its templating capabilities introduced in C++11. */ +%module cpp11_result_of %inline %{ #include diff --git a/Examples/test-suite/cpp0x_rvalue_reference.i b/Examples/test-suite/cpp11_rvalue_reference.i similarity index 94% rename from Examples/test-suite/cpp0x_rvalue_reference.i rename to Examples/test-suite/cpp11_rvalue_reference.i index 67686bc0f..45ee06354 100644 --- a/Examples/test-suite/cpp0x_rvalue_reference.i +++ b/Examples/test-suite/cpp11_rvalue_reference.i @@ -1,6 +1,6 @@ /* This testcase checks whether SWIG correctly parses the double ampersand && move operator which is currently mapped to the reference & operator. */ -%module cpp0x_rvalue_reference +%module cpp11_rvalue_reference %inline %{ #include diff --git a/Examples/test-suite/cpp0x_rvalue_reference2.i b/Examples/test-suite/cpp11_rvalue_reference2.i similarity index 98% rename from Examples/test-suite/cpp0x_rvalue_reference2.i rename to Examples/test-suite/cpp11_rvalue_reference2.i index dbeaa78fa..4ef871c63 100644 --- a/Examples/test-suite/cpp0x_rvalue_reference2.i +++ b/Examples/test-suite/cpp11_rvalue_reference2.i @@ -1,4 +1,4 @@ -%module cpp0x_rvalue_reference2 +%module cpp11_rvalue_reference2 %warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK) globalrrval; diff --git a/Examples/test-suite/cpp0x_rvalue_reference3.i b/Examples/test-suite/cpp11_rvalue_reference3.i similarity index 98% rename from Examples/test-suite/cpp0x_rvalue_reference3.i rename to Examples/test-suite/cpp11_rvalue_reference3.i index 2da1bf741..c65309945 100644 --- a/Examples/test-suite/cpp0x_rvalue_reference3.i +++ b/Examples/test-suite/cpp11_rvalue_reference3.i @@ -1,4 +1,4 @@ -%module cpp0x_rvalue_reference3 +%module cpp11_rvalue_reference3 %warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK); diff --git a/Examples/test-suite/cpp0x_sizeof_object.i b/Examples/test-suite/cpp11_sizeof_object.i similarity index 71% rename from Examples/test-suite/cpp0x_sizeof_object.i rename to Examples/test-suite/cpp11_sizeof_object.i index 72299786d..fca8a8ccc 100644 --- a/Examples/test-suite/cpp0x_sizeof_object.i +++ b/Examples/test-suite/cpp11_sizeof_object.i @@ -1,6 +1,6 @@ /* This testcase checks whether SWIG correctly uses the sizeof() on the - concrete objects and not only types introduced in C++0x. */ -%module cpp0x_sizeof_object + concrete objects and not only types introduced in C++11. */ +%module cpp11_sizeof_object %inline %{ struct B { diff --git a/Examples/test-suite/cpp0x_static_assert.i b/Examples/test-suite/cpp11_static_assert.i similarity index 92% rename from Examples/test-suite/cpp0x_static_assert.i rename to Examples/test-suite/cpp11_static_assert.i index d6413a1e5..8d616f96c 100644 --- a/Examples/test-suite/cpp0x_static_assert.i +++ b/Examples/test-suite/cpp11_static_assert.i @@ -1,7 +1,7 @@ /* This test case checks whether SWIG correctly parses and ignores the keywords "static_assert()" inside the class or struct. */ -%module cpp0x_static_assert +%module cpp11_static_assert %inline %{ template diff --git a/Examples/test-suite/cpp0x_strongly_typed_enumerations.i b/Examples/test-suite/cpp11_strongly_typed_enumerations.i similarity index 84% rename from Examples/test-suite/cpp0x_strongly_typed_enumerations.i rename to Examples/test-suite/cpp11_strongly_typed_enumerations.i index dbe6d44bc..ed466369e 100644 --- a/Examples/test-suite/cpp0x_strongly_typed_enumerations.i +++ b/Examples/test-suite/cpp11_strongly_typed_enumerations.i @@ -1,7 +1,7 @@ /* This testcase checks whether SWIG produces the correct wrapper for the strongly typed enums. Enums with the same type are comparable. Enum classes require support for nested classes. */ -%module cpp0x_strongly_typed_enumerations +%module cpp11_strongly_typed_enumerations %warnfilter(302) Val1; %warnfilter(302) Val2; %warnfilter(302) Val3; @@ -30,13 +30,13 @@ enum class Enum2 : short { %} // SWIG should fail this one -enum Enum2 : unsigned short; // Illegal in C++0x, because Enum2 was previously declared with a different type. +enum Enum2 : unsigned short; // Illegal in C++11, because Enum2 was previously declared with a different type. %inline %{ /* Forward declarations. */ -enum Enum4 : unsigned int; // Legal in C++0x. -enum class Enum5; // Legal in C++0x, because enum class declarations have a default type of "int". -enum class Enum6 : unsigned int; // Legal C++0x. +enum Enum4 : unsigned int; // Legal in C++11. +enum class Enum5; // Legal in C++11, because enum class declarations have a default type of "int". +enum class Enum6 : unsigned int; // Legal C++11. enum Enum4 : unsigned int { Val1, Val2, Val3 = 100, Val4 diff --git a/Examples/test-suite/cpp0x_template_double_brackets.i b/Examples/test-suite/cpp11_template_double_brackets.i similarity index 91% rename from Examples/test-suite/cpp0x_template_double_brackets.i rename to Examples/test-suite/cpp11_template_double_brackets.i index 6b2230362..15fe4903b 100644 --- a/Examples/test-suite/cpp0x_template_double_brackets.i +++ b/Examples/test-suite/cpp11_template_double_brackets.i @@ -1,8 +1,8 @@ /* This interface checks whether SWIG supports the new double angled brackets in the template syntax without having a space inbetween. This feature was - introduced in new C++0x standard. + introduced in new C++11 standard. */ -%module cpp0x_template_double_brackets +%module cpp11_template_double_brackets %inline %{ #include std::map> map1; diff --git a/Examples/test-suite/cpp0x_template_explicit.i b/Examples/test-suite/cpp11_template_explicit.i similarity index 81% rename from Examples/test-suite/cpp0x_template_explicit.i rename to Examples/test-suite/cpp11_template_explicit.i index bbc216ba0..80a30d283 100644 --- a/Examples/test-suite/cpp0x_template_explicit.i +++ b/Examples/test-suite/cpp11_template_explicit.i @@ -1,8 +1,8 @@ /* This unit tests whether SWIG correctly parses the code and makes wrappers - for the new C++0x extern templates (explicit template instantiation without + for the new C++11 extern templates (explicit template instantiation without using the translation unit). */ -%module cpp0x_template_explicit +%module cpp11_template_explicit #pragma SWIG nowarn=SWIGWARN_PARSE_EXPLICIT_TEMPLATE diff --git a/Examples/test-suite/cpp0x_template_typedefs.i b/Examples/test-suite/cpp11_template_typedefs.i similarity index 94% rename from Examples/test-suite/cpp0x_template_typedefs.i rename to Examples/test-suite/cpp11_template_typedefs.i index aeffde11a..ea46706a9 100644 --- a/Examples/test-suite/cpp0x_template_typedefs.i +++ b/Examples/test-suite/cpp11_template_typedefs.i @@ -1,5 +1,5 @@ /* This testcase checks whether SWIG correctly parses alias templates. */ -%module cpp0x_template_typedefs +%module cpp11_template_typedefs %warnfilter(SWIGWARN_CPP11_ALIAS_TEMPLATE) TypedefName; %warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) PF; diff --git a/Examples/test-suite/cpp0x_thread_local.i b/Examples/test-suite/cpp11_thread_local.i similarity index 97% rename from Examples/test-suite/cpp0x_thread_local.i rename to Examples/test-suite/cpp11_thread_local.i index 00f12dff9..6a1019824 100644 --- a/Examples/test-suite/cpp0x_thread_local.i +++ b/Examples/test-suite/cpp11_thread_local.i @@ -1,6 +1,6 @@ /* This testcase checks whether SWIG correctly parses the 'thread_local' storage specifier */ -%module cpp0x_thread_local +%module cpp11_thread_local %inline %{ struct ThreadLocals { diff --git a/Examples/test-suite/cpp0x_uniform_initialization.i b/Examples/test-suite/cpp11_uniform_initialization.i similarity index 96% rename from Examples/test-suite/cpp0x_uniform_initialization.i rename to Examples/test-suite/cpp11_uniform_initialization.i index 81a3e45de..07fb81280 100644 --- a/Examples/test-suite/cpp0x_uniform_initialization.i +++ b/Examples/test-suite/cpp11_uniform_initialization.i @@ -1,6 +1,6 @@ /* This testcase checks whether SWIG syntactically correctly parses the initialization syntax using {} braces for uniform member initialization. */ -%module cpp0x_uniform_initialization +%module cpp11_uniform_initialization %include diff --git a/Examples/test-suite/cpp0x_unrestricted_unions.i b/Examples/test-suite/cpp11_unrestricted_unions.i similarity index 93% rename from Examples/test-suite/cpp0x_unrestricted_unions.i rename to Examples/test-suite/cpp11_unrestricted_unions.i index be65fd83d..5facaafe1 100644 --- a/Examples/test-suite/cpp0x_unrestricted_unions.i +++ b/Examples/test-suite/cpp11_unrestricted_unions.i @@ -1,6 +1,6 @@ /* This testcase checks whether SWIG correctly parses the support for types without the defined trivial constructor in the unions. */ -%module cpp0x_unrestricted_unions +%module cpp11_unrestricted_unions %inline %{ struct point { diff --git a/Examples/test-suite/cpp0x_userdefined_literals.i b/Examples/test-suite/cpp11_userdefined_literals.i similarity index 97% rename from Examples/test-suite/cpp0x_userdefined_literals.i rename to Examples/test-suite/cpp11_userdefined_literals.i index d20345fed..43103cc8c 100644 --- a/Examples/test-suite/cpp0x_userdefined_literals.i +++ b/Examples/test-suite/cpp11_userdefined_literals.i @@ -1,6 +1,6 @@ /* This testcase checks whether SWIG correctly parses the user-defined literals - introduced in C++0x. */ -%module cpp0x_userdefined_literals + introduced in C++11. */ +%module cpp11_userdefined_literals // Unfortunately full declaration is needed for %rename atm, the parameter list cannot be omitted. %rename(MyRawLiteral) operator"" _myRawLiteral(const char * value); diff --git a/Examples/test-suite/cpp0x_variadic_templates.i b/Examples/test-suite/cpp11_variadic_templates.i similarity index 98% rename from Examples/test-suite/cpp0x_variadic_templates.i rename to Examples/test-suite/cpp11_variadic_templates.i index 2c0b2eac8..15ab4eece 100644 --- a/Examples/test-suite/cpp0x_variadic_templates.i +++ b/Examples/test-suite/cpp11_variadic_templates.i @@ -3,7 +3,7 @@ the template brackets, new functions sizeof... and multiple inheritance using variadic number of classes. */ -%module cpp0x_variadic_templates +%module cpp11_variadic_templates %warnfilter(SWIGWARN_CPP11_VARIADIC_TEMPLATE) MultiArgs; %warnfilter(SWIGWARN_CPP11_VARIADIC_TEMPLATE) SizeOf; %warnfilter(SWIGWARN_CPP11_VARIADIC_TEMPLATE) MultiInherit; diff --git a/Examples/test-suite/java/cpp0x_lambda_functions_runme.java b/Examples/test-suite/java/cpp11_lambda_functions_runme.java similarity index 52% rename from Examples/test-suite/java/cpp0x_lambda_functions_runme.java rename to Examples/test-suite/java/cpp11_lambda_functions_runme.java index 79545f87e..a0d310c7c 100644 --- a/Examples/test-suite/java/cpp0x_lambda_functions_runme.java +++ b/Examples/test-suite/java/cpp11_lambda_functions_runme.java @@ -1,10 +1,10 @@ -import cpp0x_lambda_functions.*; +import cpp11_lambda_functions.*; -public class cpp0x_lambda_functions_runme { +public class cpp11_lambda_functions_runme { static { try { - System.loadLibrary("cpp0x_lambda_functions"); + System.loadLibrary("cpp11_lambda_functions"); } 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); @@ -18,11 +18,11 @@ public class cpp0x_lambda_functions_runme { public static void main(String argv[]) { - check(cpp0x_lambda_functions.runLambda1(), 11); - check(cpp0x_lambda_functions.runLambda2(), 11); - check(cpp0x_lambda_functions.runLambda3(), 11); - check(cpp0x_lambda_functions.runLambda4(), 11); - check(cpp0x_lambda_functions.runLambda5(), 1); - check(cpp0x_lambda_functions.runLambda5(), 2); + check(cpp11_lambda_functions.runLambda1(), 11); + check(cpp11_lambda_functions.runLambda2(), 11); + check(cpp11_lambda_functions.runLambda3(), 11); + check(cpp11_lambda_functions.runLambda4(), 11); + check(cpp11_lambda_functions.runLambda5(), 1); + check(cpp11_lambda_functions.runLambda5(), 2); } } diff --git a/Examples/test-suite/java/cpp0x_thread_local_runme.java b/Examples/test-suite/java/cpp11_thread_local_runme.java similarity index 52% rename from Examples/test-suite/java/cpp0x_thread_local_runme.java rename to Examples/test-suite/java/cpp11_thread_local_runme.java index dc7cafafe..a645fbabf 100644 --- a/Examples/test-suite/java/cpp0x_thread_local_runme.java +++ b/Examples/test-suite/java/cpp11_thread_local_runme.java @@ -1,10 +1,10 @@ -import cpp0x_thread_local.*; +import cpp11_thread_local.*; -public class cpp0x_thread_local_runme { +public class cpp11_thread_local_runme { static { try { - System.loadLibrary("cpp0x_thread_local"); + System.loadLibrary("cpp11_thread_local"); } 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); @@ -20,32 +20,32 @@ public class cpp0x_thread_local_runme { if (ThreadLocals.tscval99 != 99) throw new RuntimeException(); - cpp0x_thread_local.setEtval(-11); - if (cpp0x_thread_local.getEtval() != -11) + cpp11_thread_local.setEtval(-11); + if (cpp11_thread_local.getEtval() != -11) throw new RuntimeException(); - cpp0x_thread_local.setStval(-22); - if (cpp0x_thread_local.getStval() != -22) + cpp11_thread_local.setStval(-22); + if (cpp11_thread_local.getStval() != -22) throw new RuntimeException(); - cpp0x_thread_local.setTsval(-33); - if (cpp0x_thread_local.getTsval() != -33) + cpp11_thread_local.setTsval(-33); + if (cpp11_thread_local.getTsval() != -33) throw new RuntimeException(); - cpp0x_thread_local.setEtval(-44); - if (cpp0x_thread_local.getEtval() != -44) + cpp11_thread_local.setEtval(-44); + if (cpp11_thread_local.getEtval() != -44) throw new RuntimeException(); - cpp0x_thread_local.setTeval(-55); - if (cpp0x_thread_local.getTeval() != -55) + cpp11_thread_local.setTeval(-55); + if (cpp11_thread_local.getTeval() != -55) throw new RuntimeException(); - cpp0x_thread_local.setEctval(-55); - if (cpp0x_thread_local.getEctval() != -55) + cpp11_thread_local.setEctval(-55); + if (cpp11_thread_local.getEctval() != -55) throw new RuntimeException(); - cpp0x_thread_local.setEcpptval(-66); - if (cpp0x_thread_local.getEcpptval() != -66) + cpp11_thread_local.setEcpptval(-66); + if (cpp11_thread_local.getEcpptval() != -66) throw new RuntimeException(); } } diff --git a/Examples/test-suite/python/cpp0x_function_objects_runme.py b/Examples/test-suite/python/cpp0x_function_objects_runme.py deleted file mode 100644 index ed8f888b1..000000000 --- a/Examples/test-suite/python/cpp0x_function_objects_runme.py +++ /dev/null @@ -1,12 +0,0 @@ -import cpp0x_function_objects -import sys - -t = cpp0x_function_objects.Test() -if t.value != 0: - raise RuntimeError("Runtime cpp0x_function_objects failed. t.value should be 0, but is " + str(t.value)) - -t(1,2) # adds numbers and sets value - -if t.value != 3: - raise RuntimeError("Runtime cpp0x_function_objects failed. t.value not changed - should be 3, but is " + str(t.value)) - diff --git a/Examples/test-suite/python/cpp0x_initializer_list_extend_runme.py b/Examples/test-suite/python/cpp0x_initializer_list_extend_runme.py deleted file mode 100644 index b07231408..000000000 --- a/Examples/test-suite/python/cpp0x_initializer_list_extend_runme.py +++ /dev/null @@ -1,4 +0,0 @@ -import cpp0x_initializer_list_extend - -c = cpp0x_initializer_list_extend.Container( [10, 20, 30, 40] ) - diff --git a/Examples/test-suite/python/cpp0x_initializer_list_runme.py b/Examples/test-suite/python/cpp0x_initializer_list_runme.py deleted file mode 100644 index 5c8c153a5..000000000 --- a/Examples/test-suite/python/cpp0x_initializer_list_runme.py +++ /dev/null @@ -1,5 +0,0 @@ -import cpp0x_initializer_list - -a = cpp0x_initializer_list.A() -a = cpp0x_initializer_list.A(11.1) - diff --git a/Examples/test-suite/python/cpp0x_null_pointer_constant_runme.py b/Examples/test-suite/python/cpp0x_null_pointer_constant_runme.py deleted file mode 100644 index b80dcaf2f..000000000 --- a/Examples/test-suite/python/cpp0x_null_pointer_constant_runme.py +++ /dev/null @@ -1,15 +0,0 @@ -import cpp0x_null_pointer_constant - -a = cpp0x_null_pointer_constant.A() - -if a._myA != None: - raise RuntimeError, ("cpp0x_null_pointer_constant: _myA should be None, but is ", a._myA) - -b = cpp0x_null_pointer_constant.A() -if a._myA != b._myA: - raise RuntimeError, ("cpp0x_null_pointer_constant: a._myA should be the same as b._myA, but ", a._myA, "!=", b._myA) - -a._myA = cpp0x_null_pointer_constant.A() -if a._myA == None: - raise RuntimeError, ("cpp0x_null_pointer_constant: _myA should be object, but is None") - diff --git a/Examples/test-suite/python/cpp0x_result_of_runme.py b/Examples/test-suite/python/cpp0x_result_of_runme.py deleted file mode 100644 index 5411cd1ce..000000000 --- a/Examples/test-suite/python/cpp0x_result_of_runme.py +++ /dev/null @@ -1,3 +0,0 @@ -import cpp0x_result_of -if cpp0x_result_of.test_result(cpp0x_result_of.square, 3.0) != 9.0: - raise RuntimeError, "test_result(square, 3.0) is not 9.0." diff --git a/Examples/test-suite/python/cpp0x_alternate_function_syntax_runme.py b/Examples/test-suite/python/cpp11_alternate_function_syntax_runme.py similarity index 73% rename from Examples/test-suite/python/cpp0x_alternate_function_syntax_runme.py rename to Examples/test-suite/python/cpp11_alternate_function_syntax_runme.py index 8005cfab7..0a1c45716 100644 --- a/Examples/test-suite/python/cpp0x_alternate_function_syntax_runme.py +++ b/Examples/test-suite/python/cpp11_alternate_function_syntax_runme.py @@ -1,6 +1,6 @@ -import cpp0x_alternate_function_syntax +import cpp11_alternate_function_syntax -a = cpp0x_alternate_function_syntax.SomeStruct() +a = cpp11_alternate_function_syntax.SomeStruct() res = a.addNormal(4,5) if res != 9: diff --git a/Examples/test-suite/python/cpp0x_decltype_runme.py b/Examples/test-suite/python/cpp11_decltype_runme.py similarity index 86% rename from Examples/test-suite/python/cpp0x_decltype_runme.py rename to Examples/test-suite/python/cpp11_decltype_runme.py index ce742e6b2..bfcbbec79 100644 --- a/Examples/test-suite/python/cpp0x_decltype_runme.py +++ b/Examples/test-suite/python/cpp11_decltype_runme.py @@ -1,6 +1,6 @@ -import cpp0x_decltype +import cpp11_decltype -a = cpp0x_decltype.A() +a = cpp11_decltype.A() a.i = 5 if a.i != 5: raise RuntimeError, "Assignment to a.i failed." diff --git a/Examples/test-suite/python/cpp11_function_objects_runme.py b/Examples/test-suite/python/cpp11_function_objects_runme.py new file mode 100644 index 000000000..aac7f9c5f --- /dev/null +++ b/Examples/test-suite/python/cpp11_function_objects_runme.py @@ -0,0 +1,12 @@ +import cpp11_function_objects +import sys + +t = cpp11_function_objects.Test() +if t.value != 0: + raise RuntimeError("Runtime cpp11_function_objects failed. t.value should be 0, but is " + str(t.value)) + +t(1,2) # adds numbers and sets value + +if t.value != 3: + raise RuntimeError("Runtime cpp11_function_objects failed. t.value not changed - should be 3, but is " + str(t.value)) + diff --git a/Examples/test-suite/python/cpp11_initializer_list_extend_runme.py b/Examples/test-suite/python/cpp11_initializer_list_extend_runme.py new file mode 100644 index 000000000..eedf8f148 --- /dev/null +++ b/Examples/test-suite/python/cpp11_initializer_list_extend_runme.py @@ -0,0 +1,4 @@ +import cpp11_initializer_list_extend + +c = cpp11_initializer_list_extend.Container( [10, 20, 30, 40] ) + diff --git a/Examples/test-suite/python/cpp11_initializer_list_runme.py b/Examples/test-suite/python/cpp11_initializer_list_runme.py new file mode 100644 index 000000000..395cd610d --- /dev/null +++ b/Examples/test-suite/python/cpp11_initializer_list_runme.py @@ -0,0 +1,5 @@ +import cpp11_initializer_list + +a = cpp11_initializer_list.A() +a = cpp11_initializer_list.A(11.1) + diff --git a/Examples/test-suite/python/cpp11_null_pointer_constant_runme.py b/Examples/test-suite/python/cpp11_null_pointer_constant_runme.py new file mode 100644 index 000000000..d304c139d --- /dev/null +++ b/Examples/test-suite/python/cpp11_null_pointer_constant_runme.py @@ -0,0 +1,15 @@ +import cpp11_null_pointer_constant + +a = cpp11_null_pointer_constant.A() + +if a._myA != None: + raise RuntimeError, ("cpp11_null_pointer_constant: _myA should be None, but is ", a._myA) + +b = cpp11_null_pointer_constant.A() +if a._myA != b._myA: + raise RuntimeError, ("cpp11_null_pointer_constant: a._myA should be the same as b._myA, but ", a._myA, "!=", b._myA) + +a._myA = cpp11_null_pointer_constant.A() +if a._myA == None: + raise RuntimeError, ("cpp11_null_pointer_constant: _myA should be object, but is None") + diff --git a/Examples/test-suite/python/cpp0x_raw_string_literals_runme.py b/Examples/test-suite/python/cpp11_raw_string_literals_runme.py similarity index 95% rename from Examples/test-suite/python/cpp0x_raw_string_literals_runme.py rename to Examples/test-suite/python/cpp11_raw_string_literals_runme.py index ea7d16550..32282d8d8 100644 --- a/Examples/test-suite/python/cpp0x_raw_string_literals_runme.py +++ b/Examples/test-suite/python/cpp11_raw_string_literals_runme.py @@ -1,4 +1,4 @@ -from cpp0x_raw_string_literals import * +from cpp11_raw_string_literals import * if cvar.L != 100: raise RuntimeError diff --git a/Examples/test-suite/python/cpp11_result_of_runme.py b/Examples/test-suite/python/cpp11_result_of_runme.py new file mode 100644 index 000000000..a97dd7ccc --- /dev/null +++ b/Examples/test-suite/python/cpp11_result_of_runme.py @@ -0,0 +1,3 @@ +import cpp11_result_of +if cpp11_result_of.test_result(cpp11_result_of.square, 3.0) != 9.0: + raise RuntimeError, "test_result(square, 3.0) is not 9.0." diff --git a/Examples/test-suite/python/cpp0x_rvalue_reference_runme.py b/Examples/test-suite/python/cpp11_rvalue_reference_runme.py similarity index 90% rename from Examples/test-suite/python/cpp0x_rvalue_reference_runme.py rename to Examples/test-suite/python/cpp11_rvalue_reference_runme.py index 43fbc997e..a72a3e63b 100644 --- a/Examples/test-suite/python/cpp0x_rvalue_reference_runme.py +++ b/Examples/test-suite/python/cpp11_rvalue_reference_runme.py @@ -1,6 +1,6 @@ -import cpp0x_rvalue_reference +import cpp11_rvalue_reference -a = cpp0x_rvalue_reference.A() +a = cpp11_rvalue_reference.A() a.setAcopy(5) if a.getAcopy() != 5: diff --git a/Examples/test-suite/python/cpp0x_thread_local_runme.py b/Examples/test-suite/python/cpp11_thread_local_runme.py similarity index 94% rename from Examples/test-suite/python/cpp0x_thread_local_runme.py rename to Examples/test-suite/python/cpp11_thread_local_runme.py index ff27b7785..59a657488 100644 --- a/Examples/test-suite/python/cpp0x_thread_local_runme.py +++ b/Examples/test-suite/python/cpp11_thread_local_runme.py @@ -1,4 +1,4 @@ -from cpp0x_thread_local import * +from cpp11_thread_local import * t = ThreadLocals() if t.stval != 11: diff --git a/Examples/test-suite/python/cpp0x_uniform_initialization_runme.py b/Examples/test-suite/python/cpp11_uniform_initialization_runme.py similarity index 68% rename from Examples/test-suite/python/cpp0x_uniform_initialization_runme.py rename to Examples/test-suite/python/cpp11_uniform_initialization_runme.py index 42228f3d7..85c3b2478 100644 --- a/Examples/test-suite/python/cpp0x_uniform_initialization_runme.py +++ b/Examples/test-suite/python/cpp11_uniform_initialization_runme.py @@ -1,13 +1,13 @@ -import cpp0x_uniform_initialization +import cpp11_uniform_initialization -var1 = cpp0x_uniform_initialization.cvar.var1 +var1 = cpp11_uniform_initialization.cvar.var1 if var1.x != 5: raise RuntimeError -var2 = cpp0x_uniform_initialization.cvar.var2 +var2 = cpp11_uniform_initialization.cvar.var2 if var2.getX() != 2: raise RuntimeError -m = cpp0x_uniform_initialization.MoreInit() +m = cpp11_uniform_initialization.MoreInit() if m.charptr != None: raise RuntimeError, m.charptr m.charptr = "hello sir" diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index dc033ed7b..b6366d76d 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1710,7 +1710,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %token NAME RENAME NAMEWARN EXTEND PRAGMA FEATURE VARARGS %token ENUM %token CLASS TYPENAME PRIVATE PUBLIC PROTECTED COLON STATIC VIRTUAL FRIEND THROW CATCH EXPLICIT AUTO -%token STATIC_ASSERT CONSTEXPR THREAD_LOCAL DECLTYPE /* C++0x keywords */ +%token STATIC_ASSERT CONSTEXPR THREAD_LOCAL DECLTYPE /* C++11 keywords */ %token USING %token NAMESPACE %token NATIVE INLINE @@ -3258,7 +3258,7 @@ c_decl : storage_class type declarator initializer c_decl_tail { set_nextSibling($$,$5); } } - /* Alternate function syntax introduced in C++0x: + /* Alternate function syntax introduced in C++11: auto funcName(int x, int y) -> int; */ | storage_class AUTO declarator ARROW cpp_alternate_rettype initializer c_decl_tail { $$ = new_node("cdecl"); @@ -5330,7 +5330,7 @@ declarator : pointer notso_direct_declarator { } } | LAND notso_direct_declarator { - /* Introduced in C++0x, move operator && */ + /* Introduced in C++11, move operator && */ /* Adds one S/R conflict */ $$ = $2; $$.type = NewStringEmpty(); @@ -5427,7 +5427,7 @@ declarator : pointer notso_direct_declarator { } } | LAND PERIOD PERIOD PERIOD notso_direct_declarator { - /* Introduced in C++0x, move operator && */ + /* Introduced in C++11, move operator && */ /* Adds one S/R conflict */ $$ = $5; $$.type = NewStringEmpty(); @@ -6673,7 +6673,7 @@ mem_initializer : idcolon LPAREN { skip_balanced('(',')'); Clear(scanner_ccode); } - /* Uniform initialization in C++0x. + /* Uniform initialization in C++11. Example: struct MyStruct { MyStruct(int x, double y) : x_{x}, y_{y} {} From de5e0c8655a2409814211415e086868be94031a8 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 8 Oct 2013 20:12:18 +0100 Subject: [PATCH 140/481] C++11 testing moved to a configure option Use './configure --enable-cpp11-testing' to enable the C++11 test. Off by default for now. --- Examples/test-suite/common.mk | 5 +++-- Makefile.in | 3 ++- configure.ac | 29 ++++++++++++++++++++--------- 3 files changed, 25 insertions(+), 12 deletions(-) diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index be6b4736a..caa583471 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -94,10 +94,8 @@ CPP_TEST_BROKEN += \ C_TEST_BROKEN += \ tag_no_clash_with_variable - # C++ test cases. (Can be run individually using: make testcase.cpptest) CPP_TEST_CASES += \ - $(CPP11_TEST_CASES) \ abstract_access \ abstract_inherit \ abstract_inherit_ok \ @@ -541,6 +539,9 @@ ifndef SKIP_CPP_STD_CASES CPP_TEST_CASES += ${CPP_STD_TEST_CASES} endif +ifneq (,$(HAVE_CXX11_COMPILER)) +CPP_TEST_CASES += $(CPP11_TEST_CASES) +endif # C test cases. (Can be run individually using: make testcase.ctest) C_TEST_CASES += \ diff --git a/Makefile.in b/Makefile.in index c6259916b..377086231 100644 --- a/Makefile.in +++ b/Makefile.in @@ -22,6 +22,7 @@ TARGET = $(TARGET_NOEXE)@EXEEXT@ SOURCE = Source CCACHE = CCache DOCS = Doc/Manual +HAVE_CXX11_COMPILER = @HAVE_CXX11_COMPILER@ swig: libfiles source ccache @@ -240,7 +241,7 @@ check-%-test-suite: echo warning: cannot $(ACTION) $* test-suite "(no dir $$dir)";\ else \ echo $(ACTION)ing $* test-suite; \ - (cd $$dir && $(MAKE) -k -s $(ACTION)) \ + (cd $$dir && $(MAKE) -k -s $(ACTION) HAVE_CXX11_COMPILER=$(HAVE_CXX11_COMPILER)) \ || passed=false; \ fi; \ test $$passed = true diff --git a/configure.ac b/configure.ac index 7015fb468..fa985bfd8 100644 --- a/configure.ac +++ b/configure.ac @@ -330,15 +330,26 @@ esac AC_MSG_RESULT($PLATCFLAGS) # Add switch if necessary to enable C++11 support - just for tests -AC_LANG_PUSH([C++]) -CXXFLAGS_SAVED=$CXXFLAGS -AX_CXX_COMPILE_STDCXX_11([noext], [nostop]) -CXXFLAGS=$CXXFLAGS_SAVED -AC_LANG_POP([C++]) -if test x"$CXX11FLAGS" = x; then - PLATCXXFLAGS="$PLATCFLAGS" -else - PLATCXXFLAGS="$CXX11FLAGS $PLATCFLAGS" +AC_ARG_ENABLE([cpp11-testing], AS_HELP_STRING([--enable-cpp11-testing], [enable C++11 testing if supported by compiler (default disabled)]), [enable_cpp11_testing=$enableval], [enable_cpp11_testing=no]) +AC_MSG_CHECKING([whether to enable C++11 testing]) +AC_MSG_RESULT([$enable_cpp11_testing]) + +PLATCXXFLAGS="$PLATCFLAGS" +if test x"$enable_cpp11_testing" = xyes; then + AC_LANG_PUSH([C++]) + CXXFLAGS_SAVED=$CXXFLAGS + AX_CXX_COMPILE_STDCXX_11([noext], [nostop]) + CXXFLAGS=$CXXFLAGS_SAVED + AC_LANG_POP([C++]) + if test x"$CXX11FLAGS" != x; then + PLATCXXFLAGS="$CXX11FLAGS $PLATCXXFLAGS" + fi + AC_MSG_CHECKING([for C++11 enabled compiler]) + if test x"$HAVE_CXX11_COMPILER" = x; then + AC_MSG_RESULT([no]) + else + AC_MSG_RESULT([$HAVE_CXX11_COMPILER]) + fi fi # Set info about shared libraries. From 053856893c113569f227efa78ec00559152a907f Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 10 Oct 2013 07:28:44 +0100 Subject: [PATCH 141/481] Add gsoc2009-matevz for Travis testing --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 26758304f..eca1838d2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -56,3 +56,4 @@ script: branches: only: - master + - gsoc2009-matevz From e5f9f9180707c1c30a9bc025ee3d3f171c1b8d6e Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 11 Oct 2013 19:42:19 +0100 Subject: [PATCH 142/481] Add naturalvar_more testcase runtime test --- .../java/naturalvar_more_runme.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Examples/test-suite/java/naturalvar_more_runme.java diff --git a/Examples/test-suite/java/naturalvar_more_runme.java b/Examples/test-suite/java/naturalvar_more_runme.java new file mode 100644 index 000000000..60e2fadbe --- /dev/null +++ b/Examples/test-suite/java/naturalvar_more_runme.java @@ -0,0 +1,23 @@ + +import naturalvar_more.*; + +public class naturalvar_more_runme { + static { + try { + System.loadLibrary("naturalvar_more"); + } 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[]) + { + S s = new S(); + if (!s.getConst_string_member().equals("initial string value")) + throw new RuntimeException("Test 1 fail"); + s.setString_member("some member value"); + if (!s.getString_member().equals("some member value")) + throw new RuntimeException("Test 2 fail"); + } +} From 7b08378145ad703cb6a8cc128c01975dfdce8af4 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 11 Oct 2013 21:48:45 +0100 Subject: [PATCH 143/481] Minor cleanup prior to merging to master --- .travis.yml | 1 - Examples/Makefile.in | 2 +- Lib/php/director.swg | 3 --- Source/Swig/warn.c | 38 -------------------------------------- 4 files changed, 1 insertion(+), 43 deletions(-) delete mode 100644 Source/Swig/warn.c diff --git a/.travis.yml b/.travis.yml index eca1838d2..26758304f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -56,4 +56,3 @@ script: branches: only: - master - - gsoc2009-matevz diff --git a/Examples/Makefile.in b/Examples/Makefile.in index b6712378b..b986774b6 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -1520,7 +1520,7 @@ endif r_cpp: $(CXXSRCS) $(SWIG) -c++ -r $(SWIGOPT) -o $(RCXXSRCS) $(INTERFACEPATH) ifneq ($(CXXSRCS),) - $(CXX) -g -c $(CFLAGS) $(R_CFLAGS) $(CXXSRCS) $(INCLUDES) + $(CXX) -g -c $(CXXFLAGS) $(R_CFLAGS) $(CXXSRCS) $(INCLUDES) endif +( PKG_CPPFLAGS="$(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(RCXXSRCS) $(OBJS) > /dev/null ) diff --git a/Lib/php/director.swg b/Lib/php/director.swg index a78a2370f..90f6a74a2 100644 --- a/Lib/php/director.swg +++ b/Lib/php/director.swg @@ -1,7 +1,4 @@ /* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * * director.swg * * This file contains support for director classes that proxy diff --git a/Source/Swig/warn.c b/Source/Swig/warn.c deleted file mode 100644 index dfb2e4af4..000000000 --- a/Source/Swig/warn.c +++ /dev/null @@ -1,38 +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. - * - * warn.c - * - * SWIG warning framework. This was added to warn developers about - * deprecated APIs and other features. - * ----------------------------------------------------------------------------- */ - -char cvsroot_warn_c[] = "$Id$"; - -#include "swig.h" - -static Hash *warnings = 0; - -/* ----------------------------------------------------------------------------- - * Swig_warn() - * - * Issue a warning - * ----------------------------------------------------------------------------- */ - -void Swig_warn(const char *filename, int line, const char *msg) { - String *key; - if (!warnings) { - warnings = NewHash(); - } - key = NewStringf("%s:%d", filename, line); - if (!Getattr(warnings, key)) { - Printf(stderr, "swig-dev warning:%s:%d:%s\n", filename, line, msg); - Setattr(warnings, key, key); - } - Delete(key); -} From 049d50fe919f21aaf324e8590b7b1ea671aedcb0 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 12 Oct 2013 00:16:05 +0100 Subject: [PATCH 144/481] Add C++11 to changes file --- CHANGES.current | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGES.current b/CHANGES.current index edd39af31..1b58c6592 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,11 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2013-10-12: wsfulton + Merge in C++11 support from the gsoc2009-matevz branch where Matevz Jekovec first + started the C++0x additions. Documentation of the C++11 features supported is in a + new Chapter of the documentation, "SWIG and C++11" in Doc/Manual/CPlusPlus11.html. + 2013-10-04: wsfulton Fix %naturalvar not having any affect on templated classes instantiated with an enum as the template parameter type. Problem reported by Vadim Zeitlin. From aad30cf4dea3a0fdb37985dc06b4ac38dacb3a88 Mon Sep 17 00:00:00 2001 From: Nikhil Shetty Date: Thu, 10 Oct 2013 19:33:57 -0600 Subject: [PATCH 145/481] BUGFIX: superclass name not lispy The superclass names were not lispified correctly and so the class was inheriting from erroneous class symbols. Closes #96. --- Source/Modules/cffi.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/Modules/cffi.cxx b/Source/Modules/cffi.cxx index 0b1153d61..6b331ad19 100644 --- a/Source/Modules/cffi.cxx +++ b/Source/Modules/cffi.cxx @@ -676,7 +676,7 @@ void CFFI::emit_class(Node *n) { if (!first) Printf(supers, " "); String *s = Getattr(i.item, "name"); - Printf(supers, "%s", lispify_name(i.item, s, "'classname")); + Printf(supers, "%s", lispify_name(i.item, lispy_name(Char(s)), "'classname")); } } else { // Printf(supers,"ff:foreign-pointer"); From 3b08385dec715010da541f59a6bd68dedb07be82 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 12 Oct 2013 14:31:45 +0100 Subject: [PATCH 146/481] changes note for superclass not lispify --- CHANGES.current | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGES.current b/CHANGES.current index 1b58c6592..3f5c112f3 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,9 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2013-10-13: wsfulton + [CFFI] Apply #96 - superclass not lispify + 2013-10-12: wsfulton Merge in C++11 support from the gsoc2009-matevz branch where Matevz Jekovec first started the C++0x additions. Documentation of the C++11 features supported is in a From 1a7f731d60bef65898d7b5c35d0e676e7e19ca81 Mon Sep 17 00:00:00 2001 From: Atri Date: Tue, 1 Oct 2013 01:28:26 +0530 Subject: [PATCH 147/481] Lua: Fix void return for non-void functions Commit #c3f3880d caused the functions SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State* L, swig_lua_namespace* ns) and SWIGINTERN int SWIG_Lua_namespace_register(lua_State* L, swig_lua_namespace* ns) to return void when int returns were expected resulting in the build failures for plplot's lua bindings for example. This commit fixes the issue. Closes #92 --- Lib/lua/luarun.swg | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index 4d851bdb1..8485ed499 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -524,7 +524,7 @@ SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State* L, swig_lua_namespace* /* clear stack - remove metatble */ lua_pop(L,1); - + return 0; } /* helper function. creates namespace table and add it to module table */ @@ -555,6 +555,7 @@ SWIGINTERN int SWIG_Lua_namespace_register(lua_State* L, swig_lua_namespace* ns) lua_setmetatable(L,-2); /* set metatable */ lua_rawset(L,-3); /* add namespace to module table */ + return 0; } /* ----------------------------------------------------------------------------- * global variable support code: classes From 669a27bb7b9d2da9c1758a5126d1db1f56299f08 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 12 Oct 2013 17:50:29 +0100 Subject: [PATCH 148/481] Add change note for missing Lua return statements --- CHANGES.current | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGES.current b/CHANGES.current index 3f5c112f3..350571e7b 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,7 +5,11 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ -2013-10-13: wsfulton +2013-10-12: wsfulton + [Lua] Apply #92 - missing return statements for SWIG_Lua_add_namespace_details() + and SWIG_Lua_namespace_register(). + +2013-10-12: wsfulton [CFFI] Apply #96 - superclass not lispify 2013-10-12: wsfulton From 72afb74f470841d9af504a8f85617c6a70aa837d Mon Sep 17 00:00:00 2001 From: Vadim Zeitlin Date: Fri, 30 Aug 2013 17:01:01 +0200 Subject: [PATCH 149/481] Add support for case conversion characters in regex substitutions. Allow using Perl-like \l, \L, \u, \U and \E escape sequences in the substitution string used with %rename("%(regex:/pattern/subst/)s"). This is useful for e.g. title casing all string after removing some prefix. Closes #82 --- CHANGES.current | 4 ++ Doc/Manual/SWIG.html | 21 +++++-- .../csharp/rename_pcre_encoder_runme.cs | 9 ++- .../java/rename_pcre_encoder_runme.java | 8 ++- .../python/rename_pcre_encoder_runme.py | 11 ++-- Examples/test-suite/rename_pcre_encoder.i | 13 +++- Source/Swig/misc.c | 63 ++++++++++++++++++- 7 files changed, 108 insertions(+), 21 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index 350571e7b..db0a9899f 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,10 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2013-10-15: vadz + Allow using \l, \L, \u, \U and \E in the substitution part of %(regex:/pattern/subst/) + inside %rename to change the case of the text being replaced. + 2013-10-12: wsfulton [Lua] Apply #92 - missing return statements for SWIG_Lua_add_namespace_details() and SWIG_Lua_namespace_register(). diff --git a/Doc/Manual/SWIG.html b/Doc/Manual/SWIG.html index f9ea5b2ef..c0cde0172 100644 --- a/Doc/Manual/SWIG.html +++ b/Doc/Manual/SWIG.html @@ -1888,11 +1888,22 @@ and a more descriptive one, but the two functions are otherwise equivalent: pattern part is a regular expression in Perl syntax (as supported by the Perl Compatible Regular Expressions (PCRE)) library and the subst string - can contain back-references introduced by '\' or, as backslashes need - to be escaped in C strings, rather by "\\". For example, to remove - any alphabetic prefix before an underscore you could use the following directive: - %rename("regex:/(\\w+)_(.*)/\\2/") - Prefix_PrintPrint + 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 + contents of the corresponding capture group while the escape sequences perform the + case conversion in the substitution string: \l and \L convert to + the lower case, while \u and \U convert to the upper case. The + difference between the elements of each pair is that \l and \u + change the case of the next character only, while \L and \U do + it for all the remaining characters or until \E is encountered. + + Finally please notice that backslashes need to be escaped in C strings, so in + practice "\\" must be used in all these escape sequences. For example, + to remove any alphabetic prefix before an underscore and capitalize the remaining + part you could use the following directive: + %rename("regex:/(\\w+)_(.*)/\\u\\2/") + prefix_printPrint command:cmd diff --git a/Examples/test-suite/csharp/rename_pcre_encoder_runme.cs b/Examples/test-suite/csharp/rename_pcre_encoder_runme.cs index f6289e7e2..c06fb1387 100644 --- a/Examples/test-suite/csharp/rename_pcre_encoder_runme.cs +++ b/Examples/test-suite/csharp/rename_pcre_encoder_runme.cs @@ -4,9 +4,12 @@ using rename_pcre_encoderNamespace; public class runme { static void Main() { SomeWidget w = new SomeWidget(); - w.putBorderWidth(17); - if ( w.getBorderWidth() != 17 ) + w.put_borderWidth(17); + if ( w.get_borderWidth() != 17 ) throw new Exception(String.Format("Border with should be 17, not {0}", - w.getBorderWidth())); + w.get_borderWidth())); + + if ( rename_pcre_encoder.StartINSAneAndUNSAvoryTraNSAtlanticRaNSAck() != 42 ) + throw new Exception("Unexpected result of renamed function call"); } } diff --git a/Examples/test-suite/java/rename_pcre_encoder_runme.java b/Examples/test-suite/java/rename_pcre_encoder_runme.java index cb843338b..20882e21a 100644 --- a/Examples/test-suite/java/rename_pcre_encoder_runme.java +++ b/Examples/test-suite/java/rename_pcre_encoder_runme.java @@ -6,9 +6,11 @@ public class rename_pcre_encoder_runme { public static void main(String argv[]) { SomeWidget w = new SomeWidget(); - w.putBorderWidth(17); - if ( w.getBorderWidth() != 17 ) + w.put_borderWidth(17); + if ( w.get_borderWidth() != 17 ) throw new RuntimeException(String.format("Border with should be 17, not %d", - w.getBorderWidth())); + w.get_borderWidth())); + if ( rename_pcre_encoder.StartINSAneAndUNSAvoryTraNSAtlanticRaNSAck() != 42 ) + throw new RuntimeException("Unexpected result of renamed function call"); } } diff --git a/Examples/test-suite/python/rename_pcre_encoder_runme.py b/Examples/test-suite/python/rename_pcre_encoder_runme.py index 1186703a0..419acd1a1 100644 --- a/Examples/test-suite/python/rename_pcre_encoder_runme.py +++ b/Examples/test-suite/python/rename_pcre_encoder_runme.py @@ -1,13 +1,16 @@ from rename_pcre_encoder import * s = SomeWidget() -s.putBorderWidth(3) -if s.getBorderWidth() != 3: - raise RuntimeError("Border should be 3, not %d" % (s.getBorderWidth(),)) +s.put_borderWidth(3) +if s.get_borderWidth() != 3: + raise RuntimeError("Border should be 3, not %d" % (s.get_borderWidth(),)) -s.putSize(4, 5) +s.put_size(4, 5) a = AnotherWidget() a.DoSomething() evt = wxEVTSomeEvent() t = xUnchangedName() + +if StartINSAneAndUNSAvoryTraNSAtlanticRaNSAck() != 42: + raise RuntimeError("Unexpected result of renamed function call") diff --git a/Examples/test-suite/rename_pcre_encoder.i b/Examples/test-suite/rename_pcre_encoder.i index 66f30c7bc..b29b2a056 100644 --- a/Examples/test-suite/rename_pcre_encoder.i +++ b/Examples/test-suite/rename_pcre_encoder.i @@ -3,9 +3,14 @@ // strip the wx prefix from all identifiers except those starting with wxEVT %rename("%(regex:/wx(?!EVT)(.*)/\\1/)s") ""; -// Replace "Set" and "Get" prefixes with "put" and "get" respectively. -%rename("%(regex:/^Set(.*)/put\\1/)s", %$isfunction) ""; -%rename("%(regex:/^Get(.*)/get\\1/)s", %$isfunction) ""; +// Change "{Set,Get}Foo" naming convention to "{put,get}_foo" one. +%rename("%(regex:/^Set(.*)/put_\\l\\1/)s", %$isfunction) ""; +%rename("%(regex:/^Get(.*)/get_\\l\\1/)s", %$isfunction) ""; + +// Make some words stand out (unfortunately we don't have "global" flag): we +// use \U to capitalize the second capture group and then \E to preserve the +// case of the rest. +%rename("%(regex:/(.*?)(nsa)(.*?)\\2(.*?)\\2(.*?)\\2(.*)/\\1\\U\\2\\E\\3\\U\\2\\E\\4\\U\\2\\E\\5\\U\\2\\E\\6/)s") ""; %inline %{ @@ -28,4 +33,6 @@ class wxEVTSomeEvent { class xUnchangedName { }; +inline int StartInsaneAndUnsavoryTransatlanticRansack() { return 42; } + %} diff --git a/Source/Swig/misc.c b/Source/Swig/misc.c index 596f6b424..769882bf8 100644 --- a/Source/Swig/misc.c +++ b/Source/Swig/misc.c @@ -1180,8 +1180,38 @@ err_out: exit(1); } +/* This function copies len characters from src to dst, possibly applying case conversions to them: if convertCase is 1, to upper case and if it is -1, to lower + * case. If convertNextOnly is 1, only a single character is converted (and convertCase is reset), otherwise all of them are. */ +static void copy_with_maybe_case_conversion(String *dst, const char *src, int len, int *convertCase, int convertNextOnly) +{ + /* Deal with the trivial cases first. */ + if (!len) + return; + + if (!*convertCase) { + Write(dst, src, len); + return; + } + + /* If we must convert only the first character, do it and write the rest at once. */ + if (convertNextOnly) { + Putc(*convertCase == 1 ? toupper(*src) : tolower(*src), dst); + *convertCase = 0; + if (len > 1) { + Write(dst, src + 1, len - 1); + } + } else { + /* We need to convert all characters. */ + int i; + for (i = 0; i < len; i++, src++) { + Putc(*convertCase == 1 ? toupper(*src) : tolower(*src), dst); + } + } +} + String *replace_captures(int num_captures, const char *input, String *subst, int captures[], String *pattern, String *s) { + int convertCase = 0, convertNextOnly = 0; String *result = NewStringEmpty(); const char *p = Char(subst); @@ -1189,10 +1219,10 @@ String *replace_captures(int num_captures, const char *input, String *subst, int /* Copy part without substitutions */ const char *q = strchr(p, '\\'); if (!q) { - Write(result, p, strlen(p)); + copy_with_maybe_case_conversion(result, p, strlen(p), &convertCase, convertNextOnly); break; } - Write(result, p, q - p); + copy_with_maybe_case_conversion(result, p, q - p, &convertCase, convertNextOnly); p = q + 1; /* Handle substitution */ @@ -1203,12 +1233,39 @@ String *replace_captures(int num_captures, const char *input, String *subst, int if (group < num_captures) { int l = captures[group*2], r = captures[group*2 + 1]; if (l != -1) { - Write(result, input + l, r - l); + copy_with_maybe_case_conversion(result, input + l, r - l, &convertCase, convertNextOnly); } } else { Swig_error("SWIG", Getline(s), "PCRE capture replacement failed while matching \"%s\" using \"%s\" - request for group %d is greater than the number of captures %d.\n", Char(pattern), input, group, num_captures-1); } + } else { + /* Handle Perl-like case conversion escapes. */ + switch (*p) { + case 'u': + convertCase = 1; + convertNextOnly = 1; + break; + case 'U': + convertCase = 1; + convertNextOnly = 0; + break; + case 'l': + convertCase = -1; + convertNextOnly = 1; + break; + case 'L': + convertCase = -1; + convertNextOnly = 0; + break; + case 'E': + convertCase = 0; + break; + default: + Swig_error("SWIG", Getline(s), "Unrecognized escape character '%c' in the replacement string \"%s\".\n", + *p, Char(subst)); + } + p++; } } From 0f1e73fd26238b1cb1515f8518393e8a4e0bd57d Mon Sep 17 00:00:00 2001 From: "Brant K. Kyser" Date: Tue, 15 Oct 2013 13:55:35 -0500 Subject: [PATCH 150/481] Add test case to demonstrate the name collision that occurs in the generated C# code when a namespace is named System. --- Examples/test-suite/csharp/Makefile.in | 1 + .../csharp_namespace_system_collision.i | 39 +++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 Examples/test-suite/csharp_namespace_system_collision.i diff --git a/Examples/test-suite/csharp/Makefile.in b/Examples/test-suite/csharp/Makefile.in index 4fd8052c6..91b8144de 100644 --- a/Examples/test-suite/csharp/Makefile.in +++ b/Examples/test-suite/csharp/Makefile.in @@ -17,6 +17,7 @@ CPP_TEST_CASES = \ csharp_exceptions \ csharp_features \ csharp_lib_arrays \ + csharp_namespace_system_collision \ csharp_prepost \ csharp_typemaps \ enum_thorough_simple \ diff --git a/Examples/test-suite/csharp_namespace_system_collision.i b/Examples/test-suite/csharp_namespace_system_collision.i new file mode 100644 index 000000000..6f94f8471 --- /dev/null +++ b/Examples/test-suite/csharp_namespace_system_collision.i @@ -0,0 +1,39 @@ +%module namespace_system_collision + +%{ +#include + +namespace TopLevel +{ + namespace System + { + class Foo { + public: + virtual ~Foo() {} + virtual std::string ping() { return "TopLevel::System::Foo::ping()"; } + }; + } +} + +%} + +%include + +// nspace feature only supported by these languages +#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGD) +%nspace; +#else +#warning nspace feature not yet supported in this target language +#endif + +namespace TopLevel +{ + namespace System + { + class Foo { + public: + virtual ~Foo(); + virtual std::string ping(); + }; + } +} From 9c7d0143896cee19ef704dd194ba8226cf2dc0ca Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 17 Oct 2013 18:36:59 +0100 Subject: [PATCH 151/481] T_STRING is now const char * instead of char * Fixes Guile constant wrappers removing -Wwrite-strings g++ warning. --- Source/Modules/guile.cxx | 2 +- Source/Swig/stype.c | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Source/Modules/guile.cxx b/Source/Modules/guile.cxx index e0a084583..2c48ba319 100644 --- a/Source/Modules/guile.cxx +++ b/Source/Modules/guile.cxx @@ -1350,7 +1350,7 @@ public: Printv(f_header, tm, "\n", NIL); } else { // Create variable and assign it a value - Printf(f_header, "static %s = %s;\n", SwigType_lstr(nctype, var_name), rvalue); + Printf(f_header, "static %s = %s;\n", SwigType_str(type, var_name), rvalue); } { /* Hack alert: will cleanup later -- Dave */ diff --git a/Source/Swig/stype.c b/Source/Swig/stype.c index 4b72bdaa2..506878799 100644 --- a/Source/Swig/stype.c +++ b/Source/Swig/stype.c @@ -131,6 +131,7 @@ SwigType *NewSwigType(int t) { break; case T_STRING: { SwigType *t = NewString("char"); + SwigType_add_qualifier(t, "const"); SwigType_add_pointer(t); return t; break; From 3235570619cf3c35a5fba24e32c09fedda5600ea Mon Sep 17 00:00:00 2001 From: "Brant K. Kyser" Date: Thu, 17 Oct 2013 13:27:48 -0500 Subject: [PATCH 152/481] Globablly qualify the use of types from the .NET framework's System namespace in the C# module and library. --- Lib/csharp/csharp.swg | 18 +++++++-------- Lib/csharp/csharphead.swg | 28 +++++++++++----------- Lib/csharp/enumtypesafe.swg | 2 +- Lib/csharp/std_map.i | 46 ++++++++++++++++++------------------- Lib/csharp/std_vector.i | 20 ++++++++-------- Lib/csharp/wchar.i | 4 ++-- Source/Modules/csharp.cxx | 2 +- 7 files changed, 60 insertions(+), 60 deletions(-) diff --git a/Lib/csharp/csharp.swg b/Lib/csharp/csharp.swg index bd9d8e8b2..731ed83e4 100644 --- a/Lib/csharp/csharp.swg +++ b/Lib/csharp/csharp.swg @@ -848,7 +848,7 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { %typemap(csbase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" %typemap(csclassmodifiers) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "public class" %typemap(cscode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" -%typemap(csimports) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "\nusing System;\nusing System.Runtime.InteropServices;\n" +%typemap(csimports) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "\nusing global::System;\nusing global::System.Runtime.InteropServices;\n" %typemap(csinterfaces) SWIGTYPE "IDisposable" %typemap(csinterfaces) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" %typemap(csinterfaces_derived) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" @@ -982,13 +982,13 @@ SWIG_CSBODY_TYPEWRAPPER(internal, protected, internal, SWIGTYPE) %pragma(csharp) moduleclassmodifiers="public class" %pragma(csharp) moduleimports=%{ -using System; -using System.Runtime.InteropServices; +using global::System; +using global::System.Runtime.InteropServices; %} %pragma(csharp) imclassimports=%{ -using System; -using System.Runtime.InteropServices; +using global::System; +using global::System.Runtime.InteropServices; %} /* Some ANSI C typemaps */ @@ -1018,10 +1018,10 @@ using System.Runtime.InteropServices; public class SWIGStringMarshal : IDisposable { public readonly HandleRef swigCPtr; public SWIGStringMarshal(string str) { - swigCPtr = new HandleRef(this, System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(str)); + swigCPtr = new HandleRef(this, global::System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(str)); } public virtual void Dispose() { - System.Runtime.InteropServices.Marshal.FreeHGlobal(swigCPtr.Handle); + global::System.Runtime.InteropServices.Marshal.FreeHGlobal(swigCPtr.Handle); GC.SuppressFinalize(this); } } @@ -1031,7 +1031,7 @@ using System.Runtime.InteropServices; %typemap(out) char *, char[ANY], char[] %{ $result = $1; %} %typemap(csin) char *, char[ANY], char[] "new $imclassname.SWIGStringMarshal($csinput).swigCPtr" %typemap(csout, excode=SWIGEXCODE) char *, char[ANY], char[] { - string ret = System.Runtime.InteropServices.Marshal.PtrToStringAnsi($imcall);$excode + string ret = global::System.Runtime.InteropServices.Marshal.PtrToStringAnsi($imcall);$excode return ret; } %typemap(csvarin, excode=SWIGEXCODE2) char *, char[ANY], char[] %{ @@ -1040,7 +1040,7 @@ using System.Runtime.InteropServices; } %} %typemap(csvarout, excode=SWIGEXCODE2) char *, char[ANY], char[] %{ get { - string ret = System.Runtime.InteropServices.Marshal.PtrToStringAnsi($imcall);$excode + string ret = global::System.Runtime.InteropServices.Marshal.PtrToStringAnsi($imcall);$excode return ret; } %} */ diff --git a/Lib/csharp/csharphead.swg b/Lib/csharp/csharphead.swg index a1c56a4b3..be1281a71 100644 --- a/Lib/csharp/csharphead.swg +++ b/Lib/csharp/csharphead.swg @@ -170,51 +170,51 @@ SWIGEXPORT void SWIGSTDCALL SWIGRegisterExceptionArgumentCallbacks_$module( ExceptionArgumentDelegate argumentOutOfRangeDelegate); static void SetPendingApplicationException(string message) { - SWIGPendingException.Set(new System.ApplicationException(message, SWIGPendingException.Retrieve())); + SWIGPendingException.Set(new global::System.ApplicationException(message, SWIGPendingException.Retrieve())); } static void SetPendingArithmeticException(string message) { - SWIGPendingException.Set(new System.ArithmeticException(message, SWIGPendingException.Retrieve())); + SWIGPendingException.Set(new global::System.ArithmeticException(message, SWIGPendingException.Retrieve())); } static void SetPendingDivideByZeroException(string message) { - SWIGPendingException.Set(new System.DivideByZeroException(message, SWIGPendingException.Retrieve())); + SWIGPendingException.Set(new global::System.DivideByZeroException(message, SWIGPendingException.Retrieve())); } static void SetPendingIndexOutOfRangeException(string message) { - SWIGPendingException.Set(new System.IndexOutOfRangeException(message, SWIGPendingException.Retrieve())); + SWIGPendingException.Set(new global::System.IndexOutOfRangeException(message, SWIGPendingException.Retrieve())); } static void SetPendingInvalidCastException(string message) { - SWIGPendingException.Set(new System.InvalidCastException(message, SWIGPendingException.Retrieve())); + SWIGPendingException.Set(new global::System.InvalidCastException(message, SWIGPendingException.Retrieve())); } static void SetPendingInvalidOperationException(string message) { - SWIGPendingException.Set(new System.InvalidOperationException(message, SWIGPendingException.Retrieve())); + SWIGPendingException.Set(new global::System.InvalidOperationException(message, SWIGPendingException.Retrieve())); } static void SetPendingIOException(string message) { - SWIGPendingException.Set(new System.IO.IOException(message, SWIGPendingException.Retrieve())); + SWIGPendingException.Set(new global::System.IO.IOException(message, SWIGPendingException.Retrieve())); } static void SetPendingNullReferenceException(string message) { - SWIGPendingException.Set(new System.NullReferenceException(message, SWIGPendingException.Retrieve())); + SWIGPendingException.Set(new global::System.NullReferenceException(message, SWIGPendingException.Retrieve())); } static void SetPendingOutOfMemoryException(string message) { - SWIGPendingException.Set(new System.OutOfMemoryException(message, SWIGPendingException.Retrieve())); + SWIGPendingException.Set(new global::System.OutOfMemoryException(message, SWIGPendingException.Retrieve())); } static void SetPendingOverflowException(string message) { - SWIGPendingException.Set(new System.OverflowException(message, SWIGPendingException.Retrieve())); + SWIGPendingException.Set(new global::System.OverflowException(message, SWIGPendingException.Retrieve())); } static void SetPendingSystemException(string message) { - SWIGPendingException.Set(new System.SystemException(message, SWIGPendingException.Retrieve())); + SWIGPendingException.Set(new global::System.SystemException(message, SWIGPendingException.Retrieve())); } static void SetPendingArgumentException(string message, string paramName) { - SWIGPendingException.Set(new System.ArgumentException(message, paramName, SWIGPendingException.Retrieve())); + SWIGPendingException.Set(new global::System.ArgumentException(message, paramName, SWIGPendingException.Retrieve())); } static void SetPendingArgumentNullException(string message, string paramName) { Exception e = SWIGPendingException.Retrieve(); if (e != null) message = message + " Inner Exception: " + e.Message; - SWIGPendingException.Set(new System.ArgumentNullException(paramName, message)); + SWIGPendingException.Set(new global::System.ArgumentNullException(paramName, message)); } static void SetPendingArgumentOutOfRangeException(string message, string paramName) { Exception e = SWIGPendingException.Retrieve(); if (e != null) message = message + " Inner Exception: " + e.Message; - SWIGPendingException.Set(new System.ArgumentOutOfRangeException(paramName, message)); + SWIGPendingException.Set(new global::System.ArgumentOutOfRangeException(paramName, message)); } static SWIGExceptionHelper() { diff --git a/Lib/csharp/enumtypesafe.swg b/Lib/csharp/enumtypesafe.swg index 772a88013..b7079343c 100644 --- a/Lib/csharp/enumtypesafe.swg +++ b/Lib/csharp/enumtypesafe.swg @@ -97,7 +97,7 @@ for (int i = 0; i < swigValues.Length; i++) if (swigValues[i].swigValue == swigValue) return swigValues[i]; - throw new System.ArgumentOutOfRangeException("No enum $csclassname with value " + swigValue); + throw new global::System.ArgumentOutOfRangeException("No enum $csclassname with value " + swigValue); } public override string ToString() { diff --git a/Lib/csharp/std_map.i b/Lib/csharp/std_map.i index acd190689..61b527a28 100644 --- a/Lib/csharp/std_map.i +++ b/Lib/csharp/std_map.i @@ -28,7 +28,7 @@ /* K is the C++ key type, T is the C++ value type */ %define SWIG_STD_MAP_INTERNAL(K, T, C) -%typemap(csinterfaces) std::map< K, T, C > "IDisposable \n#if !SWIG_DOTNET_1\n , System.Collections.Generic.IDictionary<$typemap(cstype, K), $typemap(cstype, T)>\n#endif\n"; +%typemap(csinterfaces) std::map< K, T, C > "IDisposable \n#if !SWIG_DOTNET_1\n , global::System.Collections.Generic.IDictionary<$typemap(cstype, K), $typemap(cstype, T)>\n#endif\n"; %typemap(cscode) std::map %{ public $typemap(cstype, T) this[$typemap(cstype, K) key] { @@ -64,9 +64,9 @@ #if !SWIG_DOTNET_1 - public System.Collections.Generic.ICollection<$typemap(cstype, K)> Keys { + public global::System.Collections.Generic.ICollection<$typemap(cstype, K)> Keys { get { - System.Collections.Generic.ICollection<$typemap(cstype, K)> keys = new System.Collections.Generic.List<$typemap(cstype, K)>(); + global::System.Collections.Generic.ICollection<$typemap(cstype, K)> keys = new global::System.Collections.Generic.List<$typemap(cstype, K)>(); int size = this.Count; if (size > 0) { IntPtr iter = create_iterator_begin(); @@ -79,21 +79,21 @@ } } - public System.Collections.Generic.ICollection<$typemap(cstype, T)> Values { + public global::System.Collections.Generic.ICollection<$typemap(cstype, T)> Values { get { - System.Collections.Generic.ICollection<$typemap(cstype, T)> vals = new System.Collections.Generic.List<$typemap(cstype, T)>(); - foreach (System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)> pair in this) { + global::System.Collections.Generic.ICollection<$typemap(cstype, T)> vals = new global::System.Collections.Generic.List<$typemap(cstype, T)>(); + foreach (global::System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)> pair in this) { vals.Add(pair.Value); } return vals; } } - public void Add(System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)> item) { + public void Add(global::System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)> item) { Add(item.Key, item.Value); } - public bool Remove(System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)> item) { + public bool Remove(global::System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)> item) { if (Contains(item)) { return Remove(item.Key); } else { @@ -101,7 +101,7 @@ } } - public bool Contains(System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)> item) { + public bool Contains(global::System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)> item) { if (this[item.Key] == item.Value) { return true; } else { @@ -109,11 +109,11 @@ } } - public void CopyTo(System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)>[] array) { + public void CopyTo(global::System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)>[] array) { CopyTo(array, 0); } - public void CopyTo(System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)>[] array, int arrayIndex) { + public void CopyTo(global::System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)>[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException("array"); if (arrayIndex < 0) @@ -123,18 +123,18 @@ if (arrayIndex+this.Count > array.Length) throw new ArgumentException("Number of elements to copy is too large."); - System.Collections.Generic.IList<$typemap(cstype, K)> keyList = new System.Collections.Generic.List<$typemap(cstype, K)>(this.Keys); + global::System.Collections.Generic.IList<$typemap(cstype, K)> keyList = new global::System.Collections.Generic.List<$typemap(cstype, K)>(this.Keys); for (int i = 0; i < keyList.Count; i++) { $typemap(cstype, K) currentKey = keyList[i]; - array.SetValue(new System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)>(currentKey, this[currentKey]), arrayIndex+i); + array.SetValue(new global::System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)>(currentKey, this[currentKey]), arrayIndex+i); } } - System.Collections.Generic.IEnumerator> System.Collections.Generic.IEnumerable>.GetEnumerator() { + global::System.Collections.Generic.IEnumerator> global::System.Collections.Generic.IEnumerable>.GetEnumerator() { return new $csclassnameEnumerator(this); } - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() { return new $csclassnameEnumerator(this); } @@ -147,25 +147,25 @@ /// whenever the collection is modified. This has been done for changes in the size of the /// collection but not when one of the elements of the collection is modified as it is a bit /// tricky to detect unmanaged code that modifies the collection under our feet. - public sealed class $csclassnameEnumerator : System.Collections.IEnumerator, - System.Collections.Generic.IEnumerator> + public sealed class $csclassnameEnumerator : global::System.Collections.IEnumerator, + global::System.Collections.Generic.IEnumerator> { private $csclassname collectionRef; - private System.Collections.Generic.IList<$typemap(cstype, K)> keyCollection; + private global::System.Collections.Generic.IList<$typemap(cstype, K)> keyCollection; private int currentIndex; private object currentObject; private int currentSize; public $csclassnameEnumerator($csclassname collection) { collectionRef = collection; - keyCollection = new System.Collections.Generic.List<$typemap(cstype, K)>(collection.Keys); + keyCollection = new global::System.Collections.Generic.List<$typemap(cstype, K)>(collection.Keys); currentIndex = -1; currentObject = null; currentSize = collectionRef.Count; } // Type-safe iterator Current - public System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)> Current { + public global::System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)> Current { get { if (currentIndex == -1) throw new InvalidOperationException("Enumeration not started."); @@ -173,12 +173,12 @@ throw new InvalidOperationException("Enumeration finished."); if (currentObject == null) throw new InvalidOperationException("Collection modified."); - return (System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)>)currentObject; + return (global::System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)>)currentObject; } } // Type-unsafe IEnumerator.Current - object System.Collections.IEnumerator.Current { + object global::System.Collections.IEnumerator.Current { get { return Current; } @@ -190,7 +190,7 @@ if (moveOkay) { currentIndex++; $typemap(cstype, K) currentKey = keyCollection[currentIndex]; - currentObject = new System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)>(currentKey, collectionRef[currentKey]); + currentObject = new global::System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)>(currentKey, collectionRef[currentKey]); } else { currentObject = null; } diff --git a/Lib/csharp/std_vector.i b/Lib/csharp/std_vector.i index 5a21ad399..50ba38739 100644 --- a/Lib/csharp/std_vector.i +++ b/Lib/csharp/std_vector.i @@ -26,9 +26,9 @@ // MACRO for use within the std::vector class body %define SWIG_STD_VECTOR_MINIMUM_INTERNAL(CSINTERFACE, CONST_REFERENCE, CTYPE...) -%typemap(csinterfaces) std::vector< CTYPE > "IDisposable, System.Collections.IEnumerable\n#if !SWIG_DOTNET_1\n , System.Collections.Generic.CSINTERFACE<$typemap(cstype, CTYPE)>\n#endif\n"; +%typemap(csinterfaces) std::vector< CTYPE > "IDisposable, global::System.Collections.IEnumerable\n#if !SWIG_DOTNET_1\n , global::System.Collections.Generic.CSINTERFACE<$typemap(cstype, CTYPE)>\n#endif\n"; %typemap(cscode) std::vector< CTYPE > %{ - public $csclassname(System.Collections.ICollection c) : this() { + public $csclassname(global::System.Collections.ICollection c) : this() { if (c == null) throw new ArgumentNullException("c"); foreach ($typemap(cstype, CTYPE) element in c) { @@ -81,7 +81,7 @@ } #if SWIG_DOTNET_1 - public void CopyTo(System.Array array) + public void CopyTo(global::System.Array array) #else public void CopyTo($typemap(cstype, CTYPE)[] array) #endif @@ -90,7 +90,7 @@ } #if SWIG_DOTNET_1 - public void CopyTo(System.Array array, int arrayIndex) + public void CopyTo(global::System.Array array, int arrayIndex) #else public void CopyTo($typemap(cstype, CTYPE)[] array, int arrayIndex) #endif @@ -99,7 +99,7 @@ } #if SWIG_DOTNET_1 - public void CopyTo(int index, System.Array array, int arrayIndex, int count) + public void CopyTo(int index, global::System.Array array, int arrayIndex, int count) #else public void CopyTo(int index, $typemap(cstype, CTYPE)[] array, int arrayIndex, int count) #endif @@ -121,12 +121,12 @@ } #if !SWIG_DOTNET_1 - System.Collections.Generic.IEnumerator<$typemap(cstype, CTYPE)> System.Collections.Generic.IEnumerable<$typemap(cstype, CTYPE)>.GetEnumerator() { + global::System.Collections.Generic.IEnumerator<$typemap(cstype, CTYPE)> global::System.Collections.Generic.IEnumerable<$typemap(cstype, CTYPE)>.GetEnumerator() { return new $csclassnameEnumerator(this); } #endif - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() { return new $csclassnameEnumerator(this); } @@ -139,9 +139,9 @@ /// whenever the collection is modified. This has been done for changes in the size of the /// collection but not when one of the elements of the collection is modified as it is a bit /// tricky to detect unmanaged code that modifies the collection under our feet. - public sealed class $csclassnameEnumerator : System.Collections.IEnumerator + public sealed class $csclassnameEnumerator : global::System.Collections.IEnumerator #if !SWIG_DOTNET_1 - , System.Collections.Generic.IEnumerator<$typemap(cstype, CTYPE)> + , global::System.Collections.Generic.IEnumerator<$typemap(cstype, CTYPE)> #endif { private $csclassname collectionRef; @@ -170,7 +170,7 @@ } // Type-unsafe IEnumerator.Current - object System.Collections.IEnumerator.Current { + object global::System.Collections.IEnumerator.Current { get { return Current; } diff --git a/Lib/csharp/wchar.i b/Lib/csharp/wchar.i index 1d95edded..066044014 100644 --- a/Lib/csharp/wchar.i +++ b/Lib/csharp/wchar.i @@ -27,7 +27,7 @@ static SWIG_CSharpWStringHelperCallback SWIG_csharp_wstring_callback = NULL; public static extern void SWIGRegisterWStringCallback_$module(SWIGWStringDelegate wstringDelegate); static string CreateWString([MarshalAs(UnmanagedType.LPWStr)]IntPtr cString) { - return System.Runtime.InteropServices.Marshal.PtrToStringUni(cString); + return global::System.Runtime.InteropServices.Marshal.PtrToStringUni(cString); } static SWIGWStringHelper() { @@ -82,7 +82,7 @@ SWIGEXPORT void SWIGSTDCALL SWIGRegisterWStringCallback_$module(SWIG_CSharpWStri %typemap(csin) wchar_t * "$csinput" %typemap(csout, excode=SWIGEXCODE) wchar_t * { - string ret = System.Runtime.InteropServices.Marshal.PtrToStringUni($imcall);$excode + string ret = global::System.Runtime.InteropServices.Marshal.PtrToStringUni($imcall);$excode return ret; } %typemap(csvarin, excode=SWIGEXCODE2) wchar_t * %{ diff --git a/Source/Modules/csharp.cxx b/Source/Modules/csharp.cxx index d30f278fc..6c314959f 100644 --- a/Source/Modules/csharp.cxx +++ b/Source/Modules/csharp.cxx @@ -1734,7 +1734,7 @@ public: Printf(proxy_class_code, "\n"); Printf(proxy_class_code, " private bool SwigDerivedClassHasMethod(string methodName, Type[] methodTypes) {\n"); Printf(proxy_class_code, - " System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(methodName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, null, methodTypes, null);\n"); + " global::System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(methodName, global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, methodTypes, null);\n"); Printf(proxy_class_code, " bool hasDerivedMethod = methodInfo.DeclaringType.IsSubclassOf(typeof(%s));\n", proxy_class_name); /* Could add this code to cover corner case where the GetMethod() returns a method which allows type * promotion, eg it will return foo(double), if looking for foo(int). From 0e54a51c104ecf1c1a68892132d9506890a99036 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 17 Oct 2013 19:56:18 +0100 Subject: [PATCH 153/481] Add missing #include for offsetof when using -builtin. Fixes SF #1345 --- CHANGES.current | 3 +++ Lib/python/pyinit.swg | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/CHANGES.current b/CHANGES.current index db0a9899f..9621a4952 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,9 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2013-10-17: wsfulton + [Python] Fix SF #1345 - Missing #include for offsetof when using -builtin. + 2013-10-15: vadz Allow using \l, \L, \u, \U and \E in the substitution part of %(regex:/pattern/subst/) inside %rename to change the case of the text being replaced. diff --git a/Lib/python/pyinit.swg b/Lib/python/pyinit.swg index 6a6de0963..79df023de 100644 --- a/Lib/python/pyinit.swg +++ b/Lib/python/pyinit.swg @@ -4,6 +4,10 @@ %insert(init) "swiginit.swg" +#if defined(SWIGPYTHON_BUILTIN) +%fragment(""); // For offsetof +#endif + %init %{ #ifdef __cplusplus From cb2df12630874dd9b11fac8805e3169691305ee0 Mon Sep 17 00:00:00 2001 From: "Brant K. Kyser" Date: Thu, 17 Oct 2013 13:58:32 -0500 Subject: [PATCH 154/481] Since SWIG 3.0 removes support for .NET 1.1, cleanup the C# library by removing the use of the SWIG_DOTNET_1 macro. --- .../test-suite/csharp/li_std_vector_runme.cs | 13 ----------- Lib/csharp/std_map.i | 9 ++------ Lib/csharp/std_vector.i | 22 +------------------ 3 files changed, 3 insertions(+), 41 deletions(-) diff --git a/Examples/test-suite/csharp/li_std_vector_runme.cs b/Examples/test-suite/csharp/li_std_vector_runme.cs index 617116d5a..fa8700d89 100644 --- a/Examples/test-suite/csharp/li_std_vector_runme.cs +++ b/Examples/test-suite/csharp/li_std_vector_runme.cs @@ -82,17 +82,6 @@ public class li_std_vector_runme { } catch (ArgumentException) { } } -#if SWIG_DOTNET_1 - { - // runtime check that 2D arrays fail - double[,] outputarray = new double[collectionSize,collectionSize]; - try { - vect.CopyTo(outputarray); - throw new Exception("CopyTo (5a) test failed"); - } catch (ArgumentException) { - } - } -#endif { StructVector inputvector = new StructVector(); int arrayLen = 10; @@ -208,7 +197,6 @@ public class li_std_vector_runme { throw new Exception("Repeat (1) test failed"); } } -#if !SWIG_DOTNET_1 { System.Collections.Generic.IEnumerator myEnumerator = dv.GetEnumerator(); while ( myEnumerator.MoveNext() ) { @@ -216,7 +204,6 @@ public class li_std_vector_runme { throw new Exception("Repeat (2) test failed"); } } -#endif } { diff --git a/Lib/csharp/std_map.i b/Lib/csharp/std_map.i index 61b527a28..045bd6e3e 100644 --- a/Lib/csharp/std_map.i +++ b/Lib/csharp/std_map.i @@ -11,9 +11,7 @@ * %template(MapIntDouble) std::map * * Notes: - * 1) For .NET 1 compatibility, define SWIG_DOTNET_1 when compiling the C# code. In this case - * the C# wrapper has only basic functionality. - * 2) IEnumerable<> is implemented in the proxy class which is useful for using LINQ with + * 1) IEnumerable<> is implemented in the proxy class which is useful for using LINQ with * C++ std::map wrappers. * * Warning: heavy macro usage in this file. Use swig -E to get a sane view on the real file contents! @@ -28,7 +26,7 @@ /* K is the C++ key type, T is the C++ value type */ %define SWIG_STD_MAP_INTERNAL(K, T, C) -%typemap(csinterfaces) std::map< K, T, C > "IDisposable \n#if !SWIG_DOTNET_1\n , global::System.Collections.Generic.IDictionary<$typemap(cstype, K), $typemap(cstype, T)>\n#endif\n"; +%typemap(csinterfaces) std::map< K, T, C > "IDisposable \n , global::System.Collections.Generic.IDictionary<$typemap(cstype, K), $typemap(cstype, T)>\n"; %typemap(cscode) std::map %{ public $typemap(cstype, T) this[$typemap(cstype, K) key] { @@ -62,8 +60,6 @@ } } -#if !SWIG_DOTNET_1 - public global::System.Collections.Generic.ICollection<$typemap(cstype, K)> Keys { get { global::System.Collections.Generic.ICollection<$typemap(cstype, K)> keys = new global::System.Collections.Generic.List<$typemap(cstype, K)>(); @@ -210,7 +206,6 @@ currentObject = null; } } -#endif %} diff --git a/Lib/csharp/std_vector.i b/Lib/csharp/std_vector.i index 50ba38739..e29c2bf2a 100644 --- a/Lib/csharp/std_vector.i +++ b/Lib/csharp/std_vector.i @@ -4,8 +4,6 @@ * SWIG typemaps for std::vector * C# implementation * The C# wrapper is made to look and feel like a C# System.Collections.Generic.List<> collection. - * For .NET 1 compatibility, define SWIG_DOTNET_1 when compiling the C# code; then the C# wrapper is - * made to look and feel like a typesafe C# System.Collections.ArrayList. * * Note that IEnumerable<> is implemented in the proxy class which is useful for using LINQ with * C++ std::vector wrappers. The IList<> interface is also implemented to provide enhanced functionality @@ -26,7 +24,7 @@ // MACRO for use within the std::vector class body %define SWIG_STD_VECTOR_MINIMUM_INTERNAL(CSINTERFACE, CONST_REFERENCE, CTYPE...) -%typemap(csinterfaces) std::vector< CTYPE > "IDisposable, global::System.Collections.IEnumerable\n#if !SWIG_DOTNET_1\n , global::System.Collections.Generic.CSINTERFACE<$typemap(cstype, CTYPE)>\n#endif\n"; +%typemap(csinterfaces) std::vector< CTYPE > "IDisposable, global::System.Collections.IEnumerable\n , global::System.Collections.Generic.CSINTERFACE<$typemap(cstype, CTYPE)>\n"; %typemap(cscode) std::vector< CTYPE > %{ public $csclassname(global::System.Collections.ICollection c) : this() { if (c == null) @@ -80,29 +78,17 @@ } } -#if SWIG_DOTNET_1 - public void CopyTo(global::System.Array array) -#else public void CopyTo($typemap(cstype, CTYPE)[] array) -#endif { CopyTo(0, array, 0, this.Count); } -#if SWIG_DOTNET_1 - public void CopyTo(global::System.Array array, int arrayIndex) -#else public void CopyTo($typemap(cstype, CTYPE)[] array, int arrayIndex) -#endif { CopyTo(0, array, arrayIndex, this.Count); } -#if SWIG_DOTNET_1 - public void CopyTo(int index, global::System.Array array, int arrayIndex, int count) -#else public void CopyTo(int index, $typemap(cstype, CTYPE)[] array, int arrayIndex, int count) -#endif { if (array == null) throw new ArgumentNullException("array"); @@ -120,11 +106,9 @@ array.SetValue(getitemcopy(index+i), arrayIndex+i); } -#if !SWIG_DOTNET_1 global::System.Collections.Generic.IEnumerator<$typemap(cstype, CTYPE)> global::System.Collections.Generic.IEnumerable<$typemap(cstype, CTYPE)>.GetEnumerator() { return new $csclassnameEnumerator(this); } -#endif global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() { return new $csclassnameEnumerator(this); @@ -140,9 +124,7 @@ /// collection but not when one of the elements of the collection is modified as it is a bit /// tricky to detect unmanaged code that modifies the collection under our feet. public sealed class $csclassnameEnumerator : global::System.Collections.IEnumerator -#if !SWIG_DOTNET_1 , global::System.Collections.Generic.IEnumerator<$typemap(cstype, CTYPE)> -#endif { private $csclassname collectionRef; private int currentIndex; @@ -196,12 +178,10 @@ } } -#if !SWIG_DOTNET_1 public void Dispose() { currentIndex = -1; currentObject = null; } -#endif } %} From adb93980f2decad8a2ab8bb2a462e66c4be51b4d Mon Sep 17 00:00:00 2001 From: "Brant K. Kyser" Date: Thu, 17 Oct 2013 15:44:24 -0500 Subject: [PATCH 155/481] Remove using directives from the generated C# code and fully qualify the use of all .NET framework types in order to minimize potential name collisions from input files defining types, namespace, etc with the same name as .NET framework members. --- Examples/test-suite/csharp_prepost.i | 6 +- Examples/test-suite/csharp_typemaps.i | 2 +- Examples/test-suite/special_variable_macros.i | 2 +- Lib/csharp/arrays_csharp.i | 10 +- Lib/csharp/boost_intrusive_ptr.i | 116 +++++++++--------- Lib/csharp/boost_shared_ptr.i | 72 +++++------ Lib/csharp/csharp.swg | 101 +++++++-------- Lib/csharp/csharphead.swg | 22 ++-- Lib/csharp/std_map.i | 20 +-- Lib/csharp/std_vector.i | 26 ++-- Lib/csharp/std_wstring.i | 4 +- Lib/csharp/typemaps.i | 6 +- Lib/csharp/wchar.i | 8 +- Source/Modules/csharp.cxx | 16 +-- 14 files changed, 200 insertions(+), 211 deletions(-) diff --git a/Examples/test-suite/csharp_prepost.i b/Examples/test-suite/csharp_prepost.i index 32ee10677..f48e5f419 100644 --- a/Examples/test-suite/csharp_prepost.i +++ b/Examples/test-suite/csharp_prepost.i @@ -116,7 +116,7 @@ struct PrePost3 { // Check attributes in the typemaps %typemap(cstype, inattributes="[CustomInt]") int val "int" %typemap(csin, pre=" int tmp_$csinput = $csinput * 100;") int val "tmp_$csinput" -%typemap(imtype, out="IntPtr/*overridden*/", outattributes="[CustomIntPtr]") CsinAttributes * "HandleRef/*overridden*/" +%typemap(imtype, out="global::System.IntPtr/*overridden*/", outattributes="[CustomIntPtr]") CsinAttributes * "global::System.Runtime.InteropServices.HandleRef/*overridden*/" %inline %{ class CsinAttributes { @@ -216,8 +216,8 @@ void subtractYears(CDate *pDate, int years) { %typemap(csvarout, excode=SWIGEXCODE2) CDate * %{ /* csvarout typemap code */ get { - IntPtr cPtr = $imcall; - CDate tempDate = (cPtr == IntPtr.Zero) ? null : new CDate(cPtr, $owner);$excode + global::System.IntPtr cPtr = $imcall; + CDate tempDate = (cPtr == global::System.IntPtr.Zero) ? null : new CDate(cPtr, $owner);$excode return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(), 0, 0, 0); } %} diff --git a/Examples/test-suite/csharp_typemaps.i b/Examples/test-suite/csharp_typemaps.i index 83097f663..32e735ca7 100644 --- a/Examples/test-suite/csharp_typemaps.i +++ b/Examples/test-suite/csharp_typemaps.i @@ -94,7 +94,7 @@ Number times12(const Number* num) { %typemap(csvarin, excode=SWIGEXCODE2) int %{ set { if ($csinput < 0) - throw new ApplicationException("number too small!"); + throw new global::System.ApplicationException("number too small!"); $imcall;$excode } %} diff --git a/Examples/test-suite/special_variable_macros.i b/Examples/test-suite/special_variable_macros.i index ddd068cc0..ca2edaa98 100644 --- a/Examples/test-suite/special_variable_macros.i +++ b/Examples/test-suite/special_variable_macros.i @@ -188,7 +188,7 @@ namespace Space { #if defined(SWIGCSHARP) %typemap(cscode) Space::RenameMe %{ - public static NewName factory(String s) { + public static NewName factory(System.String s) { //below should expand to: //return new NewName( new Name(s) ); return new $typemap(cstype, Space::RenameMe)( new $typemap(cstype, Name)(s) ); diff --git a/Lib/csharp/arrays_csharp.i b/Lib/csharp/arrays_csharp.i index 513330e4e..174a2823e 100644 --- a/Lib/csharp/arrays_csharp.i +++ b/Lib/csharp/arrays_csharp.i @@ -57,7 +57,7 @@ %typemap(ctype) CTYPE INPUT[] "CTYPE*" %typemap(cstype) CTYPE INPUT[] "CSTYPE[]" -%typemap(imtype, inattributes="[In, MarshalAs(UnmanagedType.LPArray)]") CTYPE INPUT[] "CSTYPE[]" +%typemap(imtype, inattributes="[global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.MarshalAs(global::System.Runtime.InteropServices.UnmanagedType.LPArray)]") CTYPE INPUT[] "CSTYPE[]" %typemap(csin) CTYPE INPUT[] "$csinput" %typemap(in) CTYPE INPUT[] "$1 = $input;" @@ -68,7 +68,7 @@ %typemap(ctype) CTYPE OUTPUT[] "CTYPE*" %typemap(cstype) CTYPE OUTPUT[] "CSTYPE[]" -%typemap(imtype, inattributes="[Out, MarshalAs(UnmanagedType.LPArray)]") CTYPE OUTPUT[] "CSTYPE[]" +%typemap(imtype, inattributes="[global::System.Runtime.InteropServices.Out, global::System.Runtime.InteropServices.MarshalAs(global::System.Runtime.InteropServices.UnmanagedType.LPArray)]") CTYPE OUTPUT[] "CSTYPE[]" %typemap(csin) CTYPE OUTPUT[] "$csinput" %typemap(in) CTYPE OUTPUT[] "$1 = $input;" @@ -79,7 +79,7 @@ %typemap(ctype) CTYPE INOUT[] "CTYPE*" %typemap(cstype) CTYPE INOUT[] "CSTYPE[]" -%typemap(imtype, inattributes="[In, Out, MarshalAs(UnmanagedType.LPArray)]") CTYPE INOUT[] "CSTYPE[]" +%typemap(imtype, inattributes="[global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.Out, global::System.Runtime.InteropServices.MarshalAs(global::System.Runtime.InteropServices.UnmanagedType.LPArray)]") CTYPE INOUT[] "CSTYPE[]" %typemap(csin) CTYPE INOUT[] "$csinput" %typemap(in) CTYPE INOUT[] "$1 = $input;" @@ -108,12 +108,12 @@ CSHARP_ARRAYS(double, double) %define CSHARP_ARRAYS_FIXED( CTYPE, CSTYPE ) %typemap(ctype) CTYPE FIXED[] "CTYPE*" -%typemap(imtype) CTYPE FIXED[] "IntPtr" +%typemap(imtype) CTYPE FIXED[] "global::System.IntPtr" %typemap(cstype) CTYPE FIXED[] "CSTYPE[]" %typemap(csin, pre= " fixed ( CSTYPE* swig_ptrTo_$csinput = $csinput ) {", terminator=" }") - CTYPE FIXED[] "(IntPtr)swig_ptrTo_$csinput" + CTYPE FIXED[] "(global::System.IntPtr)swig_ptrTo_$csinput" %typemap(in) CTYPE FIXED[] "$1 = $input;" %typemap(freearg) CTYPE FIXED[] "" diff --git a/Lib/csharp/boost_intrusive_ptr.i b/Lib/csharp/boost_intrusive_ptr.i index 09a164729..1cc5efda7 100644 --- a/Lib/csharp/boost_intrusive_ptr.i +++ b/Lib/csharp/boost_intrusive_ptr.i @@ -207,11 +207,11 @@ SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > &, SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *, SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *& "void *" -%typemap (imtype, out="IntPtr") SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >, +%typemap (imtype, out="global::System.IntPtr") SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > &, SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *, - SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *& "HandleRef" + SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *& "global::System.Runtime.InteropServices.HandleRef" %typemap (cstype) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > &, @@ -224,28 +224,28 @@ SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *& "$typemap(cstype, TYPE).getCPtr($csinput)" %typemap(csout, excode=SWIGEXCODE) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > { - IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode return ret; } %typemap(csout, excode=SWIGEXCODE) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > { - IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode return ret; } %typemap(csout, excode=SWIGEXCODE) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > & { - IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode return ret; } %typemap(csout, excode=SWIGEXCODE) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > * { - IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode return ret; } %typemap(csout, excode=SWIGEXCODE) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *& { - IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode return ret; } %typemap(csvarout, excode=SWIGEXCODE2) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > %{ @@ -274,76 +274,76 @@ return ret; } %typemap(csout, excode=SWIGEXCODE) CONST TYPE * { - IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode return ret; } %typemap(csout, excode=SWIGEXCODE) TYPE *CONST& { - IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode return ret; } // Base proxy classes %typemap(csbody) TYPE %{ - private HandleRef swigCPtr; + private global::System.Runtime.InteropServices.HandleRef swigCPtr; private bool swigCMemOwnBase; - PTRCTOR_VISIBILITY $csclassname(IntPtr cPtr, bool cMemoryOwn) { + PTRCTOR_VISIBILITY $csclassname(global::System.IntPtr cPtr, bool cMemoryOwn) { swigCMemOwnBase = cMemoryOwn; - swigCPtr = new HandleRef(this, cPtr); + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } - CPTR_VISIBILITY static HandleRef getCPtr($csclassname obj) { - return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; + CPTR_VISIBILITY static global::System.Runtime.InteropServices.HandleRef getCPtr($csclassname obj) { + return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } %} // Derived proxy classes %typemap(csbody_derived) TYPE %{ - private HandleRef swigCPtr; + private global::System.Runtime.InteropServices.HandleRef swigCPtr; private bool swigCMemOwnDerived; - PTRCTOR_VISIBILITY $csclassname(IntPtr cPtr, bool cMemoryOwn) : base($imclassname.$csclazznameSWIGSmartPtrUpcast(cPtr), true) { + PTRCTOR_VISIBILITY $csclassname(global::System.IntPtr cPtr, bool cMemoryOwn) : base($imclassname.$csclazznameSWIGSmartPtrUpcast(cPtr), true) { swigCMemOwnDerived = cMemoryOwn; - swigCPtr = new HandleRef(this, cPtr); + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } - CPTR_VISIBILITY static HandleRef getCPtr($csclassname obj) { - return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; + CPTR_VISIBILITY static global::System.Runtime.InteropServices.HandleRef getCPtr($csclassname obj) { + return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } %} %typemap(csdestruct, methodname="Dispose", methodmodifiers="public") TYPE { lock(this) { - if (swigCPtr.Handle != IntPtr.Zero) { + if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwnBase) { swigCMemOwnBase = false; $imcall; } - swigCPtr = new HandleRef(null, IntPtr.Zero); + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } - GC.SuppressFinalize(this); + global::System.GC.SuppressFinalize(this); } } %typemap(csdestruct_derived, methodname="Dispose", methodmodifiers="public") TYPE { lock(this) { - if (swigCPtr.Handle != IntPtr.Zero) { + if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwnDerived) { swigCMemOwnDerived = false; $imcall; } - swigCPtr = new HandleRef(null, IntPtr.Zero); + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } - GC.SuppressFinalize(this); + global::System.GC.SuppressFinalize(this); base.Dispose(); } } // CONST version needed ???? also for C# -%typemap(imtype, nopgcpp="1") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > swigSharedPtrUpcast "HandleRef" -%typemap(imtype, nopgcpp="1") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > swigSharedPtrUpcast "HandleRef" +%typemap(imtype, nopgcpp="1") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > swigSharedPtrUpcast "global::System.Runtime.InteropServices.HandleRef" +%typemap(imtype, nopgcpp="1") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > swigSharedPtrUpcast "global::System.Runtime.InteropServices.HandleRef" %template() SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >; @@ -424,8 +424,8 @@ %typemap (cstype) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > "$typemap(cstype, TYPE)" %typemap (csin) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > "$typemap(cstype, TYPE).getCPtr($csinput)" %typemap(csout, excode=SWIGEXCODE) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > { - IntPtr cPtr = $imcall; - return (cPtr == IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true); + global::System.IntPtr cPtr = $imcall; + return (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true); } %typemap(csout, excode=SWIGEXCODE) CONST TYPE { @@ -435,75 +435,75 @@ return new $typemap(cstype, TYPE)($imcall, true); } %typemap(csout, excode=SWIGEXCODE) CONST TYPE * { - IntPtr cPtr = $imcall; - return (cPtr == IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true); + global::System.IntPtr cPtr = $imcall; + return (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true); } %typemap(csout, excode=SWIGEXCODE) TYPE *CONST& { - IntPtr cPtr = $imcall; - return (cPtr == IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true); + global::System.IntPtr cPtr = $imcall; + return (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true); } // Base proxy classes %typemap(csbody) TYPE %{ - private HandleRef swigCPtr; + private global::System.Runtime.InteropServices.HandleRef swigCPtr; private bool swigCMemOwnBase; - PTRCTOR_VISIBILITY $csclassname(IntPtr cPtr, bool cMemoryOwn) { + PTRCTOR_VISIBILITY $csclassname(global::System.IntPtr cPtr, bool cMemoryOwn) { swigCMemOwnBase = cMemoryOwn; - swigCPtr = new HandleRef(this, cPtr); + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } - CPTR_VISIBILITY static HandleRef getCPtr($csclassname obj) { - return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; + CPTR_VISIBILITY static global::System.Runtime.InteropServices.HandleRef getCPtr($csclassname obj) { + return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } %} // Derived proxy classes %typemap(csbody_derived) TYPE %{ - private HandleRef swigCPtr; + private global::System.Runtime.InteropServices.HandleRef swigCPtr; private bool swigCMemOwnDerived; - PTRCTOR_VISIBILITY $csclassname(IntPtr cPtr, bool cMemoryOwn) : base($imclassname.$csclazznameSWIGSmartPtrUpcast(cPtr), true) { + PTRCTOR_VISIBILITY $csclassname(global::System.IntPtr cPtr, bool cMemoryOwn) : base($imclassname.$csclazznameSWIGSmartPtrUpcast(cPtr), true) { swigCMemOwnDerived = cMemoryOwn; - swigCPtr = new HandleRef(this, cPtr); + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } - CPTR_VISIBILITY static HandleRef getCPtr($csclassname obj) { - return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; + CPTR_VISIBILITY static global::System.Runtime.InteropServices.HandleRef getCPtr($csclassname obj) { + return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } %} %typemap(csdestruct, methodname="Dispose", methodmodifiers="public") TYPE { lock(this) { - if (swigCPtr.Handle != IntPtr.Zero) { + if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwnBase) { swigCMemOwnBase = false; $imcall; } - swigCPtr = new HandleRef(null, IntPtr.Zero); + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } - GC.SuppressFinalize(this); + global::System.GC.SuppressFinalize(this); } } %typemap(csdestruct_derived, methodname="Dispose", methodmodifiers="public") TYPE { lock(this) { - if (swigCPtr.Handle != IntPtr.Zero) { + if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwnDerived) { swigCMemOwnDerived = false; $imcall; } - swigCPtr = new HandleRef(null, IntPtr.Zero); + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } - GC.SuppressFinalize(this); + global::System.GC.SuppressFinalize(this); base.Dispose(); } } // CONST version needed ???? also for C# -%typemap(imtype, nopgcpp="1") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > swigSharedPtrUpcast "HandleRef" -%typemap(imtype, nopgcpp="1") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > swigSharedPtrUpcast "HandleRef" +%typemap(imtype, nopgcpp="1") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > swigSharedPtrUpcast "global::System.Runtime.InteropServices.HandleRef" +%typemap(imtype, nopgcpp="1") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > swigSharedPtrUpcast "global::System.Runtime.InteropServices.HandleRef" %template() SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >; diff --git a/Lib/csharp/boost_shared_ptr.i b/Lib/csharp/boost_shared_ptr.i index 5e6f66469..2b65bf20d 100644 --- a/Lib/csharp/boost_shared_ptr.i +++ b/Lib/csharp/boost_shared_ptr.i @@ -95,10 +95,10 @@ SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > &, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& "void *" -%typemap (imtype, out="IntPtr") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, +%typemap (imtype, out="global::System.IntPtr") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > &, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *, - SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& "HandleRef" + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& "global::System.Runtime.InteropServices.HandleRef" %typemap (cstype) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > &, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *, @@ -110,23 +110,23 @@ SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& "$typemap(cstype, TYPE).getCPtr($csinput)" %typemap(csout, excode=SWIGEXCODE) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > { - IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode return ret; } %typemap(csout, excode=SWIGEXCODE) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > & { - IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode return ret; } %typemap(csout, excode=SWIGEXCODE) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * { - IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode return ret; } %typemap(csout, excode=SWIGEXCODE) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& { - IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode return ret; } @@ -140,13 +140,13 @@ return ret; } %typemap(csout, excode=SWIGEXCODE) CONST TYPE * { - IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode return ret; } %typemap(csout, excode=SWIGEXCODE) TYPE *CONST& { - IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode return ret; } @@ -157,78 +157,78 @@ } %} %typemap(csvarout, excode=SWIGEXCODE2) CONST TYPE * %{ get { - IntPtr cPtr = $imcall; - $csclassname ret = (cPtr == IntPtr.Zero) ? null : new $csclassname(cPtr, true);$excode + global::System.IntPtr cPtr = $imcall; + $csclassname ret = (cPtr == global::System.IntPtr.Zero) ? null : new $csclassname(cPtr, true);$excode return ret; } %} %typemap(csvarout, excode=SWIGEXCODE2) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > & %{ get { - IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode return ret; } %} %typemap(csvarout, excode=SWIGEXCODE2) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * %{ get { - IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode return ret; } %} // Proxy classes (base classes, ie, not derived classes) %typemap(csbody) TYPE %{ - private HandleRef swigCPtr; + private global::System.Runtime.InteropServices.HandleRef swigCPtr; private bool swigCMemOwnBase; - PTRCTOR_VISIBILITY $csclassname(IntPtr cPtr, bool cMemoryOwn) { + PTRCTOR_VISIBILITY $csclassname(global::System.IntPtr cPtr, bool cMemoryOwn) { swigCMemOwnBase = cMemoryOwn; - swigCPtr = new HandleRef(this, cPtr); + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } - CPTR_VISIBILITY static HandleRef getCPtr($csclassname obj) { - return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; + CPTR_VISIBILITY static global::System.Runtime.InteropServices.HandleRef getCPtr($csclassname obj) { + return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } %} // Derived proxy classes %typemap(csbody_derived) TYPE %{ - private HandleRef swigCPtr; + private global::System.Runtime.InteropServices.HandleRef swigCPtr; private bool swigCMemOwnDerived; - PTRCTOR_VISIBILITY $csclassname(IntPtr cPtr, bool cMemoryOwn) : base($imclassname.$csclazznameSWIGSmartPtrUpcast(cPtr), true) { + PTRCTOR_VISIBILITY $csclassname(global::System.IntPtr cPtr, bool cMemoryOwn) : base($imclassname.$csclazznameSWIGSmartPtrUpcast(cPtr), true) { swigCMemOwnDerived = cMemoryOwn; - swigCPtr = new HandleRef(this, cPtr); + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } - CPTR_VISIBILITY static HandleRef getCPtr($csclassname obj) { - return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; + CPTR_VISIBILITY static global::System.Runtime.InteropServices.HandleRef getCPtr($csclassname obj) { + return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } %} %typemap(csdestruct, methodname="Dispose", methodmodifiers="public") TYPE { lock(this) { - if (swigCPtr.Handle != IntPtr.Zero) { + if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwnBase) { swigCMemOwnBase = false; $imcall; } - swigCPtr = new HandleRef(null, IntPtr.Zero); + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } - GC.SuppressFinalize(this); + global::System.GC.SuppressFinalize(this); } } %typemap(csdestruct_derived, methodname="Dispose", methodmodifiers="public") TYPE { lock(this) { - if (swigCPtr.Handle != IntPtr.Zero) { + if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwnDerived) { swigCMemOwnDerived = false; $imcall; } - swigCPtr = new HandleRef(null, IntPtr.Zero); + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } - GC.SuppressFinalize(this); + global::System.GC.SuppressFinalize(this); base.Dispose(); } } diff --git a/Lib/csharp/csharp.swg b/Lib/csharp/csharp.swg index 731ed83e4..7bd660f4d 100644 --- a/Lib/csharp/csharp.swg +++ b/Lib/csharp/csharp.swg @@ -110,23 +110,23 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { /* Non primitive types */ %typemap(ctype) SWIGTYPE "void *" -%typemap(imtype, out="IntPtr") SWIGTYPE "HandleRef" +%typemap(imtype, out="global::System.IntPtr") SWIGTYPE "global::System.Runtime.InteropServices.HandleRef" %typemap(cstype) SWIGTYPE "$&csclassname" %typemap(ctype) SWIGTYPE [] "void *" -%typemap(imtype, out="IntPtr") SWIGTYPE [] "HandleRef" +%typemap(imtype, out="global::System.IntPtr") SWIGTYPE [] "global::System.Runtime.InteropServices.HandleRef" %typemap(cstype) SWIGTYPE [] "$csclassname" %typemap(ctype) SWIGTYPE * "void *" -%typemap(imtype, out="IntPtr") SWIGTYPE * "HandleRef" +%typemap(imtype, out="global::System.IntPtr") SWIGTYPE * "global::System.Runtime.InteropServices.HandleRef" %typemap(cstype) SWIGTYPE * "$csclassname" %typemap(ctype) SWIGTYPE & "void *" -%typemap(imtype, out="IntPtr") SWIGTYPE & "HandleRef" +%typemap(imtype, out="global::System.IntPtr") SWIGTYPE & "global::System.Runtime.InteropServices.HandleRef" %typemap(cstype) SWIGTYPE & "$csclassname" %typemap(ctype) SWIGTYPE && "void *" -%typemap(imtype, out="IntPtr") SWIGTYPE && "HandleRef" +%typemap(imtype, out="global::System.IntPtr") SWIGTYPE && "global::System.Runtime.InteropServices.HandleRef" %typemap(cstype) SWIGTYPE && "$csclassname" /* pointer to a class member */ @@ -447,7 +447,7 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { %typemap(directorin) SWIGTYPE && %{ $input = ($1_ltype) &$1; %} -%typemap(csdirectorin) SWIGTYPE *, SWIGTYPE (CLASS::*) "($iminput == IntPtr.Zero) ? null : new $csclassname($iminput, false)" +%typemap(csdirectorin) SWIGTYPE *, SWIGTYPE (CLASS::*) "($iminput == global::System.IntPtr.Zero) ? null : new $csclassname($iminput, false)" %typemap(csdirectorin) SWIGTYPE & "new $csclassname($iminput, false)" %typemap(csdirectorin) SWIGTYPE && "new $csclassname($iminput, false)" %typemap(csdirectorout) SWIGTYPE *, SWIGTYPE (CLASS::*), SWIGTYPE &, SWIGTYPE && "$csclassname.getCPtr($cscall).Handle" @@ -683,8 +683,8 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { return ret; } %typemap(csout, excode=SWIGEXCODE) SWIGTYPE *, SWIGTYPE [] { - IntPtr cPtr = $imcall; - $csclassname ret = (cPtr == IntPtr.Zero) ? null : new $csclassname(cPtr, $owner);$excode + global::System.IntPtr cPtr = $imcall; + $csclassname ret = (cPtr == global::System.IntPtr.Zero) ? null : new $csclassname(cPtr, $owner);$excode return ret; } %typemap(csout, excode=SWIGEXCODE) SWIGTYPE (CLASS::*) { @@ -803,8 +803,8 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { } %} %typemap(csvarout, excode=SWIGEXCODE2) SWIGTYPE *, SWIGTYPE [] %{ get { - IntPtr cPtr = $imcall; - $csclassname ret = (cPtr == IntPtr.Zero) ? null : new $csclassname(cPtr, $owner);$excode + global::System.IntPtr cPtr = $imcall; + $csclassname ret = (cPtr == global::System.IntPtr.Zero) ? null : new $csclassname(cPtr, $owner);$excode return ret; } %} @@ -817,12 +817,12 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { /* Pointer reference typemaps */ %typemap(ctype) SWIGTYPE *const& "void *" -%typemap(imtype, out="IntPtr") SWIGTYPE *const& "HandleRef" +%typemap(imtype, out="global::System.IntPtr") SWIGTYPE *const& "global::System.Runtime.InteropServices.HandleRef" %typemap(cstype) SWIGTYPE *const& "$*csclassname" %typemap(csin) SWIGTYPE *const& "$*csclassname.getCPtr($csinput)" %typemap(csout, excode=SWIGEXCODE) SWIGTYPE *const& { - IntPtr cPtr = $imcall; - $*csclassname ret = (cPtr == IntPtr.Zero) ? null : new $*csclassname(cPtr, $owner);$excode + global::System.IntPtr cPtr = $imcall; + $*csclassname ret = (cPtr == global::System.IntPtr.Zero) ? null : new $*csclassname(cPtr, $owner);$excode return ret; } %typemap(in) SWIGTYPE *const& ($*1_ltype temp = 0) @@ -831,15 +831,15 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { %typemap(out) SWIGTYPE *const& %{ $result = (void *)*$1; %} -/* Marshal C/C++ pointer to IntPtr */ +/* Marshal C/C++ pointer to global::System.IntPtr */ %typemap(ctype) void *VOID_INT_PTR "void *" -%typemap(imtype) void *VOID_INT_PTR "IntPtr" -%typemap(cstype) void *VOID_INT_PTR "IntPtr" +%typemap(imtype) void *VOID_INT_PTR "global::System.IntPtr" +%typemap(cstype) void *VOID_INT_PTR "global::System.IntPtr" %typemap(in) void *VOID_INT_PTR %{ $1 = ($1_ltype)$input; %} %typemap(out) void *VOID_INT_PTR %{ $result = (void *)$1; %} %typemap(csin) void *VOID_INT_PTR "$csinput" %typemap(csout, excode=SWIGEXCODE) void *VOID_INT_PTR { - IntPtr ret = $imcall;$excode + global::System.IntPtr ret = $imcall;$excode return ret; } @@ -848,8 +848,7 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { %typemap(csbase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" %typemap(csclassmodifiers) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "public class" %typemap(cscode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" -%typemap(csimports) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "\nusing global::System;\nusing global::System.Runtime.InteropServices;\n" -%typemap(csinterfaces) SWIGTYPE "IDisposable" +%typemap(csinterfaces) SWIGTYPE "global::System.IDisposable" %typemap(csinterfaces) SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" %typemap(csinterfaces_derived) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" @@ -859,29 +858,29 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { %define SWIG_CSBODY_PROXY(PTRCTOR_VISIBILITY, CPTR_VISIBILITY, TYPE...) // Proxy classes (base classes, ie, not derived classes) %typemap(csbody) TYPE %{ - private HandleRef swigCPtr; + private global::System.Runtime.InteropServices.HandleRef swigCPtr; protected bool swigCMemOwn; - PTRCTOR_VISIBILITY $csclassname(IntPtr cPtr, bool cMemoryOwn) { + PTRCTOR_VISIBILITY $csclassname(global::System.IntPtr cPtr, bool cMemoryOwn) { swigCMemOwn = cMemoryOwn; - swigCPtr = new HandleRef(this, cPtr); + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } - CPTR_VISIBILITY static HandleRef getCPtr($csclassname obj) { - return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; + CPTR_VISIBILITY static global::System.Runtime.InteropServices.HandleRef getCPtr($csclassname obj) { + return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } %} // Derived proxy classes %typemap(csbody_derived) TYPE %{ - private HandleRef swigCPtr; + private global::System.Runtime.InteropServices.HandleRef swigCPtr; - PTRCTOR_VISIBILITY $csclassname(IntPtr cPtr, bool cMemoryOwn) : base($imclassname.$csclazznameSWIGUpcast(cPtr), cMemoryOwn) { - swigCPtr = new HandleRef(this, cPtr); + PTRCTOR_VISIBILITY $csclassname(global::System.IntPtr cPtr, bool cMemoryOwn) : base($imclassname.$csclazznameSWIGUpcast(cPtr), cMemoryOwn) { + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } - CPTR_VISIBILITY static HandleRef getCPtr($csclassname obj) { - return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; + CPTR_VISIBILITY static global::System.Runtime.InteropServices.HandleRef getCPtr($csclassname obj) { + return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } %} %enddef @@ -889,18 +888,18 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { %define SWIG_CSBODY_TYPEWRAPPER(PTRCTOR_VISIBILITY, DEFAULTCTOR_VISIBILITY, CPTR_VISIBILITY, TYPE...) // Typewrapper classes %typemap(csbody) TYPE *, TYPE &, TYPE &&, TYPE [] %{ - private HandleRef swigCPtr; + private global::System.Runtime.InteropServices.HandleRef swigCPtr; - PTRCTOR_VISIBILITY $csclassname(IntPtr cPtr, bool futureUse) { - swigCPtr = new HandleRef(this, cPtr); + PTRCTOR_VISIBILITY $csclassname(global::System.IntPtr cPtr, bool futureUse) { + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } DEFAULTCTOR_VISIBILITY $csclassname() { - swigCPtr = new HandleRef(null, IntPtr.Zero); + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } - CPTR_VISIBILITY static HandleRef getCPtr($csclassname obj) { - return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; + CPTR_VISIBILITY static global::System.Runtime.InteropServices.HandleRef getCPtr($csclassname obj) { + return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } %} @@ -938,27 +937,27 @@ SWIG_CSBODY_TYPEWRAPPER(internal, protected, internal, SWIGTYPE) %typemap(csdestruct, methodname="Dispose", methodmodifiers="public") SWIGTYPE { lock(this) { - if (swigCPtr.Handle != IntPtr.Zero) { + if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; $imcall; } - swigCPtr = new HandleRef(null, IntPtr.Zero); + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } - GC.SuppressFinalize(this); + global::System.GC.SuppressFinalize(this); } } %typemap(csdestruct_derived, methodname="Dispose", methodmodifiers="public") SWIGTYPE { lock(this) { - if (swigCPtr.Handle != IntPtr.Zero) { + if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; $imcall; } - swigCPtr = new HandleRef(null, IntPtr.Zero); + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } - GC.SuppressFinalize(this); + global::System.GC.SuppressFinalize(this); base.Dispose(); } } @@ -981,16 +980,6 @@ SWIG_CSBODY_TYPEWRAPPER(internal, protected, internal, SWIGTYPE) %pragma(csharp) imclassclassmodifiers="class" %pragma(csharp) moduleclassmodifiers="public class" -%pragma(csharp) moduleimports=%{ -using global::System; -using global::System.Runtime.InteropServices; -%} - -%pragma(csharp) imclassimports=%{ -using global::System; -using global::System.Runtime.InteropServices; -%} - /* Some ANSI C typemaps */ %apply unsigned long { size_t }; @@ -1015,19 +1004,19 @@ using global::System.Runtime.InteropServices; /* // Alternative char * typemaps. %pragma(csharp) imclasscode=%{ - public class SWIGStringMarshal : IDisposable { - public readonly HandleRef swigCPtr; + public class SWIGStringMarshal : global::System.IDisposable { + public readonly global::System.Runtime.InteropServices.HandleRef swigCPtr; public SWIGStringMarshal(string str) { - swigCPtr = new HandleRef(this, global::System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(str)); + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, global::System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(str)); } public virtual void Dispose() { global::System.Runtime.InteropServices.Marshal.FreeHGlobal(swigCPtr.Handle); - GC.SuppressFinalize(this); + global::System.GC.SuppressFinalize(this); } } %} -%typemap(imtype, out="IntPtr") char *, char[ANY], char[] "HandleRef" +%typemap(imtype, out="global::System.IntPtr") char *, char[ANY], char[] "global::System.Runtime.InteropServices.HandleRef" %typemap(out) char *, char[ANY], char[] %{ $result = $1; %} %typemap(csin) char *, char[ANY], char[] "new $imclassname.SWIGStringMarshal($csinput).swigCPtr" %typemap(csout, excode=SWIGEXCODE) char *, char[ANY], char[] { diff --git a/Lib/csharp/csharphead.swg b/Lib/csharp/csharphead.swg index be1281a71..0b55635b3 100644 --- a/Lib/csharp/csharphead.swg +++ b/Lib/csharp/csharphead.swg @@ -149,7 +149,7 @@ SWIGEXPORT void SWIGSTDCALL SWIGRegisterExceptionArgumentCallbacks_$module( static ExceptionArgumentDelegate argumentNullDelegate = new ExceptionArgumentDelegate(SetPendingArgumentNullException); static ExceptionArgumentDelegate argumentOutOfRangeDelegate = new ExceptionArgumentDelegate(SetPendingArgumentOutOfRangeException); - [DllImport("$dllimport", EntryPoint="SWIGRegisterExceptionCallbacks_$module")] + [global::System.Runtime.InteropServices.DllImport("$dllimport", EntryPoint="SWIGRegisterExceptionCallbacks_$module")] public static extern void SWIGRegisterExceptionCallbacks_$module( ExceptionDelegate applicationDelegate, ExceptionDelegate arithmeticDelegate, @@ -163,7 +163,7 @@ SWIGEXPORT void SWIGSTDCALL SWIGRegisterExceptionArgumentCallbacks_$module( ExceptionDelegate overflowDelegate, ExceptionDelegate systemExceptionDelegate); - [DllImport("$dllimport", EntryPoint="SWIGRegisterExceptionArgumentCallbacks_$module")] + [global::System.Runtime.InteropServices.DllImport("$dllimport", EntryPoint="SWIGRegisterExceptionArgumentCallbacks_$module")] public static extern void SWIGRegisterExceptionCallbacksArgument_$module( ExceptionArgumentDelegate argumentDelegate, ExceptionArgumentDelegate argumentNullDelegate, @@ -207,12 +207,12 @@ SWIGEXPORT void SWIGSTDCALL SWIGRegisterExceptionArgumentCallbacks_$module( SWIGPendingException.Set(new global::System.ArgumentException(message, paramName, SWIGPendingException.Retrieve())); } static void SetPendingArgumentNullException(string message, string paramName) { - Exception e = SWIGPendingException.Retrieve(); + global::System.Exception e = SWIGPendingException.Retrieve(); if (e != null) message = message + " Inner Exception: " + e.Message; SWIGPendingException.Set(new global::System.ArgumentNullException(paramName, message)); } static void SetPendingArgumentOutOfRangeException(string message, string paramName) { - Exception e = SWIGPendingException.Retrieve(); + global::System.Exception e = SWIGPendingException.Retrieve(); if (e != null) message = message + " Inner Exception: " + e.Message; SWIGPendingException.Set(new global::System.ArgumentOutOfRangeException(paramName, message)); } @@ -241,8 +241,8 @@ SWIGEXPORT void SWIGSTDCALL SWIGRegisterExceptionArgumentCallbacks_$module( protected static SWIGExceptionHelper swigExceptionHelper = new SWIGExceptionHelper(); public class SWIGPendingException { - [ThreadStatic] - private static Exception pendingException = null; + [global::System.ThreadStatic] + private static global::System.Exception pendingException = null; private static int numExceptionsPending = 0; public static bool Pending { @@ -255,17 +255,17 @@ SWIGEXPORT void SWIGSTDCALL SWIGRegisterExceptionArgumentCallbacks_$module( } } - public static void Set(Exception e) { + public static void Set(global::System.Exception e) { if (pendingException != null) - throw new ApplicationException("FATAL: An earlier pending exception from unmanaged code was missed and thus not thrown (" + pendingException.ToString() + ")", e); + throw new global::System.ApplicationException("FATAL: An earlier pending exception from unmanaged code was missed and thus not thrown (" + pendingException.ToString() + ")", e); pendingException = e; lock(typeof($imclassname)) { numExceptionsPending++; } } - public static Exception Retrieve() { - Exception e = null; + public static global::System.Exception Retrieve() { + global::System.Exception e = null; if (numExceptionsPending > 0) { if (pendingException != null) { e = pendingException; @@ -294,7 +294,7 @@ static SWIG_CSharpStringHelperCallback SWIG_csharp_string_callback = NULL; public delegate string SWIGStringDelegate(string message); static SWIGStringDelegate stringDelegate = new SWIGStringDelegate(CreateString); - [DllImport("$dllimport", EntryPoint="SWIGRegisterStringCallback_$module")] + [global::System.Runtime.InteropServices.DllImport("$dllimport", EntryPoint="SWIGRegisterStringCallback_$module")] public static extern void SWIGRegisterStringCallback_$module(SWIGStringDelegate stringDelegate); static string CreateString(string cString) { diff --git a/Lib/csharp/std_map.i b/Lib/csharp/std_map.i index 045bd6e3e..db6fa7bd1 100644 --- a/Lib/csharp/std_map.i +++ b/Lib/csharp/std_map.i @@ -26,7 +26,7 @@ /* K is the C++ key type, T is the C++ value type */ %define SWIG_STD_MAP_INTERNAL(K, T, C) -%typemap(csinterfaces) std::map< K, T, C > "IDisposable \n , global::System.Collections.Generic.IDictionary<$typemap(cstype, K), $typemap(cstype, T)>\n"; +%typemap(csinterfaces) std::map< K, T, C > "global::System.IDisposable \n , global::System.Collections.Generic.IDictionary<$typemap(cstype, K), $typemap(cstype, T)>\n"; %typemap(cscode) std::map %{ public $typemap(cstype, T) this[$typemap(cstype, K) key] { @@ -65,7 +65,7 @@ global::System.Collections.Generic.ICollection<$typemap(cstype, K)> keys = new global::System.Collections.Generic.List<$typemap(cstype, K)>(); int size = this.Count; if (size > 0) { - IntPtr iter = create_iterator_begin(); + global::System.IntPtr iter = create_iterator_begin(); for (int i = 0; i < size; i++) { keys.Add(get_next_key(iter)); } @@ -111,13 +111,13 @@ public void CopyTo(global::System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)>[] array, int arrayIndex) { if (array == null) - throw new ArgumentNullException("array"); + throw new global::System.ArgumentNullException("array"); if (arrayIndex < 0) - throw new ArgumentOutOfRangeException("arrayIndex", "Value is less than zero"); + throw new global::System.ArgumentOutOfRangeException("arrayIndex", "Value is less than zero"); if (array.Rank > 1) - throw new ArgumentException("Multi dimensional array.", "array"); + throw new global::System.ArgumentException("Multi dimensional array.", "array"); if (arrayIndex+this.Count > array.Length) - throw new ArgumentException("Number of elements to copy is too large."); + throw new global::System.ArgumentException("Number of elements to copy is too large."); global::System.Collections.Generic.IList<$typemap(cstype, K)> keyList = new global::System.Collections.Generic.List<$typemap(cstype, K)>(this.Keys); for (int i = 0; i < keyList.Count; i++) { @@ -164,11 +164,11 @@ public global::System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)> Current { get { if (currentIndex == -1) - throw new InvalidOperationException("Enumeration not started."); + throw new global::System.InvalidOperationException("Enumeration not started."); if (currentIndex > currentSize - 1) - throw new InvalidOperationException("Enumeration finished."); + throw new global::System.InvalidOperationException("Enumeration finished."); if (currentObject == null) - throw new InvalidOperationException("Collection modified."); + throw new global::System.InvalidOperationException("Collection modified."); return (global::System.Collections.Generic.KeyValuePair<$typemap(cstype, K), $typemap(cstype, T)>)currentObject; } } @@ -197,7 +197,7 @@ currentIndex = -1; currentObject = null; if (collectionRef.Count != currentSize) { - throw new InvalidOperationException("Collection modified."); + throw new global::System.InvalidOperationException("Collection modified."); } } diff --git a/Lib/csharp/std_vector.i b/Lib/csharp/std_vector.i index e29c2bf2a..9d52a962b 100644 --- a/Lib/csharp/std_vector.i +++ b/Lib/csharp/std_vector.i @@ -24,11 +24,11 @@ // MACRO for use within the std::vector class body %define SWIG_STD_VECTOR_MINIMUM_INTERNAL(CSINTERFACE, CONST_REFERENCE, CTYPE...) -%typemap(csinterfaces) std::vector< CTYPE > "IDisposable, global::System.Collections.IEnumerable\n , global::System.Collections.Generic.CSINTERFACE<$typemap(cstype, CTYPE)>\n"; +%typemap(csinterfaces) std::vector< CTYPE > "global::System.IDisposable, global::System.Collections.IEnumerable\n , global::System.Collections.Generic.CSINTERFACE<$typemap(cstype, CTYPE)>\n"; %typemap(cscode) std::vector< CTYPE > %{ public $csclassname(global::System.Collections.ICollection c) : this() { if (c == null) - throw new ArgumentNullException("c"); + throw new global::System.ArgumentNullException("c"); foreach ($typemap(cstype, CTYPE) element in c) { this.Add(element); } @@ -61,7 +61,7 @@ } set { if (value < size()) - throw new ArgumentOutOfRangeException("Capacity"); + throw new global::System.ArgumentOutOfRangeException("Capacity"); reserve((uint)value); } } @@ -91,17 +91,17 @@ public void CopyTo(int index, $typemap(cstype, CTYPE)[] array, int arrayIndex, int count) { if (array == null) - throw new ArgumentNullException("array"); + throw new global::System.ArgumentNullException("array"); if (index < 0) - throw new ArgumentOutOfRangeException("index", "Value is less than zero"); + throw new global::System.ArgumentOutOfRangeException("index", "Value is less than zero"); if (arrayIndex < 0) - throw new ArgumentOutOfRangeException("arrayIndex", "Value is less than zero"); + throw new global::System.ArgumentOutOfRangeException("arrayIndex", "Value is less than zero"); if (count < 0) - throw new ArgumentOutOfRangeException("count", "Value is less than zero"); + throw new global::System.ArgumentOutOfRangeException("count", "Value is less than zero"); if (array.Rank > 1) - throw new ArgumentException("Multi dimensional array.", "array"); + throw new global::System.ArgumentException("Multi dimensional array.", "array"); if (index+count > this.Count || arrayIndex+count > array.Length) - throw new ArgumentException("Number of elements to copy is too large."); + throw new global::System.ArgumentException("Number of elements to copy is too large."); for (int i=0; i currentSize - 1) - throw new InvalidOperationException("Enumeration finished."); + throw new global::System.InvalidOperationException("Enumeration finished."); if (currentObject == null) - throw new InvalidOperationException("Collection modified."); + throw new global::System.InvalidOperationException("Collection modified."); return ($typemap(cstype, CTYPE))currentObject; } } @@ -174,7 +174,7 @@ currentIndex = -1; currentObject = null; if (collectionRef.Count != currentSize) { - throw new InvalidOperationException("Collection modified."); + throw new global::System.InvalidOperationException("Collection modified."); } } diff --git a/Lib/csharp/std_wstring.i b/Lib/csharp/std_wstring.i index 9142d36a5..09bdaaaa2 100644 --- a/Lib/csharp/std_wstring.i +++ b/Lib/csharp/std_wstring.i @@ -23,7 +23,7 @@ class wstring; // wstring %typemap(ctype, out="void *") wstring "wchar_t *" -%typemap(imtype, inattributes="[MarshalAs(UnmanagedType.LPWStr)]") wstring "string" +%typemap(imtype, inattributes="[global::System.Runtime.InteropServices.MarshalAs(global::System.Runtime.InteropServices.UnmanagedType.LPWStr)]") wstring "string" %typemap(cstype) wstring "string" %typemap(csdirectorin) wstring "$iminput" %typemap(csdirectorout) wstring "$cscall" @@ -60,7 +60,7 @@ class wstring; // const wstring & %typemap(ctype, out="void *") const wstring & "wchar_t *" -%typemap(imtype, inattributes="[MarshalAs(UnmanagedType.LPWStr)]") const wstring & "string" +%typemap(imtype, inattributes="[global::System.Runtime.InteropServices.MarshalAs(global::System.Runtime.InteropServices.UnmanagedType.LPWStr)]") const wstring & "string" %typemap(cstype) const wstring & "string" %typemap(csdirectorin) const wstring & "$iminput" diff --git a/Lib/csharp/typemaps.i b/Lib/csharp/typemaps.i index 79f559680..b6f9bddbd 100644 --- a/Lib/csharp/typemaps.i +++ b/Lib/csharp/typemaps.i @@ -55,7 +55,7 @@ In C# you could then use it like this: %define INPUT_TYPEMAP(TYPE, CTYPE, CSTYPE) %typemap(ctype, out="void *") TYPE *INPUT, TYPE &INPUT "CTYPE" -%typemap(imtype, out="IntPtr") TYPE *INPUT, TYPE &INPUT "CSTYPE" +%typemap(imtype, out="global::System.IntPtr") TYPE *INPUT, TYPE &INPUT "CSTYPE" %typemap(cstype, out="$csclassname") TYPE *INPUT, TYPE &INPUT "CSTYPE" %typemap(csin) TYPE *INPUT, TYPE &INPUT "$csinput" @@ -135,7 +135,7 @@ value returned in the second output parameter. In C# you would use it like this: %define OUTPUT_TYPEMAP(TYPE, CTYPE, CSTYPE, TYPECHECKPRECEDENCE) %typemap(ctype, out="void *") TYPE *OUTPUT, TYPE &OUTPUT "CTYPE *" -%typemap(imtype, out="IntPtr") TYPE *OUTPUT, TYPE &OUTPUT "out CSTYPE" +%typemap(imtype, out="global::System.IntPtr") TYPE *OUTPUT, TYPE &OUTPUT "out CSTYPE" %typemap(cstype, out="$csclassname") TYPE *OUTPUT, TYPE &OUTPUT "out CSTYPE" %typemap(csin) TYPE *OUTPUT, TYPE &OUTPUT "out $csinput" @@ -224,7 +224,7 @@ of the function return value. %define INOUT_TYPEMAP(TYPE, CTYPE, CSTYPE, TYPECHECKPRECEDENCE) %typemap(ctype, out="void *") TYPE *INOUT, TYPE &INOUT "CTYPE *" -%typemap(imtype, out="IntPtr") TYPE *INOUT, TYPE &INOUT "ref CSTYPE" +%typemap(imtype, out="global::System.IntPtr") TYPE *INOUT, TYPE &INOUT "ref CSTYPE" %typemap(cstype, out="$csclassname") TYPE *INOUT, TYPE &INOUT "ref CSTYPE" %typemap(csin) TYPE *INOUT, TYPE &INOUT "ref $csinput" diff --git a/Lib/csharp/wchar.i b/Lib/csharp/wchar.i index 066044014..9361edf6f 100644 --- a/Lib/csharp/wchar.i +++ b/Lib/csharp/wchar.i @@ -20,13 +20,13 @@ static SWIG_CSharpWStringHelperCallback SWIG_csharp_wstring_callback = NULL; %pragma(csharp) imclasscode=%{ protected class SWIGWStringHelper { - public delegate string SWIGWStringDelegate(IntPtr message); + public delegate string SWIGWStringDelegate(global::System.IntPtr message); static SWIGWStringDelegate wstringDelegate = new SWIGWStringDelegate(CreateWString); - [DllImport("$dllimport", EntryPoint="SWIGRegisterWStringCallback_$module")] + [global::System.Runtime.InteropServices.DllImport("$dllimport", EntryPoint="SWIGRegisterWStringCallback_$module")] public static extern void SWIGRegisterWStringCallback_$module(SWIGWStringDelegate wstringDelegate); - static string CreateWString([MarshalAs(UnmanagedType.LPWStr)]IntPtr cString) { + static string CreateWString([global::System.Runtime.InteropServices.MarshalAs(global::System.Runtime.InteropServices.UnmanagedType.LPWStr)]global::System.IntPtr cString) { return global::System.Runtime.InteropServices.Marshal.PtrToStringUni(cString); } @@ -77,7 +77,7 @@ SWIGEXPORT void SWIGSTDCALL SWIGRegisterWStringCallback_$module(SWIG_CSharpWStri // wchar_t * %typemap(ctype) wchar_t * "wchar_t *" -%typemap(imtype, inattributes="[MarshalAs(UnmanagedType.LPWStr)]", out="IntPtr" ) wchar_t * "string" +%typemap(imtype, inattributes="[global::System.Runtime.InteropServices.MarshalAs(global::System.Runtime.InteropServices.UnmanagedType.LPWStr)]", out="global::System.IntPtr" ) wchar_t * "string" %typemap(cstype) wchar_t * "string" %typemap(csin) wchar_t * "$csinput" diff --git a/Source/Modules/csharp.cxx b/Source/Modules/csharp.cxx index 6c314959f..6b9219750 100644 --- a/Source/Modules/csharp.cxx +++ b/Source/Modules/csharp.cxx @@ -776,7 +776,7 @@ public: } } - Printv(imclass_class_code, "\n [DllImport(\"", dllimport, "\", EntryPoint=\"", wname, "\")]\n", NIL); + Printv(imclass_class_code, "\n [global::System.Runtime.InteropServices.DllImport(\"", dllimport, "\", EntryPoint=\"", wname, "\")]\n", NIL); if (im_outattributes) Printf(imclass_class_code, " %s\n", im_outattributes); @@ -1699,7 +1699,7 @@ public: if (*Char(destructor_call)) Replaceall(destruct, "$imcall", destructor_call); else - Replaceall(destruct, "$imcall", "throw new MethodAccessException(\"C++ destructor does not have public access\")"); + Replaceall(destruct, "$imcall", "throw new global::System.MethodAccessException(\"C++ destructor does not have public access\")"); if (*Char(destruct)) Printv(proxy_class_def, "\n ", destruct_methodmodifiers, " ", derived ? "override" : "virtual", " void ", destruct_methodname, "() ", destruct, "\n", NIL); @@ -1732,7 +1732,7 @@ public: if (first_class_dmethod < curr_class_dmethod) { // Only emit if there is at least one director method Printf(proxy_class_code, "\n"); - Printf(proxy_class_code, " private bool SwigDerivedClassHasMethod(string methodName, Type[] methodTypes) {\n"); + Printf(proxy_class_code, " private bool SwigDerivedClassHasMethod(string methodName, global::System.Type[] methodTypes) {\n"); Printf(proxy_class_code, " global::System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(methodName, global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, methodTypes, null);\n"); Printf(proxy_class_code, " bool hasDerivedMethod = methodInfo.DeclaringType.IsSubclassOf(typeof(%s));\n", proxy_class_name); @@ -1798,8 +1798,8 @@ public: String *upcast_method = Swig_name_member(getNSpace(), proxy_class_name, smartptr != 0 ? "SWIGSmartPtrUpcast" : "SWIGUpcast"); String *wname = Swig_name_wrapper(upcast_method); - Printv(imclass_cppcasts_code, "\n [DllImport(\"", dllimport, "\", EntryPoint=\"", wname, "\")]\n", NIL); - Printf(imclass_cppcasts_code, " public static extern IntPtr %s(IntPtr jarg1);\n", upcast_method); + Printv(imclass_cppcasts_code, "\n [global::System.Runtime.InteropServices.DllImport(\"", dllimport, "\", EntryPoint=\"", wname, "\")]\n", NIL); + Printf(imclass_cppcasts_code, " public static extern global::System.IntPtr %s(global::System.IntPtr jarg1);\n", upcast_method); Replaceall(imclass_cppcasts_code, "$csclassname", proxy_class_name); @@ -3387,8 +3387,8 @@ public: if (nspace) Insert(qualified_classname, 0, NewStringf("%s.", nspace)); - Printv(imclass_class_code, "\n [DllImport(\"", dllimport, "\", EntryPoint=\"", wname, "\")]\n", NIL); - Printf(imclass_class_code, " public static extern void %s(HandleRef jarg1", swig_director_connect); + Printv(imclass_class_code, "\n [global::System.Runtime.InteropServices.DllImport(\"", dllimport, "\", EntryPoint=\"", wname, "\")]\n", NIL); + Printf(imclass_class_code, " public static extern void %s(global::System.Runtime.InteropServices.HandleRef jarg1", swig_director_connect); Wrapper *code_wrap = NewWrapper(); Printf(code_wrap->def, "SWIGEXPORT void SWIGSTDCALL %s(void *objarg", wname); @@ -3917,7 +3917,7 @@ public: Printf(director_delegate_definitions, " SwigDelegate%s_%s(%s);\n", classname, methid, delegate_parms); Printf(director_delegate_instances, " private SwigDelegate%s_%s swigDelegate%s;\n", classname, methid, methid); - Printf(director_method_types, " private static Type[] swigMethodTypes%s = new Type[] { %s };\n", methid, proxy_method_types); + Printf(director_method_types, " private static global::System.Type[] swigMethodTypes%s = new global::System.Type[] { %s };\n", methid, proxy_method_types); Printf(director_connect_parms, "SwigDirector%s%s delegate%s", classname, methid, methid); } From 8da4d6712d3d0170d4f85813796f2e4c42c643b5 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 17 Oct 2013 21:54:58 +0100 Subject: [PATCH 156/481] Fix Visual Studio compile error in C++ wrappers due to #include within extern "C" block. Fixes SF #1340 --- CHANGES.current | 4 ++++ Lib/r/rrun.swg | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGES.current b/CHANGES.current index 9621a4952..8989ee194 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,10 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2013-10-17: wsfulton + [R] Fix SF #1340 - Visual Studio compile error in C++ wrappers due to #include + within extern "C" block. + 2013-10-17: wsfulton [Python] Fix SF #1345 - Missing #include for offsetof when using -builtin. diff --git a/Lib/r/rrun.swg b/Lib/r/rrun.swg index f8bc9f497..990443e23 100644 --- a/Lib/r/rrun.swg +++ b/Lib/r/rrun.swg @@ -1,5 +1,6 @@ #ifdef __cplusplus +#include extern "C" { #endif @@ -369,7 +370,6 @@ SWIG_R_ConvertPacked(SEXP obj, void *ptr, size_t sz, swig_type_info *ty) { } #ifdef __cplusplus -#include #define SWIG_exception_noreturn(code, msg) do { throw std::runtime_error(msg); } while(0) #else #define SWIG_exception_noreturn(code, msg) do { return result; } while(0) From 48eed4f9e4734b6611e0867ef9c71f76accca352 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 18 Oct 2013 06:49:20 +0100 Subject: [PATCH 157/481] Fix unused variable warning in Ruby wrappers when using gcc -Wall --- Lib/ruby/rubyprimtypes.swg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/ruby/rubyprimtypes.swg b/Lib/ruby/rubyprimtypes.swg index df72e97f4..aa4f7ad37 100644 --- a/Lib/ruby/rubyprimtypes.swg +++ b/Lib/ruby/rubyprimtypes.swg @@ -193,7 +193,7 @@ SWIG_AsVal_dec(unsigned long long)(VALUE obj, unsigned long long *val) } %fragment(SWIG_AsVal_frag(double),"header",fragment="SWIG_ruby_failed") { -%ruby_aux_method(double, NUM2DBL, NUM2DBL(obj)) +%ruby_aux_method(double, NUM2DBL, NUM2DBL(obj); (void)type) SWIGINTERN int SWIG_AsVal_dec(double)(VALUE obj, double *val) From 152905e19372bd2e5bc6dcb5111f575e87a9850c Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 18 Oct 2013 06:53:02 +0100 Subject: [PATCH 158/481] Fix gcc -Waddress warning in variables examples --- Examples/csharp/variables/example.c | 2 +- Examples/d/variables/example.c | 2 +- Examples/go/variables/example.c | 2 +- Examples/java/variables/example.c | 2 +- Examples/lua/variables/example.c | 2 +- Examples/octave/variables/example.c | 2 +- Examples/perl5/variables/example.c | 2 +- Examples/php/variables/example.c | 2 +- Examples/python/variables/example.c | 2 +- Examples/ruby/variables/example.c | 2 +- Examples/tcl/variables/example.c | 2 +- 11 files changed, 11 insertions(+), 11 deletions(-) diff --git a/Examples/csharp/variables/example.c b/Examples/csharp/variables/example.c index aa4ffe9b3..05e17c8c5 100644 --- a/Examples/csharp/variables/example.c +++ b/Examples/csharp/variables/example.c @@ -51,7 +51,7 @@ void print_vars() { printf("dvar = %g\n", dvar); printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); - printf("cstrvar = %s\n", cstrvar ? cstrvar : "(null)"); + printf("cstrvar = %s\n", cstrvar); printf("iptrvar = %p\n", iptrvar); printf("name = %s\n", name); printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); diff --git a/Examples/d/variables/example.c b/Examples/d/variables/example.c index 1bf9c120f..3b4e9f346 100644 --- a/Examples/d/variables/example.c +++ b/Examples/d/variables/example.c @@ -51,7 +51,7 @@ void print_vars() { printf("dvar = %g\n", dvar); printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); - printf("cstrvar = %s\n", cstrvar ? cstrvar : "(null)"); + printf("cstrvar = %s\n", cstrvar); printf("iptrvar = %p\n", iptrvar); printf("name = %s\n", name); printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); diff --git a/Examples/go/variables/example.c b/Examples/go/variables/example.c index aa4ffe9b3..05e17c8c5 100644 --- a/Examples/go/variables/example.c +++ b/Examples/go/variables/example.c @@ -51,7 +51,7 @@ void print_vars() { printf("dvar = %g\n", dvar); printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); - printf("cstrvar = %s\n", cstrvar ? cstrvar : "(null)"); + printf("cstrvar = %s\n", cstrvar); printf("iptrvar = %p\n", iptrvar); printf("name = %s\n", name); printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); diff --git a/Examples/java/variables/example.c b/Examples/java/variables/example.c index aa4ffe9b3..05e17c8c5 100644 --- a/Examples/java/variables/example.c +++ b/Examples/java/variables/example.c @@ -51,7 +51,7 @@ void print_vars() { printf("dvar = %g\n", dvar); printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); - printf("cstrvar = %s\n", cstrvar ? cstrvar : "(null)"); + printf("cstrvar = %s\n", cstrvar); printf("iptrvar = %p\n", iptrvar); printf("name = %s\n", name); printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); diff --git a/Examples/lua/variables/example.c b/Examples/lua/variables/example.c index aa4ffe9b3..05e17c8c5 100644 --- a/Examples/lua/variables/example.c +++ b/Examples/lua/variables/example.c @@ -51,7 +51,7 @@ void print_vars() { printf("dvar = %g\n", dvar); printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); - printf("cstrvar = %s\n", cstrvar ? cstrvar : "(null)"); + printf("cstrvar = %s\n", cstrvar); printf("iptrvar = %p\n", iptrvar); printf("name = %s\n", name); printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); diff --git a/Examples/octave/variables/example.c b/Examples/octave/variables/example.c index 15dcc1b8e..e2b72e0ea 100644 --- a/Examples/octave/variables/example.c +++ b/Examples/octave/variables/example.c @@ -51,7 +51,7 @@ void print_vars() { printf("dvar = %g\n", dvar); printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); - printf("cstrvar = %s\n", cstrvar ? cstrvar : "(null)"); + printf("cstrvar = %s\n", cstrvar); printf("iptrvar = %p\n", iptrvar); printf("name = %s\n", name); printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); diff --git a/Examples/perl5/variables/example.c b/Examples/perl5/variables/example.c index aa4ffe9b3..05e17c8c5 100644 --- a/Examples/perl5/variables/example.c +++ b/Examples/perl5/variables/example.c @@ -51,7 +51,7 @@ void print_vars() { printf("dvar = %g\n", dvar); printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); - printf("cstrvar = %s\n", cstrvar ? cstrvar : "(null)"); + printf("cstrvar = %s\n", cstrvar); printf("iptrvar = %p\n", iptrvar); printf("name = %s\n", name); printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); diff --git a/Examples/php/variables/example.c b/Examples/php/variables/example.c index 3114c7c5f..b21dee32d 100644 --- a/Examples/php/variables/example.c +++ b/Examples/php/variables/example.c @@ -51,7 +51,7 @@ void print_vars() { printf("dvar = %g\n", dvar); printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); - printf("cstrvar = %s\n", cstrvar ? cstrvar : "(null)"); + printf("cstrvar = %s\n", cstrvar); printf("iptrvar = %p\n", iptrvar); printf("name = %c%c%c%c%c\n", name[0],name[1],name[2],name[3],name[4]); printf("ptptr = %p %s\n", ptptr, Point_print( ptptr ) ); diff --git a/Examples/python/variables/example.c b/Examples/python/variables/example.c index aa4ffe9b3..05e17c8c5 100644 --- a/Examples/python/variables/example.c +++ b/Examples/python/variables/example.c @@ -51,7 +51,7 @@ void print_vars() { printf("dvar = %g\n", dvar); printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); - printf("cstrvar = %s\n", cstrvar ? cstrvar : "(null)"); + printf("cstrvar = %s\n", cstrvar); printf("iptrvar = %p\n", iptrvar); printf("name = %s\n", name); printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); diff --git a/Examples/ruby/variables/example.c b/Examples/ruby/variables/example.c index aa4ffe9b3..05e17c8c5 100644 --- a/Examples/ruby/variables/example.c +++ b/Examples/ruby/variables/example.c @@ -51,7 +51,7 @@ void print_vars() { printf("dvar = %g\n", dvar); printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); - printf("cstrvar = %s\n", cstrvar ? cstrvar : "(null)"); + printf("cstrvar = %s\n", cstrvar); printf("iptrvar = %p\n", iptrvar); printf("name = %s\n", name); printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); diff --git a/Examples/tcl/variables/example.c b/Examples/tcl/variables/example.c index aa4ffe9b3..05e17c8c5 100644 --- a/Examples/tcl/variables/example.c +++ b/Examples/tcl/variables/example.c @@ -51,7 +51,7 @@ void print_vars() { printf("dvar = %g\n", dvar); printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); - printf("cstrvar = %s\n", cstrvar ? cstrvar : "(null)"); + printf("cstrvar = %s\n", cstrvar); printf("iptrvar = %p\n", iptrvar); printf("name = %s\n", name); printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); From 1c5246ad667c86b869d9be2cf75e43513aec59ba Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 18 Oct 2013 18:13:11 +0100 Subject: [PATCH 159/481] Fix some gcc -Wall unused warnings in the Ruby wrappers Fixes SF bug 1333. --- Lib/ruby/rubycontainer.swg | 1 - Lib/ruby/rubyrun.swg | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/Lib/ruby/rubycontainer.swg b/Lib/ruby/rubycontainer.swg index d4eaa5f73..dd6389ce4 100644 --- a/Lib/ruby/rubycontainer.swg +++ b/Lib/ruby/rubycontainer.swg @@ -805,7 +805,6 @@ namespace swig rb_raise( rb_eTypeError, "not a valid index or range" ); } - VALUE r = Qnil; static ID id_end = rb_intern("end"); static ID id_start = rb_intern("begin"); static ID id_noend = rb_intern("exclude_end?"); diff --git a/Lib/ruby/rubyrun.swg b/Lib/ruby/rubyrun.swg index e851b1801..c3e0b749b 100644 --- a/Lib/ruby/rubyrun.swg +++ b/Lib/ruby/rubyrun.swg @@ -151,14 +151,13 @@ SWIG_Ruby_InitRuntime(void) SWIGRUNTIME void SWIG_Ruby_define_class(swig_type_info *type) { - VALUE klass; char *klass_name = (char *) malloc(4 + strlen(type->name) + 1); sprintf(klass_name, "TYPE%s", type->name); if (NIL_P(_cSWIG_Pointer)) { _cSWIG_Pointer = rb_define_class_under(_mSWIG, "Pointer", rb_cObject); rb_undef_method(CLASS_OF(_cSWIG_Pointer), "new"); } - klass = rb_define_class_under(_mSWIG, klass_name, _cSWIG_Pointer); + rb_define_class_under(_mSWIG, klass_name, _cSWIG_Pointer); free((void *) klass_name); } From d15220cba49d1fcc46fc913c1869285a4edf7e65 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 18 Oct 2013 19:10:42 +0100 Subject: [PATCH 160/481] Remove a couple of unused variable warnings in generated code --- Lib/guile/guile_scm_run.swg | 15 +++------------ Lib/guile/std_vector.i | 4 ---- Source/Modules/php.cxx | 1 - 3 files changed, 3 insertions(+), 17 deletions(-) diff --git a/Lib/guile/guile_scm_run.swg b/Lib/guile/guile_scm_run.swg index 0ac51f919..2f8f3ae98 100644 --- a/Lib/guile/guile_scm_run.swg +++ b/Lib/guile/guile_scm_run.swg @@ -446,13 +446,8 @@ SWIG_Guile_Init () SWIGINTERN swig_module_info * SWIG_Guile_GetModule(void *SWIGUNUSEDPARM(clientdata)) { - SCM module; - SCM variable; - - module = SWIG_Guile_Init(); - - variable = scm_module_variable(module, - scm_from_locale_symbol("swig-type-list-address" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME)); + SCM module = SWIG_Guile_Init(); + SCM variable = scm_module_variable(module, scm_from_locale_symbol("swig-type-list-address" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME)); if (scm_is_false(variable)) { return NULL; } else { @@ -463,11 +458,7 @@ SWIG_Guile_GetModule(void *SWIGUNUSEDPARM(clientdata)) SWIGINTERN void SWIG_Guile_SetModule(swig_module_info *swig_module) { - SCM module; - SCM variable; - - module = SWIG_Guile_Init(); - + SCM module = SWIG_Guile_Init(); scm_module_define(module, scm_from_locale_symbol("swig-type-list-address" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME), scm_from_ulong((unsigned long) swig_module)); diff --git a/Lib/guile/std_vector.i b/Lib/guile/std_vector.i index 79c716b10..1c55239c1 100644 --- a/Lib/guile/std_vector.i +++ b/Lib/guile/std_vector.i @@ -306,7 +306,6 @@ namespace std { $1 = 1; } else { /* check the first element only */ - T* x; SCM o = scm_vector_ref($input,scm_from_ulong(0)); $1 = CHECK(o) ? 1 : 0; } @@ -315,7 +314,6 @@ namespace std { $1 = 1; } else if (scm_is_pair($input)) { /* check the first element only */ - T* x; SCM head = SCM_CAR($input); $1 = CHECK(head) ? 1 : 0; } else { @@ -335,7 +333,6 @@ namespace std { $1 = 1; } else { /* check the first element only */ - T* x; SCM o = scm_vector_ref($input,scm_from_ulong(0)); $1 = CHECK(o) ? 1 : 0; } @@ -344,7 +341,6 @@ namespace std { $1 = 1; } else if (scm_is_pair($input)) { /* check the first element only */ - T* x; SCM head = SCM_CAR($input); $1 = CHECK(head) ? 1 : 0; } else { diff --git a/Source/Modules/php.cxx b/Source/Modules/php.cxx index 4ade67250..def917019 100644 --- a/Source/Modules/php.cxx +++ b/Source/Modules/php.cxx @@ -443,7 +443,6 @@ public: Append(s_header, " zval **args[2];\n"); Append(s_header, " swig_object_wrapper *value;\n"); Append(s_header, " int type;\n"); - Append(s_header, " int thisown;\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"); From 3720b4884756457ebc6bfaa4020440729e6d1512 Mon Sep 17 00:00:00 2001 From: "Brant K. Kyser" Date: Mon, 21 Oct 2013 13:13:47 -0500 Subject: [PATCH 161/481] Add support for SWIG2_CSHARP macro to create SWIG 2 backwards compatability mode. --- Examples/test-suite/csharp/Makefile.in | 2 + .../test-suite/csharp_swig2_compatability.i | 48 +++++++++++++++++++ Lib/csharp/csharp.swg | 18 +++++++ 3 files changed, 68 insertions(+) create mode 100644 Examples/test-suite/csharp_swig2_compatability.i diff --git a/Examples/test-suite/csharp/Makefile.in b/Examples/test-suite/csharp/Makefile.in index 91b8144de..4bf896385 100644 --- a/Examples/test-suite/csharp/Makefile.in +++ b/Examples/test-suite/csharp/Makefile.in @@ -14,6 +14,7 @@ top_builddir = ../@top_builddir@ CPP_TEST_CASES = \ csharp_attributes \ + csharp_swig2_compatability \ csharp_exceptions \ csharp_features \ csharp_lib_arrays \ @@ -36,6 +37,7 @@ CSHARPFLAGSSPECIAL = # Custom tests - tests with additional commandline options intermediary_classname.cpptest: SWIGOPT += -dllimport intermediary_classname csharp_lib_arrays.cpptest: CSHARPFLAGSSPECIAL = -unsafe +csharp_swig2_compatability.cpptest: SWIGOPT += -DSWIG2_CSHARP # Rules for the different types of tests %.cpptest: diff --git a/Examples/test-suite/csharp_swig2_compatability.i b/Examples/test-suite/csharp_swig2_compatability.i new file mode 100644 index 000000000..70a62647b --- /dev/null +++ b/Examples/test-suite/csharp_swig2_compatability.i @@ -0,0 +1,48 @@ +%module csharp_swig2_compatability + +%typemap(cscode) Foo %{ + +// Without the using directives generated by the +// SWIG 2 compatability mode, this code would fail +// to build. +public void FooBar(string input) +{ + Console.WriteLine(input); +} + +%} + +%pragma(csharp) imclasscode=%{ + +// Without the using directives generated by the +// SWIG 2 compatability mode, this code would fail +// to build. +public void IntermediateClassMethod(string input) +{ + Console.WriteLine(input); +} + +%} + +%pragma(csharp) modulecode=%{ + +// Without the using directives generated by the +// SWIG 2 compatability mode, this code would fail +// to build. +public void ModuleClassMethod(string input) +{ + Console.WriteLine(input); +} + +%} + +%inline %{ +class Foo { +public: + Foo() {} + + void Bar() {} +}; + +%} + diff --git a/Lib/csharp/csharp.swg b/Lib/csharp/csharp.swg index 7bd660f4d..d6943d30b 100644 --- a/Lib/csharp/csharp.swg +++ b/Lib/csharp/csharp.swg @@ -11,6 +11,24 @@ * The imtype typemap contains the C# type used in the intermediary class. * The cstype typemap contains the C# type used in the C# proxy classes, type wrapper classes and module class. */ +/* SWIG 3 no longer inserts using directives into generated C# code. For backwards compatability, the SWIG2_CSHARP + macro can be defined to have SWIG 3 generate using directives similar to those generated by SWIG 2. */ +#ifdef SWIG2_CSHARP + +%typemap(csimports) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "\nusing global::System;\nusing global::System.Runtime.InteropServices;\n" + +%pragma(csharp) moduleimports=%{ +using global::System; +using global::System.Runtime.InteropServices; +%} + +%pragma(csharp) imclassimports=%{ +using global::System; +using global::System.Runtime.InteropServices; +%} + +#endif + /* Fragments */ %fragment("SWIG_PackData", "header") { From ec1d5a5be1c7cdaaa8dedc3ba76a5792127cef0f Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 21 Oct 2013 21:36:07 +0100 Subject: [PATCH 162/481] Correct guile help for -Linkage. -linkage does not work (it clashes with the generic -l option). --- Source/Modules/guile.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/Modules/guile.cxx b/Source/Modules/guile.cxx index 2c48ba319..3a82d67d8 100644 --- a/Source/Modules/guile.cxx +++ b/Source/Modules/guile.cxx @@ -24,7 +24,7 @@ Guile Options (available with -guile)\n\ -exportprimitive - Add the (export ...) code from scmstub into the\n\ GOOPS file.\n\ -goopsprefix - Prepend to all goops identifiers\n\ - -linkage - Use linkage protocol (default `simple')\n\ + -Linkage - Use linkage protocol (default `simple')\n\ Use `module' for native Guile module linking\n\ (requires Guile >= 1.5.0). Use `passive' for\n\ passive linking (no C-level module-handling code),\n\ From 29c98fa7f839bbeb82be4cc64df41dba62ce9b73 Mon Sep 17 00:00:00 2001 From: "Brant K. Kyser" Date: Tue, 22 Oct 2013 11:52:00 -0500 Subject: [PATCH 163/481] Update documentation to reflect fully qualifying the use of .NET types in the generated code. --- Doc/Manual/CSharp.html | 146 +++++++++++++++++++++-------------------- 1 file changed, 76 insertions(+), 70 deletions(-) diff --git a/Doc/Manual/CSharp.html b/Doc/Manual/CSharp.html index 6df2594c4..b620b3513 100644 --- a/Doc/Manual/CSharp.html +++ b/Doc/Manual/CSharp.html @@ -10,6 +10,9 @@
    • Introduction +
    • Differences to the Java module
    • Void pointers
    • C# Arrays @@ -69,6 +72,12 @@ The Microsoft Developer Network (MSDN) h Monodoc, available from the Mono project, has a very useful section titled Interop with native libraries.

      +

      19.1.1 SWIG 2 Compatability

      + +

      +In order to minimize name collisions between names generated based on input to SWIG and names used in the generated code from the .NET framework, SWIG 3 fully qualifies the use of all .NET types. Furthermore, SWIG 3 avoids using directives in generated code. This breaks backwards compatability with typemaps, pragmas, etc written for use with SWIG 2 that assume the presence of using System; or using System.Runtime.InteropServices; directives in the intermediate class imports, module imports, or proxy imports. SWIG 3 supports backwards compatability though the use of the SWIG2_CSHARP macro. If SWIG2_CSHARP is defined, SWIG 3 generates using directives in the intermediate class, module class, and proxy class code similar to those generated by SWIG 2. This can be done without modifying any of the input code by passing the -DSWIG2_CSHARP commandline parameter when executing swig. +

      +

      19.2 Differences to the Java module

      @@ -262,7 +271,7 @@ An example shows that char * could be marshalled in different ways,
      -%typemap(imtype, out="IntPtr") char * "string"
      +%typemap(imtype, out="global::System.IntPtr") char * "string"
       char * function(char *);
       
      @@ -273,7 +282,7 @@ The output type is thus IntPtr and the input type is string. The resulting inter
      -public static extern IntPtr function(string jarg1);
      +public static extern global::System.IntPtr function(string jarg1);
       
      @@ -294,8 +303,8 @@ For example:
       %typemap(imtype,
      -         inattributes="[MarshalAs(UnmanagedType.LPStr)]",
      -         outattributes="[return: MarshalAs(UnmanagedType.LPStr)]") const char * "String"
      +         inattributes="[global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPStr)]",
      +         outattributes="[return: global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPStr)]") const char * "String"
       
       const char * GetMsg() {}
       void SetMsg(const char *msg) {}
      @@ -310,12 +319,12 @@ The intermediary class will then have the marshalling as specified by everything
       
       class examplePINVOKE {
         ...
      -  [DllImport("example", EntryPoint="CSharp_GetMsg")]
      -  [return: MarshalAs(UnmanagedType.LPStr)]
      +  [global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_GetMsg")]
      +  [return: global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPStr)]
         public static extern String GetMsg();
       
      -  [DllImport("example", EntryPoint="CSharp_SetMsg")]
      -  public static extern void SetMsg([MarshalAs(UnmanagedType.LPStr)]String jarg1);
      +  [global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_SetMsg")]
      +  public static extern void SetMsg([global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPStr)]String jarg1);
       }
       
      @@ -368,7 +377,7 @@ will generate a C# proxy class:
       [ThreadSafe]
      -public class AClass : IDisposable {
      +public class AClass : global::System.IDisposable {
         ...
         [ThreadSafe(false)]
         public AClass(double a) ...
      @@ -392,9 +401,9 @@ An example for attaching attributes to the enum and enum values is shown below.
       
       
      -%typemap(csattributes) Couleur "[System.ComponentModel.Description(\"Colours\")]"
      -%csattributes Rouge "[System.ComponentModel.Description(\"Red\")]"
      -%csattributes Vert "[System.ComponentModel.Description(\"Green\")]"
      +%typemap(csattributes) Couleur "[global::System.ComponentModel.Description(\"Colours\")]"
      +%csattributes Rouge "[global::System.ComponentModel.Description(\"Red\")]"
      +%csattributes Vert "[global::System.ComponentModel.Description(\"Green\")]"
       %inline %{
         enum Couleur { Rouge, Orange, Vert };
       %}
      @@ -407,12 +416,12 @@ which will result in the following C# enum:
       
       
      -[System.ComponentModel.Description("Colours")]
      +[global::System.ComponentModel.Description("Colours")]
       public enum Couleur {
      -  [System.ComponentModel.Description("Red")]
      +  [global::System.ComponentModel.Description("Red")]
         Rouge,
         Orange,
      -  [System.ComponentModel.Description("Green")]
      +  [global::System.ComponentModel.Description("Green")]
         Vert
       }
       
      @@ -618,9 +627,9 @@ marshalling for the arrays:
      -[DllImport("example", EntryPoint="CSharp_myArrayCopy")]
      -public static extern void myArrayCopy([In, MarshalAs(UnmanagedType.LPArray)]int[] jarg1, 
      -                                      [Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2,
      +[global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_myArrayCopy")]
      +public static extern void myArrayCopy([global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg1, 
      +                                      [global::System.Runtime.InteropServices.Out, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg2,
                                              int jarg3);
       
      @@ -668,9 +677,9 @@ and intermediary class method
      -  [DllImport("example", EntryPoint="CSharp_myArraySwap")]
      -  public static extern void myArraySwap([In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg1, 
      -                                        [In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2,
      +  [global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_myArraySwap")]
      +  public static extern void myArraySwap([global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.Out, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg1, 
      +                                        [global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.Out, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg2,
                                                int jarg3);
       
      @@ -743,7 +752,7 @@ As a result, we get the following method in the module class: fixed ( int *swig_ptrTo_sourceArray = sourceArray ) { fixed ( int *swig_ptrTo_targetArray = targetArray ) { { - examplePINVOKE.myArrayCopy((IntPtr)swig_ptrTo_sourceArray, (IntPtr)swig_ptrTo_targetArray, + examplePINVOKE.myArrayCopy((global::System.IntPtr)swig_ptrTo_sourceArray, (global::System.IntPtr)swig_ptrTo_targetArray, nitems); } } @@ -764,8 +773,8 @@ example - the method is expecting an IntPtr as the parameter type.
      -[DllImport("example", EntryPoint="CSharp_myArrayCopy")]
      -public static extern void myArrayCopy(IntPtr jarg1, IntPtr jarg2, int jarg3);
      +[global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_myArrayCopy")]
      +public static extern void myArrayCopy(global::System.IntPtr jarg1, global::System.IntPtr jarg2, int jarg3);
       
      @@ -1220,7 +1229,7 @@ the C# code can be generated into the intermediary class using the imclassco static CustomExceptionDelegate customDelegate = new CustomExceptionDelegate(SetPendingCustomException); - [DllImport("$dllimport", EntryPoint="CustomExceptionRegisterCallback")] + [global::System.Runtime.InteropServices.DllImport("$dllimport", EntryPoint="CustomExceptionRegisterCallback")] public static extern void CustomExceptionRegisterCallback(CustomExceptionDelegate customCallback); @@ -1264,7 +1273,7 @@ The boiler plate code above must be used in addition to a handcrafted Custom
       // Custom C# Exception
      -class CustomApplicationException : System.ApplicationException {
      +class CustomApplicationException : global::System.ApplicationException {
         public CustomApplicationException(string message) 
           : base(message) {
         }
      @@ -1457,20 +1466,17 @@ Below is the generated C# Base director class.
       
       
      -using System;
      -using System.Runtime.InteropServices;
      -
      -public class Base : IDisposable {
      -  private HandleRef swigCPtr;
      +public class Base : global::System.IDisposable {
      +  private global::System.Runtime.InteropServices.HandleRef swigCPtr;
         protected bool swigCMemOwn;
       
      -  internal Base(IntPtr cPtr, bool cMemoryOwn) {
      +  internal Base(global::System.IntPtr cPtr, bool cMemoryOwn) {
           swigCMemOwn = cMemoryOwn;
      -    swigCPtr = new HandleRef(this, cPtr);
      +    swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr);
         }
       
      -  internal static HandleRef getCPtr(Base obj) {
      -    return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
      +  internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Base obj) {
      +    return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
         }
       
         ~Base() {
      @@ -1479,12 +1485,12 @@ public class Base : IDisposable {
       
         public virtual void Dispose() {
           lock(this) {
      -      if(swigCPtr.Handle != IntPtr.Zero && swigCMemOwn) {
      +      if(swigCPtr.Handle != global::System.IntPtr.Zero && swigCMemOwn) {
               swigCMemOwn = false;
               examplePINVOKE.delete_Base(swigCPtr);
             }
      -      swigCPtr = new HandleRef(null, IntPtr.Zero);
      -      GC.SuppressFinalize(this);
      +      swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
      +      global::System.GC.SuppressFinalize(this);
           }
         }
       
      @@ -1511,7 +1517,7 @@ public class Base : IDisposable {
           examplePINVOKE.Base_director_connect(swigCPtr, swigDelegate0, swigDelegate1);
         }
       
      -  private bool SwigDerivedClassHasMethod(string methodName, Type[] methodTypes) {
      +  private bool SwigDerivedClassHasMethod(string methodName, global::System.global::System.Type[] methodTypes) {
           System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(methodName, methodTypes);
           bool hasDerivedMethod = methodInfo.DeclaringType.IsSubclassOf(typeof(Base));
           return hasDerivedMethod;
      @@ -1521,18 +1527,18 @@ public class Base : IDisposable {
           return UIntMethod(x);
         }
       
      -  private void SwigDirectorBaseBoolMethod(IntPtr b, bool flag) {
      +  private void SwigDirectorBaseBoolMethod(global::System.IntPtr b, bool flag) {
           BaseBoolMethod(new Base(b, false), flag);
         }
       
         internal delegate uint SwigDelegateBase_0(uint x);
      -  internal delegate void SwigDelegateBase_1(IntPtr b, bool flag);
      +  internal delegate void SwigDelegateBase_1(global::System.IntPtr b, bool flag);
       
         private SwigDelegateBase_0 swigDelegate0;
         private SwigDelegateBase_1 swigDelegate1;
       
      -  private static Type[] swigMethodTypes0 = new Type[] { typeof(uint) };
      -  private static Type[] swigMethodTypes1 = new Type[] { typeof(Base), typeof(bool) };
      +  private static global::System.Type[] swigMethodTypes0 = new global::System.Type[] { typeof(uint) };
      +  private static global::System.Type[] swigMethodTypes1 = new global::System.Type[] { typeof(Base), typeof(bool) };
       }
       
      @@ -1755,9 +1761,9 @@ and the following usage from C# after running the code through SWIG: Wheel wheel = new Bike(10).getWheel(); Console.WriteLine("wheel size: " + wheel.size); // Simulate a garbage collection - System.GC.Collect(); - System.GC.WaitForPendingFinalizers(); - Console.WriteLine("wheel size: " + wheel.size); + global::System.GC.Collect(); + global::System.GC.WaitForPendingFinalizers(); + global::System.Console.WriteLine("wheel size: " + wheel.size);
      @@ -1795,9 +1801,9 @@ is called using the following typemaps. // of dangling C++ pointer. Intended for methods that return pointers or // references to a member variable. %typemap(csout, excode=SWIGEXCODE) Wheel& getWheel { - IntPtr cPtr = $imcall;$excode + global::System.IntPtr cPtr = $imcall;$excode $csclassname ret = null; - if (cPtr != IntPtr.Zero) { + if (cPtr != global::System.IntPtr.Zero) { ret = new $csclassname(cPtr, $owner); ret.addReference(this); } @@ -1813,7 +1819,7 @@ The code in the second typemap constitutes the bulk of the code in the generated
      -public class Wheel : IDisposable {
      +public class Wheel : global::System.IDisposable {
         ...
         // Ensure that the GC doesn't collect any Bike instance set from C#
         private Bike bikeReference;
      @@ -1822,12 +1828,12 @@ public class Wheel : IDisposable {
         }
       }
       
      -public class Bike : IDisposable {
      +public class Bike : global::System.IDisposable {
         ...
         public Wheel getWheel() {
      -    IntPtr cPtr = examplePINVOKE.Bike_getWheel(swigCPtr);
      +    global::System.IntPtr cPtr = examplePINVOKE.Bike_getWheel(swigCPtr);
           Wheel ret = null;
      -    if (cPtr != IntPtr.Zero) {
      +    if (cPtr != global::System.IntPtr.Zero) {
             ret = new Wheel(cPtr, false);
             ret.addReference(this);
           }
      @@ -1904,9 +1910,9 @@ In order to understand why, consider a garbage collection occuring...
             container.setElement(element);
             Console.WriteLine("element.value: " + container.getElement().value);
             // Simulate a garbage collection
      -      System.GC.Collect();
      -      System.GC.WaitForPendingFinalizers();
      -      Console.WriteLine("element.value: " + container.getElement().value);
      +      global::System.GC.Collect();
      +      global::System.GC.WaitForPendingFinalizers();
      +      global::System.Console.WriteLine("element.value: " + container.getElement().value);
       
      @@ -1918,14 +1924,14 @@ One solution is to add in the appropriate references in the C# layer...
      -public class Container : IDisposable {
      +public class Container : global::System.IDisposable {
       
         ...
       
         // Ensure that the GC doesn't collect any Element set from C#
         // as the underlying C++ class stores a shallow copy
         private Element elementReference;
      -  private HandleRef getCPtrAndAddReference(Element element) {
      +  private global::System.Runtime.InteropServices.HandleRef getCPtrAndAddReference(Element element) {
           elementReference = element;
           return Element.getCPtr(element);
         }
      @@ -1951,7 +1957,7 @@ The 'cscode' typemap simply adds in the specified code into the C# proxy class.
         // Ensure that the GC doesn't collect any Element set from C#
         // as the underlying C++ class stores a shallow copy
         private Element elementReference;
      -  private HandleRef getCPtrAndAddReference(Element element) {
      +  private global::System.Runtime.InteropServices.HandleRef getCPtrAndAddReference(Element element) {
           elementReference = element;
           return Element.getCPtr(element);
         }
      @@ -2000,7 +2006,7 @@ First let's look at the code that is generated by default, where the C# proxy cl
       
       
      -public class Action : IDisposable {
      +public class Action : global::System.IDisposable {
         ...
         public Action(CDate dateIn, CDate dateOut) 
             : this(examplePINVOKE.new_Action(CDate.getCPtr(dateIn), CDate.getCPtr(dateOut)), true) {
      @@ -2081,7 +2087,7 @@ The resulting generated proxy code in the Action class follows:
       
       
      -public class Action : IDisposable {
      +public class Action : global::System.IDisposable {
         ...
         public int doSomething(System.DateTime dateIn, out System.DateTime dateOut) {
           CDate tempdateIn = new CDate(dateIn.Year, dateIn.Month, dateIn.Day);
      @@ -2099,7 +2105,7 @@ public class Action : IDisposable {
           }
         }
       
      -  static private IntPtr SwigConstructAction(System.DateTime dateIn, out System.DateTime dateOut) {
      +  static private global::System.IntPtr SwigConstructAction(System.DateTime dateIn, out System.DateTime dateOut) {
           CDate tempdateIn = new CDate(dateIn.Year, dateIn.Month, dateIn.Day);
           CDate tempdateOut = new CDate();
           try {
      @@ -2299,8 +2305,8 @@ The typemap type required is thus CDate *. Given that the previous sect
       %typemap(csvarout, excode=SWIGEXCODE2) CDate * %{
           /* csvarout typemap code */
           get {
      -      IntPtr cPtr = $imcall;
      -      CDate tempDate = (cPtr == IntPtr.Zero) ? null : new CDate(cPtr, $owner);$excode
      +      global::System.IntPtr cPtr = $imcall;
      +      CDate tempDate = (cPtr == global::System.IntPtr.Zero) ? null : new CDate(cPtr, $owner);$excode
             return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(),
                                        0, 0, 0);
           } %}
      @@ -2322,8 +2328,8 @@ public class example {
           } 
           /* csvarout typemap code */
           get {
      -      IntPtr cPtr = examplePINVOKE.ImportantDate_get();
      -      CDate tempDate = (cPtr == IntPtr.Zero) ? null : new CDate(cPtr, false);
      +      global::System.IntPtr cPtr = examplePINVOKE.ImportantDate_get();
      +      CDate tempDate = (cPtr == global::System.IntPtr.Zero) ? null : new CDate(cPtr, false);
             return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(),
                                        0, 0, 0);
           } 
      @@ -2389,7 +2395,7 @@ The generated proxy class code will then contain the following wrapper for calli
       
       
       ...
      -  private void SwigDirectorsomeCallback(IntPtr date) {
      +  private void SwigDirectorsomeCallback(global::System.IntPtr date) {
           System.DateTime tempdate = new System.DateTime();
           try {
             someCallback(out tempdate);
      @@ -2432,7 +2438,7 @@ The default C# proxy class generated is:
       
       
      -public class ExtendMe : IDisposable {
      +public class ExtendMe : global::System.IDisposable {
         ...
         public int Part1() {
           ...
      @@ -2468,7 +2474,7 @@ The C# proxy class becomes a partial class:
       
       
      -public partial class ExtendMe : IDisposable {
      +public partial class ExtendMe : global::System.IDisposable {
         ...
         public int Part1() {
           ...
      @@ -2483,7 +2489,7 @@ You can then of course declare another part of the partial class elsewhere, for
       
       
      -public partial class ExtendMe : IDisposable {
      +public partial class ExtendMe : global::System.IDisposable {
         public int Part2() {
           return 2;
         }
      @@ -2535,7 +2541,7 @@ The generated C# proxy class will instead be:
       
       
      -public class ExtendMe : IDisposable {
      +public class ExtendMe : global::System.IDisposable {
         ...
         public int Part3() {
           return 3;
      
      From 5f53503b7d7fa62a351edc7d3d579d69c55c9952 Mon Sep 17 00:00:00 2001
      From: "Brant K. Kyser" 
      Date: Tue, 22 Oct 2013 14:08:47 -0500
      Subject: [PATCH 164/481] Correct spelling of compatibility.
      
      ---
       Doc/Manual/CSharp.html                                    | 6 +++---
       Examples/test-suite/csharp/Makefile.in                    | 4 ++--
       ...swig2_compatability.i => csharp_swig2_compatibility.i} | 8 ++++----
       Lib/csharp/csharp.swg                                     | 2 +-
       4 files changed, 10 insertions(+), 10 deletions(-)
       rename Examples/test-suite/{csharp_swig2_compatability.i => csharp_swig2_compatibility.i} (75%)
      
      diff --git a/Doc/Manual/CSharp.html b/Doc/Manual/CSharp.html
      index b620b3513..764a1a6c3 100644
      --- a/Doc/Manual/CSharp.html
      +++ b/Doc/Manual/CSharp.html
      @@ -11,7 +11,7 @@
       
      • Introduction
      • Differences to the Java module
      • Void pointers @@ -72,10 +72,10 @@ The Microsoft Developer Network (MSDN) h Monodoc, available from the Mono project, has a very useful section titled Interop with native libraries.

        -

        19.1.1 SWIG 2 Compatability

        +

        19.1.1 SWIG 2 Compatibility

        -In order to minimize name collisions between names generated based on input to SWIG and names used in the generated code from the .NET framework, SWIG 3 fully qualifies the use of all .NET types. Furthermore, SWIG 3 avoids using directives in generated code. This breaks backwards compatability with typemaps, pragmas, etc written for use with SWIG 2 that assume the presence of using System; or using System.Runtime.InteropServices; directives in the intermediate class imports, module imports, or proxy imports. SWIG 3 supports backwards compatability though the use of the SWIG2_CSHARP macro. If SWIG2_CSHARP is defined, SWIG 3 generates using directives in the intermediate class, module class, and proxy class code similar to those generated by SWIG 2. This can be done without modifying any of the input code by passing the -DSWIG2_CSHARP commandline parameter when executing swig. +In order to minimize name collisions between names generated based on input to SWIG and names used in the generated code from the .NET framework, SWIG 3 fully qualifies the use of all .NET types. Furthermore, SWIG 3 avoids using directives in generated code. This breaks backwards compatibility with typemaps, pragmas, etc written for use with SWIG 2 that assume the presence of using System; or using System.Runtime.InteropServices; directives in the intermediate class imports, module imports, or proxy imports. SWIG 3 supports backwards compatibility though the use of the SWIG2_CSHARP macro. If SWIG2_CSHARP is defined, SWIG 3 generates using directives in the intermediate class, module class, and proxy class code similar to those generated by SWIG 2. This can be done without modifying any of the input code by passing the -DSWIG2_CSHARP commandline parameter when executing swig.

        19.2 Differences to the Java module

        diff --git a/Examples/test-suite/csharp/Makefile.in b/Examples/test-suite/csharp/Makefile.in index 4bf896385..22d78ee1c 100644 --- a/Examples/test-suite/csharp/Makefile.in +++ b/Examples/test-suite/csharp/Makefile.in @@ -14,7 +14,7 @@ top_builddir = ../@top_builddir@ CPP_TEST_CASES = \ csharp_attributes \ - csharp_swig2_compatability \ + csharp_swig2_compatibility \ csharp_exceptions \ csharp_features \ csharp_lib_arrays \ @@ -37,7 +37,7 @@ CSHARPFLAGSSPECIAL = # Custom tests - tests with additional commandline options intermediary_classname.cpptest: SWIGOPT += -dllimport intermediary_classname csharp_lib_arrays.cpptest: CSHARPFLAGSSPECIAL = -unsafe -csharp_swig2_compatability.cpptest: SWIGOPT += -DSWIG2_CSHARP +csharp_swig2_compatibility.cpptest: SWIGOPT += -DSWIG2_CSHARP # Rules for the different types of tests %.cpptest: diff --git a/Examples/test-suite/csharp_swig2_compatability.i b/Examples/test-suite/csharp_swig2_compatibility.i similarity index 75% rename from Examples/test-suite/csharp_swig2_compatability.i rename to Examples/test-suite/csharp_swig2_compatibility.i index 70a62647b..b11a80e68 100644 --- a/Examples/test-suite/csharp_swig2_compatability.i +++ b/Examples/test-suite/csharp_swig2_compatibility.i @@ -1,9 +1,9 @@ -%module csharp_swig2_compatability +%module csharp_swig2_compatibility %typemap(cscode) Foo %{ // Without the using directives generated by the -// SWIG 2 compatability mode, this code would fail +// SWIG 2 compatibility mode, this code would fail // to build. public void FooBar(string input) { @@ -15,7 +15,7 @@ public void FooBar(string input) %pragma(csharp) imclasscode=%{ // Without the using directives generated by the -// SWIG 2 compatability mode, this code would fail +// SWIG 2 compatibility mode, this code would fail // to build. public void IntermediateClassMethod(string input) { @@ -27,7 +27,7 @@ public void IntermediateClassMethod(string input) %pragma(csharp) modulecode=%{ // Without the using directives generated by the -// SWIG 2 compatability mode, this code would fail +// SWIG 2 compatibility mode, this code would fail // to build. public void ModuleClassMethod(string input) { diff --git a/Lib/csharp/csharp.swg b/Lib/csharp/csharp.swg index d6943d30b..70e9fd4b4 100644 --- a/Lib/csharp/csharp.swg +++ b/Lib/csharp/csharp.swg @@ -11,7 +11,7 @@ * The imtype typemap contains the C# type used in the intermediary class. * The cstype typemap contains the C# type used in the C# proxy classes, type wrapper classes and module class. */ -/* SWIG 3 no longer inserts using directives into generated C# code. For backwards compatability, the SWIG2_CSHARP +/* SWIG 3 no longer inserts using directives into generated C# code. For backwards compatibility, the SWIG2_CSHARP macro can be defined to have SWIG 3 generate using directives similar to those generated by SWIG 2. */ #ifdef SWIG2_CSHARP From 6736e74127180f012dab11379a2159cd073461d4 Mon Sep 17 00:00:00 2001 From: Marvin Greenberg Date: Tue, 22 Oct 2013 20:31:14 +0100 Subject: [PATCH 165/481] Add feature director:except for improved director exception handling in Java Closes #91 --- Doc/Manual/Java.html | 276 ++++++++++++++++++ Doc/Manual/Warnings.html | 1 + Examples/test-suite/director_exception.i | 23 ++ Examples/test-suite/java/Makefile.in | 16 +- ...rector_exception_feature_nspace_runme.java | 150 ++++++++++ ...java_director_exception_feature_runme.java | 152 ++++++++++ .../java_director_exception_feature.i | 209 +++++++++++++ .../java_director_exception_feature_nspace.i | 216 ++++++++++++++ Lib/java/director.swg | 240 ++++++++++++++- Lib/java/std_string.i | 3 +- Source/Include/swigwarn.h | 1 + Source/Modules/java.cxx | 233 ++++++++++++--- 12 files changed, 1469 insertions(+), 51 deletions(-) create mode 100644 Examples/test-suite/java/java_director_exception_feature_nspace_runme.java create mode 100644 Examples/test-suite/java/java_director_exception_feature_runme.java create mode 100644 Examples/test-suite/java_director_exception_feature.i create mode 100644 Examples/test-suite/java_director_exception_feature_nspace.i diff --git a/Doc/Manual/Java.html b/Doc/Manual/Java.html index f3d8a1684..0e9ba75de 100644 --- a/Doc/Manual/Java.html +++ b/Doc/Manual/Java.html @@ -87,6 +87,7 @@
      • Simple directors example
      • Director threading issues
      • Director performance tuning +
      • Java Exceptions from Directors
    • Accessing protected members
    • Common customization features @@ -3555,6 +3556,281 @@ However, if all director methods are expected to usually be overridden by Java s The disadvantage is that invocation of director methods from C++ when Java doesn't actually override the method will require an additional call up into Java and back to C++. As such, this option is only useful when overrides are extremely common and instantiation is frequent enough that its performance is critical.

      +

      24.5.7 Java Exceptions from Directors

      + +

      +With directors routing method calls to Java, and proxies routing them +to C++, the handling of exceptions is an important concern. In Swig +2.0, the director class methods ignored java exceptions that occurred +during method calls dispatched to the Java director class and simply +returned '$null' to the C++ caller. The default behavior now throws a +Swig-defined DirectorException C++ exception. A facility +is now provided to allow translation of thrown Java exceptions into +C++ exceptions. This can be done in two different ways using +the %feature("director:except") directive. In the +simplest approach, a code block is attached to each director method to +handle the mapping of java exceptions into C++ exceptions. +

      + +
      +
      +// All the rules to associate a feature with an element apply
      +%feature("director:except") MyClass::method(int x) {
      +  jthrowable $error = jenv->ExceptionOccurred();
      +  if ($error) {
      +    jenv->ExceptionClear();
      +    if (Swig::ExceptionMatches(jenv,$error,"java/lang/IndexOutOfBoundsException"))
      +      throw std::out_of_range(Swig::JavaExceptionMessage(jenv,$error).message());
      +    else if (Swig::ExceptionMatches(jenv,$error,"$packagepath/MyJavaException"))
      +      throw MyCppException(Swig::JavaExceptionMessage(jenv,$error).message());
      +    else
      +      throw std::runtime_error("Unexpected exception thrown by MyClass::method");
      +  }
      +}
      +
      +class MyClass {
      +  void method(int x); /* on C++ side, may get std::runtime_error or MyCppException */
      +}
      +
      +
      +

      +This approach allows mapping java exceptions thrown by director methods into +C++ exceptions, to match the exceptions expected by a C++ caller. There +need not be any exception specification on the method. This approach gives +complete flexibility to map exceptions thrown by a java director +implementation into desired C++ exceptions. The +function Swig::ExceptionMatches +and class Swig::JavaExceptionMessage are provided to simplify +writing code for wrappers that use director:exceptfeature. These simplify +testing the type of the java exception and constructing C++ exceptions. The +function Swig::ExceptionMatches matches the type of the +jthrowable thrown against a fully qualified JNI style class +name, like "java/lang/IOError". If the throwable class is the same +type, or derives from the given type, it returns true. Care must be taken to +provide the correct fully qualified name, since for wrapped exceptions the +generated proxy class will have additional package qualification, depending on +the '-package' argument and use of nspace +feature. The variable $error is simply a unique variable name to allow +assignment of the exception that occurred. The variable $packagepath is +replaced by the outer package provided for swig generation by the -package +option. The class Swig::JavaExceptionMessage is a holder +object giving access to the message from the thrown java exception. +The message() method returns the exception message as a const char *, +which is only valid during the lifetime of the holder. Any code using this message +needs to copy it, for example into a std::string or a newly constructed C++ exception. +

      + +

      +If many methods may throw different exceptions, using this approach to +write handlers for a large number of methods will result in +duplication of the code in the director:except feature +code blocks, and will require separate feature definitions for every +method. So an alternative approach is provided, using typemaps in a +fashion analagous to +the "throws" typemap. The +"throws" typemap provides an approach to automatically map all the C++ +exceptions listed in a method's defined exceptions (either from +an exception specification or a %catches +feature) into Java exceptions, for the generated proxy classes. To +provide the inverse mapping, the directorthrows typemap +is provided. + +

      Using directorthrows typemaps allows a +generic director:except feature to be combined with +method-specific handling to achieve the desired result. The +default director:except feature, in combination +with directorthrows typemaps generate exception mapping +to C++ exceptions for all the exceptions defined for each method. The +default definition is shown below.

      + +
      +
      +%feature("director:except") %{
      +   jthrowable $error = jenv->ExceptionOccurred();
      +   if ($error) {
      +     jenv->ExceptionClear();
      +     $directorthrowshandlers
      +     throw Swig::DirectorException(jenv, $error);
      +   }
      +%}
      +
      +
      + +

      The code generated using the director:except feature +replaces the $directorthrowshandlers with code that throws +appropriate C++ exceptions from directorthrows typemaps +for each exception defined for the method. Just as with +the "throws" typemap, the +possible exceptions may be defined either with an exception +specification ( throw(MyException,std::runtime_error) ) or +using the %catches feature applied to the method.

      + +

      Note: Using the %catches feature to define the +handled exceptions is preferred to using exception specifications. If +the interface is defined with an exception specification the generated +swig proxy classes will have the same exception specification. In C++ +if exceptions other than those in the specification are thrown, the +program will be terminated.

      + +

      Because this default definition maps any unhandled java exceptions to +Swig::DirectorException, any director methods that define exception +specifications will cause program termination. To simply ignore +unexpected exceptions, the default can be changed to: + +

      +
      +%feature("director:except") %{
      +   jthrowable $error = jenv->ExceptionOccurred();
      +   if ($error) {
      +     jenv->ExceptionClear();
      +     $directorthrowshandlers
      +     return $null;
      +   }
      +%}
      +
      +
      +

      + +

      Alternatively an exception compatible with the existing director +method exception specifications may be thrown. Assuming that all +methods allow std::runtime_error to be thrown, +the return $null; could be changed to: + +

      +
      +   throw std::runtime_error(Swig::JavaExceptionMessage(jenv,$error).message());
      +
      +
      +

      + +

      In more complex situations, a separate director:except feature +may need to be attached to specific methods. +

      + +

      Below is a complete example demonstrating the use +of directorthrows typemaps. The directorthrows typemap +provides a code fragment to test for a pending java exception type, and the +resulting C++ exception that will be thrown. In this example, a +generic directorthrows typemap is appropriate for all three exceptions - all +take single string constructors. If the constructors had different constructors, +it would be neccessary to have separate typemaps for each exception type. + + + +

      +
      +// Define exceptions in header section using std::runtime_error
      +%define DEFINE_EXCEPTION(NAME)
      +%{
      +  #include <exception>
      +  namespace MyNS {
      +    struct NAME : public std::runtime_error { NAME(const std::string& what):runtime_error(what) {}; };
      +  }
      +%}
      +%enddef
      +// Expose c++ exceptions as java Exceptions with getMessage
      +%define DECLARE_EXCEPTION(NAME)
      +%typemap(javabase) MyNS::NAME "java.lang.Exception";
      +%rename(getMessage,fullname=1) MyNS::NAME::what;
      +namespace MyNS {
      +  struct NAME {
      +    NAME(const std::string& what);
      +    const char * what();
      +  };
      +}
      +%enddef
      +
      +DEFINE_EXCEPTION(ExceptionA)
      +DEFINE_EXCEPTION(ExceptionB)
      +DEFINE_EXCEPTION(Unknown)
      +
      +// Mark three methods to map director-thrown exceptions.
      +// Standard rules for feature matching apply
      +%feature("director:except") MyClass::meth1(int);
      +%feature("director:except") MyClass::meth2;
      +%feature("director:except") meth3;
      +
      +%typemap(directorthrows) MyNS::ExceptionA, MyNS::ExceptionB, MyNS::Unexpected %{
      +  if (Swig::ExceptionMatches(jenv,$error,"$packagepath/$javaclassname"))
      +    throw $1_type(Swig::JavaExceptionMessage(jenv,$error).message());
      +%}
      +
      +DECLARE_EXCEPTION(ExceptionA)
      +DECLARE_EXCEPTION(ExceptionB)
      +DECLARE_EXCEPTION(Unexpected)
      +
      +%catches(MyNS::ExceptionA, MyNS::ExceptionB, MyNS::Unexpected) MyClass::meth2();
      +
      +%inline {
      +  class MyClass {
      +  public:
      +    virtual void meth1(int x) throw(MyNS::ExceptionA, MyNS::ExceptionB) = 0;
      +    virtual void meth2() = 0;   /* throws MyNS::ExceptionA, MyNS::ExceptionB, MyNS::Unexpected */
      +    virtual void meth3(float x) throw(MyNS::Unexpected) = 0;
      +    virtual ~MyClass() {};
      +  };
      +}
      +
      +
      + +

      +In this case the three different directorthrows typemaps will be used +to generate the three different exception handlers for +meth1, meth2 and meth3. The generated +handlers will have "if" blocks for each exception type specified, in +the exception specification or %catches feature. The code block +in the directorthrows typemap should always throw a c++ exception. +

      + +

      Note that the directorthrows typemaps are important +only if it is important for the the exceptions passed through the C++ +layer to be mapped to distinct C++ exceptions. If director methods +are being called by C++ code that is itself wrapped in a +Swig-generated java wrapper and access is always through this wrapper, +the default Swig::DirectorException class provides enough information +to reconstruct the original exception. In this case removing the +$directorthrowshandlers replacement variable from the +default director:except feature and simply always +throwing a Swig::DirectorException will achieve the desired result. +Along with this a generic exception feature is added to convert any +caught Swig::DirectorExceptions back into the underlying +java exceptions, for each method which may get a generic +DirectorException from a wrapped director method.

      + +
      +
      +%feature ("except",throws="Exception")  MyClass::myMeth %{
      +  try { $action }
      +  catch (Swig::DirectorException & direxcp) {
      +    // jenv always available in JNI code
      +    // raise the java exception that originally caused the DirectorException
      +    direxcp.raiseJavaException(jenv);
      +    return $null;
      +  }
      +%}
      +
      +
      + +

      The throws="Exception" attribute on the exception +feature is necessary if any of the translated exceptions will be +checked exceptions, since the java compiler will otherwise assert that +no checked exceptions can be thrown by the method. This may be more +specific that the completely generic "Exception" class, of course. A +similar feature must be added to director methods to allow checked +exceptions to be thrown from the director method implementations. +Here, no actual exception handling is needed - the feature simply +is being used to add a generic checked exception signature to the +generated director method wrapper.

      + +
      +
      +%feature ("except",throws="Exception")  MyDirectorClass::myDirMeth %{ %}
      +
      +
      + +

      24.6 Accessing protected members

      diff --git a/Doc/Manual/Warnings.html b/Doc/Manual/Warnings.html index aac415952..5b507c123 100644 --- a/Doc/Manual/Warnings.html +++ b/Doc/Manual/Warnings.html @@ -499,6 +499,7 @@ example.i(4) : Syntax error in input.
    • 474. Method method usage of the optimal attribute ignored in the out typemap as the following cannot be used to generate optimal code: code
    • 475. Multiple calls to method might be generated due to optimal attribute usage in the out typemap.
    • 476. Initialization using std::initializer_list. +
    • 477. Feature director:except on Class::method with $directorthrowshandlers requires directorthrows typemap for exception Exception
    diff --git a/Examples/test-suite/director_exception.i b/Examples/test-suite/director_exception.i index de0ef3343..3fd3e563c 100644 --- a/Examples/test-suite/director_exception.i +++ b/Examples/test-suite/director_exception.i @@ -41,6 +41,29 @@ class DirectorMethodException: public Swig::DirectorException {}; #endif +#ifdef SWIGJAVA + +// Default for director exception warns about unmapped exceptions now in java +// Suppress warnings for this older test +// %warnfilter(476) Bar; + +// Default for java is to throw Swig::DirectorException if no +// direct:except feature. Since methods below have exception specification +// cannot throw director exception. + +// Change back to old 2.0 default behavior + +%feature("director:except") { + jthrowable $error = jenv->ExceptionOccurred(); + if ($error) { + // Dont clear exception, still be active when return to java execution + // Essentially ignore exception occurred -- old behavior. + return $null; + } +} + +#endif + #ifdef SWIGRUBY %feature("director:except") { diff --git a/Examples/test-suite/java/Makefile.in b/Examples/test-suite/java/Makefile.in index e4f3c6b58..52ae78563 100644 --- a/Examples/test-suite/java/Makefile.in +++ b/Examples/test-suite/java/Makefile.in @@ -24,6 +24,8 @@ CPP_TEST_CASES = \ java_constants \ java_director \ java_director_assumeoverride \ + java_director_exception_feature \ + java_director_exception_feature_nspace \ java_enums \ java_jnitypes \ java_lib_arrays_dimensionless \ @@ -44,8 +46,18 @@ JAVA_PACKAGE = $* JAVA_PACKAGEOPT = -package $(JAVA_PACKAGE) SWIGOPT += $(JAVA_PACKAGEOPT) +RUNME_CLASSPATH = -classpath . +ifeq (Cygwin,$(shell uname -o 2>/dev/null)) +SEP=; +else +SEP=: +endif + # Custom tests - tests with additional commandline options java_nspacewithoutpackage.%: JAVA_PACKAGEOPT = +java_director_exception_feature_nspace.%: JAVA_PACKAGEOPT = +java_director_exception_feature_nspace.%: RUNME_CLASSPATH = -classpath .$(SEP)./java_director_exception_feature_nspace + nspace.%: JAVA_PACKAGE = $*Package nspace_extend.%: JAVA_PACKAGE = $*Package director_nspace.%: JAVA_PACKAGE = $*Package @@ -84,8 +96,8 @@ setup = \ run_testcase = \ cd $(JAVA_PACKAGE) && $(COMPILETOOL) $(JAVAC) -classpath . `find . -name "*.java"` && cd .. && \ if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - $(COMPILETOOL) $(JAVAC) -classpath . -d . $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ - env LD_LIBRARY_PATH="$(JAVA_PACKAGE):$$LD_LIBRARY_PATH" PATH="$(JAVA_PACKAGE):$$PATH" SHLIB_PATH="$(JAVA_PACKAGE):$$SHLIB_PATH" DYLD_LIBRARY_PATH="$(JAVA_PACKAGE):$$DYLD_LIBRARY_PATH" $(RUNTOOL) $(JAVA) $(JAVAFLAGS) -classpath . $*_runme; \ + $(COMPILETOOL) $(JAVAC) $(RUNME_CLASSPATH) -d . $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ + env LD_LIBRARY_PATH="$(JAVA_PACKAGE):$$LD_LIBRARY_PATH" PATH="$(JAVA_PACKAGE):$$PATH" SHLIB_PATH="$(JAVA_PACKAGE):$$SHLIB_PATH" DYLD_LIBRARY_PATH="$(JAVA_PACKAGE):$$DYLD_LIBRARY_PATH" $(RUNTOOL) $(JAVA) $(JAVAFLAGS) $(RUNME_CLASSPATH) $*_runme; \ fi # Clean: remove testcase directories diff --git a/Examples/test-suite/java/java_director_exception_feature_nspace_runme.java b/Examples/test-suite/java/java_director_exception_feature_nspace_runme.java new file mode 100644 index 000000000..0cde36953 --- /dev/null +++ b/Examples/test-suite/java/java_director_exception_feature_nspace_runme.java @@ -0,0 +1,150 @@ +import MyNS.*; +import MyNS_JNI.*; + +class java_director_exception_feature_nspace_Consts { + public static final String PINGEXCP1 = "Ping MyJavaException1"; // should get translated through an int on ping + public static final String PINGEXCP2 = "Ping MyJavaException2"; + + public static final String PONGEXCP1 = "Pong MyJavaException1"; + public static final String PONGEXCP2 = "Pong MyJavaException2"; + public static final String PONGUNEXPECTED = "Pong MyJavaUnexpected"; + public static final String TRANSLATED_NPE = "Pong Translated NPE"; + + public static final String GENERICPONGEXCP1 = "GenericPong Wrapped MyJavaException1"; + public static final String GENERICPONGEXCP2 = "GenericPong New Checked Exception"; + public static final String GENERICPONGEXCP3 = "GenericPong New Unchecked Exception"; + public static final String GENERICPONGEXCP4 = "GenericPong New Exception Without String ctor"; +} + +// an exception not mentioned or wrapped by the swig interface, +// to reconstruct using generic DirectorException handling +class NewCheckedException extends Exception { + public NewCheckedException(String s) { + super(s); + } +} + +// an exception not mentioned or wrapped by the swig interface, +// to reconstruct using generic DirectorException handling +class NewUncheckedException extends RuntimeException { + public NewUncheckedException(String s) { + super(s); + } +} + +// an exception not constructable from a string, +// to test DirectorException fallback reconstruction +class UnconstructableException extends Exception { + private int extrastate; + public UnconstructableException(int a, String s) { + super(s); + extrastate = a; + } +} + +class java_director_exception_feature_nspace_MyFooDirectorImpl extends Foo { + + public java_director_exception_feature_nspace_MyFooDirectorImpl() { }; + + @Override + public String ping(int excp) throws MyJavaException1, MyJavaException2 { + if (excp == 1) throw new MyJavaException1(java_director_exception_feature_nspace_Consts.PINGEXCP1); + if (excp == 2) throw new MyJavaException2(java_director_exception_feature_nspace_Consts.PINGEXCP2); + return "Ping director returned"; + } + @Override + public String pong(int excp) throws MyJavaException1, MyJavaException2, MyJavaUnexpected { + if (excp == 1) throw new MyJavaException1(java_director_exception_feature_nspace_Consts.PONGEXCP1); + if (excp == 2) throw new MyJavaException2(java_director_exception_feature_nspace_Consts.PONGEXCP2); + if (excp == 3) throw new MyJavaUnexpected(java_director_exception_feature_nspace_Consts.PONGUNEXPECTED); + if (excp == 4) throw new java.lang.NullPointerException(java_director_exception_feature_nspace_Consts.TRANSLATED_NPE); // should be translated to ::Unexpected + return "Pong director returned"; + } + + @Override + public String genericpong(int excp) throws MyJavaException1, NewCheckedException, UnconstructableException { + if (excp == 1) + throw new MyJavaException1(java_director_exception_feature_nspace_Consts.GENERICPONGEXCP1); + if (excp == 2) + throw new NewCheckedException(java_director_exception_feature_nspace_Consts.GENERICPONGEXCP2); + if (excp == 3) + throw new NewUncheckedException(java_director_exception_feature_nspace_Consts.GENERICPONGEXCP3); + if (excp == 4) + throw new UnconstructableException(1, java_director_exception_feature_nspace_Consts.GENERICPONGEXCP4); + return "GenericPong director returned"; + } +} + +public class java_director_exception_feature_nspace_runme { + + static { + try { + System.loadLibrary("java_director_exception_feature_nspace"); + } 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 fail(String msg) { + System.err.println(msg); System.exit(1); + } + public static void failif(boolean cond, String msg) { + if (cond) fail(msg); + } + + + public static void main(String argv[]) { + + Bar b = new Bar(new java_director_exception_feature_nspace_MyFooDirectorImpl()); + try { + + try { b.ping(0); } catch (Exception e) + { fail("Exception should not have been thrown: " + e + " from ping(0)"); } + try { b.ping(1); fail("No exception thrown in ping(1)"); } catch (MyJavaException1 e) + // Should say "Threw some integer", see java_director_exception_feature.i Foo::ping throws a "1" + { failif( ! "Threw some integer".equals(e.getMessage()), "Ping exception not translated through int: '" + e.getMessage() + "'"); } + try { b.ping(2); fail("No exception thrown in ping(2)"); } catch (MyJavaException2 e) + { failif( ! java_director_exception_feature_nspace_Consts.PINGEXCP2.equals(e.getMessage()), "Expected exception has unexpected message: '" + e.getMessage() + "'"); } + + try { b.pong(0); } catch (Exception e) + { fail("Exception should not have been thrown: " + e + " from pong(0)"); } + try { b.pong(1); fail("No exception thrown in pong(1)"); } catch (MyJavaException1 e) + { failif( ! java_director_exception_feature_nspace_Consts.PONGEXCP1.equals(e.getMessage()), "Expected exception has unexpected message: '" + e.getMessage() + "'"); } + try { b.pong(2); fail("No exception thrown in pong(2)");} catch (MyJavaException2 e) + { failif( ! java_director_exception_feature_nspace_Consts.PONGEXCP2.equals(e.getMessage()), "Expected exception has unexpected message: '" + e.getMessage() + "'"); } + try { b.pong(3); fail("No exception thrown in pong(3)");} catch (MyJavaUnexpected e) + { failif( ! java_director_exception_feature_nspace_Consts.PONGUNEXPECTED.equals(e.getMessage()), "Expected exception has unexpected message: '" + e.getMessage() + "'"); } + try { b.pong(4); fail("No exception thrown in pong(4)"); } catch (MyJavaUnexpected e) + { failif( ! java_director_exception_feature_nspace_Consts.TRANSLATED_NPE.equals(e.getMessage()), "Expected exception has unexpected message: '" + e.getMessage() + "'"); } + + + try { b.genericpong(0); } + catch (Exception e) { + fail("Exception should not have been thrown: " + e + " from genericpong(0)"); + } + try { b.genericpong(1); fail("No exception thrown in genericpong(1)"); } + catch (MyJavaException1 e) { + failif( ! java_director_exception_feature_nspace_Consts.GENERICPONGEXCP1.equals(e.getMessage()), "Expected exception has unexpected message: '" + e.getMessage() + "'"); + } + try { b.genericpong(2); fail("No exception thrown in genericpong(2)");} + catch (NewCheckedException e) { + failif( ! java_director_exception_feature_nspace_Consts.GENERICPONGEXCP2.equals(e.getMessage()), "Expected exception has unexpected message: '" + e.getMessage() + "'"); + } + try { b.genericpong(3); fail("No exception thrown in genericpong(3)");} + catch (NewUncheckedException e) { + failif( ! java_director_exception_feature_nspace_Consts.GENERICPONGEXCP3.equals(e.getMessage()), "Expected exception has unexpected message: '" + e.getMessage() + "'"); + } + try { b.genericpong(4); fail("No exception thrown in genericpong(4)");} + catch (RuntimeException e) { + failif ( e.getClass() != RuntimeException.class, "Exception " + e + " is not exactly RumtimeException"); + failif( ! java_director_exception_feature_nspace_Consts.GENERICPONGEXCP4.equals(e.getMessage()), "Expected exception has unexpected message: '" + e.getMessage() + "'"); + } + } + catch (Exception e) { + e.printStackTrace(); + fail("Unexpected exception thrown or exception not mapped properly"); + } + + } +} diff --git a/Examples/test-suite/java/java_director_exception_feature_runme.java b/Examples/test-suite/java/java_director_exception_feature_runme.java new file mode 100644 index 000000000..2e919c18a --- /dev/null +++ b/Examples/test-suite/java/java_director_exception_feature_runme.java @@ -0,0 +1,152 @@ + +import java_director_exception_feature.*; + +class java_director_exception_feature_Consts { + public static final String PINGEXCP1 = "Ping MyJavaException1"; // should get translated through an int on ping + public static final String PINGEXCP2 = "Ping MyJavaException2"; + + public static final String PONGEXCP1 = "Pong MyJavaException1"; + public static final String PONGEXCP2 = "Pong MyJavaException2"; + public static final String PONGUNEXPECTED = "Pong MyJavaUnexpected"; + public static final String TRANSLATED_NPE = "Pong Translated NPE"; + + public static final String GENERICPONGEXCP1 = "GenericPong Wrapped MyJavaException1"; + public static final String GENERICPONGEXCP2 = "GenericPong New Checked Exception"; + public static final String GENERICPONGEXCP3 = "GenericPong New Unchecked Exception"; + public static final String GENERICPONGEXCP4 = "GenericPong New Exception Without String ctor"; + +} + +// an exception not mentioned or wrapped by the swig interface, +// to reconstruct using generic DirectorException handling +class NewCheckedException extends Exception { + public NewCheckedException(String s) { + super(s); + } +} + +// an exception not mentioned or wrapped by the swig interface, +// to reconstruct using generic DirectorException handling +class NewUncheckedException extends RuntimeException { + public NewUncheckedException(String s) { + super(s); + } +} + +// an exception not constructable from a string, +// to test DirectorException fallback reconstruction +class UnconstructableException extends Exception { + private int extrastate; + public UnconstructableException(int a, String s) { + super(s); + extrastate = a; + } +} + +class java_director_exception_feature_MyFooDirectorImpl extends Foo { + + public java_director_exception_feature_MyFooDirectorImpl() { }; + + @Override + public String ping(int excp) throws MyJavaException1, MyJavaException2 { + if (excp == 1) throw new MyJavaException1(java_director_exception_feature_Consts.PINGEXCP1); + if (excp == 2) throw new MyJavaException2(java_director_exception_feature_Consts.PINGEXCP2); + return "Ping director returned"; + } + @Override + public String pong(int excp) throws MyJavaException1, MyJavaException2, MyJavaUnexpected { + if (excp == 1) throw new MyJavaException1(java_director_exception_feature_Consts.PONGEXCP1); + if (excp == 2) throw new MyJavaException2(java_director_exception_feature_Consts.PONGEXCP2); + if (excp == 3) throw new MyJavaUnexpected(java_director_exception_feature_Consts.PONGUNEXPECTED); + if (excp == 4) throw new java.lang.NullPointerException(java_director_exception_feature_Consts.TRANSLATED_NPE); // should be translated to ::Unexpected + return "Pong director returned"; + } + + @Override + public String genericpong(int excp) throws MyJavaException1, NewCheckedException, UnconstructableException { + if (excp == 1) + throw new MyJavaException1(java_director_exception_feature_Consts.GENERICPONGEXCP1); + if (excp == 2) + throw new NewCheckedException(java_director_exception_feature_Consts.GENERICPONGEXCP2); + if (excp == 3) + throw new NewUncheckedException(java_director_exception_feature_Consts.GENERICPONGEXCP3); + if (excp == 4) + throw new UnconstructableException(1, java_director_exception_feature_Consts.GENERICPONGEXCP4); + return "GenericPong director returned"; + } +} + +public class java_director_exception_feature_runme { + + static { + try { + System.loadLibrary("java_director_exception_feature"); + } 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 fail(String msg) { + System.err.println(msg); System.exit(1); + } + public static void failif(boolean cond, String msg) { + if (cond) fail(msg); + } + + + public static void main(String argv[]) { + + Bar b = new Bar(new java_director_exception_feature_MyFooDirectorImpl()); + try { + + try { b.ping(0); } catch (Exception e) + { fail("Exception should not have been thrown: " + e + " from ping(0)"); } + try { b.ping(1); fail("No exception thrown in ping(1)"); } catch (MyJavaException1 e) + // Should say "Threw some integer", see java_director_exception_feature.i Foo::ping throws a "1" + { failif( ! "Threw some integer".equals(e.getMessage()), "Ping exception not translated through int: '" + e.getMessage() + "'"); } + try { b.ping(2); fail("No exception thrown in ping(2)"); } catch (MyJavaException2 e) + { failif( ! java_director_exception_feature_Consts.PINGEXCP2.equals(e.getMessage()), "Expected exception has unexpected message: '" + e.getMessage() + "'"); } + + try { b.pong(0); } catch (Exception e) + { fail("Exception should not have been thrown: " + e + " from pong(0)"); } + try { b.pong(1); fail("No exception thrown in pong(1)"); } catch (MyJavaException1 e) + { failif( ! java_director_exception_feature_Consts.PONGEXCP1.equals(e.getMessage()), "Expected exception has unexpected message: '" + e.getMessage() + "'"); } + try { b.pong(2); fail("No exception thrown in pong(2)");} catch (MyJavaException2 e) + { failif( ! java_director_exception_feature_Consts.PONGEXCP2.equals(e.getMessage()), "Expected exception has unexpected message: '" + e.getMessage() + "'"); } + try { b.pong(3); fail("No exception thrown in pong(3)");} catch (MyJavaUnexpected e) + { failif( ! java_director_exception_feature_Consts.PONGUNEXPECTED.equals(e.getMessage()), "Expected exception has unexpected message: '" + e.getMessage() + "'"); } + try { b.pong(4); fail("No exception thrown in pong(4)"); } catch (MyJavaUnexpected e) + { failif( ! java_director_exception_feature_Consts.TRANSLATED_NPE.equals(e.getMessage()), "Expected exception has unexpected message: '" + e.getMessage() + "'"); } + + + try { b.genericpong(0); } + catch (Exception e) { + fail("Exception should not have been thrown: " + e + " from genericpong(0)"); + } + try { b.genericpong(1); fail("No exception thrown in genericpong(1)"); } + catch (MyJavaException1 e) { + failif( ! java_director_exception_feature_Consts.GENERICPONGEXCP1.equals(e.getMessage()), "Expected exception has unexpected message: '" + e.getMessage() + "'"); + } + try { b.genericpong(2); fail("No exception thrown in genericpong(2)");} + catch (NewCheckedException e) { + failif( ! java_director_exception_feature_Consts.GENERICPONGEXCP2.equals(e.getMessage()), "Expected exception has unexpected message: '" + e.getMessage() + "'"); + } + try { b.genericpong(3); fail("No exception thrown in genericpong(3)");} + catch (NewUncheckedException e) { + failif( ! java_director_exception_feature_Consts.GENERICPONGEXCP3.equals(e.getMessage()), "Expected exception has unexpected message: '" + e.getMessage() + "'"); + } + try { b.genericpong(4); fail("No exception thrown in genericpong(4)");} + catch (RuntimeException e) { + failif ( e.getClass() != RuntimeException.class, "Exception " + e + " is not exactly RumtimeException"); + failif( ! java_director_exception_feature_Consts.GENERICPONGEXCP4.equals(e.getMessage()), "Expected exception has unexpected message: '" + e.getMessage() + "'"); + } + + } + catch (Exception e) { + e.printStackTrace(); + fail("Unexpected exception thrown or exception not mapped properly"); + } + + } +} diff --git a/Examples/test-suite/java_director_exception_feature.i b/Examples/test-suite/java_director_exception_feature.i new file mode 100644 index 000000000..b649b541d --- /dev/null +++ b/Examples/test-suite/java_director_exception_feature.i @@ -0,0 +1,209 @@ +%module(directors="1") java_director_exception_feature + +%include + +%{ +#if defined(_MSC_VER) + #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow) +#endif + +#include +%} + +%include + +// DEFINE exceptions in header section using std::runtime_error +%{ + #include + #include + + namespace MyNS { + + struct Exception1 : public std::runtime_error { + Exception1(const std::string& what):runtime_error(what) {} + }; + struct Exception2 : public std::runtime_error { + Exception2(const std::string& what):runtime_error(what) {} + }; + struct Unexpected : public std::runtime_error { + Unexpected(const std::string& what):runtime_error(what) {} + }; + + } + +%} + +// Add an explicit handler for Foo::ping, mapping one java exception back to an 'int' +%feature("director:except") MyNS::Foo::ping { + jthrowable $error = jenv->ExceptionOccurred(); + if ($error) { + jenv->ExceptionClear(); // clear java exception since mapping to c++ exception + if (Swig::ExceptionMatches(jenv,$error,"$packagepath/MyJavaException1")) { + throw 1; + } else if (Swig::ExceptionMatches(jenv,$error,"$packagepath/MyJavaException2")) { + std::string msg(Swig::JavaExceptionMessage(jenv,$error).message()); + throw MyNS::Exception2(msg); + } else { + std::cerr << "Test failed, unexpected exception thrown: " << + Swig::JavaExceptionMessage(jenv,$error).message() << std::endl; + throw std::runtime_error("unexpected exception in Foo::ping"); + } + } +} + +// Use default handler on Foo::pong, with directorthrows typemaps + +// directorthrows typemaps for java->c++ conversions +%typemap(directorthrows) MyNS::Exception1,MyNS::Exception2,MyNS::Unexpected %{ + if (Swig::ExceptionMatches(jenv, $error, "$packagepath/$javaclassname")) { + std::string msg(Swig::JavaExceptionMessage(jenv,$error).message()); + throw $1_type(msg); + } +%} + +// Override the director:except feature so exception specification is not violated +// (Cannot use built-in default of throw DirectorException) +%feature("director:except") MyNS::Foo::pong %{ + jthrowable $error = jenv->ExceptionOccurred(); + if ($error) { + jenv->ExceptionClear(); + $directorthrowshandlers + throw ::MyNS::Unexpected(Swig::JavaExceptionMessage(jenv,$error).message()); + } +%} + +// TODO 'throws' typemap emitted by emit_action (emit.cxx) has no way +// to get access to language specific special variables like +// $javaclassname or $packagepath ("java_director_exception_feature" here) + +// throws typemaps for c++->java exception conversions +%typemap(throws,throws="MyJavaException1") MyNS::Exception1 %{ + jclass excpcls = jenv->FindClass("java_director_exception_feature/MyJavaException1"); + if (excpcls) { + jenv->ThrowNew(excpcls, $1.what()); + } + return $null; +%} + +%typemap(throws,throws="MyJavaException1") int %{ + jclass excpcls = jenv->FindClass("java_director_exception_feature/MyJavaException1"); + if (excpcls) { + jenv->ThrowNew(excpcls, "Threw some integer"); + } + return $null; +%} + +%typemap(throws,throws="MyJavaException2") MyNS::Exception2 %{ + jclass excpcls = jenv->FindClass("java_director_exception_feature/MyJavaException2"); + if (excpcls) { + jenv->ThrowNew(excpcls, $1.what()); + } + return $null; +%} + +%typemap(throws,throws="MyJavaUnexpected") MyNS::Unexpected %{ + jclass excpcls = jenv->FindClass("java_director_exception_feature/MyJavaUnexpected"); + if (excpcls) { + jenv->ThrowNew(excpcls, $1.what()); + } + return $null; +%} + +// Use generic exception translation approach like python, ruby + +%feature("director:except") MyNS::Foo::genericpong { + jthrowable $error = jenv->ExceptionOccurred(); + if ($error) { + jenv->ExceptionClear(); + throw Swig::DirectorException(jenv,$error); + } +} + +// %exception with throws attribute. Need throws attribute for checked exceptions +%feature ("except",throws="Exception") MyNS::Foo::genericpong %{ +%} + +%feature ("except",throws="Exception") MyNS::Bar::genericpong %{ + try { $action } + catch (Swig::DirectorException & direxcp) { + direxcp.raiseJavaException(jenv); // jenv always available in JNI code + return $null; + } +%} + + + +%feature("director") Foo; + +// Rename exceptions on java side to make translation of exceptions more clear +%rename(MyJavaException1,fullname=1) MyNS::Exception1; +%rename(MyJavaException2,fullname=1) MyNS::Exception2; +%rename(MyJavaUnexpected,fullname=1) MyNS::Unexpected; + +%typemap(javabase) ::MyNS::Exception1,::MyNS::Exception2,::MyNS::Unexpected "java.lang.Exception"; +%rename(getMessage) what(); // Rename all what() methods + +namespace MyNS { + + struct Exception1 { + Exception1(const std::string& what); + const char * what(); + }; + struct Exception2 { + Exception2(const std::string& what); + const char * what(); + }; + struct Unexpected { + Unexpected(const std::string& what); + const char * what(); + }; + +} +// In general it is better to use %catches instead of an exception specification on the method +// since violating an exception specification calls terminate() preventing catch-all behavior +// like throwing std::runtime_error. But an exception specification must be used if the +// actual interface being wrapped does use them. +%catches(MyNS::Exception1,MyNS::Exception2,MyNS::Unexpected) MyNS::Foo::pong; +%catches(MyNS::Exception1,MyNS::Exception2,MyNS::Unexpected) MyNS::Bar::pong; + +%inline %{ + +namespace MyNS { + +class Foo { +public: + virtual ~Foo() {} + // ping java implementation throws a java Exception1 or an Exception2 if excp is 1 or 2. + // pong java implementation throws Exception1,Exception2,Unexpected,NullPointerException for 1,2,3,4 + virtual std::string ping(int excp) throw(int,MyNS::Exception2) = 0; + virtual std::string pong(int excp) /* throws MyNS::Exception1 MyNS::Exception2 MyNS::Unexpected) */ = 0; + virtual std::string genericpong(int excp) /* unspecified throws - exception is always DirectorException in C++, translated back to whatever thrown in java */ = 0; +}; + +// Make a bar from a foo, so a call to Java Bar +// goes Java Bar -> C++ Bar -> C++ Foo -> Java Foo Director + +class Bar { +public: + Bar(Foo* d) { delegate=d; } + virtual std::string ping(int excp) throw(int,MyNS::Exception2) + { + return delegate->ping(excp); + } + + virtual std::string pong(int excp) /* throws MyNS::Exception1,MyNS::Exception2,MyNS::Unexpected */ + { + return delegate->pong(excp); + } + + virtual std::string genericpong(int excp) + { + return delegate->genericpong(excp); + } + +private: + Foo * delegate; +}; + +} +%} diff --git a/Examples/test-suite/java_director_exception_feature_nspace.i b/Examples/test-suite/java_director_exception_feature_nspace.i new file mode 100644 index 000000000..8723ef738 --- /dev/null +++ b/Examples/test-suite/java_director_exception_feature_nspace.i @@ -0,0 +1,216 @@ +%module(directors="1") java_director_exception_feature_nspace + +%include + +%nspace; // turn namespace feature on for everything. + +// When using namespaces with no -package, must put JNI classes into a namespace +%pragma(java) jniclasspackage=%{MyNS_JNI%} +%warnfilter(826); + +%{ +#if defined(_MSC_VER) + #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow) +#endif + +#include +%} + +%include + +// DEFINE exceptions in header section using std::runtime_error +%{ + #include + #include + + namespace MyNS { + + struct Exception1 : public std::runtime_error { + Exception1(const std::string& what):runtime_error(what) {} + }; + struct Exception2 : public std::runtime_error { + Exception2(const std::string& what):runtime_error(what) {} + }; + struct Unexpected : public std::runtime_error { + Unexpected(const std::string& what):runtime_error(what) {} + }; + + } + +%} + +// Add an explicit handler for Foo::ping, mapping one java exception back to an 'int' +%feature("director:except") MyNS::Foo::ping { + jthrowable $error = jenv->ExceptionOccurred(); + if ($error) { + jenv->ExceptionClear(); // clear java exception since mapping to c++ exception + if (Swig::ExceptionMatches(jenv,$error,"$packagepath/MyNS/MyJavaException1")) { + throw 1; + } else if (Swig::ExceptionMatches(jenv,$error,"$packagepath/MyNS/MyJavaException2")) { + std::string msg(Swig::JavaExceptionMessage(jenv,$error).message()); + throw MyNS::Exception2(msg); + } else { + std::cerr << "Test failed, unexpected exception thrown: " << + Swig::JavaExceptionMessage(jenv,$error).message() << std::endl; + throw std::runtime_error("unexpected exception in Foo::ping"); + } + } +} + +// Use default handler on Foo::pong, with directorthrows typemaps + +// directorthrows typemaps for java->c++ conversions +%typemap(directorthrows) MyNS::Exception1,MyNS::Exception2,MyNS::Unexpected %{ + if (Swig::ExceptionMatches(jenv, $error, "$packagepath/$javaclassname")) { + std::string msg(Swig::JavaExceptionMessage(jenv,$error).message()); + throw $1_type(msg); + } +%} + +// Override the director:except feature so exception specification is not violated +// (Cannot use built-in default of throw DirectorException) +%feature("director:except") MyNS::Foo::pong %{ + jthrowable $error = jenv->ExceptionOccurred(); + if ($error) { + jenv->ExceptionClear(); + $directorthrowshandlers + throw ::MyNS::Unexpected(Swig::JavaExceptionMessage(jenv,$error).message()); + } +%} + +// TODO 'throws' typemap emitted by emit_action (emit.cxx) has no way +// to get access to language specific special variables like +// $javaclassname or $packagepath ("java_director_exception_feature" here) + +// throws typemaps for c++->java exception conversions +%typemap(throws,throws="MyNS.MyJavaException1") MyNS::Exception1 %{ + jclass excpcls = jenv->FindClass("MyNS/MyJavaException1"); + if (excpcls) { + jenv->ThrowNew(excpcls, $1.what()); + } + return $null; +%} + +%typemap(throws,throws="MyNS.MyJavaException1") int %{ + jclass excpcls = jenv->FindClass("MyNS/MyJavaException1"); + if (excpcls) { + jenv->ThrowNew(excpcls, "Threw some integer"); + } + return $null; +%} + +%typemap(throws,throws="MyNS.MyJavaException2") MyNS::Exception2 %{ + jclass excpcls = jenv->FindClass("MyNS/MyJavaException2"); + if (excpcls) { + jenv->ThrowNew(excpcls, $1.what()); + } + return $null; +%} + + +%typemap(throws,throws="MyNS.MyJavaUnexpected") MyNS::Unexpected %{ + jclass excpcls = jenv->FindClass("MyNS/MyJavaUnexpected"); + if (excpcls) { + jenv->ThrowNew(excpcls, $1.what()); + } + return $null; +%} + +// Use generic exception translation approach like python, ruby + +%feature("director:except") MyNS::Foo::genericpong { + jthrowable $error = jenv->ExceptionOccurred(); + if ($error) { + jenv->ExceptionClear(); + throw Swig::DirectorException(jenv,$error); + } +} + +// %exception with throws attribute. Need throws attribute for checked exceptions +%feature ("except",throws="Exception") MyNS::Foo::genericpong %{ +%} + +%feature ("except",throws="Exception") MyNS::Bar::genericpong %{ + try { $action } + catch (Swig::DirectorException & direxcp) { + direxcp.raiseJavaException(jenv); // jenv always available in JNI code + return $null; + } +%} + + + +%feature("director") Foo; + +// Rename exceptions on java side to make translation of exceptions more clear +%rename(MyJavaException1,fullname=1) MyNS::Exception1; +%rename(MyJavaException2,fullname=1) MyNS::Exception2; +%rename(MyJavaUnexpected,fullname=1) MyNS::Unexpected; + +%typemap(javabase) ::MyNS::Exception1,::MyNS::Exception2,::MyNS::Unexpected "java.lang.Exception"; +%rename(getMessage) what(); // Rename all what() methods + +namespace MyNS { + + struct Exception1 { + Exception1(const std::string& what); + const char * what(); + }; + struct Exception2 { + Exception2(const std::string& what); + const char * what(); + }; + struct Unexpected { + Unexpected(const std::string& what); + const char * what(); + }; + +} +// In general it is better to use %catches instead of an exception specification on the method +// since violating an exception specification calls terminate() preventing catch-all behavior +// like throwing std::runtime_error. But an exception specification must be used if the +// actual interface being wrapped does use them. +%catches(MyNS::Exception1,MyNS::Exception2,MyNS::Unexpected) MyNS::Foo::pong; +%catches(MyNS::Exception1,MyNS::Exception2,MyNS::Unexpected) MyNS::Bar::pong; + +%inline %{ + +namespace MyNS { + +class Foo { +public: + virtual ~Foo() {} + // ping java implementation throws a java Exception1 or an Exception2 if excp is 1 or 2. + // pong java implementation throws Exception1,Exception2,Unexpected,NullPointerException for 1,2,3,4 + virtual std::string ping(int excp) throw(int,MyNS::Exception2) = 0; + virtual std::string pong(int excp) /* throws MyNS::Exception1 MyNS::Exception2 MyNS::Unexpected) */ = 0; + virtual std::string genericpong(int excp) /* unspecified throws - exception is always DirectorException in C++, translated back to whatever thrown in java */ = 0; +}; + +// Make a bar from a foo, so a call to Java Bar +// goes Java Bar -> C++ Bar -> C++ Foo -> Java Foo Director + +class Bar { +public: + Bar(Foo* d) { delegate=d; } + virtual std::string ping(int excp) throw(int,MyNS::Exception2) + { + return delegate->ping(excp); + } + + virtual std::string pong(int excp) /* throws MyNS::Exception1,MyNS::Exception2,MyNS::Unexpected */ + { + return delegate->pong(excp); + } + + virtual std::string genericpong(int excp) + { + return delegate->genericpong(excp); + } + +private: + Foo * delegate; +}; + +} +%} diff --git a/Lib/java/director.swg b/Lib/java/director.swg index f32fda350..8c7dca294 100644 --- a/Lib/java/director.swg +++ b/Lib/java/director.swg @@ -193,6 +193,242 @@ namespace Swig { }; } + +// Default exception handler for all director methods. +// Can override this for specific methods +// This just documents the default. It is not actually attached as a feature +// for efficiency reasons (and is defined in java.cxx) It can be overridden +// as a feature for specific methods or globally. + +//%feature("director:except") %{ +// jthrowable $error = jenv->ExceptionOccurred(); +// if ($error) { +// jenv->ExceptionClear(); +// $directorthrowshandlers +// throw Swig::DirectorException(jenv, $error); +// } +//%} + +// Define some utility methods and classes. Cannot use fragments since +// these may be used by %features and in directorthrows typemaps + +#include + +// Simple holder for exception messages, allowing access to a c-style string +namespace Swig { + struct JavaString { + JavaString(JNIEnv * jenv, jstring jstr):jenv_(jenv), jstr_(jstr), cstr_(0) { + if (jenv_ && jstr_) { + // Get the null-terminated c-string out, and hold it + cstr_ = (const char *) jenv_->GetStringUTFChars(jstr_, NULL); + } + } + ~JavaString() { + if (jenv_ && jstr_ && cstr_) { + jenv_->ReleaseStringUTFChars(jstr_, cstr_); + } + } + const char *cstr() { + return cstr_ ? cstr_ : ""; + } + + private: + JNIEnv * jenv_; + jstring jstr_; + const char * cstr_; + + // non-copyable + JavaString(const JavaString &); + JavaString & operator=(const JavaString &); + }; + + struct JavaExceptionMessage { + JavaExceptionMessage(JNIEnv * jenv, jthrowable excp) : + jstrholder_(jenv,exceptionMsgJstr(jenv,excp)) { + } + ~JavaExceptionMessage() { + } + const char *message() { + return jstrholder_.cstr(); + } + + private: + JavaString jstrholder_; + + // non-copyable + JavaExceptionMessage(const JavaExceptionMessage &); + JavaExceptionMessage & operator=(const JavaExceptionMessage &); + + // Static method to initialize jstrholder_ + static jstring exceptionMsgJstr(JNIEnv * jenv, jthrowable excp) { + jstring jmsg = NULL; + if (jenv && excp) { + jenv->ExceptionClear(); // Cannot invoke methods with pending exception + jclass thrwclz = jenv->GetObjectClass(excp); + if (thrwclz) { + // if no getMessage() or other exception, no msg available. + jmethodID getThrowableMsgMethodID = + jenv->GetMethodID(thrwclz, "getMessage", "()Ljava/lang/String;"); + if (getThrowableMsgMethodID && !jenv->ExceptionCheck()) { + // if problem accessing exception message string, no msg available. + jmsg = (jstring) + jenv->CallObjectMethod(excp, getThrowableMsgMethodID); + } + } + if (jmsg == NULL && jenv->ExceptionCheck()) { + jenv->ExceptionClear(); + } + } + return jmsg; + } + }; + + + //////////////////////////////////// + + bool ExceptionMatches(JNIEnv * jenv, jthrowable excp, + const char *clzname) { + jboolean matches = false; + + if (excp && jenv && clzname) { + // Have to clear exceptions for correct behavior. Code around + // ExceptionMatches should restore pending exception if + // desired - already have throwable. + jenv->ExceptionClear(); + + jclass clz = jenv->FindClass(clzname); + if (clz && ! jenv->ExceptionCheck()) { + jclass classclz = jenv->GetObjectClass(clz); + jmethodID isInstanceMethodID = + jenv->GetMethodID(classclz, "isInstance", "(Ljava/lang/Object;)Z"); + if (isInstanceMethodID) { + matches = (jboolean) + jenv->CallBooleanMethod(clz, isInstanceMethodID, excp); + } + } + // This may happen if user typemaps or director:except + // features call ExceptionMatches incorrectly, typically with + // an invalid clzname argument. Uncommenting the debug lines + // may help to diagnose. + // As is, this leaves the underlying case as a pending exception + // which may not be that clear (e.g. ClassNotFoundException) + + // if (jenv->ExceptionCheck()) { + // JavaExceptionMessage jstrmsg(jenv,jenv->ExceptionOccurred()); + // std::cerr << "Error: ExceptionMatches: class '" << + // clzname << "' : " << jstrmsg.message() << std::endl; + // } + } + return matches; + } + + // Provide the class name to allow reconstruction of the original exception + struct DirectorException : std::exception { + + // Construct a DirectorException from a java throwable + DirectorException(JNIEnv* jenv,jthrowable excp) : classname_(0), msg_(0) { + jstring jstr_classname = NULL; + jmethodID mid_getName = NULL; + jclass thrwclz; + jclass clzclz; + + if (excp) { + // Get the exception class, like Exception + thrwclz = jenv->GetObjectClass(excp); + if (thrwclz) { + // Get the java.lang.Class class + clzclz = jenv->GetObjectClass(thrwclz); + if (clzclz) { + mid_getName = jenv->GetMethodID(clzclz, "getName", "()Ljava/lang/String;"); + if (mid_getName) { + // Get the excp class name + jstr_classname = (jstring)(jenv->CallObjectMethod(thrwclz, mid_getName)); + } + } + } + } + // Copy strings, since no guarantee jenv will be active when handled + // If classname_ is 0, returned as "UnknownException" + if (jstr_classname) { + JavaString classname(jenv, jstr_classname); + classname_ = copypath(classname.cstr()); + } + JavaExceptionMessage exceptionmsg(jenv, excp); + msg_ = copystr(exceptionmsg.message()); + } + + // Throw as a wrapped Runtime Error explicitly. + DirectorException(const char * msg) : classname_(0), msg_(0) { + classname_ = copypath("java/lang/RuntimeError"); + msg_ = copystr(msg); + } + + ~DirectorException() throw() { + delete[] classname_; + delete[] msg_; + } + + // If there was problem finding classname, keep track of error + // On raiseJavaException will be mapped to a RuntimeException + const char* classname() const throw() { + return classname_ ? classname_ : "UnknownException"; + } + const char* what() const throw() { + return msg_ ? msg_ : ""; + } + + // Python director code provides static raise() methods + // Omitted here: Seems less good than + // throw DirectorException(jenv, excp) + // from which compiler can infer a C++ exception is thrown. + + // Reconstruct and raise the Java Exception that caused the DirectorException + void raiseJavaException(JNIEnv* jenv) { + if (jenv) { + jenv->ExceptionClear(); + + jmethodID strCtorID = 0; + + jclass excpclz = jenv->FindClass(classname()); + + if (excpclz) { + strCtorID = jenv->GetMethodID(excpclz,"","(Ljava/lang/String;)V"); + } + + if (strCtorID) { + // If exception has a string constructor, throw an instance + jenv->ThrowNew(excpclz, what()); + } else { + // Else, throw a runtime + SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, what() ); + } + } + } + + private: + const char * classname_; + const char * msg_; + + static const char * copypath(const char * srcmsg) { + return copystr(srcmsg, 1); + } + static const char * copystr(const char * srcmsg, int pathrepl=0) { + char * target = 0; + if (srcmsg) { + int msglen = 1+strlen(srcmsg); //+1 for null terminator + target = new char[msglen]; + strncpy(target, srcmsg, msglen); + } + // If pathrepl, replace any '.' with '/' + if (pathrepl) { + for(char *c=target; *c; ++c) { + if ('.' == *c) *c = '/'; + } + } + return target; + } + }; + +} + #endif /* __cplusplus */ - - diff --git a/Lib/java/std_string.i b/Lib/java/std_string.i index f178e6d43..6b9cb90a4 100644 --- a/Lib/java/std_string.i +++ b/Lib/java/std_string.i @@ -38,7 +38,8 @@ class string; %typemap(directorout) string %{ if(!$input) { - SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null string"); + if (!jenv->ExceptionCheck()) + SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null string"); return $null; } const char *$1_pstr = (const char *)jenv->GetStringUTFChars($input, 0); diff --git a/Source/Include/swigwarn.h b/Source/Include/swigwarn.h index 4856d9e44..65ff70dd9 100644 --- a/Source/Include/swigwarn.h +++ b/Source/Include/swigwarn.h @@ -176,6 +176,7 @@ #define WARN_TYPEMAP_OUT_OPTIMAL_IGNORED 474 #define WARN_TYPEMAP_OUT_OPTIMAL_MULTIPLE 475 #define WARN_TYPEMAP_INITIALIZER_LIST 476 +#define WARN_TYPEMAP_DIRECTORTHROWS_UNDEF 477 /* -- Fragments -- */ #define WARN_FRAGMENT_NOT_FOUND 490 diff --git a/Source/Modules/java.cxx b/Source/Modules/java.cxx index 24435ac30..acc46c15e 100644 --- a/Source/Modules/java.cxx +++ b/Source/Modules/java.cxx @@ -742,15 +742,25 @@ public: *----------------------------------------------------------------------*/ UpcallData *addUpcallMethod(String *imclass_method, String *class_method, String *imclass_desc, String *class_desc, String *decl) { + UpcallData *udata; + String *imclass_methodidx; + String *class_methodidx; + Hash *new_udata; String *key = NewStringf("%s|%s", imclass_method, decl); ++curr_class_dmethod; - String *imclass_methodidx = NewStringf("%d", n_dmethods); - String *class_methodidx = NewStringf("%d", n_dmethods - first_class_dmethod); + /* Do we know about this director class already? */ + if ((udata = Getattr(dmethods_table, key))) { + Delete(key); + return Getattr(udata, "methodoff"); + } + + imclass_methodidx = NewStringf("%d", n_dmethods); + class_methodidx = NewStringf("%d", n_dmethods - first_class_dmethod); n_dmethods++; - Hash *new_udata = NewHash(); + new_udata = NewHash(); Append(dmethods_seq, new_udata); Setattr(dmethods_table, key, new_udata); @@ -2939,20 +2949,36 @@ public: * pt - parameter type * tm - typemap contents that might contain the special variable to be replaced * jnidescriptor - if set, inner class names are separated with '$' otherwise a '.' + * p - a parameter type, that may hold a javapackage typemap. If passed, + * the $packagepath will be substituted, but call method below instead. * 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 jnidescriptor = false) { + bool substituteClassname(SwigType *pt, String *tm, + bool jnidescriptor = false, Parm * pkgpathparm = 0) + { + return substituteClassnameAndPackagePath( pt, tm, jnidescriptor, pkgpathparm); + } + + /* ----------------------------------------------------------------------------- + * substituteClassnameAndPackagePath() + * Used to canonicalize JNI descriptors, including code emitting director throws typemaps. + * + * Only usage always has jnidescriptor AND p set. Maybe collapse args. + * ----------------------------------------------------------------------------- */ + bool substituteClassnameAndPackagePath(SwigType *pt, String *tm, + bool jnidescriptor, Parm * pkgpathparm) + { bool substitution_performed = false; SwigType *type = Copy(SwigType_typedef_resolve_all(pt)); SwigType *strippedtype = SwigType_strip_qualifiers(type); if (Strstr(tm, "$javaclassname")) { SwigType *classnametype = Copy(strippedtype); - substituteClassnameSpecialVariable(classnametype, tm, "$javaclassname", jnidescriptor); + substituteClassnameSpecialVariable(classnametype, tm, "$javaclassname", jnidescriptor, pkgpathparm); substitution_performed = true; Delete(classnametype); } @@ -2960,7 +2986,7 @@ public: SwigType *classnametype = Copy(strippedtype); Delete(SwigType_pop(classnametype)); if (Len(classnametype) > 0) { - substituteClassnameSpecialVariable(classnametype, tm, "$*javaclassname", jnidescriptor); + substituteClassnameSpecialVariable(classnametype, tm, "$*javaclassname", jnidescriptor, pkgpathparm); substitution_performed = true; } Delete(classnametype); @@ -2968,7 +2994,7 @@ public: if (Strstr(tm, "$&javaclassname")) { SwigType *classnametype = Copy(strippedtype); SwigType_add_pointer(classnametype); - substituteClassnameSpecialVariable(classnametype, tm, "$&javaclassname", jnidescriptor); + substituteClassnameSpecialVariable(classnametype, tm, "$&javaclassname", jnidescriptor, pkgpathparm); substitution_performed = true; Delete(classnametype); } @@ -2982,27 +3008,46 @@ public: /* ----------------------------------------------------------------------------- * substituteClassnameSpecialVariable() * ----------------------------------------------------------------------------- */ + void substituteClassnameSpecialVariable(SwigType *classnametype, String *tm, const char *classnamespecialvariable, bool jnidescriptor, Parm * pkgpathparm) { + String * replacementname; - void substituteClassnameSpecialVariable(SwigType *classnametype, String *tm, const char *classnamespecialvariable, bool jnidescriptor) { if (SwigType_isenum(classnametype)) { - String *enumname = getEnumName(classnametype, jnidescriptor); - if (enumname) - Replaceall(tm, classnamespecialvariable, enumname); - else - Replaceall(tm, classnamespecialvariable, NewStringf("int")); + replacementname = Copy(getEnumName(classnametype, jnidescriptor)); + if (!replacementname) { + replacementname = NewString("int"); + } } else { - String *classname = getProxyName(classnametype); - if (classname) { - Replaceall(tm, classnamespecialvariable, classname); // getProxyName() works for pointers to classes too - } else { // use $descriptor if SWIG does not know anything about this type. Note that any typedefs are resolved. - String *descriptor = NewStringf("SWIGTYPE%s", SwigType_manglestr(classnametype)); - Replaceall(tm, classnamespecialvariable, descriptor); - + replacementname = Copy(getProxyName(classnametype)); + if (! replacementname) { + // use $descriptor if SWIG does not know anything about this type. Note that any typedefs are resolved. + replacementname = NewStringf("SWIGTYPE%s", SwigType_manglestr(classnametype)); // Add to hash table so that the type wrapper classes can be created later - Setattr(swig_types_hash, descriptor, classnametype); - Delete(descriptor); + Setattr(swig_types_hash, replacementname, classnametype); } } + + if (pkgpathparm) { + if (Strchr(replacementname, '.') != NULL) { + // nspace feature in use, indicated by dots (!?) + // if replacementname is in name space form, a.b.c, discard + // packagepath from any string like $packagepath/$javaclassname + // since IT WAS ADDED in getProxyName + // But $packagepath could still be used by itself in same string + // since this is used to emit general code blocks for director + // exceptions + // So do this to get rid of all combined forms before subsitituting + Replaceall(tm, "$packagepath/$javaclassname","$javaclassname"); + Replaceall(tm, "$packagepath/$*javaclassname","$*javaclassname"); + Replaceall(tm, "$packagepath/$&javaclassname","$&javaclassname"); + } + substitutePackagePath(tm, pkgpathparm); + } + if (jnidescriptor) { + Replaceall(replacementname,".","/"); + } + Replaceall(tm, classnamespecialvariable, replacementname); + + Delete(replacementname); } /* ----------------------------------------------------------------------------- @@ -3497,11 +3542,32 @@ public: // Delete(method_attr); } + /** Replace $packagepath using the javapackage typemap + associated with passed parm or global package_path + if none. "$packagepath/" is replaced with "" if no + package path is set. + */ + void substitutePackagePath(String *text, Parm *p) { + String *pkg_path= 0; + + if (p) + pkg_path = Swig_typemap_lookup("javapackage", p, "", 0); + if (!pkg_path || Len(pkg_path) == 0) + pkg_path = package_path; + + if (Len(pkg_path) > 0) { + Replaceall(text, "$packagepath", pkg_path); + } else { + Replaceall(text, "$packagepath/", empty_string); + Replaceall(text, "$packagepath", empty_string); + } + } + /* --------------------------------------------------------------- * Canonicalize the JNI field descriptor * - * Replace the $javapackage and $javaclassname family of special - * variables with the desired package and Java proxy name as + * Replace the $packagepath and $javaclassname family of + * variables with the desired package and Java descriptor as * required in the JNI field descriptors. * * !!SFM!! If $packagepath occurs in the field descriptor, but @@ -3511,27 +3577,11 @@ public: * --------------------------------------------------------------- */ String *canonicalizeJNIDescriptor(String *descriptor_in, Parm *p) { - String *pkg_path = Swig_typemap_lookup("javapackage", p, "", 0); SwigType *type = Getattr(p, "type"); - if (!pkg_path || Len(pkg_path) == 0) - pkg_path = package_path; - String *descriptor_out = Copy(descriptor_in); - - substituteClassname(type, descriptor_out, true); - - if (Len(pkg_path) > 0 && Strchr(descriptor_out, '.') == NULL) { - Replaceall(descriptor_out, "$packagepath", pkg_path); - } else { - Replaceall(descriptor_out, "$packagepath/", empty_string); - Replaceall(descriptor_out, "$packagepath", empty_string); - } - - Replaceall(descriptor_out, ".", "/"); - - if (pkg_path != package_path) - Delete(pkg_path); + // This returns a JNI descriptor, in path format + substituteClassnameAndPackagePath(type, descriptor_out, true, p); return descriptor_out; } @@ -3928,17 +3978,33 @@ public: // Get any Java exception classes in the throws typemap ParmList *throw_parm_list = NULL; + // May need to add throws to director classes if %catches defined + // Get any Java exception classes in the throws typemap + ParmList *catches_list = Getattr(n, "catchlist"); + if (catches_list) { + Swig_typemap_attach_parms("throws", catches_list, 0); + Swig_typemap_attach_parms("directorthrows", catches_list, 0); + for (p = catches_list; p; p = nextSibling(p)) { + addThrows(n, "tmap:throws", p); + } + } + if ((throw_parm_list = Getattr(n, "throws")) || Getattr(n, "throw")) { int gencomma = 0; Append(w->def, " throw("); Append(declaration, " throw("); - if (throw_parm_list) + if (throw_parm_list) { Swig_typemap_attach_parms("throws", throw_parm_list, 0); + Swig_typemap_attach_parms("directorthrows", throw_parm_list, 0); + } for (p = throw_parm_list; p; p = nextSibling(p)) { if (Getattr(p, "tmap:throws")) { - addThrows(n, "tmap:throws", p); + // If %catches feature, it overrides specified throws(). + if (! catches_list) { + addThrows(n, "tmap:throws", p); + } if (gencomma++) { Append(w->def, ", "); @@ -4001,7 +4067,8 @@ public: Printf(w->code, "jenv->%s(Swig::jclass_%s, Swig::director_methids[%s], %s);\n", methop, imclass_name, methid, jupcall_args); - Printf(w->code, "if (jenv->ExceptionCheck() == JNI_TRUE) return $null;\n"); + // Generate code to handle any java exception thrown by director delegation + directorExceptHandler(n, catches_list?catches_list:throw_parm_list, w, c_classname, name); if (!is_void) { String *jresult_str = NewString("jresult"); @@ -4042,7 +4109,8 @@ public: /* Terminate wrapper code */ Printf(w->code, "} else {\n"); - Printf(w->code, "SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, \"null upcall object\");\n"); + Printf(w->code, "SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, \"null upcall object in %s::%s \");\n", + SwigType_namestr(c_classname), SwigType_namestr(name)); Printf(w->code, "}\n"); Printf(w->code, "if (swigjobj) jenv->DeleteLocalRef(swigjobj);\n"); @@ -4098,6 +4166,79 @@ public: return status; } + /* ------------------------------------------------------------ + * directorExcept handler: Emit code to map java exceptions + * back to C++ exceptions when feature("director:except") is appied + * to a method node + * ------------------------------------------------------------ */ + void directorExceptHandler(Node *n, ParmList *throw_parm_list, Wrapper *w, String *c_classname, String *name) { + // After director java method call, allow code for director method exception to be added + // Look for director:exceptfeature + Parm *p; + + // "Default" feature, so that feature is not applied to every node, per W. Fulton + static char const * DEFAULT_DIREXCP_FEATURE = + "jthrowable $error = jenv->ExceptionOccurred();\n" + "if ($error) {\n" + " jenv->ExceptionClear();\n" + " $directorthrowshandlers\n" + " throw Swig::DirectorException(jenv, $error);\n" + "}\n"; + + String * featdirexcp = Getattr(n, "feature:director:except"); + + if (!featdirexcp) { + featdirexcp = NewString(DEFAULT_DIREXCP_FEATURE); + } else { + featdirexcp = Copy(featdirexcp); + } + // Can explicitly disable director:except by setting to "" or "0" + if (0 != Len(featdirexcp) && 0 != Cmp(featdirexcp,"0")) { + + // Replace any $packagepath with global -package package_path + substitutePackagePath(featdirexcp, 0); + + // Replace $action with any defined typemap handlers (or nothing) + if (Strstr(featdirexcp, "$directorthrowshandlers")) { + String *directorthrowshandlers_code = NewString(""); + + for (p = throw_parm_list; p; p = nextSibling(p)) { + String *tmapdirthrows = Getattr(p, "tmap:directorthrows"); + String * excptype = Getattr(p,"type"); + + if (!tmapdirthrows) { + Swig_warning(WARN_TYPEMAP_DIRECTORTHROWS_UNDEF, input_file, line_number, + "Feature director:except on %s::%s with $directorthrowshandlers requires directorthrows typemap for exception %s.\n", + SwigType_namestr(c_classname),SwigType_namestr(name), excptype); + } else { + // replace $packagepath + tmapdirthrows = Copy(tmapdirthrows); + substituteClassnameAndPackagePath(excptype, tmapdirthrows, true, p); + + Printf(directorthrowshandlers_code, + "// Handle exception %s using directorthrows typemap\n" + "%s", + excptype, tmapdirthrows); + Delete(tmapdirthrows); + } + } + // Delete extra new line if no handlers. + while (Replaceall(featdirexcp, "$directorthrowshandlers ", + "$directorthrowshandlers")) {} + if (0 == Len(directorthrowshandlers_code)) + Replaceall(featdirexcp, "$directorthrowshandlers\n", ""); + else + Replaceall(featdirexcp, "$directorthrowshandlers", directorthrowshandlers_code); + Delete(directorthrowshandlers_code); + } + + // Replace all occurrences of $error with common var name. + Replaceall(featdirexcp, "$error", "thrown_"); + Printf(w->code, " %s\n", featdirexcp); + } + Delete(featdirexcp); + } + /* ------------------------------------------------------------ * directorPrefixArgs() * ------------------------------------------------------------ */ From 9237c4553c93f9e0d265b483e63486da8c49f31e Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Wed, 23 Oct 2013 18:26:41 +0100 Subject: [PATCH 166/481] Code style conforming channges for Java director:except patch --- Source/Modules/java.cxx | 100 ++++++++++++++++++---------------------- 1 file changed, 46 insertions(+), 54 deletions(-) diff --git a/Source/Modules/java.cxx b/Source/Modules/java.cxx index acc46c15e..40c60e4da 100644 --- a/Source/Modules/java.cxx +++ b/Source/Modules/java.cxx @@ -742,25 +742,22 @@ public: *----------------------------------------------------------------------*/ UpcallData *addUpcallMethod(String *imclass_method, String *class_method, String *imclass_desc, String *class_desc, String *decl) { - UpcallData *udata; - String *imclass_methodidx; - String *class_methodidx; - Hash *new_udata; String *key = NewStringf("%s|%s", imclass_method, decl); ++curr_class_dmethod; /* Do we know about this director class already? */ - if ((udata = Getattr(dmethods_table, key))) { + UpcallData *udata = Getattr(dmethods_table, key); + if (udata) { Delete(key); return Getattr(udata, "methodoff"); } - imclass_methodidx = NewStringf("%d", n_dmethods); - class_methodidx = NewStringf("%d", n_dmethods - first_class_dmethod); + String *imclass_methodidx = NewStringf("%d", n_dmethods); + String *class_methodidx = NewStringf("%d", n_dmethods - first_class_dmethod); n_dmethods++; - new_udata = NewHash(); + Hash *new_udata = NewHash(); Append(dmethods_seq, new_udata); Setattr(dmethods_table, key, new_udata); @@ -2957,9 +2954,7 @@ public: * substitution_performed - flag indicating if a substitution was performed * ----------------------------------------------------------------------------- */ - bool substituteClassname(SwigType *pt, String *tm, - bool jnidescriptor = false, Parm * pkgpathparm = 0) - { + bool substituteClassname(SwigType *pt, String *tm, bool jnidescriptor = false, Parm *pkgpathparm = 0) { return substituteClassnameAndPackagePath( pt, tm, jnidescriptor, pkgpathparm); } @@ -2969,9 +2964,8 @@ public: * * Only usage always has jnidescriptor AND p set. Maybe collapse args. * ----------------------------------------------------------------------------- */ - bool substituteClassnameAndPackagePath(SwigType *pt, String *tm, - bool jnidescriptor, Parm * pkgpathparm) - { + + bool substituteClassnameAndPackagePath(SwigType *pt, String *tm, bool jnidescriptor, Parm *pkgpathparm) { bool substitution_performed = false; SwigType *type = Copy(SwigType_typedef_resolve_all(pt)); SwigType *strippedtype = SwigType_strip_qualifiers(type); @@ -3008,6 +3002,7 @@ public: /* ----------------------------------------------------------------------------- * substituteClassnameSpecialVariable() * ----------------------------------------------------------------------------- */ + void substituteClassnameSpecialVariable(SwigType *classnametype, String *tm, const char *classnamespecialvariable, bool jnidescriptor, Parm * pkgpathparm) { String * replacementname; @@ -3042,9 +3037,8 @@ public: } substitutePackagePath(tm, pkgpathparm); } - if (jnidescriptor) { + if (jnidescriptor) Replaceall(replacementname,".","/"); - } Replaceall(tm, classnamespecialvariable, replacementname); Delete(replacementname); @@ -3542,11 +3536,14 @@ public: // Delete(method_attr); } - /** Replace $packagepath using the javapackage typemap - associated with passed parm or global package_path - if none. "$packagepath/" is replaced with "" if no - package path is set. - */ + /* ----------------------------------------------------------------------------- + * substitutePackagePath() + * + * Replace $packagepath using the javapackage typemap associated with passed + * parm or global package_path if none. "$packagepath/" is replaced with "" if + * no package path is set. + * ----------------------------------------------------------------------------- */ + void substitutePackagePath(String *text, Parm *p) { String *pkg_path= 0; @@ -4002,7 +3999,7 @@ public: for (p = throw_parm_list; p; p = nextSibling(p)) { if (Getattr(p, "tmap:throws")) { // If %catches feature, it overrides specified throws(). - if (! catches_list) { + if (!catches_list) { addThrows(n, "tmap:throws", p); } @@ -4067,8 +4064,8 @@ public: Printf(w->code, "jenv->%s(Swig::jclass_%s, Swig::director_methids[%s], %s);\n", methop, imclass_name, methid, jupcall_args); - // Generate code to handle any java exception thrown by director delegation - directorExceptHandler(n, catches_list?catches_list:throw_parm_list, w, c_classname, name); + // Generate code to handle any Java exception thrown by director delegation + directorExceptHandler(n, catches_list ? catches_list : throw_parm_list, w, c_classname, name); if (!is_void) { String *jresult_str = NewString("jresult"); @@ -4167,44 +4164,42 @@ public: } /* ------------------------------------------------------------ - * directorExcept handler: Emit code to map java exceptions - * back to C++ exceptions when feature("director:except") is appied - * to a method node + * directorExceptHandler() + * + * Emit code to map Java exceptions back to C++ exceptions when + * feature("director:except") is applied to a method node * ------------------------------------------------------------ */ + void directorExceptHandler(Node *n, ParmList *throw_parm_list, Wrapper *w, String *c_classname, String *name) { - // After director java method call, allow code for director method exception to be added + // After director Java method call, allow code for director method exception to be added // Look for director:exceptfeature - Parm *p; - - // "Default" feature, so that feature is not applied to every node, per W. Fulton - static char const * DEFAULT_DIREXCP_FEATURE = - "jthrowable $error = jenv->ExceptionOccurred();\n" - "if ($error) {\n" - " jenv->ExceptionClear();\n" - " $directorthrowshandlers\n" - " throw Swig::DirectorException(jenv, $error);\n" - "}\n"; - - String * featdirexcp = Getattr(n, "feature:director:except"); + String *featdirexcp = Getattr(n, "feature:director:except"); if (!featdirexcp) { - featdirexcp = NewString(DEFAULT_DIREXCP_FEATURE); + featdirexcp = NewString(""); + Printf(featdirexcp, "jthrowable $error = jenv->ExceptionOccurred();\n"); + Printf(featdirexcp, "if ($error) {\n"); + Printf(featdirexcp, " jenv->ExceptionClear();\n"); + Printf(featdirexcp, " $directorthrowshandlers\n"); + Printf(featdirexcp, " throw Swig::DirectorException(jenv, $error);\n"); + Printf(featdirexcp, "}\n"); } else { featdirexcp = Copy(featdirexcp); } - // Can explicitly disable director:except by setting to "" or "0" - if (0 != Len(featdirexcp) && 0 != Cmp(featdirexcp,"0")) { - // Replace any $packagepath with global -package package_path + // Can explicitly disable director:except by setting to "" or "0" + if (Len(featdirexcp) != 0 && Cmp(featdirexcp, "0") != 0) { + + // Replace $packagepath substitutePackagePath(featdirexcp, 0); - // Replace $action with any defined typemap handlers (or nothing) + // Replace $directorthrowshandlers with any defined typemap handlers (or nothing) if (Strstr(featdirexcp, "$directorthrowshandlers")) { String *directorthrowshandlers_code = NewString(""); - for (p = throw_parm_list; p; p = nextSibling(p)) { + for (Parm *p = throw_parm_list; p; p = nextSibling(p)) { String *tmapdirthrows = Getattr(p, "tmap:directorthrows"); - String * excptype = Getattr(p,"type"); + String *excptype = Getattr(p,"type"); if (!tmapdirthrows) { Swig_warning(WARN_TYPEMAP_DIRECTORTHROWS_UNDEF, input_file, line_number, @@ -4215,17 +4210,14 @@ public: tmapdirthrows = Copy(tmapdirthrows); substituteClassnameAndPackagePath(excptype, tmapdirthrows, true, p); - Printf(directorthrowshandlers_code, - "// Handle exception %s using directorthrows typemap\n" - "%s", - excptype, tmapdirthrows); + Printf(directorthrowshandlers_code, "// Handle exception %s using directorthrows typemap\n" "%s", excptype, tmapdirthrows); Delete(tmapdirthrows); } } // Delete extra new line if no handlers. - while (Replaceall(featdirexcp, "$directorthrowshandlers ", - "$directorthrowshandlers")) {} - if (0 == Len(directorthrowshandlers_code)) + while (Replaceall(featdirexcp, "$directorthrowshandlers ", "$directorthrowshandlers")) { + } + if (Len(directorthrowshandlers_code) == 0) Replaceall(featdirexcp, "$directorthrowshandlers\n", ""); else Replaceall(featdirexcp, "$directorthrowshandlers", directorthrowshandlers_code); From 97fd20a58d8273cb2097d7661ddde70ccf426cac Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Wed, 23 Oct 2013 18:43:13 +0100 Subject: [PATCH 167/481] Minor improvements to Java director:except patch --- Lib/java/std_string.i | 3 ++- Source/Modules/java.cxx | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Lib/java/std_string.i b/Lib/java/std_string.i index 6b9cb90a4..5ad7d30bc 100644 --- a/Lib/java/std_string.i +++ b/Lib/java/std_string.i @@ -38,8 +38,9 @@ class string; %typemap(directorout) string %{ if(!$input) { - if (!jenv->ExceptionCheck()) + if (!jenv->ExceptionCheck()) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null string"); + } return $null; } const char *$1_pstr = (const char *)jenv->GetStringUTFChars($input, 0); diff --git a/Source/Modules/java.cxx b/Source/Modules/java.cxx index 40c60e4da..ab15b371f 100644 --- a/Source/Modules/java.cxx +++ b/Source/Modules/java.cxx @@ -4225,7 +4225,7 @@ public: } // Replace all occurrences of $error with common var name. - Replaceall(featdirexcp, "$error", "thrown_"); + Replaceall(featdirexcp, "$error", "swigerror"); Printf(w->code, " %s\n", featdirexcp); } Delete(featdirexcp); From f55e0092efd6073542b7669381a751b3c7c7a60f Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Wed, 23 Oct 2013 18:43:36 +0100 Subject: [PATCH 168/481] Remove pointless code from Java director:except patch --- Source/Modules/java.cxx | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Source/Modules/java.cxx b/Source/Modules/java.cxx index ab15b371f..a68b3f32b 100644 --- a/Source/Modules/java.cxx +++ b/Source/Modules/java.cxx @@ -746,13 +746,6 @@ public: ++curr_class_dmethod; - /* Do we know about this director class already? */ - UpcallData *udata = Getattr(dmethods_table, key); - if (udata) { - Delete(key); - return Getattr(udata, "methodoff"); - } - String *imclass_methodidx = NewStringf("%d", n_dmethods); String *class_methodidx = NewStringf("%d", n_dmethods - first_class_dmethod); n_dmethods++; From 88678ed492f1c8c163c52059945b7cb1db30d19c Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 24 Oct 2013 07:06:55 +0100 Subject: [PATCH 169/481] director:except tweaks Recode whitespace handling, remove unnecessary comments in generated code. --- Source/Modules/java.cxx | 22 ++++++---------------- 1 file changed, 6 insertions(+), 16 deletions(-) diff --git a/Source/Modules/java.cxx b/Source/Modules/java.cxx index a68b3f32b..a0b094e34 100644 --- a/Source/Modules/java.cxx +++ b/Source/Modules/java.cxx @@ -4160,20 +4160,18 @@ public: * directorExceptHandler() * * Emit code to map Java exceptions back to C++ exceptions when - * feature("director:except") is applied to a method node + * feature("director:except") is applied to a method node. + * This is generated after the Java method upcall. * ------------------------------------------------------------ */ void directorExceptHandler(Node *n, ParmList *throw_parm_list, Wrapper *w, String *c_classname, String *name) { - // After director Java method call, allow code for director method exception to be added - // Look for director:exceptfeature String *featdirexcp = Getattr(n, "feature:director:except"); if (!featdirexcp) { featdirexcp = NewString(""); Printf(featdirexcp, "jthrowable $error = jenv->ExceptionOccurred();\n"); Printf(featdirexcp, "if ($error) {\n"); - Printf(featdirexcp, " jenv->ExceptionClear();\n"); - Printf(featdirexcp, " $directorthrowshandlers\n"); + Printf(featdirexcp, " jenv->ExceptionClear();$directorthrowshandlers\n"); Printf(featdirexcp, " throw Swig::DirectorException(jenv, $error);\n"); Printf(featdirexcp, "}\n"); } else { @@ -4181,7 +4179,7 @@ public: } // Can explicitly disable director:except by setting to "" or "0" - if (Len(featdirexcp) != 0 && Cmp(featdirexcp, "0") != 0) { + if (Len(featdirexcp) > 0 && Cmp(featdirexcp, "0") != 0) { // Replace $packagepath substitutePackagePath(featdirexcp, 0); @@ -4202,22 +4200,14 @@ public: // replace $packagepath tmapdirthrows = Copy(tmapdirthrows); substituteClassnameAndPackagePath(excptype, tmapdirthrows, true, p); - - Printf(directorthrowshandlers_code, "// Handle exception %s using directorthrows typemap\n" "%s", excptype, tmapdirthrows); + Printv(directorthrowshandlers_code, tmapdirthrows, NIL); Delete(tmapdirthrows); } } - // Delete extra new line if no handlers. - while (Replaceall(featdirexcp, "$directorthrowshandlers ", "$directorthrowshandlers")) { - } - if (Len(directorthrowshandlers_code) == 0) - Replaceall(featdirexcp, "$directorthrowshandlers\n", ""); - else - Replaceall(featdirexcp, "$directorthrowshandlers", directorthrowshandlers_code); + Replaceall(featdirexcp, "$directorthrowshandlers", directorthrowshandlers_code); Delete(directorthrowshandlers_code); } - // Replace all occurrences of $error with common var name. Replaceall(featdirexcp, "$error", "swigerror"); Printf(w->code, " %s\n", featdirexcp); } From fc13a24ecb16d26e38c68d9b72dcdcde6611c72d Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 24 Oct 2013 07:45:56 +0100 Subject: [PATCH 170/481] directorthrows warning fixes - Fix line number display - now the usual simpler warning message can be displayed for WARN_TYPEMAP_DIRECTORTHROWS_UNDEF - it still points to the problem method. - Use macro names for warning suppression in test. --- .../java_director_exception_feature.i | 3 +++ .../java_director_exception_feature_nspace.i | 2 +- Source/Modules/java.cxx | 24 +++++++++---------- 3 files changed, 15 insertions(+), 14 deletions(-) diff --git a/Examples/test-suite/java_director_exception_feature.i b/Examples/test-suite/java_director_exception_feature.i index b649b541d..fc1af7a96 100644 --- a/Examples/test-suite/java_director_exception_feature.i +++ b/Examples/test-suite/java_director_exception_feature.i @@ -2,6 +2,8 @@ %include +%warnfilter(SWIGWARN_TYPEMAP_DIRECTORTHROWS_UNDEF) MyNS::Foo::directorthrows_warning; + %{ #if defined(_MSC_VER) #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow) @@ -178,6 +180,7 @@ public: virtual std::string ping(int excp) throw(int,MyNS::Exception2) = 0; virtual std::string pong(int excp) /* throws MyNS::Exception1 MyNS::Exception2 MyNS::Unexpected) */ = 0; virtual std::string genericpong(int excp) /* unspecified throws - exception is always DirectorException in C++, translated back to whatever thrown in java */ = 0; + virtual std::string directorthrows_warning(int excp) throw(double) {} }; // Make a bar from a foo, so a call to Java Bar diff --git a/Examples/test-suite/java_director_exception_feature_nspace.i b/Examples/test-suite/java_director_exception_feature_nspace.i index 8723ef738..1f3d97ad3 100644 --- a/Examples/test-suite/java_director_exception_feature_nspace.i +++ b/Examples/test-suite/java_director_exception_feature_nspace.i @@ -6,7 +6,7 @@ // When using namespaces with no -package, must put JNI classes into a namespace %pragma(java) jniclasspackage=%{MyNS_JNI%} -%warnfilter(826); +%warnfilter(SWIGWARN_JAVA_NSPACE_WITHOUT_PACKAGE); %{ #if defined(_MSC_VER) diff --git a/Source/Modules/java.cxx b/Source/Modules/java.cxx index a0b094e34..37c3c5afb 100644 --- a/Source/Modules/java.cxx +++ b/Source/Modules/java.cxx @@ -4058,7 +4058,7 @@ public: Printf(w->code, "jenv->%s(Swig::jclass_%s, Swig::director_methids[%s], %s);\n", methop, imclass_name, methid, jupcall_args); // Generate code to handle any Java exception thrown by director delegation - directorExceptHandler(n, catches_list ? catches_list : throw_parm_list, w, c_classname, name); + directorExceptHandler(n, catches_list ? catches_list : throw_parm_list, w); if (!is_void) { String *jresult_str = NewString("jresult"); @@ -4164,7 +4164,7 @@ public: * This is generated after the Java method upcall. * ------------------------------------------------------------ */ - void directorExceptHandler(Node *n, ParmList *throw_parm_list, Wrapper *w, String *c_classname, String *name) { + void directorExceptHandler(Node *n, ParmList *throw_parm_list, Wrapper *w) { String *featdirexcp = Getattr(n, "feature:director:except"); if (!featdirexcp) { @@ -4189,19 +4189,17 @@ public: String *directorthrowshandlers_code = NewString(""); for (Parm *p = throw_parm_list; p; p = nextSibling(p)) { - String *tmapdirthrows = Getattr(p, "tmap:directorthrows"); - String *excptype = Getattr(p,"type"); + String *tm = Getattr(p, "tmap:directorthrows"); + String *t = Getattr(p,"type"); - if (!tmapdirthrows) { - Swig_warning(WARN_TYPEMAP_DIRECTORTHROWS_UNDEF, input_file, line_number, - "Feature director:except on %s::%s with $directorthrowshandlers requires directorthrows typemap for exception %s.\n", - SwigType_namestr(c_classname),SwigType_namestr(name), excptype); - } else { + if (tm) { + String *directorthrows = Copy(tm); // replace $packagepath - tmapdirthrows = Copy(tmapdirthrows); - substituteClassnameAndPackagePath(excptype, tmapdirthrows, true, p); - Printv(directorthrowshandlers_code, tmapdirthrows, NIL); - Delete(tmapdirthrows); + substituteClassnameAndPackagePath(t, directorthrows, true, p); + Printv(directorthrowshandlers_code, directorthrows, NIL); + Delete(directorthrows); + } else { + Swig_warning(WARN_TYPEMAP_DIRECTORTHROWS_UNDEF, Getfile(n), Getline(n), "No directorthrows typemap defined for %s\n", SwigType_str(t, 0)); } } Replaceall(featdirexcp, "$directorthrowshandlers", directorthrowshandlers_code); From cf4f5e8118021de221390bbb1a03df3a129d8adb Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 24 Oct 2013 08:03:33 +0100 Subject: [PATCH 171/481] More conventional variable naming in directorExceptHandling --- Source/Modules/java.cxx | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/Source/Modules/java.cxx b/Source/Modules/java.cxx index 37c3c5afb..4a2870505 100644 --- a/Source/Modules/java.cxx +++ b/Source/Modules/java.cxx @@ -4166,26 +4166,26 @@ public: void directorExceptHandler(Node *n, ParmList *throw_parm_list, Wrapper *w) { - String *featdirexcp = Getattr(n, "feature:director:except"); - if (!featdirexcp) { - featdirexcp = NewString(""); - Printf(featdirexcp, "jthrowable $error = jenv->ExceptionOccurred();\n"); - Printf(featdirexcp, "if ($error) {\n"); - Printf(featdirexcp, " jenv->ExceptionClear();$directorthrowshandlers\n"); - Printf(featdirexcp, " throw Swig::DirectorException(jenv, $error);\n"); - Printf(featdirexcp, "}\n"); + String *directorexcept = Getattr(n, "feature:director:except"); + if (!directorexcept) { + directorexcept = NewString(""); + Printf(directorexcept, "jthrowable $error = jenv->ExceptionOccurred();\n"); + Printf(directorexcept, "if ($error) {\n"); + Printf(directorexcept, " jenv->ExceptionClear();$directorthrowshandlers\n"); + Printf(directorexcept, " throw Swig::DirectorException(jenv, $error);\n"); + Printf(directorexcept, "}\n"); } else { - featdirexcp = Copy(featdirexcp); + directorexcept = Copy(directorexcept); } // Can explicitly disable director:except by setting to "" or "0" - if (Len(featdirexcp) > 0 && Cmp(featdirexcp, "0") != 0) { + if (Len(directorexcept) > 0 && Cmp(directorexcept, "0") != 0) { // Replace $packagepath - substitutePackagePath(featdirexcp, 0); + substitutePackagePath(directorexcept, 0); // Replace $directorthrowshandlers with any defined typemap handlers (or nothing) - if (Strstr(featdirexcp, "$directorthrowshandlers")) { + if (Strstr(directorexcept, "$directorthrowshandlers")) { String *directorthrowshandlers_code = NewString(""); for (Parm *p = throw_parm_list; p; p = nextSibling(p)) { @@ -4202,14 +4202,14 @@ public: Swig_warning(WARN_TYPEMAP_DIRECTORTHROWS_UNDEF, Getfile(n), Getline(n), "No directorthrows typemap defined for %s\n", SwigType_str(t, 0)); } } - Replaceall(featdirexcp, "$directorthrowshandlers", directorthrowshandlers_code); + Replaceall(directorexcept, "$directorthrowshandlers", directorthrowshandlers_code); Delete(directorthrowshandlers_code); } - Replaceall(featdirexcp, "$error", "swigerror"); - Printf(w->code, " %s\n", featdirexcp); + Replaceall(directorexcept, "$error", "swigerror"); + Printf(w->code, " %s\n", directorexcept); } - Delete(featdirexcp); + Delete(directorexcept); } /* ------------------------------------------------------------ From e717ed3056b5f369e28b9a24b41dab3e9b15a0c6 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 29 Oct 2013 19:50:13 +0000 Subject: [PATCH 172/481] Improve directorthrows patch Separate $packagepath substitution from non-director code (as documented). Some of the directorthrows code has been rewritten so that fewer code changes are present compared to before the patch. canonicalizeJNIDescriptor() refactored so it can be used for general code, not just the directorin:descriptor typemap attribute. Better implementation for substituting '$packagepath/$javaclassname' - fixes some quirks in '$packagepath/$javaclassname' descriptor substitutions if a dot was present in the descriptor string. --- Source/Modules/java.cxx | 112 +++++++++++++++++----------------------- 1 file changed, 46 insertions(+), 66 deletions(-) diff --git a/Source/Modules/java.cxx b/Source/Modules/java.cxx index 4a2870505..6576ad544 100644 --- a/Source/Modules/java.cxx +++ b/Source/Modules/java.cxx @@ -192,28 +192,31 @@ public: * * Test to see if a type corresponds to something wrapped with a proxy class. * Return NULL if not otherwise the proxy class name, fully qualified with - * package name if the nspace feature is used. + * package name if the nspace feature is used, unless jnidescriptor is true as + * the package name is handled differently (unfortunately for legacy reasons). * ----------------------------------------------------------------------------- */ - String *getProxyName(SwigType *t) { + String *getProxyName(SwigType *t, bool jnidescriptor = false) { String *proxyname = NULL; if (proxy_flag) { Node *n = classLookup(t); if (n) { proxyname = Getattr(n, "proxyname"); - if (!proxyname) { + if (!proxyname || jnidescriptor) { String *nspace = Getattr(n, "sym:nspace"); String *symname = Getattr(n, "sym:name"); if (nspace) { - if (package) + if (package && !jnidescriptor) proxyname = NewStringf("%s.%s.%s", package, nspace, symname); else proxyname = NewStringf("%s.%s", nspace, symname); } else { proxyname = Copy(symname); } - Setattr(n, "proxyname", proxyname); - Delete(proxyname); + if (!jnidescriptor) { + Setattr(n, "proxyname", proxyname); // Cache it + Delete(proxyname); + } } } } @@ -2885,6 +2888,7 @@ public: * getEnumName() * * If jnidescriptor is set, inner class names are separated with '$' otherwise a '.' + * and the package is also not added to the name. * ----------------------------------------------------------------------------- */ String *getEnumName(SwigType *t, bool jnidescriptor) { @@ -2899,7 +2903,7 @@ public: String *scopename_prefix = Swig_scopename_prefix(Getattr(n, "name")); String *proxyname = 0; if (scopename_prefix) { - proxyname = getProxyName(scopename_prefix); + proxyname = getProxyName(scopename_prefix, jnidescriptor); } if (proxyname) { const char *class_separator = jnidescriptor ? "$" : "."; @@ -2908,7 +2912,7 @@ public: // global enum or enum in a namespace String *nspace = Getattr(n, "sym:nspace"); if (nspace) { - if (package) + if (package && !jnidescriptor) enumname = NewStringf("%s.%s.%s", package, nspace, symname); else enumname = NewStringf("%s.%s", nspace, symname); @@ -2916,8 +2920,8 @@ public: enumname = Copy(symname); } } - if (!jnidescriptor) { // not cached - Setattr(n, "enumname", enumname); + if (!jnidescriptor) { + Setattr(n, "enumname", enumname); // Cache it Delete(enumname); } Delete(scopename_prefix); @@ -2935,37 +2939,25 @@ public: * that SWIG knows about. Also substitutes enums with enum name. * Otherwise use the $descriptor name for the Java class name. Note that the $&javaclassname substitution * is the same as a $&descriptor substitution, ie one pointer added to descriptor name. + * Note that the path separator is a '.' unless jnidescriptor is set. * Inputs: * pt - parameter type * tm - typemap contents that might contain the special variable to be replaced - * jnidescriptor - if set, inner class names are separated with '$' otherwise a '.' - * p - a parameter type, that may hold a javapackage typemap. If passed, - * the $packagepath will be substituted, but call method below instead. + * jnidescriptor - if set, inner class names are separated with '$' otherwise a '/' is used for the path separator * 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 jnidescriptor = false, Parm *pkgpathparm = 0) { - return substituteClassnameAndPackagePath( pt, tm, jnidescriptor, pkgpathparm); - } - - /* ----------------------------------------------------------------------------- - * substituteClassnameAndPackagePath() - * Used to canonicalize JNI descriptors, including code emitting director throws typemaps. - * - * Only usage always has jnidescriptor AND p set. Maybe collapse args. - * ----------------------------------------------------------------------------- */ - - bool substituteClassnameAndPackagePath(SwigType *pt, String *tm, bool jnidescriptor, Parm *pkgpathparm) { + bool substituteClassname(SwigType *pt, String *tm, bool jnidescriptor = false) { bool substitution_performed = false; SwigType *type = Copy(SwigType_typedef_resolve_all(pt)); SwigType *strippedtype = SwigType_strip_qualifiers(type); if (Strstr(tm, "$javaclassname")) { SwigType *classnametype = Copy(strippedtype); - substituteClassnameSpecialVariable(classnametype, tm, "$javaclassname", jnidescriptor, pkgpathparm); + substituteClassnameSpecialVariable(classnametype, tm, "$javaclassname", jnidescriptor); substitution_performed = true; Delete(classnametype); } @@ -2973,7 +2965,7 @@ public: SwigType *classnametype = Copy(strippedtype); Delete(SwigType_pop(classnametype)); if (Len(classnametype) > 0) { - substituteClassnameSpecialVariable(classnametype, tm, "$*javaclassname", jnidescriptor, pkgpathparm); + substituteClassnameSpecialVariable(classnametype, tm, "$*javaclassname", jnidescriptor); substitution_performed = true; } Delete(classnametype); @@ -2981,7 +2973,7 @@ public: if (Strstr(tm, "$&javaclassname")) { SwigType *classnametype = Copy(strippedtype); SwigType_add_pointer(classnametype); - substituteClassnameSpecialVariable(classnametype, tm, "$&javaclassname", jnidescriptor, pkgpathparm); + substituteClassnameSpecialVariable(classnametype, tm, "$&javaclassname", jnidescriptor); substitution_performed = true; Delete(classnametype); } @@ -2996,40 +2988,27 @@ public: * substituteClassnameSpecialVariable() * ----------------------------------------------------------------------------- */ - void substituteClassnameSpecialVariable(SwigType *classnametype, String *tm, const char *classnamespecialvariable, bool jnidescriptor, Parm * pkgpathparm) { - String * replacementname; + void substituteClassnameSpecialVariable(SwigType *classnametype, String *tm, const char *classnamespecialvariable, bool jnidescriptor) { + String *replacementname; if (SwigType_isenum(classnametype)) { - replacementname = Copy(getEnumName(classnametype, jnidescriptor)); - if (!replacementname) { + String *enumname = getEnumName(classnametype, jnidescriptor); + if (enumname) + replacementname = Copy(enumname); + else replacementname = NewString("int"); - } } else { - replacementname = Copy(getProxyName(classnametype)); - if (! replacementname) { + String *classname = getProxyName(classnametype, jnidescriptor); // getProxyName() works for pointers to classes too + if (classname) { + replacementname = Copy(classname); + } else { // use $descriptor if SWIG does not know anything about this type. Note that any typedefs are resolved. replacementname = NewStringf("SWIGTYPE%s", SwigType_manglestr(classnametype)); + // Add to hash table so that the type wrapper classes can be created later Setattr(swig_types_hash, replacementname, classnametype); } } - - if (pkgpathparm) { - if (Strchr(replacementname, '.') != NULL) { - // nspace feature in use, indicated by dots (!?) - // if replacementname is in name space form, a.b.c, discard - // packagepath from any string like $packagepath/$javaclassname - // since IT WAS ADDED in getProxyName - // But $packagepath could still be used by itself in same string - // since this is used to emit general code blocks for director - // exceptions - // So do this to get rid of all combined forms before subsitituting - Replaceall(tm, "$packagepath/$javaclassname","$javaclassname"); - Replaceall(tm, "$packagepath/$*javaclassname","$*javaclassname"); - Replaceall(tm, "$packagepath/$&javaclassname","$&javaclassname"); - } - substitutePackagePath(tm, pkgpathparm); - } if (jnidescriptor) Replaceall(replacementname,".","/"); Replaceall(tm, classnamespecialvariable, replacementname); @@ -3533,8 +3512,8 @@ public: * substitutePackagePath() * * Replace $packagepath using the javapackage typemap associated with passed - * parm or global package_path if none. "$packagepath/" is replaced with "" if - * no package path is set. + * parm or global package if p is 0. "$packagepath/" is replaced with "" if + * no package is set. Note that the path separator is a '/'. * ----------------------------------------------------------------------------- */ void substitutePackagePath(String *text, Parm *p) { @@ -3543,21 +3522,23 @@ public: if (p) pkg_path = Swig_typemap_lookup("javapackage", p, "", 0); if (!pkg_path || Len(pkg_path) == 0) - pkg_path = package_path; + pkg_path = Copy(package_path); if (Len(pkg_path) > 0) { + Replaceall(pkg_path, ".", "/"); Replaceall(text, "$packagepath", pkg_path); } else { Replaceall(text, "$packagepath/", empty_string); Replaceall(text, "$packagepath", empty_string); } + Delete(pkg_path); } /* --------------------------------------------------------------- * Canonicalize the JNI field descriptor * - * Replace the $packagepath and $javaclassname family of - * variables with the desired package and Java descriptor as + * Replace the $packagepath and $javaclassname family of special + * variables with the desired package and Java proxy name as * required in the JNI field descriptors. * * !!SFM!! If $packagepath occurs in the field descriptor, but @@ -3568,10 +3549,10 @@ public: String *canonicalizeJNIDescriptor(String *descriptor_in, Parm *p) { SwigType *type = Getattr(p, "type"); - String *descriptor_out = Copy(descriptor_in); - // This returns a JNI descriptor, in path format - substituteClassnameAndPackagePath(type, descriptor_out, true, p); + + substituteClassname(type, descriptor_out, true); + substitutePackagePath(descriptor_out, p); return descriptor_out; } @@ -3968,7 +3949,7 @@ public: // Get any Java exception classes in the throws typemap ParmList *throw_parm_list = NULL; - // May need to add throws to director classes if %catches defined + // May need to add Java throws clause to director methods if %catches defined // Get any Java exception classes in the throws typemap ParmList *catches_list = Getattr(n, "catchlist"); if (catches_list) { @@ -3991,7 +3972,7 @@ public: } for (p = throw_parm_list; p; p = nextSibling(p)) { if (Getattr(p, "tmap:throws")) { - // If %catches feature, it overrides specified throws(). + // %catches replaces the specified exception specification if (!catches_list) { addThrows(n, "tmap:throws", p); } @@ -4190,15 +4171,14 @@ public: for (Parm *p = throw_parm_list; p; p = nextSibling(p)) { String *tm = Getattr(p, "tmap:directorthrows"); - String *t = Getattr(p,"type"); if (tm) { - String *directorthrows = Copy(tm); - // replace $packagepath - substituteClassnameAndPackagePath(t, directorthrows, true, p); + // replace $packagepath/$javaclassname + String *directorthrows = canonicalizeJNIDescriptor(tm, p); Printv(directorthrowshandlers_code, directorthrows, NIL); Delete(directorthrows); } else { + String *t = Getattr(p,"type"); Swig_warning(WARN_TYPEMAP_DIRECTORTHROWS_UNDEF, Getfile(n), Getline(n), "No directorthrows typemap defined for %s\n", SwigType_str(t, 0)); } } From baec61c5abc689379c205ffdaea395c96a3482cd Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 2 Nov 2013 12:33:33 +0000 Subject: [PATCH 173/481] java_director_exception_feature_nspace test case changes - The implementation for SEP for the classpath is not portable, eg the separator should be ':' not ';' on Cygwin, but clearly it could be ';' if using a native Windows version of Java. In the past the test-suite has been constructed to avoid this problem and these changes go back to this approach at the expense of not testing nspace without -package (but not specifying -package is quite unusual when using nspace, so no great loss). This test could be restored to how it was if the separator is detected at configure time from the JVM itself, eg by calling Java code: System.out.println(System.getProperty("path.separator")); - Mangle the non-public classes in the _runme.java file so that they are unique to this testcase (the .class files generated can interfere with other tests). - Const corrections and spelling mistakes fixed in test case. test case improvements --- Examples/test-suite/java/Makefile.in | 15 ++----- ...rector_exception_feature_nspace_runme.java | 30 +++++++------- .../java_director_exception_feature.i | 14 +++---- .../java_director_exception_feature_nspace.i | 39 ++++++++++--------- 4 files changed, 46 insertions(+), 52 deletions(-) diff --git a/Examples/test-suite/java/Makefile.in b/Examples/test-suite/java/Makefile.in index 52ae78563..1bd4b0261 100644 --- a/Examples/test-suite/java/Makefile.in +++ b/Examples/test-suite/java/Makefile.in @@ -46,18 +46,9 @@ JAVA_PACKAGE = $* JAVA_PACKAGEOPT = -package $(JAVA_PACKAGE) SWIGOPT += $(JAVA_PACKAGEOPT) -RUNME_CLASSPATH = -classpath . -ifeq (Cygwin,$(shell uname -o 2>/dev/null)) -SEP=; -else -SEP=: -endif - # Custom tests - tests with additional commandline options java_nspacewithoutpackage.%: JAVA_PACKAGEOPT = -java_director_exception_feature_nspace.%: JAVA_PACKAGEOPT = -java_director_exception_feature_nspace.%: RUNME_CLASSPATH = -classpath .$(SEP)./java_director_exception_feature_nspace - +java_director_exception_feature_nspace.%: JAVA_PACKAGE = $*Package nspace.%: JAVA_PACKAGE = $*Package nspace_extend.%: JAVA_PACKAGE = $*Package director_nspace.%: JAVA_PACKAGE = $*Package @@ -96,8 +87,8 @@ setup = \ run_testcase = \ cd $(JAVA_PACKAGE) && $(COMPILETOOL) $(JAVAC) -classpath . `find . -name "*.java"` && cd .. && \ if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - $(COMPILETOOL) $(JAVAC) $(RUNME_CLASSPATH) -d . $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ - env LD_LIBRARY_PATH="$(JAVA_PACKAGE):$$LD_LIBRARY_PATH" PATH="$(JAVA_PACKAGE):$$PATH" SHLIB_PATH="$(JAVA_PACKAGE):$$SHLIB_PATH" DYLD_LIBRARY_PATH="$(JAVA_PACKAGE):$$DYLD_LIBRARY_PATH" $(RUNTOOL) $(JAVA) $(JAVAFLAGS) $(RUNME_CLASSPATH) $*_runme; \ + $(COMPILETOOL) $(JAVAC) -classpath . -d . $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ + env LD_LIBRARY_PATH="$(JAVA_PACKAGE):$$LD_LIBRARY_PATH" PATH="$(JAVA_PACKAGE):$$PATH" SHLIB_PATH="$(JAVA_PACKAGE):$$SHLIB_PATH" DYLD_LIBRARY_PATH="$(JAVA_PACKAGE):$$DYLD_LIBRARY_PATH" $(RUNTOOL) $(JAVA) $(JAVAFLAGS) -classpath . $*_runme; \ fi # Clean: remove testcase directories diff --git a/Examples/test-suite/java/java_director_exception_feature_nspace_runme.java b/Examples/test-suite/java/java_director_exception_feature_nspace_runme.java index 0cde36953..ea7da5c1a 100644 --- a/Examples/test-suite/java/java_director_exception_feature_nspace_runme.java +++ b/Examples/test-suite/java/java_director_exception_feature_nspace_runme.java @@ -1,5 +1,5 @@ -import MyNS.*; -import MyNS_JNI.*; +import java_director_exception_feature_nspacePackage.*; +import java_director_exception_feature_nspacePackage.MyNS.*; class java_director_exception_feature_nspace_Consts { public static final String PINGEXCP1 = "Ping MyJavaException1"; // should get translated through an int on ping @@ -18,25 +18,25 @@ class java_director_exception_feature_nspace_Consts { // an exception not mentioned or wrapped by the swig interface, // to reconstruct using generic DirectorException handling -class NewCheckedException extends Exception { - public NewCheckedException(String s) { +class java_director_exception_feature_nspace_NewCheckedException extends Exception { + public java_director_exception_feature_nspace_NewCheckedException(String s) { super(s); } } // an exception not mentioned or wrapped by the swig interface, // to reconstruct using generic DirectorException handling -class NewUncheckedException extends RuntimeException { - public NewUncheckedException(String s) { +class java_director_exception_feature_nspace_NewUncheckedException extends RuntimeException { + public java_director_exception_feature_nspace_NewUncheckedException(String s) { super(s); } } -// an exception not constructable from a string, +// an exception not constructible from a string, // to test DirectorException fallback reconstruction -class UnconstructableException extends Exception { +class java_director_exception_feature_nspace_UnconstructibleException extends Exception { private int extrastate; - public UnconstructableException(int a, String s) { + public java_director_exception_feature_nspace_UnconstructibleException(int a, String s) { super(s); extrastate = a; } @@ -62,15 +62,15 @@ class java_director_exception_feature_nspace_MyFooDirectorImpl extends Foo { } @Override - public String genericpong(int excp) throws MyJavaException1, NewCheckedException, UnconstructableException { + public String genericpong(int excp) throws MyJavaException1, java_director_exception_feature_nspace_NewCheckedException, java_director_exception_feature_nspace_UnconstructibleException { if (excp == 1) throw new MyJavaException1(java_director_exception_feature_nspace_Consts.GENERICPONGEXCP1); if (excp == 2) - throw new NewCheckedException(java_director_exception_feature_nspace_Consts.GENERICPONGEXCP2); + throw new java_director_exception_feature_nspace_NewCheckedException(java_director_exception_feature_nspace_Consts.GENERICPONGEXCP2); if (excp == 3) - throw new NewUncheckedException(java_director_exception_feature_nspace_Consts.GENERICPONGEXCP3); + throw new java_director_exception_feature_nspace_NewUncheckedException(java_director_exception_feature_nspace_Consts.GENERICPONGEXCP3); if (excp == 4) - throw new UnconstructableException(1, java_director_exception_feature_nspace_Consts.GENERICPONGEXCP4); + throw new java_director_exception_feature_nspace_UnconstructibleException(1, java_director_exception_feature_nspace_Consts.GENERICPONGEXCP4); return "GenericPong director returned"; } } @@ -128,11 +128,11 @@ public class java_director_exception_feature_nspace_runme { failif( ! java_director_exception_feature_nspace_Consts.GENERICPONGEXCP1.equals(e.getMessage()), "Expected exception has unexpected message: '" + e.getMessage() + "'"); } try { b.genericpong(2); fail("No exception thrown in genericpong(2)");} - catch (NewCheckedException e) { + catch (java_director_exception_feature_nspace_NewCheckedException e) { failif( ! java_director_exception_feature_nspace_Consts.GENERICPONGEXCP2.equals(e.getMessage()), "Expected exception has unexpected message: '" + e.getMessage() + "'"); } try { b.genericpong(3); fail("No exception thrown in genericpong(3)");} - catch (NewUncheckedException e) { + catch (java_director_exception_feature_nspace_NewUncheckedException e) { failif( ! java_director_exception_feature_nspace_Consts.GENERICPONGEXCP3.equals(e.getMessage()), "Expected exception has unexpected message: '" + e.getMessage() + "'"); } try { b.genericpong(4); fail("No exception thrown in genericpong(4)");} diff --git a/Examples/test-suite/java_director_exception_feature.i b/Examples/test-suite/java_director_exception_feature.i index fc1af7a96..1552454dc 100644 --- a/Examples/test-suite/java_director_exception_feature.i +++ b/Examples/test-suite/java_director_exception_feature.i @@ -138,26 +138,26 @@ %feature("director") Foo; // Rename exceptions on java side to make translation of exceptions more clear -%rename(MyJavaException1,fullname=1) MyNS::Exception1; -%rename(MyJavaException2,fullname=1) MyNS::Exception2; -%rename(MyJavaUnexpected,fullname=1) MyNS::Unexpected; +%rename(MyJavaException1) MyNS::Exception1; +%rename(MyJavaException2) MyNS::Exception2; +%rename(MyJavaUnexpected) MyNS::Unexpected; %typemap(javabase) ::MyNS::Exception1,::MyNS::Exception2,::MyNS::Unexpected "java.lang.Exception"; -%rename(getMessage) what(); // Rename all what() methods +%rename(getMessage) what() const; // Rename all what() methods namespace MyNS { struct Exception1 { Exception1(const std::string& what); - const char * what(); + const char * what() const; }; struct Exception2 { Exception2(const std::string& what); - const char * what(); + const char * what() const; }; struct Unexpected { Unexpected(const std::string& what); - const char * what(); + const char * what() const; }; } diff --git a/Examples/test-suite/java_director_exception_feature_nspace.i b/Examples/test-suite/java_director_exception_feature_nspace.i index 1f3d97ad3..aea362905 100644 --- a/Examples/test-suite/java_director_exception_feature_nspace.i +++ b/Examples/test-suite/java_director_exception_feature_nspace.i @@ -4,9 +4,12 @@ %nspace; // turn namespace feature on for everything. -// When using namespaces with no -package, must put JNI classes into a namespace -%pragma(java) jniclasspackage=%{MyNS_JNI%} -%warnfilter(SWIGWARN_JAVA_NSPACE_WITHOUT_PACKAGE); +#define PACKAGEDOT "java_director_exception_feature_nspacePackage." +#define PACKAGESLASH "java_director_exception_feature_nspacePackage/" +%{ +#define PACKAGEDOT "java_director_exception_feature_nspacePackage." +#define PACKAGESLASH "java_director_exception_feature_nspacePackage/" +%} %{ #if defined(_MSC_VER) @@ -83,24 +86,24 @@ // $javaclassname or $packagepath ("java_director_exception_feature" here) // throws typemaps for c++->java exception conversions -%typemap(throws,throws="MyNS.MyJavaException1") MyNS::Exception1 %{ - jclass excpcls = jenv->FindClass("MyNS/MyJavaException1"); +%typemap(throws,throws=PACKAGEDOT"MyNS.MyJavaException1") MyNS::Exception1 %{ + jclass excpcls = jenv->FindClass(PACKAGESLASH"MyNS/MyJavaException1"); if (excpcls) { jenv->ThrowNew(excpcls, $1.what()); } return $null; %} -%typemap(throws,throws="MyNS.MyJavaException1") int %{ - jclass excpcls = jenv->FindClass("MyNS/MyJavaException1"); +%typemap(throws,throws=PACKAGEDOT"MyNS.MyJavaException1") int %{ + jclass excpcls = jenv->FindClass(PACKAGESLASH"MyNS/MyJavaException1"); if (excpcls) { jenv->ThrowNew(excpcls, "Threw some integer"); } return $null; %} -%typemap(throws,throws="MyNS.MyJavaException2") MyNS::Exception2 %{ - jclass excpcls = jenv->FindClass("MyNS/MyJavaException2"); +%typemap(throws,throws=PACKAGEDOT"MyNS.MyJavaException2") MyNS::Exception2 %{ + jclass excpcls = jenv->FindClass(PACKAGESLASH"MyNS/MyJavaException2"); if (excpcls) { jenv->ThrowNew(excpcls, $1.what()); } @@ -108,8 +111,8 @@ %} -%typemap(throws,throws="MyNS.MyJavaUnexpected") MyNS::Unexpected %{ - jclass excpcls = jenv->FindClass("MyNS/MyJavaUnexpected"); +%typemap(throws,throws=PACKAGEDOT"MyNS.MyJavaUnexpected") MyNS::Unexpected %{ + jclass excpcls = jenv->FindClass(PACKAGESLASH"MyNS/MyJavaUnexpected"); if (excpcls) { jenv->ThrowNew(excpcls, $1.what()); } @@ -143,26 +146,26 @@ %feature("director") Foo; // Rename exceptions on java side to make translation of exceptions more clear -%rename(MyJavaException1,fullname=1) MyNS::Exception1; -%rename(MyJavaException2,fullname=1) MyNS::Exception2; -%rename(MyJavaUnexpected,fullname=1) MyNS::Unexpected; +%rename(MyJavaException1) MyNS::Exception1; +%rename(MyJavaException2) MyNS::Exception2; +%rename(MyJavaUnexpected) MyNS::Unexpected; %typemap(javabase) ::MyNS::Exception1,::MyNS::Exception2,::MyNS::Unexpected "java.lang.Exception"; -%rename(getMessage) what(); // Rename all what() methods +%rename(getMessage) what() const; // Rename all what() methods namespace MyNS { struct Exception1 { Exception1(const std::string& what); - const char * what(); + const char * what() const; }; struct Exception2 { Exception2(const std::string& what); - const char * what(); + const char * what() const; }; struct Unexpected { Unexpected(const std::string& what); - const char * what(); + const char * what() const; }; } From fdc1772e38b4d27050bc1d4958f155ec67760fc8 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 2 Nov 2013 19:56:51 +0000 Subject: [PATCH 174/481] Cosmetics/code style conformance in newly added Java director exception handling --- Lib/java/director.swg | 252 +++++++++++++++++++----------------------- 1 file changed, 113 insertions(+), 139 deletions(-) diff --git a/Lib/java/director.swg b/Lib/java/director.swg index 8c7dca294..346cec2cc 100644 --- a/Lib/java/director.swg +++ b/Lib/java/director.swg @@ -11,7 +11,10 @@ #include #endif +#include + namespace Swig { + /* Java object wrapper */ class JObjectWrapper { public: @@ -74,8 +77,7 @@ namespace Swig { } /* Java proxy releases ownership of C++ object, C++ object is now - responsible for destruction (creates NewGlobalRef to pin Java - proxy) */ + responsible for destruction (creates NewGlobalRef to pin Java proxy) */ void java_change_ownership(JNIEnv *jenv, jobject jself, bool take_or_release) { if (take_or_release) { /* Java takes ownership of C++ object's lifetime. */ if (!weak_global_) { @@ -83,7 +85,8 @@ namespace Swig { jthis_ = jenv->NewWeakGlobalRef(jself); weak_global_ = true; } - } else { /* Java releases ownership of C++ object's lifetime */ + } else { + /* Java releases ownership of C++ object's lifetime */ if (weak_global_) { jenv->DeleteWeakGlobalRef((jweak)jthis_); jthis_ = jenv->NewGlobalRef(jself); @@ -191,119 +194,26 @@ namespace Swig { swig_self_.java_change_ownership(jenv, jself, take_or_release); } }; -} -// Default exception handler for all director methods. -// Can override this for specific methods -// This just documents the default. It is not actually attached as a feature -// for efficiency reasons (and is defined in java.cxx) It can be overridden -// as a feature for specific methods or globally. + // Utility methods and classes for exception handling. -//%feature("director:except") %{ -// jthrowable $error = jenv->ExceptionOccurred(); -// if ($error) { -// jenv->ExceptionClear(); -// $directorthrowshandlers -// throw Swig::DirectorException(jenv, $error); -// } -//%} - -// Define some utility methods and classes. Cannot use fragments since -// these may be used by %features and in directorthrows typemaps - -#include - -// Simple holder for exception messages, allowing access to a c-style string -namespace Swig { - struct JavaString { - JavaString(JNIEnv * jenv, jstring jstr):jenv_(jenv), jstr_(jstr), cstr_(0) { - if (jenv_ && jstr_) { - // Get the null-terminated c-string out, and hold it - cstr_ = (const char *) jenv_->GetStringUTFChars(jstr_, NULL); - } - } - ~JavaString() { - if (jenv_ && jstr_ && cstr_) { - jenv_->ReleaseStringUTFChars(jstr_, cstr_); - } - } - const char *cstr() { - return cstr_ ? cstr_ : ""; - } - - private: - JNIEnv * jenv_; - jstring jstr_; - const char * cstr_; - - // non-copyable - JavaString(const JavaString &); - JavaString & operator=(const JavaString &); - }; - - struct JavaExceptionMessage { - JavaExceptionMessage(JNIEnv * jenv, jthrowable excp) : - jstrholder_(jenv,exceptionMsgJstr(jenv,excp)) { - } - ~JavaExceptionMessage() { - } - const char *message() { - return jstrholder_.cstr(); - } - - private: - JavaString jstrholder_; - - // non-copyable - JavaExceptionMessage(const JavaExceptionMessage &); - JavaExceptionMessage & operator=(const JavaExceptionMessage &); - - // Static method to initialize jstrholder_ - static jstring exceptionMsgJstr(JNIEnv * jenv, jthrowable excp) { - jstring jmsg = NULL; - if (jenv && excp) { - jenv->ExceptionClear(); // Cannot invoke methods with pending exception - jclass thrwclz = jenv->GetObjectClass(excp); - if (thrwclz) { - // if no getMessage() or other exception, no msg available. - jmethodID getThrowableMsgMethodID = - jenv->GetMethodID(thrwclz, "getMessage", "()Ljava/lang/String;"); - if (getThrowableMsgMethodID && !jenv->ExceptionCheck()) { - // if problem accessing exception message string, no msg available. - jmsg = (jstring) - jenv->CallObjectMethod(excp, getThrowableMsgMethodID); - } - } - if (jmsg == NULL && jenv->ExceptionCheck()) { - jenv->ExceptionClear(); - } - } - return jmsg; - } - }; - - - //////////////////////////////////// - - bool ExceptionMatches(JNIEnv * jenv, jthrowable excp, - const char *clzname) { + // Helper method to determine if a Java throwable matches a particular Java class type + bool ExceptionMatches(JNIEnv *jenv, jthrowable excp, const char *clzname) { jboolean matches = false; if (excp && jenv && clzname) { - // Have to clear exceptions for correct behavior. Code around - // ExceptionMatches should restore pending exception if - // desired - already have throwable. + // Exceptions need to be cleared for correct behavior. + // The caller of ExceptionMatches should restore pending exceptions if desired - + // the caller already has the throwable. jenv->ExceptionClear(); jclass clz = jenv->FindClass(clzname); - if (clz && ! jenv->ExceptionCheck()) { + if (clz && !jenv->ExceptionCheck()) { jclass classclz = jenv->GetObjectClass(clz); - jmethodID isInstanceMethodID = - jenv->GetMethodID(classclz, "isInstance", "(Ljava/lang/Object;)Z"); + jmethodID isInstanceMethodID = jenv->GetMethodID(classclz, "isInstance", "(Ljava/lang/Object;)Z"); if (isInstanceMethodID) { - matches = (jboolean) - jenv->CallBooleanMethod(clz, isInstanceMethodID, excp); + matches = (jboolean)jenv->CallBooleanMethod(clz, isInstanceMethodID, excp); } } // This may happen if user typemaps or director:except @@ -314,7 +224,7 @@ namespace Swig { // which may not be that clear (e.g. ClassNotFoundException) // if (jenv->ExceptionCheck()) { - // JavaExceptionMessage jstrmsg(jenv,jenv->ExceptionOccurred()); + // JavaExceptionMessage jstrmsg(jenv, jenv->ExceptionOccurred()); // std::cerr << "Error: ExceptionMatches: class '" << // clzname << "' : " << jstrmsg.message() << std::endl; // } @@ -322,24 +232,91 @@ namespace Swig { return matches; } - // Provide the class name to allow reconstruction of the original exception - struct DirectorException : std::exception { + // Simple holder for a Java string during exception handling, allowing access to a c-style string + class JavaString { + public: + JavaString(JNIEnv *jenv, jstring jstr) : jenv_(jenv), jstr_(jstr), cstr_(0) { + if (jenv_ && jstr_) + cstr_ = (const char *) jenv_->GetStringUTFChars(jstr_, NULL); + } - // Construct a DirectorException from a java throwable - DirectorException(JNIEnv* jenv,jthrowable excp) : classname_(0), msg_(0) { + ~JavaString() { + if (jenv_ && jstr_ && cstr_) + jenv_->ReleaseStringUTFChars(jstr_, cstr_); + } + + const char *cstr() { + return cstr_ ? cstr_ : ""; + } + + private: + // non-copyable + JavaString(const JavaString &); + JavaString &operator=(const JavaString &); + + JNIEnv *jenv_; + jstring jstr_; + const char *cstr_; + }; + + // Helper to extract the exception message from a Java throwable + class JavaExceptionMessage { + public: + JavaExceptionMessage(JNIEnv *jenv, jthrowable excp) : jstrholder_(jenv, exceptionMsgJstr(jenv, excp)) { + } + + ~JavaExceptionMessage() { + } + + const char *message() { + return jstrholder_.cstr(); + } + + private: + // non-copyable + JavaExceptionMessage(const JavaExceptionMessage &); + JavaExceptionMessage &operator=(const JavaExceptionMessage &); + + // Static method to initialize jstrholder_ + static jstring exceptionMsgJstr(JNIEnv *jenv, jthrowable excp) { + jstring jmsg = NULL; + if (jenv && excp) { + jenv->ExceptionClear(); // Cannot invoke methods with pending exception + jclass thrwclz = jenv->GetObjectClass(excp); + if (thrwclz) { + // if no getMessage() or other exception, no msg available. + jmethodID getThrowableMsgMethodID = jenv->GetMethodID(thrwclz, "getMessage", "()Ljava/lang/String;"); + if (getThrowableMsgMethodID && !jenv->ExceptionCheck()) { + // if problem accessing exception message string, no msg will be available. + jmsg = (jstring)jenv->CallObjectMethod(excp, getThrowableMsgMethodID); + } + } + if (jmsg == NULL && jenv->ExceptionCheck()) { + jenv->ExceptionClear(); + } + } + return jmsg; + } + + JavaString jstrholder_; + }; + + // C++ Exception class for converting from Java exceptions thrown during a director method Java upcall + class DirectorException : public std::exception { + public: + + // Construct a DirectorException from a Java throwable + DirectorException(JNIEnv *jenv, jthrowable excp) : classname_(0), msg_(0) { jstring jstr_classname = NULL; - jmethodID mid_getName = NULL; - jclass thrwclz; - jclass clzclz; if (excp) { // Get the exception class, like Exception - thrwclz = jenv->GetObjectClass(excp); + jclass thrwclz = jenv->GetObjectClass(excp); if (thrwclz) { - // Get the java.lang.Class class - clzclz = jenv->GetObjectClass(thrwclz); + // Get the Java.lang.Class class + jclass clzclz = jenv->GetObjectClass(thrwclz); if (clzclz) { - mid_getName = jenv->GetMethodID(clzclz, "getName", "()Ljava/lang/String;"); + jmethodID mid_getName = mid_getName = jenv->GetMethodID(clzclz, "getName", "()Ljava/lang/String;"); if (mid_getName) { // Get the excp class name jstr_classname = (jstring)(jenv->CallObjectMethod(thrwclz, mid_getName)); @@ -357,8 +334,8 @@ namespace Swig { msg_ = copystr(exceptionmsg.message()); } - // Throw as a wrapped Runtime Error explicitly. - DirectorException(const char * msg) : classname_(0), msg_(0) { + // Throw as a wrapped RuntimeError explicitly. + DirectorException(const char *msg) : classname_(0), msg_(0) { classname_ = copypath("java/lang/RuntimeError"); msg_ = copystr(msg); } @@ -368,27 +345,22 @@ namespace Swig { delete[] msg_; } - // If there was problem finding classname, keep track of error - // On raiseJavaException will be mapped to a RuntimeException - const char* classname() const throw() { + // If there was a problem finding classname, keep track of error + // On raiseJavaException will be mapped to a RuntimeException + const char *classname() const throw() { return classname_ ? classname_ : "UnknownException"; } - const char* what() const throw() { + + const char *what() const throw() { return msg_ ? msg_ : ""; } - // Python director code provides static raise() methods - // Omitted here: Seems less good than - // throw DirectorException(jenv, excp) - // from which compiler can infer a C++ exception is thrown. - // Reconstruct and raise the Java Exception that caused the DirectorException - void raiseJavaException(JNIEnv* jenv) { + void raiseJavaException(JNIEnv *jenv) { if (jenv) { jenv->ExceptionClear(); jmethodID strCtorID = 0; - jclass excpclz = jenv->FindClass(classname()); if (excpclz) { @@ -406,27 +378,29 @@ namespace Swig { } private: - const char * classname_; - const char * msg_; - - static const char * copypath(const char * srcmsg) { + static const char *copypath(const char *srcmsg) { return copystr(srcmsg, 1); } - static const char * copystr(const char * srcmsg, int pathrepl=0) { - char * target = 0; + + static const char *copystr(const char *srcmsg, int pathrepl=0) { + char *target = 0; if (srcmsg) { - int msglen = 1+strlen(srcmsg); //+1 for null terminator + int msglen = 1 + strlen(srcmsg); target = new char[msglen]; strncpy(target, srcmsg, msglen); } // If pathrepl, replace any '.' with '/' if (pathrepl) { - for(char *c=target; *c; ++c) { - if ('.' == *c) *c = '/'; + for (char *c=target; *c; ++c) { + if ('.' == *c) + *c = '/'; } } return target; } + + const char *classname_; + const char *msg_; }; } From e7a6be289e7db30307c5d2b379a3e867b5d01e0e Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 5 Nov 2013 18:49:21 +0000 Subject: [PATCH 175/481] Rework the director.swg changes for director exception handling - More robust implementation. - Fix some bugs to give better exception messages when a user uses the director utility exception functions and classes. - Replace unnecessarily shortened variable names for easier reading of code. --- Lib/java/director.swg | 211 +++++++++++++++++++----------------------- 1 file changed, 95 insertions(+), 116 deletions(-) diff --git a/Lib/java/director.swg b/Lib/java/director.swg index 346cec2cc..f9ddbeffe 100644 --- a/Lib/java/director.swg +++ b/Lib/java/director.swg @@ -7,7 +7,7 @@ #ifdef __cplusplus -#if defined(DEBUG_DIRECTOR_OWNED) +#if defined(DEBUG_DIRECTOR_OWNED) || defined(DEBUG_DIRECTOR_EXCEPTION) #include #endif @@ -196,43 +196,9 @@ namespace Swig { }; - // Utility methods and classes for exception handling. + // Utility classes and functions for exception handling. - // Helper method to determine if a Java throwable matches a particular Java class type - bool ExceptionMatches(JNIEnv *jenv, jthrowable excp, const char *clzname) { - jboolean matches = false; - - if (excp && jenv && clzname) { - // Exceptions need to be cleared for correct behavior. - // The caller of ExceptionMatches should restore pending exceptions if desired - - // the caller already has the throwable. - jenv->ExceptionClear(); - - jclass clz = jenv->FindClass(clzname); - if (clz && !jenv->ExceptionCheck()) { - jclass classclz = jenv->GetObjectClass(clz); - jmethodID isInstanceMethodID = jenv->GetMethodID(classclz, "isInstance", "(Ljava/lang/Object;)Z"); - if (isInstanceMethodID) { - matches = (jboolean)jenv->CallBooleanMethod(clz, isInstanceMethodID, excp); - } - } - // This may happen if user typemaps or director:except - // features call ExceptionMatches incorrectly, typically with - // an invalid clzname argument. Uncommenting the debug lines - // may help to diagnose. - // As is, this leaves the underlying case as a pending exception - // which may not be that clear (e.g. ClassNotFoundException) - - // if (jenv->ExceptionCheck()) { - // JavaExceptionMessage jstrmsg(jenv, jenv->ExceptionOccurred()); - // std::cerr << "Error: ExceptionMatches: class '" << - // clzname << "' : " << jstrmsg.message() << std::endl; - // } - } - return matches; - } - - // Simple holder for a Java string during exception handling, allowing access to a c-style string + // Simple holder for a Java string during exception handling, providing access to a c-style string class JavaString { public: JavaString(JNIEnv *jenv, jstring jstr) : jenv_(jenv), jstr_(jstr), cstr_(0) { @@ -245,8 +211,8 @@ namespace Swig { jenv_->ReleaseStringUTFChars(jstr_, cstr_); } - const char *cstr() { - return cstr_ ? cstr_ : ""; + const char *c_str(const char *null_string = "null JavaString") const { + return cstr_ ? cstr_ : null_string; } private: @@ -259,17 +225,14 @@ namespace Swig { const char *cstr_; }; - // Helper to extract the exception message from a Java throwable + // Helper class to extract the exception message from a Java throwable class JavaExceptionMessage { public: - JavaExceptionMessage(JNIEnv *jenv, jthrowable excp) : jstrholder_(jenv, exceptionMsgJstr(jenv, excp)) { + JavaExceptionMessage(JNIEnv *jenv, jthrowable throwable) : message_(jenv, exceptionMessageFromThrowable(jenv, throwable)) { } - ~JavaExceptionMessage() { - } - - const char *message() { - return jstrholder_.cstr(); + const char *message() const { + return message_.c_str("Could not get exception message in JavaExceptionMessage"); } private: @@ -277,67 +240,61 @@ namespace Swig { JavaExceptionMessage(const JavaExceptionMessage &); JavaExceptionMessage &operator=(const JavaExceptionMessage &); - // Static method to initialize jstrholder_ - static jstring exceptionMsgJstr(JNIEnv *jenv, jthrowable excp) { + // Get exception message by calling Java method Throwable.getMessage() + static jstring exceptionMessageFromThrowable(JNIEnv *jenv, jthrowable throwable) { jstring jmsg = NULL; - if (jenv && excp) { - jenv->ExceptionClear(); // Cannot invoke methods with pending exception - jclass thrwclz = jenv->GetObjectClass(excp); - if (thrwclz) { - // if no getMessage() or other exception, no msg available. - jmethodID getThrowableMsgMethodID = jenv->GetMethodID(thrwclz, "getMessage", "()Ljava/lang/String;"); - if (getThrowableMsgMethodID && !jenv->ExceptionCheck()) { - // if problem accessing exception message string, no msg will be available. - jmsg = (jstring)jenv->CallObjectMethod(excp, getThrowableMsgMethodID); - } + if (jenv && throwable) { + jenv->ExceptionClear(); // Cannot invoke methods with any pending exceptions + jclass throwclz = jenv->GetObjectClass(throwable); + if (throwclz) { + // All Throwable classes have a getMessage() method, so call it to extract the exception message + jmethodID getMessageMethodID = jenv->GetMethodID(throwclz, "getMessage", "()Ljava/lang/String;"); + if (getMessageMethodID) + jmsg = (jstring)jenv->CallObjectMethod(throwable, getMessageMethodID); } - if (jmsg == NULL && jenv->ExceptionCheck()) { + if (jmsg == NULL && jenv->ExceptionCheck()) jenv->ExceptionClear(); - } } return jmsg; } - JavaString jstrholder_; + JavaString message_; }; - // C++ Exception class for converting from Java exceptions thrown during a director method Java upcall + // C++ Exception class for handling Java exceptions thrown during a director method Java upcall class DirectorException : public std::exception { public: - // Construct a DirectorException from a Java throwable - DirectorException(JNIEnv *jenv, jthrowable excp) : classname_(0), msg_(0) { - jstring jstr_classname = NULL; + // Construct exception from a Java throwable + DirectorException(JNIEnv *jenv, jthrowable throwable) : classname_(0), msg_(0) { - if (excp) { - // Get the exception class, like Exception - jclass thrwclz = jenv->GetObjectClass(excp); - if (thrwclz) { - // Get the Java.lang.Class class - jclass clzclz = jenv->GetObjectClass(thrwclz); + // Call Java method Object.getClass().getName() to obtain the throwable's class name (delimited by '/') + if (throwable) { + jclass throwclz = jenv->GetObjectClass(throwable); + if (throwclz) { + jclass clzclz = jenv->GetObjectClass(throwclz); if (clzclz) { - jmethodID mid_getName = mid_getName = jenv->GetMethodID(clzclz, "getName", "()Ljava/lang/String;"); - if (mid_getName) { - // Get the excp class name - jstr_classname = (jstring)(jenv->CallObjectMethod(thrwclz, mid_getName)); + jmethodID getNameMethodID = jenv->GetMethodID(clzclz, "getName", "()Ljava/lang/String;"); + if (getNameMethodID) { + jstring jstr_classname = (jstring)(jenv->CallObjectMethod(throwclz, getNameMethodID)); + // Copy strings, since there is no guarantee that jenv will be active when handled + if (jstr_classname) { + JavaString jsclassname(jenv, jstr_classname); + const char *classname = jsclassname.c_str(0); + if (classname) + classname_ = copypath(classname); + } } } } } - // Copy strings, since no guarantee jenv will be active when handled - // If classname_ is 0, returned as "UnknownException" - if (jstr_classname) { - JavaString classname(jenv, jstr_classname); - classname_ = copypath(classname.cstr()); - } - JavaExceptionMessage exceptionmsg(jenv, excp); + + JavaExceptionMessage exceptionmsg(jenv, throwable); msg_ = copystr(exceptionmsg.message()); } - // Throw as a wrapped RuntimeError explicitly. - DirectorException(const char *msg) : classname_(0), msg_(0) { - classname_ = copypath("java/lang/RuntimeError"); - msg_ = copystr(msg); + // More general constructor for handling as a java.lang.RuntimeException + DirectorException(const char *msg) : classname_(0), msg_(copystr(msg ? msg : "Unspecified DirectorException message")) { } ~DirectorException() throw() { @@ -345,57 +302,49 @@ namespace Swig { delete[] msg_; } - // If there was a problem finding classname, keep track of error - // On raiseJavaException will be mapped to a RuntimeException - const char *classname() const throw() { - return classname_ ? classname_ : "UnknownException"; - } - const char *what() const throw() { - return msg_ ? msg_ : ""; + return msg_; } - // Reconstruct and raise the Java Exception that caused the DirectorException - void raiseJavaException(JNIEnv *jenv) { + // Reconstruct and raise/throw the Java Exception that caused the DirectorException + // Note that any error in the JNI exception handling results in a Java RuntimeException + void raiseJavaException(JNIEnv *jenv) const { if (jenv) { jenv->ExceptionClear(); - jmethodID strCtorID = 0; - jclass excpclz = jenv->FindClass(classname()); - - if (excpclz) { - strCtorID = jenv->GetMethodID(excpclz,"","(Ljava/lang/String;)V"); + jmethodID ctorMethodID = 0; + jclass throwableclass = 0; + if (classname_) { + throwableclass = jenv->FindClass(classname_); + if (throwableclass) + ctorMethodID = jenv->GetMethodID(throwableclass, "", "(Ljava/lang/String;)V"); } - if (strCtorID) { - // If exception has a string constructor, throw an instance - jenv->ThrowNew(excpclz, what()); + if (ctorMethodID) { + jenv->ThrowNew(throwableclass, what()); } else { - // Else, throw a runtime - SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, what() ); + SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, what()); } } } private: - static const char *copypath(const char *srcmsg) { - return copystr(srcmsg, 1); + static char *copypath(const char *srcmsg) { + char *target = copystr(srcmsg); + for (char *c=target; *c; ++c) { + if ('.' == *c) + *c = '/'; + } + return target; } - static const char *copystr(const char *srcmsg, int pathrepl=0) { + static char *copystr(const char *srcmsg) { char *target = 0; if (srcmsg) { - int msglen = 1 + strlen(srcmsg); + int msglen = strlen(srcmsg) + 1; target = new char[msglen]; strncpy(target, srcmsg, msglen); } - // If pathrepl, replace any '.' with '/' - if (pathrepl) { - for (char *c=target; *c; ++c) { - if ('.' == *c) - *c = '/'; - } - } return target; } @@ -403,6 +352,36 @@ namespace Swig { const char *msg_; }; + // Helper method to determine if a Java throwable matches a particular Java class type + bool ExceptionMatches(JNIEnv *jenv, jthrowable throwable, const char *classname) { + bool matches = false; + + if (throwable && jenv && classname) { + // Exceptions need to be cleared for correct behavior. + // The caller of ExceptionMatches should restore pending exceptions if desired - + // the caller already has the throwable. + jenv->ExceptionClear(); + + jclass clz = jenv->FindClass(classname); + if (clz) { + jclass classclz = jenv->GetObjectClass(clz); + jmethodID isInstanceMethodID = jenv->GetMethodID(classclz, "isInstance", "(Ljava/lang/Object;)Z"); + if (isInstanceMethodID) { + matches = jenv->CallBooleanMethod(clz, isInstanceMethodID, throwable) != 0; + } + } + +#if defined(DEBUG_DIRECTOR_EXCEPTION) + if (jenv->ExceptionCheck()) { + // Typically occurs when an invalid classname argument is passed resulting in a ClassNotFoundException + JavaExceptionMessage exc(jenv, jenv->ExceptionOccurred()); + std::cout << "Error: ExceptionMatches: class '" << classname << "' : " << exc.message() << std::endl; + } +#endif + } + return matches; + } + } #endif /* __cplusplus */ From 9df7bee57057668ef878e075ae070acfecd515b1 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 5 Nov 2013 18:55:49 +0000 Subject: [PATCH 176/481] Changes file for recent director improvements --- CHANGES.current | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGES.current b/CHANGES.current index 8989ee194..0f964b114 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,13 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2013-11-05: wsfulton + [Java] Fix some corner cases for the $packagepath/$javaclassname special variable substitution. + +2013-11-05: wsfulton + [Java] Apply patch #91 from Marvin Greenberg - Add director:except feature for improved + exception handling in director methods for Java. + 2013-10-17: wsfulton [R] Fix SF #1340 - Visual Studio compile error in C++ wrappers due to #include within extern "C" block. From d73f04e925e9210f2c688ef3656e6059eb540565 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 7 Nov 2013 22:48:17 +0000 Subject: [PATCH 177/481] Documentation edit for the director:except feature and directorthrows typemap --- Doc/Manual/Java.html | 329 +++++++++++++++++++++++---------------- Doc/Manual/Warnings.html | 2 +- 2 files changed, 200 insertions(+), 131 deletions(-) diff --git a/Doc/Manual/Java.html b/Doc/Manual/Java.html index 0e9ba75de..08c80c83a 100644 --- a/Doc/Manual/Java.html +++ b/Doc/Manual/Java.html @@ -3556,99 +3556,108 @@ However, if all director methods are expected to usually be overridden by Java s The disadvantage is that invocation of director methods from C++ when Java doesn't actually override the method will require an additional call up into Java and back to C++. As such, this option is only useful when overrides are extremely common and instantiation is frequent enough that its performance is critical.

    -

    24.5.7 Java Exceptions from Directors

    +

    24.5.7 Java exceptions from directors

    With directors routing method calls to Java, and proxies routing them -to C++, the handling of exceptions is an important concern. In Swig -2.0, the director class methods ignored java exceptions that occurred -during method calls dispatched to the Java director class and simply -returned '$null' to the C++ caller. The default behavior now throws a -Swig-defined DirectorException C++ exception. A facility -is now provided to allow translation of thrown Java exceptions into -C++ exceptions. This can be done in two different ways using -the %feature("director:except") directive. In the -simplest approach, a code block is attached to each director method to -handle the mapping of java exceptions into C++ exceptions. +to C++, the handling of exceptions is an important concern. +The default behavior from SWIG 3.0 +onwards is to convert the thrown Java exception into a SWIG defined +DirectorException C++ exception. +SWIG 2.0 and earlier versions didn't provide any mechanism to handle the Java director method exceptions in C++. +

    + +

    +Converting Java exceptions into C++ exceptions can be done in two different ways using +the director:except feature. +In the simplest approach, a code block is attached to each director method to +handle the mapping of Java exceptions into C++ exceptions.

    -// All the rules to associate a feature with an element apply
     %feature("director:except") MyClass::method(int x) {
    -  jthrowable $error = jenv->ExceptionOccurred();
    +  jthrowable $error = jenv->ExceptionOccurred();
       if ($error) {
    -    jenv->ExceptionClear();
    -    if (Swig::ExceptionMatches(jenv,$error,"java/lang/IndexOutOfBoundsException"))
    -      throw std::out_of_range(Swig::JavaExceptionMessage(jenv,$error).message());
    -    else if (Swig::ExceptionMatches(jenv,$error,"$packagepath/MyJavaException"))
    -      throw MyCppException(Swig::JavaExceptionMessage(jenv,$error).message());
    -    else
    -      throw std::runtime_error("Unexpected exception thrown by MyClass::method");
    +    jenv->ExceptionClear();
    +    if (Swig::ExceptionMatches(jenv, $error, "java/lang/IndexOutOfBoundsException"))
    +      throw std::out_of_range(Swig::JavaExceptionMessage(jenv, $error).message());
    +    if (Swig::ExceptionMatches(jenv, $error, "$packagepath/MyJavaException"))
    +      throw MyCppException(Swig::JavaExceptionMessage(jenv, $error).message());
    +    throw std::runtime_error("Unexpected exception thrown in MyClass::method");
       }
     }
     
     class MyClass {
    -  void method(int x); /* on C++ side, may get std::runtime_error or MyCppException */
    +  /** Throws either a std::out_of_range or MyCppException on error */
    +  void method(int x);
     }
     
    +

    -This approach allows mapping java exceptions thrown by director methods into -C++ exceptions, to match the exceptions expected by a C++ caller. There -need not be any exception specification on the method. This approach gives -complete flexibility to map exceptions thrown by a java director -implementation into desired C++ exceptions. The -function Swig::ExceptionMatches +This approach allows a flexible mapping of Java exceptions thrown by director methods into +C++ exceptions expected by a C++ caller. There +need not be any C++ exception specifications on the C++ method. The +utility function Swig::ExceptionMatches and class Swig::JavaExceptionMessage are provided to simplify -writing code for wrappers that use director:exceptfeature. These simplify -testing the type of the java exception and constructing C++ exceptions. The +writing code for wrappers that use the director:except feature. The function Swig::ExceptionMatches matches the type of the jthrowable thrown against a fully qualified JNI style class -name, like "java/lang/IOError". If the throwable class is the same -type, or derives from the given type, it returns true. Care must be taken to +name, such as "java/lang/IOError". If the throwable class is the same +type, or derives from the given type, Swig::ExceptionMatches will return true. Care must be taken to provide the correct fully qualified name, since for wrapped exceptions the generated proxy class will have additional package qualification, depending on -the '-package' argument and use of nspace -feature. The variable $error is simply a unique variable name to allow -assignment of the exception that occurred. The variable $packagepath is -replaced by the outer package provided for swig generation by the -package -option. The class Swig::JavaExceptionMessage is a holder -object giving access to the message from the thrown java exception. -The message() method returns the exception message as a const char *, +the '-package' argument and use of the nspace + feature. The special variable $error is expanded by SWIG into a unique variable name and +should be used for the +assignment of the exception that occurred. The special variable $packagepath is +replaced by the outer package provided for SWIG generation by the -package +option. The utility class Swig::JavaExceptionMessage is a holder +providing access to the message from the thrown Java exception. +The message() method returns the exception message as a const char *, which is only valid during the lifetime of the holder. Any code using this message needs to copy it, for example into a std::string or a newly constructed C++ exception.

    -If many methods may throw different exceptions, using this approach to -write handlers for a large number of methods will result in -duplication of the code in the director:except feature -code blocks, and will require separate feature definitions for every -method. So an alternative approach is provided, using typemaps in a +Using the above approach to +write handlers for a large number of methods will require +repetitive duplication of the director:except feature code. +To mitigate this, an alternative approach is provided via typemaps in a fashion analagous to the "throws" typemap. The "throws" typemap provides an approach to automatically map all the C++ exceptions listed in a method's defined exceptions (either from -an exception specification or a %catches -feature) into Java exceptions, for the generated proxy classes. To -provide the inverse mapping, the directorthrows typemap -is provided. +a C++ exception specification or a %catches +feature) into Java exceptions. +The "directorthrows" typemap provides the inverse mapping and should contain +code to convert a suitably matching Java exception into a C++ exception. +The example below converts a Java java.lang.IndexOutOfBoundsException exception +to the typemap's type, that is std::out_of_range: -

    Using directorthrows typemaps allows a -generic director:except feature to be combined with -method-specific handling to achieve the desired result. The -default director:except feature, in combination -with directorthrows typemaps generate exception mapping -to C++ exceptions for all the exceptions defined for each method. The -default definition is shown below.

    +
    +
    +%typemap(directorthrows) std::out_of_range %{
    +  if (Swig::ExceptionMatches(jenv, $error, "java/lang/IndexOutOfBoundsException")) {
    +    throw std::out_of_range(Swig::JavaExceptionMessage(jenv, $error).message());
    +  }
    +%}
    +
    +
    + +

    +The "directorthrows" typemap is then used in conjunction with the +director:except feature if the $directorthrowshandlers special variable +is used in the feature code. Consider the following, which also happens to be the default: +

     %feature("director:except") %{
    -   jthrowable $error = jenv->ExceptionOccurred();
    +   jthrowable $error = jenv->ExceptionOccurred();
        if ($error) {
    -     jenv->ExceptionClear();
    +     jenv->ExceptionClear();
          $directorthrowshandlers
          throw Swig::DirectorException(jenv, $error);
        }
    @@ -3657,34 +3666,66 @@ default definition is shown below.

    The code generated using the director:except feature -replaces the $directorthrowshandlers with code that throws -appropriate C++ exceptions from directorthrows typemaps -for each exception defined for the method. Just as with -the "throws" typemap, the -possible exceptions may be defined either with an exception -specification ( throw(MyException,std::runtime_error) ) or -using the %catches feature applied to the method.

    +replaces the $directorthrowshandlers special variable with the code in +the "directorthrows" typemaps, for each and every exception defined for the method. +The possible exceptions can be defined either with a C++ exception +specification or %catches as described for the +"throws" typemap. +

    -

    Note: Using the %catches feature to define the -handled exceptions is preferred to using exception specifications. If -the interface is defined with an exception specification the generated -swig proxy classes will have the same exception specification. In C++ -if exceptions other than those in the specification are thrown, the -program will be terminated.

    +

    +Consider the following director method: +

    -

    Because this default definition maps any unhandled java exceptions to -Swig::DirectorException, any director methods that define exception -specifications will cause program termination. To simply ignore -unexpected exceptions, the default can be changed to: +

    +
    +  ...
    +  virtual void doSomething(int index) throw (std::out_of_range);
    +  ...
    +
    +
    + +

    +When combined with the default director:except feature and the "directorthrows" typemap above, +the resulting code generated in the director method after calling up to Java will be: +

    + +
    +
    +jthrowable swigerror = jenv->ExceptionOccurred();
    +if (swigerror) {
    +  jenv->ExceptionClear();
    +  if (Swig::ExceptionMatches(jenv, swigerror, "java/lang/IndexOutOfBoundsException")) {
    +    throw std::out_of_range(Swig::JavaExceptionMessage(jenv, swigerror).message());
    +  }
    +  
    +  throw Swig::DirectorException(jenv, swigerror);
    +}
    +
    +
    + +

    +Note: Beware of using exception specifications as the SWIG director methods +will be generated with the same exception specifications and if the +director method throws an exception that is not specified it is likely +to terminate your program. See the C++ standard for more details. +Using the %catches feature instead to define the handled exceptions does not suffer +this potential fate. +

    + +

    Because the default code generation maps any unhandled Java exceptions to +Swig::DirectorException, any director methods that have exception +specifications may cause program termination. To simply ignore +unexpected exceptions, the default handling can be changed with:

     %feature("director:except") %{
    -   jthrowable $error = jenv->ExceptionOccurred();
    +   jthrowable $error = jenv->ExceptionOccurred();
        if ($error) {
    -     jenv->ExceptionClear();
    +     jenv->ExceptionClear();
          $directorthrowshandlers
    -     return $null;
    +     return $null; // exception is ignored
        }
     %}
     
    @@ -3692,27 +3733,25 @@ unexpected exceptions, the default can be changed to:

    Alternatively an exception compatible with the existing director -method exception specifications may be thrown. Assuming that all +method exception specifications can be thrown. Assuming that all methods allow std::runtime_error to be thrown, the return $null; could be changed to: +

    -   throw std::runtime_error(Swig::JavaExceptionMessage(jenv,$error).message());
    +   throw std::runtime_error(Swig::JavaExceptionMessage(jenv, $error).message());
     
    -

    In more complex situations, a separate director:except feature may need to be attached to specific methods.

    Below is a complete example demonstrating the use -of directorthrows typemaps. The directorthrows typemap -provides a code fragment to test for a pending java exception type, and the -resulting C++ exception that will be thrown. In this example, a -generic directorthrows typemap is appropriate for all three exceptions - all -take single string constructors. If the constructors had different constructors, +of the "directorthrows" typemaps. In this example, a +generic "directorthrows" typemap is appropriate for all three exceptions - all +take single string constructors. If the exceptions had different constructors, it would be neccessary to have separate typemaps for each exception type. @@ -3721,22 +3760,29 @@ it would be neccessary to have separate typemaps for each exception type. example interface that could be generated and built. -->

    +%module(directors="1") example
    +
    +%{
    +  #include <string>
    +  #include <stdexcept>
    +%}
    +
     // Define exceptions in header section using std::runtime_error
     %define DEFINE_EXCEPTION(NAME)
     %{
    -  #include <exception>
       namespace MyNS {
    -    struct NAME : public std::runtime_error { NAME(const std::string& what):runtime_error(what) {}; };
    +    struct NAME : public std::runtime_error { NAME(const std::string &what) : runtime_error(what) {} };
       }
     %}
     %enddef
    -// Expose c++ exceptions as java Exceptions with getMessage
    +
    +// Expose C++ exceptions as Java Exceptions by changing the Java base class and providing a getMessage()
     %define DECLARE_EXCEPTION(NAME)
     %typemap(javabase) MyNS::NAME "java.lang.Exception";
    -%rename(getMessage,fullname=1) MyNS::NAME::what;
    +%rename(getMessage) MyNS::NAME::what;
     namespace MyNS {
       struct NAME {
    -    NAME(const std::string& what);
    +    NAME(const std::string& what);
         const char * what();
       };
     }
    @@ -3744,17 +3790,16 @@ namespace MyNS {
     
     DEFINE_EXCEPTION(ExceptionA)
     DEFINE_EXCEPTION(ExceptionB)
    -DEFINE_EXCEPTION(Unknown)
    +DEFINE_EXCEPTION(Unexpected)
     
    -// Mark three methods to map director-thrown exceptions.
    -// Standard rules for feature matching apply
    +// Mark three methods to map director thrown exceptions.
     %feature("director:except") MyClass::meth1(int);
     %feature("director:except") MyClass::meth2;
     %feature("director:except") meth3;
     
     %typemap(directorthrows) MyNS::ExceptionA, MyNS::ExceptionB, MyNS::Unexpected %{
    -  if (Swig::ExceptionMatches(jenv,$error,"$packagepath/$javaclassname"))
    -    throw $1_type(Swig::JavaExceptionMessage(jenv,$error).message());
    +  if (Swig::ExceptionMatches(jenv, $error, "$packagepath/$javaclassname"))
    +    throw $1_type(Swig::JavaExceptionMessage(jenv, $error).message());
     %}
     
     DECLARE_EXCEPTION(ExceptionA)
    @@ -3769,68 +3814,54 @@ DECLARE_EXCEPTION(Unexpected)
         virtual void meth1(int x) throw(MyNS::ExceptionA, MyNS::ExceptionB) = 0;
         virtual void meth2() = 0;   /* throws MyNS::ExceptionA, MyNS::ExceptionB, MyNS::Unexpected */
         virtual void meth3(float x) throw(MyNS::Unexpected) = 0;
    -    virtual ~MyClass() {};
    +    virtual ~MyClass() {}
       };
     }
     

    -In this case the three different directorthrows typemaps will be used +In this case the three different "directorthrows" typemaps will be used to generate the three different exception handlers for meth1, meth2 and meth3. The generated handlers will have "if" blocks for each exception type specified, in -the exception specification or %catches feature. The code block -in the directorthrows typemap should always throw a c++ exception. +the exception specification or %catches feature.

    -

    Note that the directorthrows typemaps are important +

    Note that the "directorthrows" typemaps are important only if it is important for the the exceptions passed through the C++ layer to be mapped to distinct C++ exceptions. If director methods are being called by C++ code that is itself wrapped in a -Swig-generated java wrapper and access is always through this wrapper, -the default Swig::DirectorException class provides enough information +SWIG generated Java wrapper and access is always through this wrapper, +the default Swig::DirectorException class provides enough information to reconstruct the original exception. In this case removing the -$directorthrowshandlers replacement variable from the +$directorthrowshandlers special variable from the default director:except feature and simply always -throwing a Swig::DirectorException will achieve the desired result. +throwing a Swig::DirectorException will achieve the desired result. Along with this a generic exception feature is added to convert any caught Swig::DirectorExceptions back into the underlying -java exceptions, for each method which may get a generic -DirectorException from a wrapped director method.

    +Java exceptions via the Swig::DirectorException::raiseJavaException method, +as demonstrated with %javaexception below: +

    -%feature ("except",throws="Exception")  MyClass::myMeth %{
    -  try { $action }
    -  catch (Swig::DirectorException & direxcp) {
    -    // jenv always available in JNI code
    -    // raise the java exception that originally caused the DirectorException
    -    direxcp.raiseJavaException(jenv);
    +%javaexception("Exception") MyClass::myMethod %{
    +  try {
    +    $action
    +  } catch (Swig::DirectorException &e) {
    +    // raise/throw the Java exception that originally caused the DirectorException
    +    e.raiseJavaException(jenv);
         return $null;
       }
     %}
     
    -

    The throws="Exception" attribute on the exception -feature is necessary if any of the translated exceptions will be -checked exceptions, since the java compiler will otherwise assert that -no checked exceptions can be thrown by the method. This may be more -specific that the completely generic "Exception" class, of course. A -similar feature must be added to director methods to allow checked -exceptions to be thrown from the director method implementations. -Here, no actual exception handling is needed - the feature simply -is being used to add a generic checked exception signature to the -generated director method wrapper.

    - -
    -
    -%feature ("except",throws="Exception")  MyDirectorClass::myDirMeth %{ %}
    -
    -
    - - +

    +See the Exception handling with %exception and %javaexception +section for more on converting C++ exceptions to Java exceptions. +

    24.6 Accessing protected members

    @@ -5643,7 +5674,7 @@ can be wrapped with the Java equivalent, that is, static inner proxy classes.

    -$jniinput, $javacall and $packagepath
    +$error, $jniinput, $javacall and $packagepath
    These special variables are used in the directors typemaps. See Director specific typemaps for details.

    @@ -5977,6 +6008,10 @@ is the package name passed from the SWIG command line and $javaclassname-package
    commandline option is not used to specify the package, then '$packagepath/' will be removed from the resulting output JNI field descriptor. Do not forget the terminating ';' for JNI field descriptors starting with 'L'. If the ';' is left out, Java will generate a "method not found" runtime error. +Note that the $packagepath substitution always uses the path separator '/' when expanded. +The $javaclassname expansion can be confusing as it is normally expanded using the '.' separator. +However, $javaclassname is expanded using the path separator '/' in typemap's "descriptor" attribute +as well as in the "directorthrows" typemap.

    @@ -6072,6 +6107,40 @@ The target method is the method in the Java proxy class which overrides the virt
    +

    %typemap(directorthrows)

    +
    + +

    +Conversion of Java exceptions to C++ exceptions in director method's exception handling. +This typemap is expected to test the $error special variable for a matching Java exception +and if successful convert and throw it into a C++ exception given by the typemap's type. +The $error special variable is of type jthrowable and is +substituted with a unique variable name in the generated code. +

    + +

    +The example below converts a Java java.lang.IndexOutOfBoundsException exception +to the typemap's type, that is std::out_of_range: +

    + +
    +
    +%typemap(directorthrows) std::out_of_range %{
    +  if (Swig::ExceptionMatches(jenv, $error, "java/lang/IndexOutOfBoundsException")) {
    +    throw std::out_of_range(Swig::JavaExceptionMessage(jenv, $error).message());
    +  }
    +%}
    +
    +
    + +

    +The utility function Swig::ExceptionMatches +and class Swig::JavaExceptionMessage are helpers available when using directors and are described +in the Java Exceptions from Directors section. +

    + +
    +

    %typemap(javapackage)

    diff --git a/Doc/Manual/Warnings.html b/Doc/Manual/Warnings.html index 5b507c123..e0debe41c 100644 --- a/Doc/Manual/Warnings.html +++ b/Doc/Manual/Warnings.html @@ -499,7 +499,7 @@ example.i(4) : Syntax error in input.
  • 474. Method method usage of the optimal attribute ignored in the out typemap as the following cannot be used to generate optimal code: code
  • 475. Multiple calls to method might be generated due to optimal attribute usage in the out typemap.
  • 476. Initialization using std::initializer_list. -
  • 477. Feature director:except on Class::method with $directorthrowshandlers requires directorthrows typemap for exception Exception +
  • 477. No directorthrows typemap defined for type From efe1d8aea7d72fca68cfa0730a32b6bee05f0fdb Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 9 Nov 2013 12:17:52 +0000 Subject: [PATCH 178/481] Update changes file with previous commit dropping .NET 1.1 support --- CHANGES.current | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/CHANGES.current b/CHANGES.current index 0f964b114..c587ff07f 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,25 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2013-11-09: wsfulton + [C#] Apply patch #79 from Brant Kyser + - Remove using directives from the generated C# code and fully qualify the use of all .NET + framework types in order to minimize potential name collisions from input files defining + types, namespace, etc with the same name as .NET framework members. + - Globally qualify the use of .NET framework types in the System namespace + - Remove .NET 1.1 support, .NET 2 is the minimum for the C# module + + This is a potential backwards compatibility break if code has been added relying on these using + statements that used to be generated: + + using System; + using System.Runtime.InteropServices; + + The quick fix to add these back in is to add the -DSWIG2_CSHARP command line option when + executing SWIG. See CSharp.html documentation for more info. + + *** POTENTIAL INCOMPATIBILITY *** + 2013-11-05: wsfulton [Java] Fix some corner cases for the $packagepath/$javaclassname special variable substitution. From dfc02f306de0de87042991e6d6afedf587219af0 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Thu, 31 Oct 2013 20:49:15 +0400 Subject: [PATCH 179/481] First banch of tests --- .../test-suite/lua/cpp_namespace_runme.lua | 27 +++++++++ .../test-suite/lua/cpp_nodefault_runme.lua | 24 ++++++++ Examples/test-suite/lua/cpp_static_runme.lua | 16 +++++ Examples/test-suite/lua/cpp_typedef_runme.lua | 23 ++++++++ .../extend_constructor_destructor_runme.lua | 32 ++++++++++ .../test-suite/lua/extend_placement_runme.lua | 37 ++++++++++++ Examples/test-suite/lua/extend_runme.lua | 28 +++++++++ .../test-suite/lua/extend_template_runme.lua | 12 ++++ .../lua/extend_typedef_class_runme.lua | 37 ++++++++++++ .../test-suite/lua/extend_variable_runme.lua | 29 ++++++++++ Examples/test-suite/lua/friends_runme.lua | 27 +++++++++ Examples/test-suite/lua/funcptr_cpp_runme.lua | 18 ++++++ Examples/test-suite/lua/fvirtual_runme.lua | 17 ++++++ .../test-suite/lua/global_namespace_runme.lua | 58 +++++++++++++++++++ 14 files changed, 385 insertions(+) create mode 100644 Examples/test-suite/lua/cpp_namespace_runme.lua create mode 100644 Examples/test-suite/lua/cpp_nodefault_runme.lua create mode 100644 Examples/test-suite/lua/cpp_static_runme.lua create mode 100644 Examples/test-suite/lua/cpp_typedef_runme.lua create mode 100644 Examples/test-suite/lua/extend_constructor_destructor_runme.lua create mode 100644 Examples/test-suite/lua/extend_placement_runme.lua create mode 100644 Examples/test-suite/lua/extend_runme.lua create mode 100644 Examples/test-suite/lua/extend_template_runme.lua create mode 100644 Examples/test-suite/lua/extend_typedef_class_runme.lua create mode 100644 Examples/test-suite/lua/extend_variable_runme.lua create mode 100644 Examples/test-suite/lua/friends_runme.lua create mode 100644 Examples/test-suite/lua/funcptr_cpp_runme.lua create mode 100644 Examples/test-suite/lua/fvirtual_runme.lua create mode 100644 Examples/test-suite/lua/global_namespace_runme.lua diff --git a/Examples/test-suite/lua/cpp_namespace_runme.lua b/Examples/test-suite/lua/cpp_namespace_runme.lua new file mode 100644 index 000000000..620b42671 --- /dev/null +++ b/Examples/test-suite/lua/cpp_namespace_runme.lua @@ -0,0 +1,27 @@ +require("import") -- the import fn +import("cpp_namespace") -- import lib into global +cn=cpp_namespace --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +assert( cn.fact(4) == 24 ) +assert( cn.Foo == 42 ) + +t1 = cn.Test() +assert( t1:method() == "Test::method" ) + +cn.weird("t1", 4) + +assert( cn.do_method(t1) == "Test::method" ) +assert( cn.do_method2(t1) == "Test::method" ) + +t2 = cn.Test2() +assert( t2:method() == "Test2::method" ) + + +assert( cn.foo3(5) == 5 ) + +assert( cn.do_method3(t2, 7) == "Test2::method" ) diff --git a/Examples/test-suite/lua/cpp_nodefault_runme.lua b/Examples/test-suite/lua/cpp_nodefault_runme.lua new file mode 100644 index 000000000..52dc7a30c --- /dev/null +++ b/Examples/test-suite/lua/cpp_nodefault_runme.lua @@ -0,0 +1,24 @@ +-- Run file +require("import") -- the import fn +import("cpp_nodefault") -- import lib into global +cn=cpp_nodefault --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +foo1 = cn.Foo(1,2) +foo1.a = 5 +assert(foo1.a == 5) + +foo2 = cn.create(1,2) + +cn.consume(foo1,foo2) + +bar1 = cn.Bar() +bar1:consume( cn.gvar, foo2) +foo3 = bar1:create(1,2) + +foo3.a = 6 +assert( foo3.a == 6 ) diff --git a/Examples/test-suite/lua/cpp_static_runme.lua b/Examples/test-suite/lua/cpp_static_runme.lua new file mode 100644 index 000000000..e9ee887f2 --- /dev/null +++ b/Examples/test-suite/lua/cpp_static_runme.lua @@ -0,0 +1,16 @@ +-- demo of lua swig capacilities (operator overloading) +require("import") -- the import fn +import("cpp_static") -- import lib into global +cs=cpp_static --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +cs.StaticMemberTest.static_int = 5; +assert(cs.StaticMemberTest.static_int == 5); + +cs.StaticFunctionTest.static_func() +cs.StaticFunctionTest.static_func_2(2) +cs.StaticFunctionTest.static_func_3(3,3) diff --git a/Examples/test-suite/lua/cpp_typedef_runme.lua b/Examples/test-suite/lua/cpp_typedef_runme.lua new file mode 100644 index 000000000..e791f899a --- /dev/null +++ b/Examples/test-suite/lua/cpp_typedef_runme.lua @@ -0,0 +1,23 @@ + +require("import") -- the import fn +import("cpp_typedef") -- import lib into global +ct = cpp_typedef --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +foo1 = ct.Foo() +bar1 = foo1:bar() +bar2 = ct.Foo.sbar() + +u1 = ct.UnnamedStruct() +n1 = ct.TypedefNamedStruct() + +test = ct.Test() + +u2 = test:test1(u1) +n2 = test:test2(n1) +n3 = test:test3(n1) +n4 = test:test4(n1) diff --git a/Examples/test-suite/lua/extend_constructor_destructor_runme.lua b/Examples/test-suite/lua/extend_constructor_destructor_runme.lua new file mode 100644 index 000000000..7f18e07a2 --- /dev/null +++ b/Examples/test-suite/lua/extend_constructor_destructor_runme.lua @@ -0,0 +1,32 @@ +require("import") -- the import fn +import("extend_constructor_destructor") -- import lib into global +ecd=extend_constructor_destructor --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +a1 = ecd.AStruct(101) +assert(a1.ivar == 101) +assert(ecd.globalVar == 101) + +b1 = ecd.BStruct(201) +assert(b1.ivar == 201) +assert(ecd.globalVar == 201) + +c1 = ecd.CStruct(301) +assert(c1.ivar == 301) +assert(ecd.globalVar == 301) + +d1 = ecd.DStruct(401) +assert(d1.ivar == 401) +assert(ecd.globalVar == 401) + +e1 = ecd.EStruct(501) +assert(e1.ivar == 501) +assert(ecd.globalVar == 501) + +f1 = ecd.FStruct(601) +assert(f1.ivar == 601) +assert(ecd.globalVar == 601) diff --git a/Examples/test-suite/lua/extend_placement_runme.lua b/Examples/test-suite/lua/extend_placement_runme.lua new file mode 100644 index 000000000..96108a979 --- /dev/null +++ b/Examples/test-suite/lua/extend_placement_runme.lua @@ -0,0 +1,37 @@ +require("import") -- the import fn +import("extend_placement") -- import lib into global +ep=extend_placement --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +function test_obj( main, suppl ) + assert(main:spam() == 1) + assert(main:spam("this_is_string") == 2) + assert(main:spam(5) == 5) + assert(main:spam(5,6) == 11) + assert(main:spam( 7,8,9) == 15) + assert(main:spam(suppl,12.0) == 0) + assert(main:spam(suppl) == 0) +end + +foo1 = ep.Foo(0) +foo2 = ep.Foo(1,2) +foo3 = ep.Foo() +test_obj(foo1,foo2) + + +bar1 = ep.Bar() +bar2 = ep.Bar(5) +test_obj(bar1,bar2) + +fti1 = ep.FooTi(0) +fti2 = ep.FooTi(1,2) +fti3 = ep.FooTi() +test_obj(fti1,foo1) + +bti1 = ep.BarTi() +bti2 = ep.BarTi(5) +test_obj(bti1,bar1) diff --git a/Examples/test-suite/lua/extend_runme.lua b/Examples/test-suite/lua/extend_runme.lua new file mode 100644 index 000000000..026f20d81 --- /dev/null +++ b/Examples/test-suite/lua/extend_runme.lua @@ -0,0 +1,28 @@ +require("import") -- the import fn +import("extend") -- import lib into global +e=extend --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +base1 = e.Base() +assert(base1.value == 0) +base2 = e.Base(10) +assert(base2.value == 10) + +assert(base1:method(5) == 5) +assert(e.Base.zeroVal() == 0) +assert(base2:currentValue() == 10) +assert(base2:extendmethod(7) == 14) + +der1 = e.Derived(0) +assert(der1.value == 0) +assert(der1:method(5) == 10) + +der2 = e.Derived(17) +assert(der2.value == 34) +der2.extendval = 200.0 +assert( math.abs(der2.actualval - 2.0) < 0.001 ) +assert( math.abs(der2.extendval - 200.0) < 0.001 ) diff --git a/Examples/test-suite/lua/extend_template_runme.lua b/Examples/test-suite/lua/extend_template_runme.lua new file mode 100644 index 000000000..987d599f1 --- /dev/null +++ b/Examples/test-suite/lua/extend_template_runme.lua @@ -0,0 +1,12 @@ +require("import") -- the import fn +import("extend_template") -- import lib into global +et=extend_template--alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +foo1 = et.Foo_0() +assert(foo1:test1(5) == 5) +assert(foo1:test2(7) == 7) diff --git a/Examples/test-suite/lua/extend_typedef_class_runme.lua b/Examples/test-suite/lua/extend_typedef_class_runme.lua new file mode 100644 index 000000000..c2535483f --- /dev/null +++ b/Examples/test-suite/lua/extend_typedef_class_runme.lua @@ -0,0 +1,37 @@ +require("import") -- the import fn +import("extend_typedef_class") -- import lib into global +etc=extend_typedef_class --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +function test_obj( obj, const ) + obj.membervar = const + assert(obj:getvar() == const) +end + +a1 = etc.AClass() +test_obj(a1,1) + +b1 = etc.BClass() +test_obj(b1,2) + +c1 = etc.CClass() +test_obj(c1,3) + +d1 = etc.DClass() +test_obj(d1,4) + +a2 = etc.AStruct() +test_obj(a2,5) + +b2 = etc.BStruct() +test_obj(b2,6) + +c2 = etc.CStruct() +test_obj(c2,7) + +d2 = etc.DStruct() +test_obj(d2,8) diff --git a/Examples/test-suite/lua/extend_variable_runme.lua b/Examples/test-suite/lua/extend_variable_runme.lua new file mode 100644 index 000000000..cc2b6844e --- /dev/null +++ b/Examples/test-suite/lua/extend_variable_runme.lua @@ -0,0 +1,29 @@ +require("import") -- the import fn +import("extend_variable") -- import lib into global +ev=extend_variable --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +e1 = ev.ExtendMe() +answ = 1.0 +assert( e1:set(7.0) ) +--assert( e1:get(answ) ) -- doesn't work. Lua can't pass primitive type by non-const reference +--assert( answ == 7.0 ) + +e1.ExtendVar = 5.0 +assert(e1.ExtendVar == 5.0) + +assert(ev.Foo.Bar == 42) +assert(ev.Foo.AllBarOne == 4422) + +assert(ev.Foo.StaticInt == 1111) +ev.Foo.StaticInt = 3333 +assert(ev.Foo.StaticInt == 3333) + +assert(ev.Foo.StaticConstInt == 2222) + +b1 = ev.Bar() +assert(b1.x == 1) diff --git a/Examples/test-suite/lua/friends_runme.lua b/Examples/test-suite/lua/friends_runme.lua new file mode 100644 index 000000000..499322691 --- /dev/null +++ b/Examples/test-suite/lua/friends_runme.lua @@ -0,0 +1,27 @@ +require("import") -- the import fn +import("friends") -- import lib into global +f=friends --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +f.globalscope() + +b1 = f.B(5) +a1 = f.A(10) + +assert(f.get_val1(a1) == 10) +assert(f.get_val1(a1, 2) == 12) +assert(f.get_val2(a1) == 20) +assert(f.get_val3(a1) == 30) + +assert(f.get_val1(100, 1, 2) == 100) + +assert( f.mix(a1,b1) == 15); + +d1 = f.D_i(7) +assert(f.get_val1(d1) == 7) +f.set(d1,9) +assert(f.get_val1(d1) == 9) diff --git a/Examples/test-suite/lua/funcptr_cpp_runme.lua b/Examples/test-suite/lua/funcptr_cpp_runme.lua new file mode 100644 index 000000000..ba396da51 --- /dev/null +++ b/Examples/test-suite/lua/funcptr_cpp_runme.lua @@ -0,0 +1,18 @@ +require("import") -- the import fn +import("funcptr_cpp") -- import lib into global +fc=funcptr_cpp --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +assert( fc.addByValue(5,10) == 15) +-- These two won't work. Lua will successfully store the answer as userdata, but there is +-- no way of accessing the insides of userdata. +-- assert( fc.addByPointer(7, 9) == 16) +-- assert( fc.addByReference(8, 9) == 17) + +assert( fc.call1(fc.ADD_BY_VALUE, 5, 10) == 15) +assert( fc.call2(fc.ADD_BY_POINTER, 7, 9) == 16) +assert( fc.call3(fc.ADD_BY_REFERENCE, 8, 9) == 17) diff --git a/Examples/test-suite/lua/fvirtual_runme.lua b/Examples/test-suite/lua/fvirtual_runme.lua new file mode 100644 index 000000000..7f3056535 --- /dev/null +++ b/Examples/test-suite/lua/fvirtual_runme.lua @@ -0,0 +1,17 @@ +require("import") -- the import fn +import("fvirtual") -- import lib into global +f=fvirtual --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +n1 = f.Node() +n2 = f.Node() +assert(n1:addChild(n2) == 1) + +ns = f.NodeSwitch() +assert(ns:addChild(n2) == 2) +assert(ns:addChild(ns) == 2) +assert(ns:addChild(n1, false) == 3) diff --git a/Examples/test-suite/lua/global_namespace_runme.lua b/Examples/test-suite/lua/global_namespace_runme.lua new file mode 100644 index 000000000..b06caf722 --- /dev/null +++ b/Examples/test-suite/lua/global_namespace_runme.lua @@ -0,0 +1,58 @@ +require("import") -- the import fn +import("global_namespace") -- import lib into global +gn=global_namespace --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +k1 = gn.Klass1() +k2 = gn.Klass2() +k3 = gn.Klass3() +k4 = gn.Klass4() +k5 = gn.Klass5() +k6 = gn.Klass6() +k7 = gn.Klass7() + +gn.KlassMethods.methodA(k1,k2,k3,k4,k5,k6,k7) +gn.KlassMethods.methodB(k1,k2,k3,k4,k5,k6,k7) + +k1 = gn.getKlass1A() +k2 = gn.getKlass2A() +k3 = gn.getKlass3A() +k4 = gn.getKlass4A() +k5 = gn.getKlass5A() +k6 = gn.getKlass6A() +k7 = gn.getKlass7A() + +gn.KlassMethods.methodA(k1,k2,k3,k4,k5,k6,k7) +gn.KlassMethods.methodB(k1,k2,k3,k4,k5,k6,k7) + +k1 = gn.getKlass1B() +k2 = gn.getKlass2B() +k3 = gn.getKlass3B() +k4 = gn.getKlass4B() +k5 = gn.getKlass5B() +k6 = gn.getKlass6B() +k7 = gn.getKlass7B() + +gn.KlassMethods.methodA(k1,k2,k3,k4,k5,k6,k7) +gn.KlassMethods.methodB(k1,k2,k3,k4,k5,k6,k7) + +x1 = gn.XYZ1() +x2 = gn.XYZ2() +x3 = gn.XYZ3() +x4 = gn.XYZ4() +x5 = gn.XYZ5() +x6 = gn.XYZ6() +x7 = gn.XYZ7() + +gn.XYZMethods.methodA(x1,x2,x3,x4,x5,x6,x7) +gn.XYZMethods.methodB(x1,x2,x3,x4,x5,x6,x7) + +gn.AnEnumMethods.methodA(gn.anenum1, gn.anenum2, gn.anenum3) +gn.AnEnumMethods.methodB(gn.anenum1, gn.anenum2, gn.anenum3) + +gn.TheEnumMethods.methodA(gn.theenum1, gn.theenum2, gn.theenum3) +gn.TheEnumMethods.methodB(gn.theenum1, gn.theenum2, gn.theenum3) From c9279ab0e77dbc9a565b0a427fb9b5f36472b6b5 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Thu, 31 Oct 2013 23:25:40 +0400 Subject: [PATCH 180/481] More tests --- Examples/test-suite/keyword_rename.i | 4 +++ Examples/test-suite/lua/grouping_runme.lua | 17 ++++++++++ Examples/test-suite/lua/iadd_runme.lua | 17 ++++++++++ .../test-suite/lua/keyword_rename_runme.lua | 16 +++++++++ .../lua/overload_complicated_runme.lua | 22 ++++++++++++ .../lua/smart_pointer_extend_runme.lua | 34 +++++++++++++++++++ .../lua/smart_pointer_inherit_runme.lua | 18 ++++++++++ .../lua/smart_pointer_multi_runme.lua | 23 +++++++++++++ .../lua/smart_pointer_not_runme.lua | 25 ++++++++++++++ .../lua/smart_pointer_rename_runme.lua | 18 ++++++++++ .../lua/smart_pointer_simple_runme.lua | 22 ++++++++++++ .../smart_pointer_templatemethods_runme.lua | 18 ++++++++++ .../lua/template_construct_runme.lua | 10 ++++++ .../test-suite/lua/template_extend1_runme.lua | 14 ++++++++ .../test-suite/lua/template_extend2_runme.lua | 14 ++++++++ .../test-suite/lua/template_inherit_runme.lua | 24 +++++++++++++ 16 files changed, 296 insertions(+) create mode 100644 Examples/test-suite/lua/grouping_runme.lua create mode 100644 Examples/test-suite/lua/iadd_runme.lua create mode 100644 Examples/test-suite/lua/keyword_rename_runme.lua create mode 100644 Examples/test-suite/lua/overload_complicated_runme.lua create mode 100644 Examples/test-suite/lua/smart_pointer_extend_runme.lua create mode 100644 Examples/test-suite/lua/smart_pointer_inherit_runme.lua create mode 100644 Examples/test-suite/lua/smart_pointer_multi_runme.lua create mode 100644 Examples/test-suite/lua/smart_pointer_not_runme.lua create mode 100644 Examples/test-suite/lua/smart_pointer_rename_runme.lua create mode 100644 Examples/test-suite/lua/smart_pointer_simple_runme.lua create mode 100644 Examples/test-suite/lua/smart_pointer_templatemethods_runme.lua create mode 100644 Examples/test-suite/lua/template_construct_runme.lua create mode 100644 Examples/test-suite/lua/template_extend1_runme.lua create mode 100644 Examples/test-suite/lua/template_extend2_runme.lua create mode 100644 Examples/test-suite/lua/template_inherit_runme.lua diff --git a/Examples/test-suite/keyword_rename.i b/Examples/test-suite/keyword_rename.i index 6a6082ff9..46c3338b3 100644 --- a/Examples/test-suite/keyword_rename.i +++ b/Examples/test-suite/keyword_rename.i @@ -31,6 +31,10 @@ struct sealed {int i;}; KW(go, defer) KW(chan, fallthrough) +/* Lua keywords */ +KW(end, function) +KW(nil,local) + %} diff --git a/Examples/test-suite/lua/grouping_runme.lua b/Examples/test-suite/lua/grouping_runme.lua new file mode 100644 index 000000000..798a7359e --- /dev/null +++ b/Examples/test-suite/lua/grouping_runme.lua @@ -0,0 +1,17 @@ +require("import") -- the import fn +import("grouping") -- import lib into global +g=grouping --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +assert( g.test1(5) == 5 ) +g.test2(42) -- Return value is int* packed into userdata. We can't do anything with it + +assert( g.test3 == 37 ) +g.test3 = 42 +assert( g.test3 == 42 ) + +assert( g.do_unary(5, g.NEGATE) == -5 ) diff --git a/Examples/test-suite/lua/iadd_runme.lua b/Examples/test-suite/lua/iadd_runme.lua new file mode 100644 index 000000000..556644061 --- /dev/null +++ b/Examples/test-suite/lua/iadd_runme.lua @@ -0,0 +1,17 @@ +require("import") -- the import fn +import("iadd") -- import lib into global +i=iadd --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +foo1 = i.Foo() +foo1_a = foo1.AsA +assert( foo1_a.x == 5 ) +assert( foo1_a:get_me().x == 5 ) +-- Unfortunately, in Lua operator+= can't be overloaded + +foo1.AsLong = 1000 +assert( foo1.AsLong == 1000 ) diff --git a/Examples/test-suite/lua/keyword_rename_runme.lua b/Examples/test-suite/lua/keyword_rename_runme.lua new file mode 100644 index 000000000..5d54ef123 --- /dev/null +++ b/Examples/test-suite/lua/keyword_rename_runme.lua @@ -0,0 +1,16 @@ +require("import") -- the import fn +import("keyword_rename") -- import lib into global +kn=keyword_rename--alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + + +-- assert( kn.end(5) == 5 ) -- Curretly SWIG/Lua doesn't rename keywords +-- assert( kn.nil(7) == 7 ) + +-- But you can always access wrongly named members using string constants +assert( kn["end"](5) == 5 ) +assert( kn["nil"](7) == 7 ) diff --git a/Examples/test-suite/lua/overload_complicated_runme.lua b/Examples/test-suite/lua/overload_complicated_runme.lua new file mode 100644 index 000000000..5670607bf --- /dev/null +++ b/Examples/test-suite/lua/overload_complicated_runme.lua @@ -0,0 +1,22 @@ +require("import") -- the import fn +import("overload_complicated") -- import lib into global +oc=overload_complicated --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +assert( oc.foo(1,1,"test",1) == 15 ) + +p1 = oc.Pop(nil) +p1 = oc.Pop(nil,false) + +assert( p1:hip(true) == 701 ) +assert( p1:hip(nil) == 702 ) + +assert( p1:hop(true) == 801 ) +assert( p1:hop(nil) == 805 ) + +assert( oc.muzak(true) == 3001 ) +assert( oc.muzak(nil) == 3002 ) diff --git a/Examples/test-suite/lua/smart_pointer_extend_runme.lua b/Examples/test-suite/lua/smart_pointer_extend_runme.lua new file mode 100644 index 000000000..6d33c57b1 --- /dev/null +++ b/Examples/test-suite/lua/smart_pointer_extend_runme.lua @@ -0,0 +1,34 @@ +require("import") -- the import fn +import("smart_pointer_extend") -- import lib into global +spe=smart_pointer_extend --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +assert( spe.CBase.hello() == 1 ) +assert( spe.CBase.z == 1 ) + +base1 = spe.CBase() +base1.x = 7 + +p1 = spe.CPtr() + +assert( spe.get_hello(p1) == 1 ) +assert( p1:foo() == 1 ) +assert( p1:bar() == 2 ) +assert( p1:boo(5) == 5 ) + +foo = spe.Foo() +bar = spe.Bar(foo) + +assert( bar:extension(5,7) == 5 ) +assert( bar:extension(7) == 7 ) +assert( bar:extension() == 1 ) + +dfoo = spe.DFoo() +dptr = spe.DPtrFoo(dfoo) + +assert( dptr:Ext() == 2 ) +assert( dptr:Ext(5) == 5 ) diff --git a/Examples/test-suite/lua/smart_pointer_inherit_runme.lua b/Examples/test-suite/lua/smart_pointer_inherit_runme.lua new file mode 100644 index 000000000..75510ad08 --- /dev/null +++ b/Examples/test-suite/lua/smart_pointer_inherit_runme.lua @@ -0,0 +1,18 @@ +require("import") -- the import fn +import("smart_pointer_inherit") -- import lib into global +spi=smart_pointer_inherit --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +der = spi.Derived(7) + +ptr = spi.SmartDerived(der) + +assert( ptr.val == 7 ) +assert( ptr:value() == 7 ) +assert( ptr:value2() == 7 ) +assert( ptr:value3() == 7 ) +assert( ptr:valuehide() == -1 ) diff --git a/Examples/test-suite/lua/smart_pointer_multi_runme.lua b/Examples/test-suite/lua/smart_pointer_multi_runme.lua new file mode 100644 index 000000000..ed3693727 --- /dev/null +++ b/Examples/test-suite/lua/smart_pointer_multi_runme.lua @@ -0,0 +1,23 @@ +require("import") -- the import fn +import("smart_pointer_multi") -- import lib into global +spm=smart_pointer_multi --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +foo = spm.Foo() +foo.x = 5 +assert( foo:getx() == 5 ) + +bar = spm.Bar(foo) +spam = spm.Spam(bar) +grok = spm.Grok(bar) + +assert( bar:getx() == 5 ) +assert( spam:getx() == 5 ) +spam.x = 7 +assert( grok:getx() == 7 ) +grok.x = 10 +assert( foo:getx() == 10 ) diff --git a/Examples/test-suite/lua/smart_pointer_not_runme.lua b/Examples/test-suite/lua/smart_pointer_not_runme.lua new file mode 100644 index 000000000..2f009a7f6 --- /dev/null +++ b/Examples/test-suite/lua/smart_pointer_not_runme.lua @@ -0,0 +1,25 @@ +require("import") -- the import fn +import("smart_pointer_not") -- import lib into global +spn=smart_pointer_not --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + + +foo = spn.Foo() +foo.x = 7 +assert( foo:getx() == 7 ) + +bar = spn.Bar(foo) +success = pcall(bar.getx, bar) -- Bar is not a smart pointer. Call should fail +assert( not success ) + +spam = spn.Spam(foo) +success = pcall(spam.getx, spam) -- Spam is not a smart pointer. Call should fail +assert( not success ) + +grok = spn.Grok(foo) +success = pcall(grok.getx, grok) -- Spam is not a smart pointer. Call should fail +assert( not success ) diff --git a/Examples/test-suite/lua/smart_pointer_rename_runme.lua b/Examples/test-suite/lua/smart_pointer_rename_runme.lua new file mode 100644 index 000000000..51b07f61b --- /dev/null +++ b/Examples/test-suite/lua/smart_pointer_rename_runme.lua @@ -0,0 +1,18 @@ +require("import") -- the import fn +import("smart_pointer_rename") -- import lib into global +spr=smart_pointer_rename --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + + +foo = spr.Foo() +assert( foo:ftest1(1) == 1 ) +assert( foo:ftest2(1,2) == 2 ) + +bar = spr.Bar(foo) +assert( bar:test() == 3 ) +assert( bar:ftest1(1) == 1 ) +assert( bar:ftest2(1,2) == 2 ) diff --git a/Examples/test-suite/lua/smart_pointer_simple_runme.lua b/Examples/test-suite/lua/smart_pointer_simple_runme.lua new file mode 100644 index 000000000..8513931b2 --- /dev/null +++ b/Examples/test-suite/lua/smart_pointer_simple_runme.lua @@ -0,0 +1,22 @@ +require("import") -- the import fn +import("smart_pointer_simple") -- import lib into global +sps=smart_pointer_simple --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +foo1 = sps.Foo() +foo1.x = 5 +assert( foo1.x == 5 ) +assert( foo1:getx() == 5 ) + +bar1 = sps.Bar(foo1) +bar1.x = 3 +assert(bar1.x == 3) +assert(bar1:getx() == 3) + +bar1.x = 5 +assert(bar1.x == 5) +assert(bar1:getx() == 5) diff --git a/Examples/test-suite/lua/smart_pointer_templatemethods_runme.lua b/Examples/test-suite/lua/smart_pointer_templatemethods_runme.lua new file mode 100644 index 000000000..018881c42 --- /dev/null +++ b/Examples/test-suite/lua/smart_pointer_templatemethods_runme.lua @@ -0,0 +1,18 @@ +require("import") -- the import fn +import("smart_pointer_templatemethods") -- import lib into global +spt=smart_pointer_templatemethods --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +o1 = spt.Objct() + +iid = spt.InterfaceId() + +po2 = o1:QueryInterfaceObjct(iid) +-- we can't call po2:DisposeObjct, because smart pointer Ptr always return 0 when dereferencing +-- (see interface file). So we only check that po2 has necessary method +assert( po2.DisposeObjct ~= nil ) +assert( po2.QueryInterfaceObjct ~= nil ) diff --git a/Examples/test-suite/lua/template_construct_runme.lua b/Examples/test-suite/lua/template_construct_runme.lua new file mode 100644 index 000000000..aad9c3be4 --- /dev/null +++ b/Examples/test-suite/lua/template_construct_runme.lua @@ -0,0 +1,10 @@ +require("import") -- the import fn +import("template_construct") -- import lib into global +tc=template_construct --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +foo = tc.Foo_int(1) diff --git a/Examples/test-suite/lua/template_extend1_runme.lua b/Examples/test-suite/lua/template_extend1_runme.lua new file mode 100644 index 000000000..44774e949 --- /dev/null +++ b/Examples/test-suite/lua/template_extend1_runme.lua @@ -0,0 +1,14 @@ +require("import") -- the import fn +import("template_extend1") -- import lib into global +te=template_extend1 --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +lb = te.lBaz() +assert( lb:foo() == "lBaz::foo" ) + +db = te.dBaz() +assert( db:foo() == "dBaz::foo" ) diff --git a/Examples/test-suite/lua/template_extend2_runme.lua b/Examples/test-suite/lua/template_extend2_runme.lua new file mode 100644 index 000000000..23c25705b --- /dev/null +++ b/Examples/test-suite/lua/template_extend2_runme.lua @@ -0,0 +1,14 @@ +require("import") -- the import fn +import("template_extend2") -- import lib into global +te=template_extend2 --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +lb = te.lBaz() +assert( lb:foo() == "lBaz::foo" ) + +db = te.dBaz() +assert( db:foo() == "dBaz::foo" ) diff --git a/Examples/test-suite/lua/template_inherit_runme.lua b/Examples/test-suite/lua/template_inherit_runme.lua new file mode 100644 index 000000000..f2bfca00b --- /dev/null +++ b/Examples/test-suite/lua/template_inherit_runme.lua @@ -0,0 +1,24 @@ +require("import") -- the import fn +import("template_inherit") -- import lib into global +ti=template_inherit --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + + +fi = ti.FooInt() +assert( fi:blah() == "Foo" ) +assert( fi:foomethod() == "foomethod" ) + +bi = ti.BarInt() +assert( bi:blah() == "Bar" ) +assert( bi:foomethod() == "foomethod" ) + +assert( ti.invoke_blah_int(fi) == "Foo" ) +assert( ti.invoke_blah_int(bi) == "Bar" ) + +bd = ti.BarDouble() +success = pcall( ti.invoke_blah_int, bd ) +assert( not success ) From b9ba05be81dd466c15e7bf5d88e2e87a35ab3f09 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Fri, 1 Nov 2013 02:09:06 +0400 Subject: [PATCH 181/481] Style patches --- .../test-suite/lua/cpp_namespace_runme.lua | 16 +++++++------- .../test-suite/lua/cpp_nodefault_runme.lua | 4 ++-- .../test-suite/lua/extend_placement_runme.lua | 4 ++-- Examples/test-suite/lua/extend_runme.lua | 4 ++-- .../lua/extend_typedef_class_runme.lua | 2 +- .../test-suite/lua/extend_variable_runme.lua | 6 ++--- Examples/test-suite/lua/friends_runme.lua | 2 +- Examples/test-suite/lua/funcptr_cpp_runme.lua | 12 +++++----- Examples/test-suite/lua/grouping_runme.lua | 8 +++---- Examples/test-suite/lua/iadd_runme.lua | 6 ++--- .../test-suite/lua/keyword_rename_runme.lua | 8 +++---- .../test-suite/lua/li_std_vector_runme.lua | 2 +- .../lua/overload_complicated_runme.lua | 14 ++++++------ .../lua/smart_pointer_extend_runme.lua | 22 +++++++++---------- .../lua/smart_pointer_inherit_runme.lua | 10 ++++----- .../lua/smart_pointer_multi_runme.lua | 10 ++++----- .../lua/smart_pointer_not_runme.lua | 8 +++---- .../lua/smart_pointer_rename_runme.lua | 10 ++++----- .../lua/smart_pointer_simple_runme.lua | 4 ++-- .../smart_pointer_templatemethods_runme.lua | 4 ++-- .../test-suite/lua/template_extend1_runme.lua | 4 ++-- .../test-suite/lua/template_extend2_runme.lua | 4 ++-- .../test-suite/lua/template_inherit_runme.lua | 16 +++++++------- 23 files changed, 90 insertions(+), 90 deletions(-) diff --git a/Examples/test-suite/lua/cpp_namespace_runme.lua b/Examples/test-suite/lua/cpp_namespace_runme.lua index 620b42671..6f59cb14b 100644 --- a/Examples/test-suite/lua/cpp_namespace_runme.lua +++ b/Examples/test-suite/lua/cpp_namespace_runme.lua @@ -7,21 +7,21 @@ local env = _ENV -- Lua 5.2 if not env then env = getfenv () end -- Lua 5.1 setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) -assert( cn.fact(4) == 24 ) -assert( cn.Foo == 42 ) +assert(cn.fact(4) == 24) +assert(cn.Foo == 42) t1 = cn.Test() -assert( t1:method() == "Test::method" ) +assert(t1:method() == "Test::method") cn.weird("t1", 4) -assert( cn.do_method(t1) == "Test::method" ) -assert( cn.do_method2(t1) == "Test::method" ) +assert(cn.do_method(t1) == "Test::method") +assert(cn.do_method2(t1) == "Test::method") t2 = cn.Test2() -assert( t2:method() == "Test2::method" ) +assert(t2:method() == "Test2::method") -assert( cn.foo3(5) == 5 ) +assert(cn.foo3(5) == 5) -assert( cn.do_method3(t2, 7) == "Test2::method" ) +assert(cn.do_method3(t2, 7) == "Test2::method") diff --git a/Examples/test-suite/lua/cpp_nodefault_runme.lua b/Examples/test-suite/lua/cpp_nodefault_runme.lua index 52dc7a30c..86f5e840d 100644 --- a/Examples/test-suite/lua/cpp_nodefault_runme.lua +++ b/Examples/test-suite/lua/cpp_nodefault_runme.lua @@ -17,8 +17,8 @@ foo2 = cn.create(1,2) cn.consume(foo1,foo2) bar1 = cn.Bar() -bar1:consume( cn.gvar, foo2) +bar1:consume(cn.gvar, foo2) foo3 = bar1:create(1,2) foo3.a = 6 -assert( foo3.a == 6 ) +assert(foo3.a == 6) diff --git a/Examples/test-suite/lua/extend_placement_runme.lua b/Examples/test-suite/lua/extend_placement_runme.lua index 96108a979..28a2380d5 100644 --- a/Examples/test-suite/lua/extend_placement_runme.lua +++ b/Examples/test-suite/lua/extend_placement_runme.lua @@ -7,12 +7,12 @@ local env = _ENV -- Lua 5.2 if not env then env = getfenv () end -- Lua 5.1 setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) -function test_obj( main, suppl ) +function test_obj(main, suppl) assert(main:spam() == 1) assert(main:spam("this_is_string") == 2) assert(main:spam(5) == 5) assert(main:spam(5,6) == 11) - assert(main:spam( 7,8,9) == 15) + assert(main:spam(7,8,9) == 15) assert(main:spam(suppl,12.0) == 0) assert(main:spam(suppl) == 0) end diff --git a/Examples/test-suite/lua/extend_runme.lua b/Examples/test-suite/lua/extend_runme.lua index 026f20d81..3944dbfe8 100644 --- a/Examples/test-suite/lua/extend_runme.lua +++ b/Examples/test-suite/lua/extend_runme.lua @@ -24,5 +24,5 @@ assert(der1:method(5) == 10) der2 = e.Derived(17) assert(der2.value == 34) der2.extendval = 200.0 -assert( math.abs(der2.actualval - 2.0) < 0.001 ) -assert( math.abs(der2.extendval - 200.0) < 0.001 ) +assert(math.abs(der2.actualval - 2.0) < 0.001) +assert(math.abs(der2.extendval - 200.0) < 0.001) diff --git a/Examples/test-suite/lua/extend_typedef_class_runme.lua b/Examples/test-suite/lua/extend_typedef_class_runme.lua index c2535483f..66c9c670a 100644 --- a/Examples/test-suite/lua/extend_typedef_class_runme.lua +++ b/Examples/test-suite/lua/extend_typedef_class_runme.lua @@ -7,7 +7,7 @@ local env = _ENV -- Lua 5.2 if not env then env = getfenv () end -- Lua 5.1 setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) -function test_obj( obj, const ) +function test_obj(obj, const) obj.membervar = const assert(obj:getvar() == const) end diff --git a/Examples/test-suite/lua/extend_variable_runme.lua b/Examples/test-suite/lua/extend_variable_runme.lua index cc2b6844e..58e9c984a 100644 --- a/Examples/test-suite/lua/extend_variable_runme.lua +++ b/Examples/test-suite/lua/extend_variable_runme.lua @@ -9,9 +9,9 @@ setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i e1 = ev.ExtendMe() answ = 1.0 -assert( e1:set(7.0) ) ---assert( e1:get(answ) ) -- doesn't work. Lua can't pass primitive type by non-const reference ---assert( answ == 7.0 ) +assert(e1:set(7.0)) +--assert(e1:get(answ)) -- doesn't work. Lua can't pass primitive type by non-const reference +--assert(answ == 7.0) e1.ExtendVar = 5.0 assert(e1.ExtendVar == 5.0) diff --git a/Examples/test-suite/lua/friends_runme.lua b/Examples/test-suite/lua/friends_runme.lua index 499322691..bdf97934d 100644 --- a/Examples/test-suite/lua/friends_runme.lua +++ b/Examples/test-suite/lua/friends_runme.lua @@ -19,7 +19,7 @@ assert(f.get_val3(a1) == 30) assert(f.get_val1(100, 1, 2) == 100) -assert( f.mix(a1,b1) == 15); +assert(f.mix(a1,b1) == 15); d1 = f.D_i(7) assert(f.get_val1(d1) == 7) diff --git a/Examples/test-suite/lua/funcptr_cpp_runme.lua b/Examples/test-suite/lua/funcptr_cpp_runme.lua index ba396da51..3b8469348 100644 --- a/Examples/test-suite/lua/funcptr_cpp_runme.lua +++ b/Examples/test-suite/lua/funcptr_cpp_runme.lua @@ -7,12 +7,12 @@ local env = _ENV -- Lua 5.2 if not env then env = getfenv () end -- Lua 5.1 setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) -assert( fc.addByValue(5,10) == 15) +assert(fc.addByValue(5,10) == 15) -- These two won't work. Lua will successfully store the answer as userdata, but there is -- no way of accessing the insides of userdata. --- assert( fc.addByPointer(7, 9) == 16) --- assert( fc.addByReference(8, 9) == 17) +-- assert(fc.addByPointer(7, 9) == 16) +-- assert(fc.addByReference(8, 9) == 17) -assert( fc.call1(fc.ADD_BY_VALUE, 5, 10) == 15) -assert( fc.call2(fc.ADD_BY_POINTER, 7, 9) == 16) -assert( fc.call3(fc.ADD_BY_REFERENCE, 8, 9) == 17) +assert(fc.call1(fc.ADD_BY_VALUE, 5, 10) == 15) +assert(fc.call2(fc.ADD_BY_POINTER, 7, 9) == 16) +assert(fc.call3(fc.ADD_BY_REFERENCE, 8, 9) == 17) diff --git a/Examples/test-suite/lua/grouping_runme.lua b/Examples/test-suite/lua/grouping_runme.lua index 798a7359e..7ab08499f 100644 --- a/Examples/test-suite/lua/grouping_runme.lua +++ b/Examples/test-suite/lua/grouping_runme.lua @@ -7,11 +7,11 @@ local env = _ENV -- Lua 5.2 if not env then env = getfenv () end -- Lua 5.1 setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) -assert( g.test1(5) == 5 ) +assert(g.test1(5) == 5) g.test2(42) -- Return value is int* packed into userdata. We can't do anything with it -assert( g.test3 == 37 ) +assert(g.test3 == 37) g.test3 = 42 -assert( g.test3 == 42 ) +assert(g.test3 == 42) -assert( g.do_unary(5, g.NEGATE) == -5 ) +assert(g.do_unary(5, g.NEGATE) == -5) diff --git a/Examples/test-suite/lua/iadd_runme.lua b/Examples/test-suite/lua/iadd_runme.lua index 556644061..214433795 100644 --- a/Examples/test-suite/lua/iadd_runme.lua +++ b/Examples/test-suite/lua/iadd_runme.lua @@ -9,9 +9,9 @@ setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i foo1 = i.Foo() foo1_a = foo1.AsA -assert( foo1_a.x == 5 ) -assert( foo1_a:get_me().x == 5 ) +assert(foo1_a.x == 5) +assert(foo1_a:get_me().x == 5) -- Unfortunately, in Lua operator+= can't be overloaded foo1.AsLong = 1000 -assert( foo1.AsLong == 1000 ) +assert(foo1.AsLong == 1000) diff --git a/Examples/test-suite/lua/keyword_rename_runme.lua b/Examples/test-suite/lua/keyword_rename_runme.lua index 5d54ef123..a9dea466a 100644 --- a/Examples/test-suite/lua/keyword_rename_runme.lua +++ b/Examples/test-suite/lua/keyword_rename_runme.lua @@ -8,9 +8,9 @@ if not env then env = getfenv () end -- Lua 5.1 setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) --- assert( kn.end(5) == 5 ) -- Curretly SWIG/Lua doesn't rename keywords --- assert( kn.nil(7) == 7 ) +-- assert(kn.end(5) == 5) -- Curretly SWIG/Lua doesn't rename keywords +-- assert(kn.nil(7) == 7) -- But you can always access wrongly named members using string constants -assert( kn["end"](5) == 5 ) -assert( kn["nil"](7) == 7 ) +assert(kn["end"](5) == 5) +assert(kn["nil"](7) == 7) diff --git a/Examples/test-suite/lua/li_std_vector_runme.lua b/Examples/test-suite/lua/li_std_vector_runme.lua index 81994b92f..361b42461 100644 --- a/Examples/test-suite/lua/li_std_vector_runme.lua +++ b/Examples/test-suite/lua/li_std_vector_runme.lua @@ -43,7 +43,7 @@ for i=0,3 do end for i=0,3 do - assert( swig_type(sv[i]) =='Struct *' and sv[i].num==i) + assert(swig_type(sv[i]) =='Struct *' and sv[i].num==i) end -- range checking diff --git a/Examples/test-suite/lua/overload_complicated_runme.lua b/Examples/test-suite/lua/overload_complicated_runme.lua index 5670607bf..e8ef43107 100644 --- a/Examples/test-suite/lua/overload_complicated_runme.lua +++ b/Examples/test-suite/lua/overload_complicated_runme.lua @@ -7,16 +7,16 @@ local env = _ENV -- Lua 5.2 if not env then env = getfenv () end -- Lua 5.1 setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) -assert( oc.foo(1,1,"test",1) == 15 ) +assert(oc.foo(1,1,"test",1) == 15) p1 = oc.Pop(nil) p1 = oc.Pop(nil,false) -assert( p1:hip(true) == 701 ) -assert( p1:hip(nil) == 702 ) +assert(p1:hip(true) == 701) +assert(p1:hip(nil) == 702) -assert( p1:hop(true) == 801 ) -assert( p1:hop(nil) == 805 ) +assert(p1:hop(true) == 801) +assert(p1:hop(nil) == 805) -assert( oc.muzak(true) == 3001 ) -assert( oc.muzak(nil) == 3002 ) +assert(oc.muzak(true) == 3001) +assert(oc.muzak(nil) == 3002) diff --git a/Examples/test-suite/lua/smart_pointer_extend_runme.lua b/Examples/test-suite/lua/smart_pointer_extend_runme.lua index 6d33c57b1..e7241738a 100644 --- a/Examples/test-suite/lua/smart_pointer_extend_runme.lua +++ b/Examples/test-suite/lua/smart_pointer_extend_runme.lua @@ -7,28 +7,28 @@ local env = _ENV -- Lua 5.2 if not env then env = getfenv () end -- Lua 5.1 setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) -assert( spe.CBase.hello() == 1 ) -assert( spe.CBase.z == 1 ) +assert(spe.CBase.hello() == 1) +assert(spe.CBase.z == 1) base1 = spe.CBase() base1.x = 7 p1 = spe.CPtr() -assert( spe.get_hello(p1) == 1 ) -assert( p1:foo() == 1 ) -assert( p1:bar() == 2 ) -assert( p1:boo(5) == 5 ) +assert(spe.get_hello(p1) == 1) +assert(p1:foo() == 1) +assert(p1:bar() == 2) +assert(p1:boo(5) == 5) foo = spe.Foo() bar = spe.Bar(foo) -assert( bar:extension(5,7) == 5 ) -assert( bar:extension(7) == 7 ) -assert( bar:extension() == 1 ) +assert(bar:extension(5,7) == 5) +assert(bar:extension(7) == 7) +assert(bar:extension() == 1) dfoo = spe.DFoo() dptr = spe.DPtrFoo(dfoo) -assert( dptr:Ext() == 2 ) -assert( dptr:Ext(5) == 5 ) +assert(dptr:Ext() == 2) +assert(dptr:Ext(5) == 5) diff --git a/Examples/test-suite/lua/smart_pointer_inherit_runme.lua b/Examples/test-suite/lua/smart_pointer_inherit_runme.lua index 75510ad08..0cbebb0c8 100644 --- a/Examples/test-suite/lua/smart_pointer_inherit_runme.lua +++ b/Examples/test-suite/lua/smart_pointer_inherit_runme.lua @@ -11,8 +11,8 @@ der = spi.Derived(7) ptr = spi.SmartDerived(der) -assert( ptr.val == 7 ) -assert( ptr:value() == 7 ) -assert( ptr:value2() == 7 ) -assert( ptr:value3() == 7 ) -assert( ptr:valuehide() == -1 ) +assert(ptr.val == 7) +assert(ptr:value() == 7) +assert(ptr:value2() == 7) +assert(ptr:value3() == 7) +assert(ptr:valuehide() == -1) diff --git a/Examples/test-suite/lua/smart_pointer_multi_runme.lua b/Examples/test-suite/lua/smart_pointer_multi_runme.lua index ed3693727..38d99ae5c 100644 --- a/Examples/test-suite/lua/smart_pointer_multi_runme.lua +++ b/Examples/test-suite/lua/smart_pointer_multi_runme.lua @@ -9,15 +9,15 @@ setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i foo = spm.Foo() foo.x = 5 -assert( foo:getx() == 5 ) +assert(foo:getx() == 5) bar = spm.Bar(foo) spam = spm.Spam(bar) grok = spm.Grok(bar) -assert( bar:getx() == 5 ) -assert( spam:getx() == 5 ) +assert(bar:getx() == 5) +assert(spam:getx() == 5) spam.x = 7 -assert( grok:getx() == 7 ) +assert(grok:getx() == 7) grok.x = 10 -assert( foo:getx() == 10 ) +assert(foo:getx() == 10) diff --git a/Examples/test-suite/lua/smart_pointer_not_runme.lua b/Examples/test-suite/lua/smart_pointer_not_runme.lua index 2f009a7f6..5e58648ee 100644 --- a/Examples/test-suite/lua/smart_pointer_not_runme.lua +++ b/Examples/test-suite/lua/smart_pointer_not_runme.lua @@ -10,16 +10,16 @@ setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i foo = spn.Foo() foo.x = 7 -assert( foo:getx() == 7 ) +assert(foo:getx() == 7) bar = spn.Bar(foo) success = pcall(bar.getx, bar) -- Bar is not a smart pointer. Call should fail -assert( not success ) +assert(not success) spam = spn.Spam(foo) success = pcall(spam.getx, spam) -- Spam is not a smart pointer. Call should fail -assert( not success ) +assert(not success) grok = spn.Grok(foo) success = pcall(grok.getx, grok) -- Spam is not a smart pointer. Call should fail -assert( not success ) +assert(not success) diff --git a/Examples/test-suite/lua/smart_pointer_rename_runme.lua b/Examples/test-suite/lua/smart_pointer_rename_runme.lua index 51b07f61b..2b6e971d2 100644 --- a/Examples/test-suite/lua/smart_pointer_rename_runme.lua +++ b/Examples/test-suite/lua/smart_pointer_rename_runme.lua @@ -9,10 +9,10 @@ setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i foo = spr.Foo() -assert( foo:ftest1(1) == 1 ) -assert( foo:ftest2(1,2) == 2 ) +assert(foo:ftest1(1) == 1) +assert(foo:ftest2(1,2) == 2) bar = spr.Bar(foo) -assert( bar:test() == 3 ) -assert( bar:ftest1(1) == 1 ) -assert( bar:ftest2(1,2) == 2 ) +assert(bar:test() == 3) +assert(bar:ftest1(1) == 1) +assert(bar:ftest2(1,2) == 2) diff --git a/Examples/test-suite/lua/smart_pointer_simple_runme.lua b/Examples/test-suite/lua/smart_pointer_simple_runme.lua index 8513931b2..ca3a85161 100644 --- a/Examples/test-suite/lua/smart_pointer_simple_runme.lua +++ b/Examples/test-suite/lua/smart_pointer_simple_runme.lua @@ -9,8 +9,8 @@ setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i foo1 = sps.Foo() foo1.x = 5 -assert( foo1.x == 5 ) -assert( foo1:getx() == 5 ) +assert(foo1.x == 5) +assert(foo1:getx() == 5) bar1 = sps.Bar(foo1) bar1.x = 3 diff --git a/Examples/test-suite/lua/smart_pointer_templatemethods_runme.lua b/Examples/test-suite/lua/smart_pointer_templatemethods_runme.lua index 018881c42..63a34e91b 100644 --- a/Examples/test-suite/lua/smart_pointer_templatemethods_runme.lua +++ b/Examples/test-suite/lua/smart_pointer_templatemethods_runme.lua @@ -14,5 +14,5 @@ iid = spt.InterfaceId() po2 = o1:QueryInterfaceObjct(iid) -- we can't call po2:DisposeObjct, because smart pointer Ptr always return 0 when dereferencing -- (see interface file). So we only check that po2 has necessary method -assert( po2.DisposeObjct ~= nil ) -assert( po2.QueryInterfaceObjct ~= nil ) +assert(po2.DisposeObjct ~= nil) +assert(po2.QueryInterfaceObjct ~= nil) diff --git a/Examples/test-suite/lua/template_extend1_runme.lua b/Examples/test-suite/lua/template_extend1_runme.lua index 44774e949..28ccb24c7 100644 --- a/Examples/test-suite/lua/template_extend1_runme.lua +++ b/Examples/test-suite/lua/template_extend1_runme.lua @@ -8,7 +8,7 @@ if not env then env = getfenv () end -- Lua 5.1 setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) lb = te.lBaz() -assert( lb:foo() == "lBaz::foo" ) +assert(lb:foo() == "lBaz::foo") db = te.dBaz() -assert( db:foo() == "dBaz::foo" ) +assert(db:foo() == "dBaz::foo") diff --git a/Examples/test-suite/lua/template_extend2_runme.lua b/Examples/test-suite/lua/template_extend2_runme.lua index 23c25705b..124d70e04 100644 --- a/Examples/test-suite/lua/template_extend2_runme.lua +++ b/Examples/test-suite/lua/template_extend2_runme.lua @@ -8,7 +8,7 @@ if not env then env = getfenv () end -- Lua 5.1 setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) lb = te.lBaz() -assert( lb:foo() == "lBaz::foo" ) +assert(lb:foo() == "lBaz::foo") db = te.dBaz() -assert( db:foo() == "dBaz::foo" ) +assert(db:foo() == "dBaz::foo") diff --git a/Examples/test-suite/lua/template_inherit_runme.lua b/Examples/test-suite/lua/template_inherit_runme.lua index f2bfca00b..a337c044f 100644 --- a/Examples/test-suite/lua/template_inherit_runme.lua +++ b/Examples/test-suite/lua/template_inherit_runme.lua @@ -9,16 +9,16 @@ setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i fi = ti.FooInt() -assert( fi:blah() == "Foo" ) -assert( fi:foomethod() == "foomethod" ) +assert(fi:blah() == "Foo") +assert(fi:foomethod() == "foomethod") bi = ti.BarInt() -assert( bi:blah() == "Bar" ) -assert( bi:foomethod() == "foomethod" ) +assert(bi:blah() == "Bar") +assert(bi:foomethod() == "foomethod") -assert( ti.invoke_blah_int(fi) == "Foo" ) -assert( ti.invoke_blah_int(bi) == "Bar" ) +assert(ti.invoke_blah_int(fi) == "Foo") +assert(ti.invoke_blah_int(bi) == "Bar") bd = ti.BarDouble() -success = pcall( ti.invoke_blah_int, bd ) -assert( not success ) +success = pcall(ti.invoke_blah_int, bd) +assert(not success) From 89bc5576c99a6b41eb52c179c4c8e694f3409128 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Fri, 1 Nov 2013 15:10:02 +0400 Subject: [PATCH 182/481] More tests --- Examples/test-suite/keyword_rename.i | 2 + Examples/test-suite/lua/enum_plus_runme.lua | 11 ++++++ Examples/test-suite/lua/enum_rename_runme.lua | 11 ++++++ .../lua/enum_scope_template_runme.lua | 12 ++++++ .../test-suite/lua/enum_template_runme.lua | 16 ++++++++ .../test-suite/lua/inherit_missing_runme.lua | 14 +++++++ .../lua/nested_workaround_runme.lua | 22 +++++++++++ Examples/test-suite/lua/refcount_runme.lua | 26 +++++++++++++ .../lua/static_const_member_2_runme.lua | 37 +++++++++++++++++++ .../lua/static_const_member_runme.lua | 17 +++++++++ .../test-suite/lua/template_static_runme.lua | 20 ++++++++++ Examples/test-suite/lua/varargs_runme.lua | 18 +++++++++ 12 files changed, 206 insertions(+) create mode 100644 Examples/test-suite/lua/enum_plus_runme.lua create mode 100644 Examples/test-suite/lua/enum_rename_runme.lua create mode 100644 Examples/test-suite/lua/enum_scope_template_runme.lua create mode 100644 Examples/test-suite/lua/enum_template_runme.lua create mode 100644 Examples/test-suite/lua/inherit_missing_runme.lua create mode 100644 Examples/test-suite/lua/nested_workaround_runme.lua create mode 100644 Examples/test-suite/lua/refcount_runme.lua create mode 100644 Examples/test-suite/lua/static_const_member_2_runme.lua create mode 100644 Examples/test-suite/lua/static_const_member_runme.lua create mode 100644 Examples/test-suite/lua/template_static_runme.lua create mode 100644 Examples/test-suite/lua/varargs_runme.lua diff --git a/Examples/test-suite/keyword_rename.i b/Examples/test-suite/keyword_rename.i index 46c3338b3..7d14b9b66 100644 --- a/Examples/test-suite/keyword_rename.i +++ b/Examples/test-suite/keyword_rename.i @@ -32,8 +32,10 @@ KW(go, defer) KW(chan, fallthrough) /* Lua keywords */ +#if defined(SWIGLUA) KW(end, function) KW(nil,local) +#endif %} diff --git a/Examples/test-suite/lua/enum_plus_runme.lua b/Examples/test-suite/lua/enum_plus_runme.lua new file mode 100644 index 000000000..ee48df6cd --- /dev/null +++ b/Examples/test-suite/lua/enum_plus_runme.lua @@ -0,0 +1,11 @@ +require("import") -- the import fn +import("enum_plus") -- import lib +ep=enum_plus + +-- catch "undefined" global variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +assert(ep.iFoo_Phoo == 50) -- Old variant of enum bindings +assert(ep.iFoo.Phoo == 50) -- New variant of enum bindings diff --git a/Examples/test-suite/lua/enum_rename_runme.lua b/Examples/test-suite/lua/enum_rename_runme.lua new file mode 100644 index 000000000..84b61d7fc --- /dev/null +++ b/Examples/test-suite/lua/enum_rename_runme.lua @@ -0,0 +1,11 @@ +require("import") -- the import fn +import("enum_rename") -- import lib +er=enum_rename + +-- catch "undefined" global variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +assert(er.M_Jan ~= nil) +assert(er.May ~= nil) diff --git a/Examples/test-suite/lua/enum_scope_template_runme.lua b/Examples/test-suite/lua/enum_scope_template_runme.lua new file mode 100644 index 000000000..176d5904c --- /dev/null +++ b/Examples/test-suite/lua/enum_scope_template_runme.lua @@ -0,0 +1,12 @@ +require("import") -- the import fn +import("enum_scope_template") -- import lib +est=enum_scope_template + +-- catch "undefined" global variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +assert(est.TreeInt.Oak ~= nil) +assert(est.TreeInt_Oak ~= nil) +assert(est.TreeInt.Cedar ~= nil) diff --git a/Examples/test-suite/lua/enum_template_runme.lua b/Examples/test-suite/lua/enum_template_runme.lua new file mode 100644 index 000000000..a32f5fbd5 --- /dev/null +++ b/Examples/test-suite/lua/enum_template_runme.lua @@ -0,0 +1,16 @@ +require("import") -- the import fn +import("enum_template") -- import lib +et=enum_template + +-- catch "undefined" global variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +assert(et.eTest0 ~= nil) +assert(et.eTest1 ~= nil) + +et.TakeETest(et.eTest0) + +res = et.MakeETest() +et.TakeETest(res) diff --git a/Examples/test-suite/lua/inherit_missing_runme.lua b/Examples/test-suite/lua/inherit_missing_runme.lua new file mode 100644 index 000000000..40b3b1717 --- /dev/null +++ b/Examples/test-suite/lua/inherit_missing_runme.lua @@ -0,0 +1,14 @@ +require("import") -- the import fn +import("inherit_missing") -- import lib +im=inherit_missing + +-- catch "undefined" global variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +bar = im.Bar() +spam = im.Spam() + +assert(im.do_blah(bar) == "Bar::blah") +assert(im.do_blah(spam) == "Spam::blah") diff --git a/Examples/test-suite/lua/nested_workaround_runme.lua b/Examples/test-suite/lua/nested_workaround_runme.lua new file mode 100644 index 000000000..20f899523 --- /dev/null +++ b/Examples/test-suite/lua/nested_workaround_runme.lua @@ -0,0 +1,22 @@ +require("import") -- the import fn +import("nested_workaround") -- import lib +nw=nested_workaround + +-- catch "undefined" global variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +i1 = nw.Inner(5) +assert(i1:getValue() == 5) +i1:setValue(7) +assert(i1:getValue() == 7) + +o1 = nw.Outer() +i2 = o1:createInner(9) +assert(i2:getValue() == 9) +i2:setValue(11) +assert(o1:getInnerValue(i2) == 11) + +i3 = o1:doubleInnerValue(i2) +assert(i3:getValue() == 22) diff --git a/Examples/test-suite/lua/refcount_runme.lua b/Examples/test-suite/lua/refcount_runme.lua new file mode 100644 index 000000000..dc97a77bf --- /dev/null +++ b/Examples/test-suite/lua/refcount_runme.lua @@ -0,0 +1,26 @@ +require("import") -- the import fn +import("refcount") -- import lib +r=refcount + +-- catch "undefined" global variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +a = r.A() +assert(a:ref_count() == 1) + +b1 = r.B(a) +assert(a:ref_count() == 2) + +b2 = r.B.create(a) +assert(a:ref_count() == 3) + +b3 = b2:cloner() +assert(a:ref_count() == 4) + +rca = b1:get_rca() -- RCPtr is not wrapped +assert(a:ref_count() == 5) + +b4 = r.global_create(a) +assert(a:ref_count() == 6) diff --git a/Examples/test-suite/lua/static_const_member_2_runme.lua b/Examples/test-suite/lua/static_const_member_2_runme.lua new file mode 100644 index 000000000..dfee5699e --- /dev/null +++ b/Examples/test-suite/lua/static_const_member_2_runme.lua @@ -0,0 +1,37 @@ +require("import") -- the import fn +import("static_const_member_2") -- import lib +scm=static_const_member_2 + +-- catch "undefined" global variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +assert(scm.CavityPackFlags.forward_field == 1) +assert(scm.CavityPackFlags.backward_field == 2) +assert(scm.CavityPackFlags.cavity_flags == 3) + +assert(scm.CavityPackFlags.flags == 0) +scm.CavityPackFlags.flags = 91 +assert(scm.CavityPackFlags.flags == 91) +assert(scm.CavityPackFlags_flags == 91) -- old style bindings + +assert(scm.CavityPackFlags.reftest == 42) + +assert(scm.Test_int.LeftIndex ~= nil) +assert(scm.Test_int.current_profile == 4) + +assert(scm.Foo.BAR.val == 1) +assert(scm.Foo.BAZ.val == 2) + +assert(scm.Foo_BAR.val == 1) +assert(scm.Foo_BAZ.val == 2) + +scm.Foo.BAR.val = 4 +scm.Foo.BAZ.val = 5 + +assert(scm.Foo.BAR.val == 4) +assert(scm.Foo.BAZ.val == 5) + +assert(scm.Foo_BAR.val == 4) +assert(scm.Foo_BAZ.val == 5) diff --git a/Examples/test-suite/lua/static_const_member_runme.lua b/Examples/test-suite/lua/static_const_member_runme.lua new file mode 100644 index 000000000..a53c63872 --- /dev/null +++ b/Examples/test-suite/lua/static_const_member_runme.lua @@ -0,0 +1,17 @@ +require("import") -- the import fn +import("static_const_member") -- import lib into global +scm=static_const_member --alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +assert(scm.X.PN == 0) +assert(scm.X.CN == 1) +assert(scm.X.EN == 2) + +-- Old-style bindings +assert(scm.X_PN == 0) +assert(scm.X_CN == 1) +assert(scm.X_EN == 2) diff --git a/Examples/test-suite/lua/template_static_runme.lua b/Examples/test-suite/lua/template_static_runme.lua new file mode 100644 index 000000000..bde56ebae --- /dev/null +++ b/Examples/test-suite/lua/template_static_runme.lua @@ -0,0 +1,20 @@ +require("import") -- the import fn +import("template_static") -- import lib +ts=template_static + +-- catch "undefined" global variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +assert(ts.foo_i.test == 0) +ts.foo_i.test = 42 +assert(ts.foo_i.test == 42) +assert(ts.foo_i_test == 42) +ts.foo_i_test = 57 +assert(ts.foo_i.test == 57) +assert(ts.foo_i_test == 57) +assert(ts.foo_d.test == 0) + +assert(ts.Foo.bar_double(4) == 1.0) +assert(ts.Foo_bar_double(4) == 1.0) diff --git a/Examples/test-suite/lua/varargs_runme.lua b/Examples/test-suite/lua/varargs_runme.lua new file mode 100644 index 000000000..027a4b920 --- /dev/null +++ b/Examples/test-suite/lua/varargs_runme.lua @@ -0,0 +1,18 @@ +require("import") -- the import fn +import("varargs") -- import lib +v=varargs + +-- catch "undefined" global variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +assert(v.test("Hello") == "Hello") +assert(v.test_def("Hello",0) == "Hello") + +assert(v.Foo.statictest("Hello") == "Hello") +assert(v.Foo.statictest("Hello",1) == "Hello") + +assert(v.test_plenty("Hello") == "Hello") +assert(v.test_plenty("Hello",1) == "Hello") +assert(v.test_plenty("Hello",1,2) == "Hello") From b901979d1c5c839edb09fe3190eaf27236662d09 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Thu, 7 Nov 2013 20:26:27 +0400 Subject: [PATCH 183/481] Tests for enum/consts old-style bindings and for static const char; bindings --- Examples/test-suite/lua/cpp_basic_runme.lua | 3 +++ Examples/test-suite/lua/cpp_enum_runme.lua | 21 +++++++++++++++++++ .../lua/static_const_member_runme.lua | 4 ++++ 3 files changed, 28 insertions(+) create mode 100644 Examples/test-suite/lua/cpp_enum_runme.lua diff --git a/Examples/test-suite/lua/cpp_basic_runme.lua b/Examples/test-suite/lua/cpp_basic_runme.lua index 3d5ccaadf..3e2fb963e 100644 --- a/Examples/test-suite/lua/cpp_basic_runme.lua +++ b/Examples/test-suite/lua/cpp_basic_runme.lua @@ -59,6 +59,9 @@ cb.Bar_global_fval=cb.Foo(-34) assert(cb.Bar_global_fval.num==-34) assert(cb.Bar.global_fval.num==-34) +assert(cb.Bar.global_cint == -4) +assert(cb.Bar_global_cint == -4) + -- Now test member function pointers func1_ptr=cb.get_func1_ptr() func2_ptr=cb.get_func2_ptr() diff --git a/Examples/test-suite/lua/cpp_enum_runme.lua b/Examples/test-suite/lua/cpp_enum_runme.lua new file mode 100644 index 000000000..e8b53c728 --- /dev/null +++ b/Examples/test-suite/lua/cpp_enum_runme.lua @@ -0,0 +1,21 @@ +require("import") -- the import fn +import("cpp_enum") -- import code +ce=cpp_enum -- renaming import + +-- catch "undefined" global variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +assert(ce.ENUM_ONE ~= nil) +assert(ce.ENUM_TWO ~= nil) + +-- Enums inside classes +assert(ce.Foo.Hi == 0) +assert(ce.Foo.Hello == 1); +-- old-style bindings +assert(ce.Foo_Hi == 0) +assert(ce.Foo_Hello == 1); + +assert(ce.Hi == 0) +assert(ce.Hello == 1) diff --git a/Examples/test-suite/lua/static_const_member_runme.lua b/Examples/test-suite/lua/static_const_member_runme.lua index a53c63872..4e2b144c5 100644 --- a/Examples/test-suite/lua/static_const_member_runme.lua +++ b/Examples/test-suite/lua/static_const_member_runme.lua @@ -10,8 +10,12 @@ setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i assert(scm.X.PN == 0) assert(scm.X.CN == 1) assert(scm.X.EN == 2) +assert(scm.X.CHARTEST == "A") -- Old-style bindings assert(scm.X_PN == 0) assert(scm.X_CN == 1) assert(scm.X_EN == 2) +assert(scm.X_CHARTEST == "A") + + From 14de0de5e764246a1ed68b8f3b78f7fb9db83b5f Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Fri, 8 Nov 2013 02:47:34 +0400 Subject: [PATCH 184/481] Tests for arrays and global vars --- .../test-suite/lua/array_member_runme.lua | 30 +++++++++++++ .../test-suite/lua/arrays_global_runme.lua | 14 ++++++ Examples/test-suite/lua/global_vars_runme.lua | 44 +++++++++++++++++++ 3 files changed, 88 insertions(+) create mode 100644 Examples/test-suite/lua/array_member_runme.lua create mode 100644 Examples/test-suite/lua/arrays_global_runme.lua create mode 100644 Examples/test-suite/lua/global_vars_runme.lua diff --git a/Examples/test-suite/lua/array_member_runme.lua b/Examples/test-suite/lua/array_member_runme.lua new file mode 100644 index 000000000..321e7d57d --- /dev/null +++ b/Examples/test-suite/lua/array_member_runme.lua @@ -0,0 +1,30 @@ +require("import") -- the import fn +import("array_member") -- import lib +am = array_member + +-- catch "undefined" global variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +assert(am.get_value(am.global_data,0) == 0) +assert(am.get_value(am.global_data,7) == 7) + +foo = am.Foo() +foo.data = am.global_data +assert(am.get_value(foo.data,0) == 0) + +for i = 0, 7 do + assert(am.get_value(foo.data,i) == am.get_value(am.global_data,i)) +end + + +for i = 0, 7 do + am.set_value(am.global_data,i,-i) +end + +am.global_data = foo.data + +for i = 0, 7 do + assert(am.get_value(foo.data,i) == am.get_value(am.global_data,i)) +end diff --git a/Examples/test-suite/lua/arrays_global_runme.lua b/Examples/test-suite/lua/arrays_global_runme.lua new file mode 100644 index 000000000..fc0d340bf --- /dev/null +++ b/Examples/test-suite/lua/arrays_global_runme.lua @@ -0,0 +1,14 @@ +require("import") -- the import fn +import("arrays_global") -- import lib +ag = arrays_global + +-- catch "undefined" global variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +assert(ag.BeginString_FIX44a == "FIX.a.a") +assert(ag.BeginString_FIX44b == "FIX.b.b") + +assert(ag.BeginString_FIX44c == "FIX.c.c") +assert(ag.BeginString_FIX44d == "FIX.d.d") diff --git a/Examples/test-suite/lua/global_vars_runme.lua b/Examples/test-suite/lua/global_vars_runme.lua new file mode 100644 index 000000000..3c019aee1 --- /dev/null +++ b/Examples/test-suite/lua/global_vars_runme.lua @@ -0,0 +1,44 @@ +require("import") -- the import fn +import("global_vars") -- import lib +gv = global_vars + +-- catch "undefined" global variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +gv.b = "abcde" +assert(gv.b == "abcde") + +gv.a.x = 7 +assert(gv.a.x == 7) + +a1 = gv.A() +a1.x = 11 +gv.a = a1 +assert(gv.a.x == 11) + +gv.x = 10 +assert(gv.x == 10) + +assert(gv.Hi ~= nil) +assert(gv.Hola ~= nil) + +gv.h = gv.Hi +assert(gv.h == gv.Hi) + + +-- It is not clear whether these tests should work or not +-- Currently they don't. +-- +-- assert(gv.c_member == 10) +-- +-- gv.c_member = 5 +-- assert(gv.x == 5) +-- +-- gv.h = gv.Hi +-- assert(gv.hr == gv.Hi) +-- +-- gv.hr = gv.Hola +-- assert(gv.h == gv.Hola) +-- assert(gv.hr == gv.Hola) From 8b35c0b5cef599a0ac3a65343bf729a73222b568 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Fri, 8 Nov 2013 04:33:45 +0400 Subject: [PATCH 185/481] Add runfile to check for correct compatibility name generation Checks that if OldClass was renamed to NewClass, then not only OldClass.static_method is now NewClass.static_method, but also compatibility name OldClass_static_method is now NewClass_static_method. Same for enums, static vars etc --- .../test-suite/lua/rename_simple_runme.lua | 25 +++++++++++++++++++ Examples/test-suite/rename_simple.i | 1 + 2 files changed, 26 insertions(+) create mode 100644 Examples/test-suite/lua/rename_simple_runme.lua diff --git a/Examples/test-suite/lua/rename_simple_runme.lua b/Examples/test-suite/lua/rename_simple_runme.lua new file mode 100644 index 000000000..90f510a54 --- /dev/null +++ b/Examples/test-suite/lua/rename_simple_runme.lua @@ -0,0 +1,25 @@ +require("import") -- the import fn +import("rename_simple") -- import lib +rs = rename_simple + +-- catch "undefined" global variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +assert(rs.NewStruct ~= nil) +assert(rs.NewStruct.NewStaticVariable == 444) +assert(rs.NewStruct_NewStaticVariable == 444) + +assert(rs.NewStruct.NewStaticMethod() == 333) +assert(rs.NewStruct_NewStaticMethod() == 333) + +assert(rs.NewStruct.ONE == 1) +assert(rs.NewStruct_ONE == 1) + +assert(rs.NewFunction() == 555) + +assert(rs.OldStruct == nil) +assert(rs.OldFunction == nil) +assert(rs.OldGlobalVariable == nil) +assert(rs.OldStruct_ONE == nil) diff --git a/Examples/test-suite/rename_simple.i b/Examples/test-suite/rename_simple.i index feba53fa1..5616b16ea 100644 --- a/Examples/test-suite/rename_simple.i +++ b/Examples/test-suite/rename_simple.i @@ -11,6 +11,7 @@ %inline %{ struct OldStruct { + enum { ONE = 1, TWO, THREE }; OldStruct() : OldInstanceVariable(111) {} int OldInstanceVariable; int OldInstanceMethod() { return 222; } From ca5327d0dad8589f0a6691ae1391a68238895f35 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 9 Nov 2013 14:04:24 +0000 Subject: [PATCH 186/481] Remove Lua specifics from keyword_rename testcase --- Examples/test-suite/keyword_rename.i | 2 -- 1 file changed, 2 deletions(-) diff --git a/Examples/test-suite/keyword_rename.i b/Examples/test-suite/keyword_rename.i index 7d14b9b66..46c3338b3 100644 --- a/Examples/test-suite/keyword_rename.i +++ b/Examples/test-suite/keyword_rename.i @@ -32,10 +32,8 @@ KW(go, defer) KW(chan, fallthrough) /* Lua keywords */ -#if defined(SWIGLUA) KW(end, function) KW(nil,local) -#endif %} From 65de78b8b4caefbbd3afd420122c2946760b3047 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 9 Nov 2013 14:52:59 +0000 Subject: [PATCH 187/481] enum_plus testcase was never been run --- Examples/test-suite/common.mk | 1 + 1 file changed, 1 insertion(+) diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 0f3f82629..e25d36715 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -194,6 +194,7 @@ CPP_TEST_CASES += \ disown \ dynamic_cast \ empty \ + enum_plus \ enum_rename \ enum_scope_template \ enum_template \ From c151a0d69ae4d9e415abc5600330e152831c1fea Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 11 Nov 2013 19:12:48 +0000 Subject: [PATCH 188/481] Add array function PHP keywords --- Lib/php/phpkw.swg | 102 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 90 insertions(+), 12 deletions(-) diff --git a/Lib/php/phpkw.swg b/Lib/php/phpkw.swg index c55766928..78a93369f 100644 --- a/Lib/php/phpkw.swg +++ b/Lib/php/phpkw.swg @@ -588,26 +588,104 @@ PHPCN(sqliteexception); PHPCN(datetime); /* Built-in PHP functions (incomplete). */ -PHPFN(cos); -PHPFN(sin); -PHPFN(tan); +/* Includes Array Functions - http://us3.php.net/manual/en/ref.array.php */ PHPFN(acos); +PHPFN(array_change_key_case); +PHPFN(array_chunk); +PHPFN(array_column); +PHPFN(array_combine); +PHPFN(array_count_values); +PHPFN(array_diff); +PHPFN(array_diff_assoc); +PHPFN(array_diff_key); +PHPFN(array_diff_uassoc); +PHPFN(array_diff_ukey); +PHPFN(array_fill); +PHPFN(array_fill_keys); +PHPFN(array_filter); +PHPFN(array_flip); +PHPFN(array_intersect); +PHPFN(array_intersect_assoc); +PHPFN(array_intersect_key); +PHPFN(array_intersect_uassoc); +PHPFN(array_intersect_ukey); +PHPFN(array_key_exists); +PHPFN(array_keys); +PHPFN(array_map); +PHPFN(array_merge); +PHPFN(array_merge_recursive); +PHPFN(array_multisort); +PHPFN(array_pad); +PHPFN(array_pop); +PHPFN(array_product); +PHPFN(array_push); +PHPFN(array_rand); +PHPFN(array_reduce); +PHPFN(array_replace); +PHPFN(array_replace_recursive); +PHPFN(array_reverse); +PHPFN(array_search); +PHPFN(array_shift); +PHPFN(array_slice); +PHPFN(array_splice); +PHPFN(array_sum); +PHPFN(array_udiff); +PHPFN(array_udiff_assoc); +PHPFN(array_udiff_uassoc); +PHPFN(array_uintersect); +PHPFN(array_uintersect_assoc); +PHPFN(array_uintersect_uassoc); +PHPFN(array_unique); +PHPFN(array_unshift); +PHPFN(array_values); +PHPFN(array_walk); +PHPFN(array_walk_recursive); +PHPFN(arsort); PHPFN(asin); +PHPFN(asort); PHPFN(atan); PHPFN(atan2); -PHPFN(cosh); -PHPFN(sinh); -PHPFN(tanh); -PHPFN(exp); -PHPFN(log); -PHPFN(log10); -PHPFN(pow); -PHPFN(sqrt); PHPFN(ceil); +PHPFN(compact); +PHPFN(cos); +PHPFN(cosh); +PHPFN(count); +PHPFN(current); +PHPFN(each); +PHPFN(end); +PHPFN(exp); +PHPFN(extract); PHPFN(floor); PHPFN(fmod); -PHPFN(min); +PHPFN(in_array); +PHPFN(key); +PHPFN(key_exists); +PHPFN(krsort); +PHPFN(ksort); +PHPFN(log); +PHPFN(log10); PHPFN(max); +PHPFN(min); +PHPFN(natcasesort); +PHPFN(natsort); +PHPFN(next); +PHPFN(pos); +PHPFN(pow); +PHPFN(prev); +PHPFN(range); +PHPFN(reset); +PHPFN(rsort); +PHPFN(shuffle); +PHPFN(sin); +PHPFN(sinh); +PHPFN(sizeof); +PHPFN(sort); +PHPFN(sqrt); +PHPFN(tan); +PHPFN(tanh); +PHPFN(uasort); +PHPFN(uksort); +PHPFN(usort); #undef PHPKW #undef PHPBN1 From 0901a3e867a733cbede8b034f92c964025c38c8a Mon Sep 17 00:00:00 2001 From: Robert Stone Date: Tue, 12 Nov 2013 12:45:03 -0800 Subject: [PATCH 189/481] steals python directors and adapts to perl5 --- .../perl5/director_abstract_runme.pl | 62 ++ .../perl5/director_alternating_runme.pl | 8 + .../test-suite/perl5/director_basic_runme.pl | 57 ++ .../perl5/director_classes_runme.pl | 70 ++ .../perl5/director_classic_runme.pl | 128 +++ .../perl5/director_constructor_runme.pl | 46 + .../perl5/director_default_runme.pl | 18 + .../test-suite/perl5/director_detect_runme.pl | 45 + .../test-suite/perl5/director_enum_runme.pl | 21 + .../perl5/director_exception_runme.pl | 57 ++ .../test-suite/perl5/director_extend_runme.pl | 16 + .../perl5/director_finalizer_runme.pl | 83 ++ .../test-suite/perl5/director_frob_runme.pl | 10 + .../test-suite/perl5/director_ignore_runme.pl | 25 + .../test-suite/perl5/director_nested_runme.pl | 59 ++ .../perl5/director_primitives_runme.pl | 68 ++ .../perl5/director_protected_runme.pl | 48 ++ .../test-suite/perl5/director_string_runme.pl | 34 + .../test-suite/perl5/director_unroll_runme.pl | 17 + .../test-suite/perl5/director_wombat_runme.pl | 53 ++ Lib/perl5/perlrun.swg | 3 +- Lib/perl5/perltypemaps.swg | 6 +- Source/Modules/perl5.cxx | 812 +++++++++++++++++- 23 files changed, 1741 insertions(+), 5 deletions(-) create mode 100644 Examples/test-suite/perl5/director_abstract_runme.pl create mode 100644 Examples/test-suite/perl5/director_alternating_runme.pl create mode 100644 Examples/test-suite/perl5/director_basic_runme.pl create mode 100644 Examples/test-suite/perl5/director_classes_runme.pl create mode 100644 Examples/test-suite/perl5/director_classic_runme.pl create mode 100644 Examples/test-suite/perl5/director_constructor_runme.pl create mode 100644 Examples/test-suite/perl5/director_default_runme.pl create mode 100644 Examples/test-suite/perl5/director_detect_runme.pl create mode 100644 Examples/test-suite/perl5/director_enum_runme.pl create mode 100644 Examples/test-suite/perl5/director_exception_runme.pl create mode 100644 Examples/test-suite/perl5/director_extend_runme.pl create mode 100644 Examples/test-suite/perl5/director_finalizer_runme.pl create mode 100644 Examples/test-suite/perl5/director_frob_runme.pl create mode 100644 Examples/test-suite/perl5/director_ignore_runme.pl create mode 100644 Examples/test-suite/perl5/director_nested_runme.pl create mode 100644 Examples/test-suite/perl5/director_primitives_runme.pl create mode 100644 Examples/test-suite/perl5/director_protected_runme.pl create mode 100644 Examples/test-suite/perl5/director_string_runme.pl create mode 100644 Examples/test-suite/perl5/director_unroll_runme.pl create mode 100644 Examples/test-suite/perl5/director_wombat_runme.pl diff --git a/Examples/test-suite/perl5/director_abstract_runme.pl b/Examples/test-suite/perl5/director_abstract_runme.pl new file mode 100644 index 000000000..d369eac17 --- /dev/null +++ b/Examples/test-suite/perl5/director_abstract_runme.pl @@ -0,0 +1,62 @@ +use strict; +use warnings; +use Test::More tests => 13; +BEGIN { use_ok('director_abstract') } +require_ok('director_abstract'); + +{ + package MyFoo; + use base 'director_abstract::Foo'; + sub ping { + return 'MyFoo::ping()'; + } +} + +my $f = MyFoo->new(); + +is($f->ping, "MyFoo::ping()"); + +is($f->pong(),"Foo::pong();MyFoo::ping()"); + +{ + package MyExample1; + use base 'director_abstract::Example1'; + sub Color { my($self, $r, $g, $b) = @_; + return $r; + } +} +{ + package MyExample2; + use base 'director_abstract::Example2'; + sub Color { my($self, $r, $g, $b) = @_; + return $g; + } +} +{ + package MyExample3; + use base 'director_abstract::Example3_i'; + sub Color { my($self, $r, $g, $b) = @_; + return $b; + } +} + +my $me1 = MyExample1->new(); +isa_ok($me1, 'MyExample1'); +is(director_abstract::Example1::get_color($me1, 1, 2, 3), 1, 'me1'); + +my $me2 = MyExample2->new(1,2); +isa_ok($me2, 'MyExample2'); +is(director_abstract::Example2::get_color($me2, 1, 2, 3), 2, 'me2'); + +my $me3 = MyExample3->new(); +isa_ok($me3, 'MyExample3'); +is(director_abstract::Example3_i::get_color($me3, 1, 2, 3), 3, 'me3'); + +eval { $me1 = director_abstract::Example1->new() }; +like($@, qr/\babstract\b/i, 'E1.new()'); + +eval { $me2 = director_abstract::Example2->new() }; +like($@, qr/Example2/, 'E2.new()'); + +eval { $me3 = director_abstract::Example3_i->new() }; +like($@, qr/\babstract\b/i, 'E3.new()'); diff --git a/Examples/test-suite/perl5/director_alternating_runme.pl b/Examples/test-suite/perl5/director_alternating_runme.pl new file mode 100644 index 000000000..83d30af6d --- /dev/null +++ b/Examples/test-suite/perl5/director_alternating_runme.pl @@ -0,0 +1,8 @@ +use strict; +use warnings; +use Test::More tests => 3; +BEGIN { use_ok('director_alternating') } +require_ok('director_alternating'); + +my $id = director_alternating::getBar()->id(); +is($id, director_alternating::idFromGetBar(), "got Bar id"); diff --git a/Examples/test-suite/perl5/director_basic_runme.pl b/Examples/test-suite/perl5/director_basic_runme.pl new file mode 100644 index 000000000..55e70dc9c --- /dev/null +++ b/Examples/test-suite/perl5/director_basic_runme.pl @@ -0,0 +1,57 @@ +use strict; +use warnings; +use Test::More tests => 12; +BEGIN { use_ok 'director_basic' } +require_ok 'director_basic'; + +{ + package MyFoo; + use base 'director_basic::Foo'; + sub ping { + return 'MyFoo::ping()'; + } +} + +{ + package MyOverriddenClass; + use base 'director_basic::MyClass'; + use fields qw(expectNull nonNullReceived); + sub new { + my $self = shift->SUPER::new(@_); + $self->{expectNull} = undef; + $self->{nonNullReceived} = undef; + return $self; + } + sub pmethod { my($self, $b) = @_; + die "null not received as expected" + if $self->{expectNull} and defined $b; + return $b; + } +} + +{ + my $a = MyFoo->new(); + isa_ok $a, 'MyFoo'; + is $a->ping(), 'MyFoo::ping()', 'a.ping()'; + is $a->pong(), 'Foo::pong();MyFoo::ping()', 'a.pong()'; + + my $b = director_basic::Foo->new(); + isa_ok $b, 'director_basic::Foo'; + is $b->ping(), 'Foo::ping()', 'b.ping()'; + is $b->pong(), 'Foo::pong();Foo::ping()', 'b.pong()'; + + my $a1 = director_basic::A1->new(1, undef); + isa_ok $a1, 'director_basic::A1'; + is $a1->rg(2), 2, 'A1.rg'; + + my $my = MyOverriddenClass->new(); + $my->{expectNull} = 1; + is(director_basic::MyClass::call_pmethod($my, undef), undef, + 'null pointer marshalling'); + + my $myBar = director_basic::Bar->new(); + $my->{expectNull} = undef; + my $myNewBar = director_basic::MyClass::call_pmethod($my, $myBar); + isnt($myNewBar, undef, 'non-null pointer marshalling'); + $myNewBar->{x} = 10; +} diff --git a/Examples/test-suite/perl5/director_classes_runme.pl b/Examples/test-suite/perl5/director_classes_runme.pl new file mode 100644 index 000000000..a4fddeed9 --- /dev/null +++ b/Examples/test-suite/perl5/director_classes_runme.pl @@ -0,0 +1,70 @@ +use strict; +use warnings; +use Test::More tests => 29; +BEGIN { use_ok 'director_classes' } +require_ok 'director_classes'; + +{ + package PerlDerived; + use base 'director_classes::Base'; + sub Val { $_[1] } + sub Ref { $_[1] } + sub Ptr { $_[1] } + sub FullyOverloaded { + my $rv = shift->SUPER::FullyOverloaded(@_); + $rv =~ s/Base/__PACKAGE__/sge; + return $rv; + } + sub SemiOverloaded { + # this is going to be awkward because we can't really + # semi-overload in Perl, but we can sort of fake it. + return shift->SUPER::SemiOverloaded(@_) unless $_[0] =~ /^\d+/; + my $rv = shift->SUPER::SemiOverloaded(@_); + $rv =~ s/Base/__PACKAGE__/sge; + return $rv; + } + sub DefaultParms { + my $rv = shift->SUPER::DefaultParms(@_); + $rv =~ s/Base/__PACKAGE__/sge; + return $rv; + } +} + +{ + my $c = director_classes::Caller->new(); + makeCalls($c, director_classes::Base->new(100.0)); + makeCalls($c, director_classes::Derived->new(200.0)); + makeCalls($c, PerlDerived->new(300.0)); +} + +sub makeCalls { my($caller, $base) = @_; + my $bname = ref $base; + $bname = $1 if $bname =~ /^director_classes::(.*)$/; + $caller->set($base); + my $dh = director_classes::DoubleHolder->new(444.555); + is($caller->ValCall($dh)->{val}, $dh->{val}, "$bname.Val"); + is($caller->RefCall($dh)->{val}, $dh->{val}, "$bname.Ref"); + is($caller->PtrCall($dh)->{val}, $dh->{val}, "$bname.Ptr"); + is($caller->FullyOverloadedCall(1), + "${bname}::FullyOverloaded(int)", + "$bname.FullyOverloaded(int)"); + is($caller->FullyOverloadedCall(''), + "${bname}::FullyOverloaded(bool)", + "$bname.FullyOverloaded(bool)"); +TODO: { + local $TODO = 'investigation needed here' if $bname eq 'PerlDerived'; + is($caller->SemiOverloadedCall(-678), + "${bname}::SemiOverloaded(int)", + "$bname.SemiOverloaded(int)"); +} + is($caller->SemiOverloadedCall(''), + "Base::SemiOverloaded(bool)", + "$bname.SemiOverloaded(bool)"); + is($caller->DefaultParmsCall(10, 2.2), + "${bname}::DefaultParms(int, double)", + "$bname.DefaultParms(int, double)"); + is($caller->DefaultParmsCall(10), + "${bname}::DefaultParms(int)", + "$bname.DefaultParms(int)"); + $caller->reset(); +} diff --git a/Examples/test-suite/perl5/director_classic_runme.pl b/Examples/test-suite/perl5/director_classic_runme.pl new file mode 100644 index 000000000..2fa4fde56 --- /dev/null +++ b/Examples/test-suite/perl5/director_classic_runme.pl @@ -0,0 +1,128 @@ +use strict; +use warnings; +use Test::More tests => 41; +BEGIN { use_ok('director_classic') } +require_ok('director_classic'); + +{ + package TargetLangPerson; + use base 'director_classic::Person'; + sub id { return 'TargetLangPerson' } +} + +{ + package TargetLangChild; + use base 'director_classic::Child'; + sub id { return 'TargetLangChild' } +} + +{ + package TargetLangGrandChild; + use base 'director_classic::GrandChild'; + sub id { return 'TargetLangGrandChild' } +} + +# Semis - don't override id() in target language +{ + package TargetLangSemiPerson; + use base 'director_classic::Person'; + # No id() override +} + +{ + package TargetLangSemiChild; + use base 'director_classic::Child'; + # No id() override +} + +{ + package TargetLangSemiGrandChild; + use base 'director_classic::GrandChild'; + # No id() override +} + +# Orphans - don't override id() in C++ +{ + package TargetLangOrphanPerson; + use base 'director_classic::OrphanPerson'; + sub id { return "TargetLangOrphanPerson" } +} + +{ + package TargetLangOrphanChild; + use base 'director_classic::OrphanChild'; + sub id { return "TargetLangOrphanChild" } +} + +sub check { my($person, $expected) = @_; + # Normal target language polymorphic call + is($person->id(), $expected, "$expected from Perl"); + + # Polymorphic call from C++ + my $caller = director_classic::Caller->new(); + $caller->setCallback($person); + is($caller->call(), $expected, "$expected from C++"); + + # Polymorphic call of object created in target language and passed to C++ and back again + my $baseclass = $caller->baseClass(); + is($baseclass->id(), $expected, "$expected after bounce"); + + $caller->resetCallback(); +} + +my $person; + +$person = director_classic::Person->new(); +check($person, "Person"); +undef $person; + +$person = director_classic::Child->new(); +check($person, "Child"); +undef $person; + +$person = director_classic::GrandChild->new(); +check($person, "GrandChild"); +undef $person; + +$person = TargetLangPerson->new(); +check($person, "TargetLangPerson"); +undef $person; + +$person = TargetLangChild->new(); +check($person, "TargetLangChild"); +undef $person; + +$person = TargetLangGrandChild->new(); +check($person, "TargetLangGrandChild"); +undef $person; + +# Semis - don't override id() in target language +$person = TargetLangSemiPerson->new(); +check($person, "Person"); +undef $person; + +$person = TargetLangSemiChild->new(); +check($person, "Child"); +undef $person; + +$person = TargetLangSemiGrandChild->new(); +check($person, "GrandChild"); +undef $person; + +# Orphans - don't override id() in C++ +$person = director_classic::OrphanPerson->new(); +check($person, "Person"); +undef $person; + +$person = director_classic::OrphanChild->new(); +check($person, "Child"); +undef $person; + +$person = TargetLangOrphanPerson->new(); +check($person, "TargetLangOrphanPerson"); +undef $person; + +$person = TargetLangOrphanChild->new(); +check($person, "TargetLangOrphanChild"); +undef $person; + diff --git a/Examples/test-suite/perl5/director_constructor_runme.pl b/Examples/test-suite/perl5/director_constructor_runme.pl new file mode 100644 index 000000000..c990fc3a1 --- /dev/null +++ b/Examples/test-suite/perl5/director_constructor_runme.pl @@ -0,0 +1,46 @@ +use strict; +use warnings; +use Test::More tests => 9; +BEGIN { use_ok 'director_constructor' } +require_ok 'director_constructor'; + +{ + package Test; + use base 'director_constructor::Foo'; + sub doubleit { my($self) = @_; + $self->{a} *= 2; + } + sub test { 3 } +} +my $t = Test->new(5); +isa_ok $t, 'Test'; +is $t->getit, 5; +is $t->do_test, 3; + +$t->doubleit(); + +is $t->getit, 10; + +{ + package Wrong; + use base 'director_constructor::Foo'; + sub doubleit { my($self) = @_; + # calling this should trigger a type error on attribute + # assignment + $self->{a} = {}; + } + sub test { + # if c++ calls this, retval copyout should trigger a type error + return bless {}, 'TotallyBogus'; + } +} + +# TODO: these TypeErrors in director classes should be more detailed +my $w = Wrong->new(12); +is eval { $w->doubleit() }, undef; +like $@, qr/TypeError/; +is $w->getit(), 12, 'W.a should be unaffected'; + +# TODO: this is giving an unhandled C++ exception right now +#is eval { $W->do_test() }, undef; +#like $@, qr/TypeError/; diff --git a/Examples/test-suite/perl5/director_default_runme.pl b/Examples/test-suite/perl5/director_default_runme.pl new file mode 100644 index 000000000..281c8ebd3 --- /dev/null +++ b/Examples/test-suite/perl5/director_default_runme.pl @@ -0,0 +1,18 @@ +use strict; +use warnings; +use Test::More tests => 6; +BEGIN { use_ok 'director_default' } +require_ok 'director_default'; + +my $f; + +$f = director_default::Foo->new(); +isa_ok $f, 'director_default::Foo'; +$f = director_default::Foo->new(1); +isa_ok $f, 'director_default::Foo'; + + +$f = director_default::Bar->new(); +isa_ok $f, 'director_default::Bar'; +$f = director_default::Bar->new(1); +isa_ok $f, 'director_default::Bar'; diff --git a/Examples/test-suite/perl5/director_detect_runme.pl b/Examples/test-suite/perl5/director_detect_runme.pl new file mode 100644 index 000000000..3e2c652cb --- /dev/null +++ b/Examples/test-suite/perl5/director_detect_runme.pl @@ -0,0 +1,45 @@ +use strict; +use warnings; +use Test::More tests => 9; +BEGIN { use_ok 'director_detect' } +require_ok 'director_detect'; + +{ + package MyBar; + use base 'director_detect::Bar'; + sub new { my $class = shift; + my $val = @_ ? shift : 2; + my $self = $class->SUPER::new(); + $self->{val} = $val; + return $self; + } + sub get_value { my($self) = @_; + $self->{val}++; + return $self->{val}; + } + sub get_class { my($self) = @_; + $self->{val}++; + return director_detect::A->new(); + } + sub just_do_it { my($self) = @_; + $self->{val}++; + } + sub clone { my($self) = @_; + MyBar->new($self->{val}); + } +} + +my $b = MyBar->new(); +isa_ok $b, 'MyBar'; + +my $f = $b->baseclass(); +isa_ok $f, 'director_detect::Foo'; +is $f->get_value(), 3; + +isa_ok $f->get_class(), 'director_detect::A'; +$f->just_do_it(); + +my $c = $b->clone(); +isa_ok $c, 'MyBar'; +is $b->{val}, 5; +is $c->get_value(), 6; diff --git a/Examples/test-suite/perl5/director_enum_runme.pl b/Examples/test-suite/perl5/director_enum_runme.pl new file mode 100644 index 000000000..6d58b376e --- /dev/null +++ b/Examples/test-suite/perl5/director_enum_runme.pl @@ -0,0 +1,21 @@ +use strict; +use warnings; +use Test::More tests => 5; +BEGIN { use_ok 'director_enum' } +require_ok 'director_enum'; + +{ + package MyFoo; + use base 'director_enum::Foo'; + sub say_hi { my($self, $val) = @_; + return $val; + } +} + +my $b = director_enum::Foo->new(); +isa_ok $b, 'director_enum::Foo'; +my $a = MyFoo->new(); +isa_ok $a, 'MyFoo'; + +is $a->say_hi($director_enum::hello), + $a->say_hello($director_enum::hi); diff --git a/Examples/test-suite/perl5/director_exception_runme.pl b/Examples/test-suite/perl5/director_exception_runme.pl new file mode 100644 index 000000000..62c103b6c --- /dev/null +++ b/Examples/test-suite/perl5/director_exception_runme.pl @@ -0,0 +1,57 @@ +use strict; +use warnings; +use Test::More tests => 7; +BEGIN { use_ok 'director_exception' } +require_ok 'director_exception'; + +{ + package MyFoo; + use base 'director_exception::Foo'; + sub ping { + die "MyFoo::ping() EXCEPTION"; + } +} +{ + package MyFoo2; + use base 'director_exception::Foo'; + sub ping { + # error should return a string + return bless [ 1 ], 'main'; + } +} +{ + package MyFoo3; + use base 'director_exception::Foo'; + sub ping { + # error should return a string + return sub { 1 } + } +} + +{ + my $a = MyFoo->new(); + my $b = director_exception::launder($a); + eval { $b->pong() }; + like($@, qr/\bMyFoo::ping\(\) EXCEPTION\b/, + 'MyFoo.pong() error content preserved'); +} +{ + my $a = MyFoo2->new(); + my $b = director_exception::launder($a); + eval { $b->pong() }; + like($@, qr/\bTypeError\b/, + 'MyFoo2.pong() error content preserved'); +} +{ + my $a = MyFoo3->new(); + my $b = director_exception::launder($a); + eval { $b->pong() }; + like($@, qr/\bTypeError\b/, + 'MyFoo2.pong() error content preserved'); +} + +eval { die director_exception::Exception1->new() }; +isa_ok($@, 'director_exception::Exception1', 'Exception1'); + +eval { die director_exception::Exception2->new() }; +isa_ok($@, 'director_exception::Exception2', 'Exception2'); diff --git a/Examples/test-suite/perl5/director_extend_runme.pl b/Examples/test-suite/perl5/director_extend_runme.pl new file mode 100644 index 000000000..c3d7fb934 --- /dev/null +++ b/Examples/test-suite/perl5/director_extend_runme.pl @@ -0,0 +1,16 @@ +use strict; +use warnings; +use Test::More tests => 5; +BEGIN { use_ok 'director_extend' } +require_ok 'director_extend'; + +{ + package MyObject; + use base 'director_extend::SpObject'; + sub getFoo { 123 } +} + +my $m = MyObject->new(); +isa_ok $m, 'MyObject'; +is($m->dummy(), 666, '1st call'); +is($m->dummy(), 666, '2nd call'); diff --git a/Examples/test-suite/perl5/director_finalizer_runme.pl b/Examples/test-suite/perl5/director_finalizer_runme.pl new file mode 100644 index 000000000..bb6e1fa71 --- /dev/null +++ b/Examples/test-suite/perl5/director_finalizer_runme.pl @@ -0,0 +1,83 @@ +use strict; +use warnings; +use Test::More tests => 13; +BEGIN { use_ok('director_finalizer') } +require_ok('director_finalizer'); + +{ + package MyFoo; + use base 'director_finalizer::Foo'; + sub DIRECTOR_DESTROY { my($self) = @_; + $self->orStatus(2); + } +} + +{ + director_finalizer::resetStatus(); + my $f = MyFoo->new(); + undef $f; + is(director_finalizer::getStatus(), 3, 'shadow release fires destructor'); +} + +{ # again, this time with DESTROY + director_finalizer::resetStatus(); + my $f = MyFoo->new(); + $f->DESTROY(); + is(director_finalizer::getStatus(), 3, 'DESTROY method fires destructor'); +} + +{ + director_finalizer::resetStatus(); + my $f = MyFoo->new(); + director_finalizer::launder($f); + is(director_finalizer::getStatus(), 0, 'wrap release does not fire destructor'); + undef $f; + is(director_finalizer::getStatus(), 3, 'shadow release still fires destructor'); +} + +{ # again, this time with DESTROY + director_finalizer::resetStatus(); + my $f = MyFoo->new(); + director_finalizer::launder($f); + is(director_finalizer::getStatus(), 0, 'wrap release does not fire destructor'); + $f->DESTROY(); + is(director_finalizer::getStatus(), 3, 'DESTROY method still fires destructor'); +} + +{ + director_finalizer::resetStatus(); + my $f = MyFoo->new(); + $f->DISOWN(); + is(director_finalizer::getStatus(), 0, 'shadow release does not fire destructor of disowned object'); + director_finalizer::deleteFoo($f); + is(director_finalizer::getStatus(), 3, 'c++ release fires destructors of disowned object'); +} + +{ # again, this time with DESTROY + my $f = MyFoo->new(); + $f->DISOWN(); + director_finalizer::deleteFoo($f); + director_finalizer::resetStatus(); + $f->DESTROY(); + is(director_finalizer::getStatus(), 0, 'DESTROY method does not fire destructor of disowned object'); +} + +{ + director_finalizer::resetStatus(); + my $f = MyFoo->new(); + $f->DISOWN(); + my $g = director_finalizer::launder($f); + undef $f; + director_finalizer::deleteFoo($g); + is(director_finalizer::getStatus(), 3, 'c++ release fires destructors on disowned opaque object'); +} + +{ # again, this time with DESTROY + director_finalizer::resetStatus(); + my $f = MyFoo->new(); + $f->DISOWN(); + my $g = director_finalizer::launder($f); + $f->DESTROY(); + director_finalizer::deleteFoo($g); + is(director_finalizer::getStatus(), 3, 'c++ release fires destructors on disowned opaque object after DESTROY'); +} diff --git a/Examples/test-suite/perl5/director_frob_runme.pl b/Examples/test-suite/perl5/director_frob_runme.pl new file mode 100644 index 000000000..0faf440c5 --- /dev/null +++ b/Examples/test-suite/perl5/director_frob_runme.pl @@ -0,0 +1,10 @@ +use strict; +use warnings; +use Test::More tests => 4; +BEGIN { use_ok 'director_frob' } +require_ok 'director_frob'; + +my $foo = director_frob::Bravo->new(); +isa_ok $foo, 'director_frob::Bravo'; + +is($foo->abs_method(), 'Bravo::abs_method()'); diff --git a/Examples/test-suite/perl5/director_ignore_runme.pl b/Examples/test-suite/perl5/director_ignore_runme.pl new file mode 100644 index 000000000..9566f4bb3 --- /dev/null +++ b/Examples/test-suite/perl5/director_ignore_runme.pl @@ -0,0 +1,25 @@ +use strict; +use warnings; +use Test::More tests => 6; +BEGIN { use_ok 'director_ignore' } +require_ok 'director_ignore'; + +{ + package DIgnoresDerived; + use base 'director_ignore::DIgnores'; + sub PublicMethod1 { + return 18.75; + } +} +{ + package DAbstractIgnoresDerived; + use base 'director_ignore::DAbstractIgnores'; +} + +my $a = DIgnoresDerived->new(); +isa_ok $a, 'DIgnoresDerived'; +is $a->Triple(5), 15; + +my $b = DAbstractIgnoresDerived->new(); +isa_ok $b, 'DAbstractIgnoresDerived'; +is $b->Quadruple(5), 20; diff --git a/Examples/test-suite/perl5/director_nested_runme.pl b/Examples/test-suite/perl5/director_nested_runme.pl new file mode 100644 index 000000000..e6c19665a --- /dev/null +++ b/Examples/test-suite/perl5/director_nested_runme.pl @@ -0,0 +1,59 @@ +use strict; +use warnings; +use Test::More tests => 9; +BEGIN { use_ok 'director_nested' } +require_ok 'director_nested'; + +{ + package A; + use base 'director_nested::FooBar_int'; + sub do_step { 'A::do_step;' } + sub get_value { 'A::get_value' } +} + +my $a = A->new(); +isa_ok $a, 'A'; + +is $a->step(), "Bar::step;Foo::advance;Bar::do_advance;A::do_step;", + 'A virtual resolution'; + +{ + package B; + use base 'director_nested::FooBar_int'; + sub do_advance { my($self) = @_; + return "B::do_advance;" . $self->do_step(); + } + sub do_step { "B::do_step;" } + sub get_value { 1 } +} + +my $b = B->new(); +isa_ok $b, 'B'; +is $b->step(), "Bar::step;Foo::advance;B::do_advance;B::do_step;", + 'B virtual resolution'; + +{ + package C; + use base 'director_nested::FooBar_int'; + our $in_do_advance = 0; + sub do_advance { my($self) = @_; + # found a case where upcall didn't happen right in a perl space + # SUPER:: call. + die "SUPERCALL RESOLVE FAILURE" if $in_do_advance; + local $in_do_advance = 1; + return "C::do_advance;" . + $self->SUPER::do_advance(); + } + sub do_step { "C::do_step;" } + sub get_value { 2 } + sub get_name { my($self) = @_; + return $self->director_nested::FooBar_int::get_name() . " hello"; + } +} + +my $cc = C->new(); +isa_ok $cc, 'C'; +my $c = director_nested::FooBar_int::get_self($cc); +$c->advance(); +is $c->get_name(), "FooBar::get_name hello"; +is $c->name(), "FooBar::get_name hello"; diff --git a/Examples/test-suite/perl5/director_primitives_runme.pl b/Examples/test-suite/perl5/director_primitives_runme.pl new file mode 100644 index 000000000..e70f39166 --- /dev/null +++ b/Examples/test-suite/perl5/director_primitives_runme.pl @@ -0,0 +1,68 @@ +use strict; +use warnings; +use Test::More tests => 27; +BEGIN { use_ok 'director_primitives' } +require_ok 'director_primitives'; + +{ + package PerlDerived; + use base 'director_primitives::Base'; + sub NoParmsMethod { + } + sub BoolMethod { my($self, $x) = @_; + return $x; + } + sub IntMethod { my($self, $x) = @_; + return $x; + } + sub UIntMethod { my($self, $x) = @_; + return $x; + } + sub FloatMethod { my($self, $x) = @_; + return $x; + } + sub CharPtrMethod { my($self, $x) = @_; + return $x; + } + sub ConstCharPtrMethod { my($self, $x) = @_; + return $x; + } + sub EnumMethod { my($self, $x) = @_; + return $x; + } + sub ManyParmsMethod { + } +} + +my $myCaller = director_primitives::Caller->new(); +isa_ok $myCaller, 'director_primitives::Caller'; + +{ + my $myBase = director_primitives::Base->new(100.0); + makeCalls($myCaller, $myBase); +} +{ + my $myBase = director_primitives::Derived->new(200.0); + makeCalls($myCaller, $myBase); +} +{ + my $myBase = PerlDerived->new(300.0); + makeCalls($myCaller, $myBase); +} + +sub makeCalls { my($myCaller, $myBase) = @_; + $myCaller->set($myBase); + $myCaller->NoParmsMethodCall(); + is $myCaller->BoolMethodCall(1), '1'; + is $myCaller->BoolMethodCall(0), ''; + is $myCaller->IntMethodCall(-123), -123; + is $myCaller->UIntMethodCall(123), 123; + is $myCaller->FloatMethodCall(-123 / 128), -0.9609375; + is $myCaller->CharPtrMethodCall("test string"), "test string"; + is $myCaller->ConstCharPtrMethodCall("another string"), "another string"; + is $myCaller->EnumMethodCall($director_primitives::HShadowHard), $director_primitives::HShadowHard; + $myCaller->ManyParmsMethodCall(1, -123, 123, 123.456, "test string", "another string", $director_primitives::HShadowHard); + $myCaller->NotOverriddenMethodCall(); + $myCaller->reset(); +} + diff --git a/Examples/test-suite/perl5/director_protected_runme.pl b/Examples/test-suite/perl5/director_protected_runme.pl new file mode 100644 index 000000000..07ed1563e --- /dev/null +++ b/Examples/test-suite/perl5/director_protected_runme.pl @@ -0,0 +1,48 @@ +use strict; +use warnings; +use Test::More tests => 19; +BEGIN { use_ok 'director_protected' } +require_ok 'director_protected'; + +{ + package FooBar; + use base 'director_protected::Bar'; + sub ping { 'FooBar::ping();' } +} +{ + package FooBar2; + use base 'director_protected::Bar'; + sub ping { 'FooBar2::ping();' } + sub pang { 'FooBar2::pang();' } +} + +my $b = director_protected::Bar->new(); +isa_ok $b, 'director_protected::Bar'; +my $f = $b->create(); +my $fb = FooBar->new(); +isa_ok $fb, 'FooBar'; +my $fb2 = FooBar2->new(); +isa_ok $fb2, 'FooBar2'; + +is $b->used(), "Foo::pang();Bar::pong();Foo::pong();Bar::ping();"; +eval { $f->used() }; +like $@, qr/protected member/; +is $fb->used(), "Foo::pang();Bar::pong();Foo::pong();FooBar::ping();"; +is $fb2->used(), "FooBar2::pang();Bar::pong();Foo::pong();FooBar2::ping();"; + +is $b->pong(), "Bar::pong();Foo::pong();Bar::ping();"; +is $f->pong(), "Bar::pong();Foo::pong();Bar::ping();"; +is $fb->pong(), "Bar::pong();Foo::pong();FooBar::ping();"; +is $fb2->pong(), "Bar::pong();Foo::pong();FooBar2::ping();"; + +eval { $b->ping() }; +like $@, qr/protected member/; +eval { $f->ping () }; +like $@, qr/protected member/; +is $fb->ping(), 'FooBar::ping();'; +is $fb2->ping(), 'FooBar2::ping();'; + +eval { $b->pang() }; +like $@, qr/protected member/; +eval { $f->pang() }; +like $@, qr/protected member/; diff --git a/Examples/test-suite/perl5/director_string_runme.pl b/Examples/test-suite/perl5/director_string_runme.pl new file mode 100644 index 000000000..4d996ef0f --- /dev/null +++ b/Examples/test-suite/perl5/director_string_runme.pl @@ -0,0 +1,34 @@ +use strict; +use warnings; +use Test::More tests => 5; +BEGIN { use_ok 'director_string' } +require_ok 'director_string'; + +{ + package B; + use base 'director_string::A'; + our $in_first = 0; + sub get_first { my($self) = @_; + die "SUPER RESOLVE BAD" if $in_first; + local $in_first = 1; + return $self->SUPER::get_first() . " world!"; + } + our $in_process_text = 0; + sub process_text { my($self, $string) = @_; + die "SUPER RESOLVE BAD" if $in_process_text; + local $in_process_text = 1; + $self->SUPER::process_text($string); + $self->{'smem'} = "hello"; + } +} + +my $b = B->new("hello"); +isa_ok $b, 'B'; + +$b->get(0); + +is $b->get_first(), "hello world!"; + +$b->call_process_func(); + +is $b->{'smem'}, "hello"; diff --git a/Examples/test-suite/perl5/director_unroll_runme.pl b/Examples/test-suite/perl5/director_unroll_runme.pl new file mode 100644 index 000000000..572b99834 --- /dev/null +++ b/Examples/test-suite/perl5/director_unroll_runme.pl @@ -0,0 +1,17 @@ +use strict; +use warnings; +use Test::More tests => 3; +BEGIN { use_ok 'director_unroll' }; +require_ok 'director_unroll'; + +{ + package MyFoo; + use base 'director_unroll::Foo'; + sub ping { "MyFoo::ping()" } +} + +$a = MyFoo->new(); +$b = director_unroll::Bar->new(); +$b->set($a); +my $c = $b->get(); +is(${$a->this}, ${$c->this}, "unrolling"); diff --git a/Examples/test-suite/perl5/director_wombat_runme.pl b/Examples/test-suite/perl5/director_wombat_runme.pl new file mode 100644 index 000000000..81f34e71b --- /dev/null +++ b/Examples/test-suite/perl5/director_wombat_runme.pl @@ -0,0 +1,53 @@ +use strict; +use warnings; +use Test::More tests => 9; +BEGIN { use_ok 'director_wombat' } +require_ok 'director_wombat'; + +{ + package director_wombat_Foo_integers_derived; + use base 'director_wombat::Foo_integers'; + sub meth { my($self, $param) = @_; + return $param + 2; + } +} +{ + package director_wombat_Foo_integers_derived_2; + use base 'director_wombat::Foo_integers'; +} +{ + package director_wombat_Bar_derived_1; + use base 'director_wombat::Bar'; + sub foo_meth_ref { my($self, $foo_obj, $param) = @_; + die "foo_obj in foo_meth_ref is not director_wombat_Foo_integers_derived_2" + unless $foo_obj->isa('director_wombat_Foo_integers_derived_2'); + } + sub foo_meth_ptr { my($self, $foo_obj, $param) = @_; + die "foo_obj in foo_meth_ptr is not director_wombat_Foo_integers_derived_2" + unless $foo_obj->isa('director_wombat_Foo_integers_derived_2'); + } + sub foo_meth_val { my($self, $foo_obj, $param) = @_; + die "foo_obj in foo_meth_val is not director_wombat_Foo_integers_derived_2" + unless $foo_obj->isa('director_wombat_Foo_integers_derived_2'); + } +} + +my $b = director_wombat::Bar->new(); +isa_ok $b, 'director_wombat::Bar'; +my $a = $b->meth(); +is $a->meth(49), 49; + +$a = director_wombat_Foo_integers_derived->new(); +isa_ok $a, 'director_wombat_Foo_integers_derived'; +is $a->meth(62), 62 + 2; + +$a = director_wombat_Foo_integers_derived_2->new(); +isa_ok $a, 'director_wombat_Foo_integers_derived_2'; +is $a->meth(37), 37; + +$b = director_wombat_Bar_derived_1->new(); +isa_ok $b, 'director_wombat_Bar_derived_1'; +$b->foo_meth_ref($a, 0); +$b->foo_meth_ptr($a, 1); +$b->foo_meth_val($a, 2); + diff --git a/Lib/perl5/perlrun.swg b/Lib/perl5/perlrun.swg index ebc4fecd5..4e31c4754 100644 --- a/Lib/perl5/perlrun.swg +++ b/Lib/perl5/perlrun.swg @@ -20,6 +20,7 @@ #define SWIG_ConvertPtr(obj, pp, type, flags) SWIG_Perl_ConvertPtr(SWIG_PERL_OBJECT_CALL obj, pp, type, flags) #define SWIG_ConvertPtrAndOwn(obj, pp, type, flags,own) SWIG_Perl_ConvertPtrAndOwn(SWIG_PERL_OBJECT_CALL obj, pp, type, flags, own) #define SWIG_NewPointerObj(p, type, flags) SWIG_Perl_NewPointerObj(SWIG_PERL_OBJECT_CALL p, type, flags) +#define swig_owntype int /* for raw packed data */ #define SWIG_ConvertPacked(obj, p, s, type) SWIG_Perl_ConvertPacked(SWIG_PERL_OBJECT_CALL obj, p, s, type) @@ -288,7 +289,7 @@ SWIG_Perl_ConvertPtrAndOwn(SWIG_MAYBE_PERL_OBJECT SV *sv, void **ptr, swig_type_ /* Now see if the types match */ char *_c = HvNAME(SvSTASH(SvRV(sv))); tc = SWIG_TypeProxyCheck(_c,_t); - if (!tc) { + if (!tc && !sv_derived_from(sv,SWIG_Perl_TypeProxyName(_t))) { return SWIG_ERROR; } { diff --git a/Lib/perl5/perltypemaps.swg b/Lib/perl5/perltypemaps.swg index fc7100e89..f47a5ef82 100644 --- a/Lib/perl5/perltypemaps.swg +++ b/Lib/perl5/perltypemaps.swg @@ -35,9 +35,9 @@ * Unified typemap section * ------------------------------------------------------------ */ -/* No director supported in Perl */ -#ifdef SWIG_DIRECTOR_TYPEMAPS -#undef SWIG_DIRECTOR_TYPEMAPS +/* director support in Perl is experimental */ +#ifndef SWIG_DIRECTOR_TYPEMAPS +#define SWIG_DIRECTOR_TYPEMAPS #endif diff --git a/Source/Modules/perl5.cxx b/Source/Modules/perl5.cxx index 09500b23b..182835645 100644 --- a/Source/Modules/perl5.cxx +++ b/Source/Modules/perl5.cxx @@ -79,8 +79,11 @@ static String *variable_tab = 0; static File *f_begin = 0; static File *f_runtime = 0; +static File *f_runtime_h = 0; static File *f_header = 0; static File *f_wrappers = 0; +static File *f_directors = 0; +static File *f_directors_h = 0; static File *f_init = 0; static File *f_pm = 0; static String *pm; /* Package initialization code */ @@ -124,6 +127,7 @@ public: Printv(argc_template_string, "items", NIL); Clear(argv_template_string); Printv(argv_template_string, "ST(%d)", NIL); + director_language = 1; } /* Test to see if a type corresponds to something wrapped with a shadow class */ @@ -219,9 +223,68 @@ public: * ------------------------------------------------------------ */ virtual int top(Node *n) { + /* check if directors are enabled for this module. note: this + * is a "master" switch, without which no director code will be + * emitted. %feature("director") statements are also required + * to enable directors for individual classes or methods. + * + * use %module(directors="1") modulename at the start of the + * interface file to enable director generation. + * + * TODO: directors are disallowed in conjunction with many command + * line options. Some of them are probably safe, but it will take + * some effort to validate each one. + */ + { + Node *mod = Getattr(n, "module"); + if (mod) { + Node *options = Getattr(mod, "options"); + if (options) { + int dirprot = 0; + if (Getattr(options, "dirprot")) + dirprot = 1; + if (Getattr(options, "nodirprot")) + dirprot = 0; + if (Getattr(options, "directors")) { + int allow = 1; + if (export_all) { + Printv(stderr, + "*** directors are not supported with -exportall\n", NIL); + allow = 0; + } + if (staticoption) { + Printv(stderr, + "*** directors are not supported with -static\n", NIL); + allow = 0; + } + if (!blessed) { + Printv(stderr, + "*** directors are not supported with -noproxy\n", NIL); + allow = 0; + } + if (no_pmfile) { + Printv(stderr, + "*** directors are not supported with -nopm\n", NIL); + allow = 0; + } + if (compat) { + Printv(stderr, + "*** directors are not supported with -compat\n", NIL); + allow = 0; + } + if (allow) { + allow_directors(); + if (dirprot) + allow_dirprot(); + } + } + } + } + } /* Initialize all of the output files */ String *outfile = Getattr(n, "outfile"); + String *outfile_h = Getattr(n, "outfile_h"); f_begin = NewFile(outfile, "w", SWIG_output_files()); if (!f_begin) { @@ -232,6 +295,16 @@ public: f_init = NewString(""); f_header = NewString(""); f_wrappers = NewString(""); + f_directors_h = NewString(""); + f_directors = NewString(""); + + if (directorsEnabled()) { + f_runtime_h = NewFile(outfile_h, "w", SWIG_output_files()); + if (!f_runtime_h) { + FileErrorDisplay(outfile_h); + SWIG_exit(EXIT_FAILURE); + } + } /* Register file targets with the SWIG file handler */ Swig_register_filebyname("header", f_header); @@ -239,6 +312,8 @@ public: Swig_register_filebyname("begin", f_begin); Swig_register_filebyname("runtime", f_runtime); Swig_register_filebyname("init", f_init); + Swig_register_filebyname("director", f_directors); + Swig_register_filebyname("director_h", f_directors_h); classlist = NewList(); @@ -259,6 +334,9 @@ public: Printf(f_runtime, "\n"); Printf(f_runtime, "#define SWIGPERL\n"); + if (directorsEnabled()) { + Printf(f_runtime, "#define SWIG_DIRECTORS\n"); + } Printf(f_runtime, "#define SWIG_CASTRANK_MODE\n"); Printf(f_runtime, "\n"); @@ -269,6 +347,27 @@ public: Node *options = Getattr(mod, "options"); module = Copy(Getattr(n,"name")); + if (directorsEnabled()) { + Swig_banner(f_directors_h); + Printf(f_directors_h, "\n"); + Printf(f_directors_h, "#ifndef SWIG_%s_WRAP_H_\n", module); + Printf(f_directors_h, "#define SWIG_%s_WRAP_H_\n\n", module); + if (dirprot_mode()) { + Printf(f_directors_h, "#include \n"); + Printf(f_directors_h, "#include \n\n"); + } + + Printf(f_directors, "\n\n"); + Printf(f_directors, "/* ---------------------------------------------------\n"); + Printf(f_directors, " * C++ director class methods\n"); + Printf(f_directors, " * --------------------------------------------------- */\n\n"); + if (outfile_h) { + String *filename = Swig_file_filename(outfile_h); + Printf(magic, "#include \"%s\"\n\n", filename); + Delete(filename); + } + } + if (verbose > 0) { fprintf(stdout, "top: using module: %s\n", Char(module)); } @@ -374,6 +473,11 @@ public: /* emit wrappers */ Language::top(n); + if (directorsEnabled()) { + // Insert director runtime into the f_runtime file (make it occur before %header section) + Swig_insert_file("director.swg", f_runtime); + } + String *base = NewString(""); /* Dump out variable wrappers */ @@ -526,11 +630,21 @@ public: /* Close all of the files */ Dump(f_runtime, f_begin); Dump(f_header, f_begin); + + if (directorsEnabled()) { + Dump(f_directors_h, f_runtime_h); + Printf(f_runtime_h, "\n"); + Printf(f_runtime_h, "#endif\n"); + Dump(f_directors, 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_directors); + Delete(f_directors_h); Delete(f_runtime); Delete(f_begin); return SWIG_OK; @@ -560,6 +674,7 @@ public: SwigType *d = Getattr(n, "type"); ParmList *l = Getattr(n, "parms"); String *overname = 0; + int director_method = 0; Parm *p; int i; @@ -720,11 +835,36 @@ public: Wrapper_add_localv(f, "_saved", "SV *", temp, NIL); } + director_method = is_member_director(n) && !is_smart_pointer() && 0 != Cmp(nodeType(n), "destructor"); + if (director_method) { + Wrapper_add_local(f, "director", "Swig::Director *director = 0"); + Append(f->code, "director = SWIG_DIRECTOR_CAST(arg1);\n"); + if (dirprot_mode() && !is_public(n)) { + Printf(f->code, "if (!director || !(director->swig_get_inner(\"%s\"))) {\n", name); + Printf(f->code, "SWIG_exception_fail(SWIG_RuntimeError, \"accessing protected member %s\");\n", name); + Append(f->code, "}\n"); + } + Wrapper_add_local(f, "upcall", "bool upcall = false"); + Printf(f->code, "upcall = director && SvSTASH(SvRV(ST(0))) == gv_stashpv(director->swig_get_class(), 0);\n"); + } + + /* Emit the function call */ + if (director_method) { + Append(f->code, "try {\n"); + } + /* Now write code to make the function call */ Swig_director_emit_dynamic_cast(n, f); String *actioncode = emit_action(n); + if (director_method) { + Append(actioncode, "} catch (Swig::DirectorException& swig_err) {\n"); + Append(actioncode, " sv_setsv(ERRSV, swig_err.getNative());\n"); + Append(actioncode, " SWIG_fail;\n"); + Append(actioncode, "}\n"); + } + if ((tm = Swig_typemap_lookup_out("out", n, Swig_cresult_name(), f, actioncode))) { SwigType *t = Getattr(n, "type"); Replaceall(tm, "$source", Swig_cresult_name()); @@ -1335,17 +1475,67 @@ public: /* Output methods for managing ownership */ + String *director_disown; + if (Getattr(n, "perl5:directordisown")) { + director_disown = NewStringf("%s%s($self);\n", + tab4, Getattr(n, "perl5:directordisown")); + } else { + director_disown = NewString(""); + } Printv(pm, "sub DISOWN {\n", tab4, "my $self = shift;\n", + director_disown, tab4, "my $ptr = tied(%$self);\n", tab4, "delete $OWNER{$ptr};\n", "}\n\n", "sub ACQUIRE {\n", tab4, "my $self = shift;\n", tab4, "my $ptr = tied(%$self);\n", tab4, "$OWNER{$ptr} = 1;\n", "}\n\n", NIL); + Delete(director_disown); /* Only output the following methods if a class has member data */ Delete(operators); operators = 0; + if (Swig_directorclass(n)) { + /* director classes need a way to recover subclass instance attributes */ + Node *get_attr = NewHash(); + String *mrename; + String *symname = Getattr(n, "sym:name"); + mrename = Swig_name_disown(NSPACE_TODO, symname); + Replaceall(mrename, "disown", "swig_get_attr"); + String *type = NewString(getClassType()); + String *name = NewString("self"); + SwigType_add_pointer(type); + Parm *p = NewParm(type, name, n); + Delete(name); + Delete(type); + type = NewString("SV"); + SwigType_add_pointer(type); + String *action = NewString(""); + Printv(action, "{\n", " Swig::Director *director = SWIG_DIRECTOR_CAST(arg1);\n", " result = sv_newmortal();\n" " if (director) sv_setsv(result, director->swig_get_self());\n", "}\n", NIL); + Setfile(get_attr, Getfile(n)); + Setline(get_attr, Getline(n)); + Setattr(get_attr, "wrap:action", action); + Setattr(get_attr, "name", mrename); + Setattr(get_attr, "sym:name", mrename); + Setattr(get_attr, "type", type); + Setattr(get_attr, "parms", p); + Delete(action); + Delete(type); + Delete(p); + + member_func = 1; + functionWrapper(get_attr); + member_func = 0; + Delete(get_attr); + + Printv(pm, "sub FETCH {\n", tab4, "my ($self,$field) = @_;\n", tab4, "my $member_func = \"swig_${field}_get\";\n", tab4, + "if (not $self->can(\"$member_func\")) {\n", tab4, tab4, "my $h = ", cmodule, "::", mrename, "($self);\n", tab4, tab4, + "return $h->{$field} if $h;\n", tab4, "}\n", tab4, "return $self->$member_func;\n", "}\n", "\n", "sub STORE {\n", tab4, + "my ($self,$field,$newval) = @_;\n", tab4, "my $member_func = \"swig_${field}_set\";\n", tab4, + "if (not $self->can(\"$member_func\")) {\n", tab4, tab4, "my $h = ", cmodule, "::", mrename, "($self);\n", tab4, tab4, + "return $h->{$field} = $newval if $h;\n", tab4, "}\n", tab4, "return $self->$member_func($newval);\n", "}\n", NIL); + Delete(mrename); + } } return SWIG_OK; } @@ -1494,7 +1684,41 @@ public: String *symname = Getattr(n, "sym:name"); member_func = 1; + + Swig_save("perl5:constructorHandler", n, "parms", NIL); + if (Swig_directorclass(n)) { + Parm *parms = Getattr(n, "parms"); + Parm *self; + String *name = NewString("self"); + String *type = NewString("SV"); + SwigType_add_pointer(type); + self = NewParm(type, name, n); + Delete(type); + Delete(name); + Setattr(self, "lname", "O"); + if (parms) + set_nextSibling(self, parms); + Setattr(n, "parms", self); + Setattr(n, "wrap:self", "1"); + Setattr(n, "hidden", "1"); + Delete(self); + } + + String *saved_nc = none_comparison; + none_comparison = NewStringf("strcmp(SvPV_nolen(ST(0)), \"%s::%s\") != 0", module, class_name); + String *saved_director_prot_ctor_code = director_prot_ctor_code; + director_prot_ctor_code = NewStringf( + "if ($comparison) { /* subclassed */\n" + " $director_new\n" + "} else {\n" + " SWIG_exception_fail(SWIG_RuntimeError, \"accessing abstract class or protected constructor\");\n" + "}\n"); Language::constructorHandler(n); + Delete(none_comparison); + none_comparison = saved_nc; + Delete(director_prot_ctor_code); + director_prot_ctor_code = saved_director_prot_ctor_code; + Swig_restore(n); if ((blessed) && (!Getattr(n, "sym:nextSibling"))) { if (Getattr(n, "feature:shadow")) { @@ -1512,8 +1736,9 @@ public: Printv(pcode, "sub ", Swig_name_construct(NSPACE_TODO, symname), " {\n", NIL); } + const char *pkg = getCurrentClass() && Swig_directorclass(getCurrentClass()) ? "$_[0]" : "shift"; Printv(pcode, - tab4, "my $pkg = shift;\n", + tab4, "my $pkg = ", pkg, ";\n", tab4, "my $self = ", cmodule, "::", Swig_name_construct(NSPACE_TODO, symname), "(@_);\n", tab4, "bless $self, $pkg if defined($self);\n", "}\n\n", NIL); have_constructor = 1; @@ -1752,6 +1977,591 @@ public: String *defaultExternalRuntimeFilename() { return NewString("swigperlrun.h"); } + + virtual int classDirectorInit(Node *n) { + String *declaration = Swig_director_declaration(n); + Printf(f_directors_h, "\n"); + Printf(f_directors_h, "%s\n", declaration); + Printf(f_directors_h, "public:\n"); + Delete(declaration); + return Language::classDirectorInit(n); + } + + virtual int classDirectorEnd(Node *n) { + if (dirprot_mode()) { + /* + This implementation uses a std::map. + + It should be possible to rewrite it using a more elegant way, + like copying the Java approach for the 'override' array. + + But for now, this seems to be the least intrusive way. + */ + Printf(f_directors_h, "\n\n"); + Printf(f_directors_h, "/* Internal Director utilities */\n"); + Printf(f_directors_h, "public:\n"); + Printf(f_directors_h, " bool swig_get_inner(const char* swig_protected_method_name) const {\n"); + Printf(f_directors_h, " std::map::const_iterator iv = swig_inner.find(swig_protected_method_name);\n"); + Printf(f_directors_h, " return (iv != swig_inner.end() ? iv->second : false);\n"); + Printf(f_directors_h, " }\n\n"); + + Printf(f_directors_h, " void swig_set_inner(const char* swig_protected_method_name, bool val) const\n"); + Printf(f_directors_h, " { swig_inner[swig_protected_method_name] = val;}\n\n"); + Printf(f_directors_h, "private:\n"); + Printf(f_directors_h, " mutable std::map swig_inner;\n"); + } + Printf(f_directors_h, "};\n"); + return Language::classDirectorEnd(n); + } + + virtual int classDirectorConstructor(Node *n) { + Node *parent = Getattr(n, "parentNode"); + String *sub = NewString(""); + String *decl = Getattr(n, "decl"); + String *supername = Swig_class_name(parent); + String *classname = NewString(""); + Printf(classname, "SwigDirector_%s", supername); + + /* insert self parameter */ + Parm *p; + ParmList *superparms = Getattr(n, "parms"); + ParmList *parms = CopyParmList(superparms); + String *type = NewString("SV"); + SwigType_add_pointer(type); + p = NewParm(type, NewString("self"), n); + set_nextSibling(p, parms); + parms = p; + + if (!Getattr(n, "defaultargs")) { + /* constructor */ + { + Wrapper *w = NewWrapper(); + String *call; + String *basetype = Getattr(parent, "classtype"); + String *target = Swig_method_decl(0, decl, classname, parms, 0, 0); + call = Swig_csuperclass_call(0, basetype, superparms); + Printf(w->def, "%s::%s: %s, Swig::Director(self) { \n", classname, target, call); + Printf(w->def, " SWIG_DIRECTOR_RGTR((%s *)this, this); \n", basetype); + Append(w->def, "}\n"); + Delete(target); + Wrapper_print(w, f_directors); + Delete(call); + DelWrapper(w); + } + + /* constructor header */ + { + String *target = Swig_method_decl(0, decl, classname, parms, 0, 1); + Printf(f_directors_h, " %s;\n", target); + Delete(target); + } + } + + Delete(sub); + Delete(classname); + Delete(supername); + Delete(parms); + return Language::classDirectorConstructor(n); + } + + virtual int classDirectorMethod(Node *n, Node *parent, String *super) { + int is_void = 0; + int is_pointer = 0; + String *decl = Getattr(n, "decl"); + String *name = Getattr(n, "name"); + String *classname = Getattr(parent, "sym:name"); + String *c_classname = Getattr(parent, "name"); + String *symname = Getattr(n, "sym:name"); + String *declaration = NewString(""); + ParmList *l = Getattr(n, "parms"); + Wrapper *w = NewWrapper(); + String *tm; + String *wrap_args = NewString(""); + String *returntype = Getattr(n, "type"); + String *value = Getattr(n, "value"); + String *storage = Getattr(n, "storage"); + bool pure_virtual = false; + int status = SWIG_OK; + int idx; + bool ignored_method = GetFlag(n, "feature:ignore") ? true : false; + int addfail = 0; + + if (Cmp(storage, "virtual") == 0) { + if (Cmp(value, "0") == 0) { + pure_virtual = true; + } + } + + /* determine if the method returns a pointer */ + is_pointer = SwigType_ispointer_return(decl); + is_void = (!Cmp(returntype, "void") && !is_pointer); + + /* virtual method definition */ + String *target; + String *pclassname = NewStringf("SwigDirector_%s", classname); + String *qualified_name = NewStringf("%s::%s", pclassname, name); + SwigType *rtype = Getattr(n, "conversion_operator") ? 0 : Getattr(n, "classDirectorMethods:type"); + target = Swig_method_decl(rtype, decl, qualified_name, l, 0, 0); + Printf(w->def, "%s", target); + Delete(qualified_name); + Delete(target); + /* header declaration */ + target = Swig_method_decl(rtype, decl, name, l, 0, 1); + Printf(declaration, " virtual %s", target); + Delete(target); + + // Get any exception classes in the throws typemap + ParmList *throw_parm_list = 0; + + if ((throw_parm_list = Getattr(n, "throws")) || Getattr(n, "throw")) { + Parm *p; + int gencomma = 0; + + Append(w->def, " throw("); + Append(declaration, " throw("); + + if (throw_parm_list) + Swig_typemap_attach_parms("throws", throw_parm_list, 0); + for (p = throw_parm_list; p; p = nextSibling(p)) { + if (Getattr(p, "tmap:throws")) { + if (gencomma++) { + Append(w->def, ", "); + Append(declaration, ", "); + } + String *str = SwigType_str(Getattr(p, "type"), 0); + Append(w->def, str); + Append(declaration, str); + Delete(str); + } + } + + Append(w->def, ")"); + Append(declaration, ")"); + } + + Append(w->def, " {"); + Append(declaration, ";\n"); + + /* 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). + */ + if (!is_void) { + if (!(ignored_method && !pure_virtual)) { + String *cres = SwigType_lstr(returntype, "c_result"); + Printf(w->code, "%s;\n", cres); + Delete(cres); + String *pres = NewStringf("SV *%s", Swig_cresult_name()); + Wrapper_add_local(w, Swig_cresult_name(), pres); + Delete(pres); + } + } + + //if (builtin) { + // Printv(w->code, "PyObject *self = NULL;\n", NIL); + // Printv(w->code, "(void)self;\n", NIL); + //} + + if (ignored_method) { + if (!pure_virtual) { + if (!is_void) + Printf(w->code, "return "); + String *super_call = Swig_method_call(super, l); + Printf(w->code, "%s;\n", super_call); + 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)); + } + } else { + /* attach typemaps to arguments (C/C++ -> Perl) */ + String *arglist = NewString(""); + String *parse_args = NewString(""); + String *pstack = NewString(""); + + Swig_director_parms_fixup(l); + + /* remove the wrapper 'w' since it was producing spurious temps */ + Swig_typemap_attach_parms("in", l, 0); + Swig_typemap_attach_parms("directorin", l, 0); + Swig_typemap_attach_parms("directorargout", l, w); + + Wrapper_add_local(w, "SP", "dSP"); + + { + String *ptype = Copy(getClassType()); + SwigType_add_pointer(ptype); + String *mangle = SwigType_manglestr(ptype); + + Wrapper_add_local(w, "self", "SV *self"); + Printf(w->code, "self = SWIG_NewPointerObj(SWIG_as_voidptr(this), SWIGTYPE%s, SWIG_SHADOW);\n", mangle); + Printf(w->code, "sv_bless(self, gv_stashpv(swig_get_class(), 0));\n"); + Delete(mangle); + Delete(ptype); + Append(pstack, "XPUSHs(self);\n"); + } + + Parm *p; + char source[256]; + + int outputs = 0; + if (!is_void) + outputs++; + + /* build argument list and type conversion string */ + idx = 0; + p = l; + int use_parse = 0; + while (p) { + if (checkAttribute(p, "tmap:in:numinputs", "0")) { + p = Getattr(p, "tmap:in:next"); + continue; + } + + /* old style? caused segfaults without the p!=0 check + in the for() condition, and seems dangerous in the + while loop as well. + while (Getattr(p, "tmap:ignore")) { + p = Getattr(p, "tmap:ignore:next"); + } + */ + + if (Getattr(p, "tmap:directorargout") != 0) + outputs++; + + String *pname = Getattr(p, "name"); + String *ptype = Getattr(p, "type"); + + Putc(',', arglist); + if ((tm = Getattr(p, "tmap:directorin")) != 0) { + String *parse = Getattr(p, "tmap:directorin:parse"); + if (!parse) { + sprintf(source, "obj%d", idx++); + String *input = NewString(source); + Setattr(p, "emit:directorinput", input); + Replaceall(tm, "$input", input); + Delete(input); + Replaceall(tm, "$owner", "0"); + Replaceall(tm, "$shadow", "0"); + /* Wrapper_add_localv(w, source, "SV *", source, "= 0", NIL); */ + Printv(wrap_args, "SV *", source, ";\n", NIL); + + Printv(wrap_args, tm, "\n", NIL); + Printv(arglist, "(PyObject *)", source, NIL); + Putc('O', parse_args); + Printv(pstack, "XPUSHs(", source, ");\n", NIL); + } else { + use_parse = 1; + Append(parse_args, parse); + Setattr(p, "emit:directorinput", pname); + Replaceall(tm, "$input", pname); + Replaceall(tm, "$owner", "0"); + Replaceall(tm, "$shadow", "0"); + if (Len(tm) == 0) + Append(tm, pname); + Append(arglist, tm); + } + p = Getattr(p, "tmap:directorin:next"); + continue; + } else if (Cmp(ptype, "void")) { + /* special handling for pointers to other C++ director classes. + * ideally this would be left to a typemap, but there is currently no + * way to selectively apply the dynamic_cast<> to classes that have + * directors. in other words, the type "SwigDirector_$1_lname" only exists + * for classes with directors. we avoid the problem here by checking + * module.wrap::directormap, but it's not clear how to get a typemap to + * do something similar. perhaps a new default typemap (in addition + * to SWIGTYPE) called DIRECTORTYPE? + */ + if (SwigType_ispointer(ptype) || SwigType_isreference(ptype)) { + Node *module = Getattr(parent, "module"); + Node *target = Swig_directormap(module, ptype); + sprintf(source, "obj%d", idx++); + String *nonconst = 0; + /* strip pointer/reference --- should move to Swig/stype.c */ + String *nptype = NewString(Char(ptype) + 2); + /* name as pointer */ + String *ppname = Copy(pname); + if (SwigType_isreference(ptype)) { + Insert(ppname, 0, "&"); + } + /* if necessary, cast away const since Python doesn't support it! */ + if (SwigType_isconst(nptype)) { + nonconst = NewStringf("nc_tmp_%s", pname); + String *nonconst_i = NewStringf("= const_cast< %s >(%s)", SwigType_lstr(ptype, 0), ppname); + Wrapper_add_localv(w, nonconst, SwigType_lstr(ptype, 0), nonconst, nonconst_i, NIL); + Delete(nonconst_i); + Swig_warning(WARN_LANG_DISCARD_CONST, input_file, line_number, + "Target language argument '%s' discards const in director method %s::%s.\n", + SwigType_str(ptype, pname), SwigType_namestr(c_classname), SwigType_namestr(name)); + } else { + nonconst = Copy(ppname); + } + Delete(nptype); + Delete(ppname); + String *mangle = SwigType_manglestr(ptype); + if (target) { + String *director = NewStringf("director_%s", mangle); + Wrapper_add_localv(w, director, "Swig::Director *", director, "= 0", NIL); + Wrapper_add_localv(w, source, "swig::SwigVar_PyObject", source, "= 0", NIL); + Printf(wrap_args, "%s = SWIG_DIRECTOR_CAST(%s);\n", director, nonconst); + Printf(wrap_args, "if (!%s) {\n", director); + Printf(wrap_args, "%s = SWIG_InternalNewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle); + Append(wrap_args, "} else {\n"); + Printf(wrap_args, "%s = %s->swig_get_self();\n", source, director); + Printf(wrap_args, "Py_INCREF((PyObject *)%s);\n", source); + Append(wrap_args, "}\n"); + Delete(director); + Printv(arglist, source, NIL); + } else { + Wrapper_add_localv(w, source, "SV *", source, "= 0", NIL); + Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle); + Printf(pstack, "XPUSHs(sv_2mortal(%s));\n", source); + //Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE_p_%s, 0);\n", + // source, nonconst, base); + Printv(arglist, source, NIL); + } + Putc('O', parse_args); + Delete(mangle); + Delete(nonconst); + } else { + Swig_warning(WARN_TYPEMAP_DIRECTORIN_UNDEF, input_file, line_number, + "Unable to use type %s as a function argument in director method %s::%s (skipping method).\n", SwigType_str(ptype, 0), + SwigType_namestr(c_classname), SwigType_namestr(name)); + status = SWIG_NOWRAP; + break; + } + } + p = nextSibling(p); + } + + /* add the method name as a PyString */ + String *pyname = Getattr(n, "sym:name"); + + //int allow_thread = threads_enable(n); + // + //if (allow_thread) { + // thread_begin_block(n, w->code); + // Append(w->code, "{\n"); + //} + + /* wrap complex arguments to PyObjects */ + Printv(w->code, wrap_args, NIL); + + /* pass the method call on to the Python object */ + if (dirprot_mode() && !is_public(n)) { + Printf(w->code, "swig_set_inner(\"%s\", true);\n", name); + } + + Append(w->code, "ENTER;\n"); + Append(w->code, "SAVETMPS;\n"); + Append(w->code, "PUSHMARK(SP);\n"); + Append(w->code, pstack); + Delete(pstack); + Append(w->code, "PUTBACK;\n"); + Printf(w->code, "call_method(\"%s\", G_EVAL | G_SCALAR);\n", pyname); + + if (dirprot_mode() && !is_public(n)) + Printf(w->code, "swig_set_inner(\"%s\", false);\n", name); + + /* 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, "if (SvTRUE(ERRSV)) {\n"); + Append(w->code, " PUTBACK;\n FREETMPS;\n LEAVE;\n"); + if ((tm) && Len(tm) && (Strcmp(tm, "1") != 0)) { + Replaceall(tm, "$error", "error"); + Printv(w->code, Str(tm), "\n", NIL); + } else { + Printf(w->code, " Swig::DirectorMethodException::raise(ERRSV);\n", classname, pyname); + } + Append(w->code, "}\n"); + Delete(tm); + + /* + * Python method may return a simple object, or a tuple. + * for in/out aruments, we have to extract the appropriate PyObjects from the tuple, + * then marshal everything back to C/C++ (return value and output arguments). + * + */ + + /* marshal return value and other outputs (if any) from PyObject to C/C++ type */ + + String *cleanup = NewString(""); + String *outarg = NewString(""); + + if (outputs > 1) { + Wrapper_add_local(w, "output", "PyObject *output"); + Printf(w->code, "if (!PyTuple_Check(%s)) {\n", Swig_cresult_name()); + Printf(w->code, " Swig::DirectorTypeMismatchException::raise(\"Python method %s.%sfailed to return a tuple.\");\n", classname, pyname); + Append(w->code, "}\n"); + } + + idx = 0; + + /* marshal return value */ + if (!is_void) { + Append(w->code, "SPAGAIN;\n"); + Printf(w->code, "%s = POPs;\n", Swig_cresult_name()); + tm = Swig_typemap_lookup("directorout", n, Swig_cresult_name(), w); + if (tm != 0) { + if (outputs > 1) { + Printf(w->code, "output = PyTuple_GetItem(%s, %d);\n", Swig_cresult_name(), idx++); + Replaceall(tm, "$input", "output"); + } else { + Replaceall(tm, "$input", Swig_cresult_name()); + } + char temp[24]; + sprintf(temp, "%d", idx); + Replaceall(tm, "$argnum", temp); + + /* TODO check this */ + if (Getattr(n, "wrap:disown")) { + Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); + } else { + Replaceall(tm, "$disown", "0"); + } + //if (Getattr(n, "tmap:directorout:implicitconv")) { + // Replaceall(tm, "$implicitconv", get_implicitconv_flag(n)); + //} + Replaceall(tm, "$result", "c_result"); + Printv(w->code, tm, "\n", NIL); + Delete(tm); + } else { + Swig_print_node(n); + 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)); + status = SWIG_ERROR; + } + } + + /* marshal outputs */ + for (p = l; p;) { + if ((tm = Getattr(p, "tmap:directorargout")) != 0) { + if (outputs > 1) { + Printf(w->code, "output = PyTuple_GetItem(%s, %d);\n", Swig_cresult_name(), idx++); + Replaceall(tm, "$result", "output"); + } else { + Replaceall(tm, "$result", Swig_cresult_name()); + } + Replaceall(tm, "$input", Getattr(p, "emit:directorinput")); + Printv(w->code, tm, "\n", NIL); + p = Getattr(p, "tmap:directorargout:next"); + } else { + p = nextSibling(p); + } + } + + /* any existing helper functions to handle this? */ + //if (allow_thread) { + // Append(w->code, "}\n"); + // thread_end_block(n, w->code); + //} + + Delete(parse_args); + Delete(arglist); + Delete(cleanup); + Delete(outarg); + } + + if (!ignored_method) { + Append(w->code, "PUTBACK;\n"); + Append(w->code, "FREETMPS;\n"); + Append(w->code, "LEAVE;\n"); + } + + if (!is_void) { + if (!(ignored_method && !pure_virtual)) { + String *rettype = SwigType_str(returntype, 0); + if (!SwigType_isreference(returntype)) { + Printf(w->code, "return (%s) c_result;\n", rettype); + } else { + Printf(w->code, "return (%s) *c_result;\n", rettype); + } + Delete(rettype); + } + } + + if (addfail) { + Append(w->code, "fail:\n"); + Printf(w->code, " Swig::DirectorMethodException::raise(\"Error detected when calling '%s->%s'\");\n", classname, Getattr(n, "sym:name")); + } + + Append(w->code, "}\n"); + + // We expose protected methods via an extra public inline method which makes a straight call to the wrapped class' method + String *inline_extra_method = NewString(""); + if (dirprot_mode() && !is_public(n) && !pure_virtual) { + Printv(inline_extra_method, declaration, NIL); + String *extra_method_name = NewStringf("%sSwigPublic", name); + Replaceall(inline_extra_method, name, extra_method_name); + Replaceall(inline_extra_method, ";\n", " {\n "); + if (!is_void) + Printf(inline_extra_method, "return "); + String *methodcall = Swig_method_call(super, l); + Printv(inline_extra_method, methodcall, ";\n }\n", NIL); + Delete(methodcall); + Delete(extra_method_name); + } + + /* emit the director method */ + if (status == SWIG_OK) { + if (!Getattr(n, "defaultargs")) { + Replaceall(w->code, "$symname", symname); + Wrapper_print(w, f_directors); + Printv(f_directors_h, declaration, NIL); + Printv(f_directors_h, inline_extra_method, NIL); + } + } + + /* clean up */ + Delete(wrap_args); + Delete(pclassname); + DelWrapper(w); + return status; + } + int classDirectorDisown(Node *n) { + int rv; + member_func = 1; + rv = Language::classDirectorDisown(n); + member_func = 0; + if(rv == SWIG_OK && Swig_directorclass(n)) { + String *symname = Getattr(n, "sym:name"); + String *disown = Swig_name_disown(NSPACE_TODO, symname); + Setattr(n, "perl5:directordisown", NewStringf("%s::%s", cmodule, disown)); + } + return rv; + } + int classDirectorDestructor(Node *n) { + /* TODO: it would be nice if this didn't have to copy the body of Language::classDirectorDestructor() */ + String *DirectorClassName = directorClassName(getCurrentClass()); + String *body = NewString("\n"); + + String *ptype = Copy(getClassType()); + SwigType_add_pointer(ptype); + String *mangle = SwigType_manglestr(ptype); + + Printv(body, tab4, "dSP;\n", tab4, "SV *self = SWIG_NewPointerObj(SWIG_as_voidptr(this), SWIGTYPE", mangle, ", SWIG_SHADOW);\n", tab4, "\n", tab4, + "sv_bless(self, gv_stashpv(swig_get_class(), 0));\n", tab4, "ENTER;\n", tab4, "SAVETMPS;\n", tab4, "PUSHMARK(SP);\n", tab4, "XPUSHs(self);\n", + tab4, "PUTBACK;\n", tab4, "call_method(\"DIRECTOR_DESTROY\", G_EVAL | G_VOID);\n", tab4, "FREETMPS;\n", tab4, "LEAVE;\n", NIL); + + Delete(mangle); + Delete(ptype); + + if (Getattr(n, "throw")) { + Printf(f_directors_h, " virtual ~%s() throw ();\n", DirectorClassName); + Printf(f_directors, "%s::~%s() throw () {%s}\n\n", DirectorClassName, DirectorClassName, body); + } else { + Printf(f_directors_h, " virtual ~%s();\n", DirectorClassName); + Printf(f_directors, "%s::~%s() {%s}\n\n", DirectorClassName, DirectorClassName, body); + } + return SWIG_OK; + } }; /* ----------------------------------------------------------------------------- From 34c374d7ae201a2a9902f721e4e31a2ad785b557 Mon Sep 17 00:00:00 2001 From: Robert Stone Date: Tue, 12 Nov 2013 12:48:21 -0800 Subject: [PATCH 190/481] don't forget the most important part --- Lib/perl5/director.swg | 479 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 479 insertions(+) create mode 100644 Lib/perl5/director.swg diff --git a/Lib/perl5/director.swg b/Lib/perl5/director.swg new file mode 100644 index 000000000..937b727a4 --- /dev/null +++ b/Lib/perl5/director.swg @@ -0,0 +1,479 @@ +/* ----------------------------------------------------------------------------- + * director.swg + * + * This file contains support for director classes that proxy + * method calls from C++ to Python extensions. + * ----------------------------------------------------------------------------- */ + +#ifndef SWIG_DIRECTOR_PERL_HEADER_ +#define SWIG_DIRECTOR_PERL_HEADER_ + +#ifdef __cplusplus + +#include +#include +#include +#include +#include + + +/* + Use -DSWIG_PYTHON_DIRECTOR_NO_VTABLE if you don't want to generate a 'virtual + table', and avoid multiple GetAttr calls to retrieve the python + methods. +*/ + +#ifndef SWIG_PERL_DIRECTOR_NO_VTABLE +#ifndef SWIG_PERL_DIRECTOR_VTABLE +#define SWIG_PERL_DIRECTOR_VTABLE +#endif +#endif + + + +/* + Use -DSWIG_DIRECTOR_NO_UEH if you prefer to avoid the use of the + Undefined Exception Handler provided by swig. +*/ +#ifndef SWIG_DIRECTOR_NO_UEH +#ifndef SWIG_DIRECTOR_UEH +#define SWIG_DIRECTOR_UEH +#endif +#endif + + +/* + Use -DSWIG_DIRECTOR_STATIC if you prefer to avoid the use of the + 'Swig' namespace. This could be useful for multi-modules projects. +*/ +#ifdef SWIG_DIRECTOR_STATIC +/* Force anonymous (static) namespace */ +#define Swig +#endif + + +/* + Use -DSWIG_DIRECTOR_NORTTI if you prefer to avoid the use of the + native C++ RTTI and dynamic_cast<>. But be aware that directors + could stop working when using this option. +*/ +#ifdef SWIG_DIRECTOR_NORTTI +/* + When we don't use the native C++ RTTI, we implement a minimal one + only for Directors. +*/ +# ifndef SWIG_DIRECTOR_RTDIR +# define SWIG_DIRECTOR_RTDIR +#include + +namespace Swig { + class Director; + SWIGINTERN std::map& get_rtdir_map() { + static std::map rtdir_map; + return rtdir_map; + } + + SWIGINTERNINLINE void set_rtdir(void *vptr, Director *rtdir) { + get_rtdir_map()[vptr] = rtdir; + } + + SWIGINTERNINLINE Director *get_rtdir(void *vptr) { + std::map::const_iterator pos = get_rtdir_map().find(vptr); + Director *rtdir = (pos != get_rtdir_map().end()) ? pos->second : 0; + return rtdir; + } +} +# endif /* SWIG_DIRECTOR_RTDIR */ + +# define SWIG_DIRECTOR_CAST(ARG) Swig::get_rtdir(static_cast(ARG)) +# define SWIG_DIRECTOR_RGTR(ARG1, ARG2) Swig::set_rtdir(static_cast(ARG1), ARG2) + +#else + +# define SWIG_DIRECTOR_CAST(ARG) dynamic_cast(ARG) +# define SWIG_DIRECTOR_RGTR(ARG1, ARG2) + +#endif /* SWIG_DIRECTOR_NORTTI */ + +extern "C" { + struct swig_type_info; +} + +namespace Swig { + + /* memory handler */ + struct GCItem + { + virtual ~GCItem() {} + + virtual int get_own() const + { + return 0; + } + }; + + struct GCItem_var + { + GCItem_var(GCItem *item = 0) : _item(item) + { + } + + GCItem_var& operator=(GCItem *item) + { + GCItem *tmp = _item; + _item = item; + delete tmp; + return *this; + } + + ~GCItem_var() + { + delete _item; + } + + GCItem * operator->() const + { + return _item; + } + + private: + GCItem *_item; + }; + + struct GCItem_Object : GCItem + { + GCItem_Object(int own) : _own(own) + { + } + + virtual ~GCItem_Object() + { + } + + int get_own() const + { + return _own; + } + + private: + int _own; + }; + + template + struct GCItem_T : GCItem + { + GCItem_T(Type *ptr) : _ptr(ptr) + { + } + + virtual ~GCItem_T() + { + delete _ptr; + } + + private: + Type *_ptr; + }; + + template + struct GCArray_T : GCItem + { + GCArray_T(Type *ptr) : _ptr(ptr) + { + } + + virtual ~GCArray_T() + { + delete[] _ptr; + } + + private: + Type *_ptr; + }; + + /* base class for director exceptions */ + class DirectorException { + public: + virtual const char *getMessage() const = 0; + virtual SV *getNative() const = 0; + }; + /* exceptions emitted by Perl */ + class DirectorMethodException : public Swig::DirectorException { + protected: + SV *err; + public: + DirectorMethodException(SV *sv) + : err(sv) + { + SvREFCNT_inc(err); + } + ~DirectorMethodException() + { + SvREFCNT_dec(err); + } + const char *getMessage() const + { + return SvPV_nolen(err); + } + SV *getNative() const + { + return sv_2mortal(newSVsv(err)); + } + static void raise(SV *sv) + { + throw DirectorMethodException(sv); + } + }; + /* exceptions emitted by wrap code */ + class DirectorWrapException : public Swig::DirectorException { + protected: + std::string msg; + DirectorWrapException(const char *str) + : msg(str) + { + } + public: + virtual const char *getMessage() const + { + return msg.c_str(); + } + virtual SV *getNative() const { + return sv_2mortal(newSVpvn(msg.data(), msg.size())); + } + }; + class DirectorTypeMismatchException : public Swig::DirectorWrapException { + public: + DirectorTypeMismatchException(const char *str) + : DirectorWrapException(str) + { + } + static void raise(const char *type, const char *msg) + { + std::string err = std::string(type); + err += ": "; + err += msg; + throw DirectorTypeMismatchException(err.c_str()); + } + }; + class DirectorPureVirtualException : public Swig::DirectorWrapException { + public: + DirectorPureVirtualException(const char *name) + : DirectorWrapException("SWIG director pure virtual method called: ") + { + msg += name; + } + static void raise(const char *name) + { + throw DirectorPureVirtualException(name); + } + }; +// /* unknown exception handler */ +// class UnknownExceptionHandler +// { +//#ifdef SWIG_DIRECTOR_UEH +// static void handler() { +// try { +// throw; +// } catch (DirectorException& e) { +// std::cerr << "SWIG Director exception caught:" << std::endl +// << e.getMessage() << std::endl; +// } catch (std::exception& e) { +// std::cerr << "std::exception caught: "<< e.what() << std::endl; +// } catch (...) { +// std::cerr << "Unknown exception caught." << std::endl; +// } +// +// //std::cerr << std::endl +// // << "Python interpreter traceback:" << std::endl; +// //PyErr_Print(); +// //std::cerr << std::endl; +// +// std::cerr << "This exception was caught by the SWIG unexpected exception handler." << std::endl +// << "Try using %feature(\"director:except\") to avoid reaching this point." << std::endl +// << std::endl +// << "Exception is being re-thrown, program will likely abort/terminate." << std::endl; +// throw; +// } +// +// public: +// +// std::unexpected_handler old; +// UnknownExceptionHandler(std::unexpected_handler nh = handler) +// { +// old = std::set_unexpected(nh); +// } +// +// ~UnknownExceptionHandler() +// { +// std::set_unexpected(old); +// } +//#endif +// }; + +#if defined(SWIG_PYTHON_THREADS) +/* __THREAD__ is the old macro to activate some thread support */ +# if !defined(__THREAD__) +# define __THREAD__ 1 +# endif +#endif + +#ifdef __THREAD__ +# include "pythread.h" + class Guard + { + PyThread_type_lock & mutex_; + + public: + Guard(PyThread_type_lock & mutex) : mutex_(mutex) + { + PyThread_acquire_lock(mutex_, WAIT_LOCK); + } + + ~Guard() + { + PyThread_release_lock(mutex_); + } + }; +# define SWIG_GUARD(mutex) Guard _guard(mutex) +#else +# define SWIG_GUARD(mutex) +#endif + + /* director base class */ + class Director { + private: + /* pointer to the wrapped perl object */ + SV *swig_self; + /* class of wrapped perl object */ + std::string swig_class; + /* flag indicating whether the object is owned by perl or c++ */ + mutable bool swig_disown_flag; + + /* decrement the reference count of the wrapped perl object */ + void swig_decref() const { + if (swig_disown_flag) { + SvREFCNT_dec(swig_self); + } + } + + public: + /* wrap a python object, optionally taking ownership */ + Director(SV *pkg) : swig_disown_flag(false) { + STRLEN len; + char *str = SvPV(pkg, len); + swig_class = std::string(str, len); + swig_self = newRV_inc((SV *)newHV()); + swig_incref(); + } + + + /* discard our reference at destruction */ + virtual ~Director() { + swig_decref(); + } + + + /* return a pointer to the wrapped python object */ + SV *swig_get_self() const { + return swig_self; + } + + const char *swig_get_class() const { + return swig_class.c_str(); + } + + /* acquire ownership of the wrapped python object (the sense of "disown" + * is from python) */ + void swig_disown() const { + if (!swig_disown_flag) { + swig_disown_flag=true; + swig_incref(); + } + } + + /* increase the reference count of the wrapped python object */ + void swig_incref() const { + if (swig_disown_flag) { + SvREFCNT_inc(swig_self); + } + } + + /* methods to implement pseudo protected director members */ + virtual bool swig_get_inner(const char* /* swig_protected_method_name */) const { + return true; + } + + virtual void swig_set_inner(const char* /* swig_protected_method_name */, bool /* swig_val */) const { + } + + /* ownership management */ + private: + typedef std::map swig_ownership_map; + mutable swig_ownership_map swig_owner; +#ifdef __THREAD__ + static PyThread_type_lock swig_mutex_own; +#endif + + public: + template + void swig_acquire_ownership_array(Type *vptr) const + { + if (vptr) { + SWIG_GUARD(swig_mutex_own); + swig_owner[vptr] = new GCArray_T(vptr); + } + } + + template + void swig_acquire_ownership(Type *vptr) const + { + if (vptr) { + SWIG_GUARD(swig_mutex_own); + swig_owner[vptr] = new GCItem_T(vptr); + } + } + + void swig_acquire_ownership_obj(void *vptr, int own) const + { + if (vptr && own) { + SWIG_GUARD(swig_mutex_own); + swig_owner[vptr] = new GCItem_Object(own); + } + } + + int swig_release_ownership(void *vptr) const + { + int own = 0; + if (vptr) { + SWIG_GUARD(swig_mutex_own); + swig_ownership_map::iterator iter = swig_owner.find(vptr); + if (iter != swig_owner.end()) { + own = iter->second->get_own(); + swig_owner.erase(iter); + } + } + return own; + } + + //template + //static PyObject* swig_pyobj_disown(PyObject *pyobj, PyObject *SWIGUNUSEDPARM(args)) + //{ + // SwigPyObject *sobj = (SwigPyObject *)pyobj; + // sobj->own = 0; + // Director *d = SWIG_DIRECTOR_CAST(reinterpret_cast(sobj->ptr)); + // if (d) + // d->swig_disown(); + // return PyWeakref_NewProxy(pyobj, NULL); + //} + + }; + +#ifdef __THREAD__ + PyThread_type_lock Director::swig_mutex_own = PyThread_allocate_lock(); +#endif +} + +#endif /* __cplusplus */ + + +#endif From 73e2de7538f5439aab14a7163df7c00310ea3201 Mon Sep 17 00:00:00 2001 From: Robert Stone Date: Tue, 12 Nov 2013 13:03:49 -0800 Subject: [PATCH 191/481] adds "callback" and "extend" examples --- Examples/perl5/callback/Makefile | 20 +++++++++ Examples/perl5/callback/example.cxx | 4 ++ Examples/perl5/callback/example.h | 23 ++++++++++ Examples/perl5/callback/example.i | 17 ++++++++ Examples/perl5/callback/index.html | 20 +++++++++ Examples/perl5/callback/runme.pl | 40 ++++++++++++++++++ Examples/perl5/check.list | 3 +- Examples/perl5/extend/Makefile | 20 +++++++++ Examples/perl5/extend/example.cxx | 4 ++ Examples/perl5/extend/example.h | 56 +++++++++++++++++++++++++ Examples/perl5/extend/example.i | 20 +++++++++ Examples/perl5/extend/index.html | 19 +++++++++ Examples/perl5/extend/runme.pl | 65 +++++++++++++++++++++++++++++ Examples/perl5/index.html | 2 + 14 files changed, 312 insertions(+), 1 deletion(-) create mode 100644 Examples/perl5/callback/Makefile create mode 100644 Examples/perl5/callback/example.cxx create mode 100644 Examples/perl5/callback/example.h create mode 100644 Examples/perl5/callback/example.i create mode 100644 Examples/perl5/callback/index.html create mode 100644 Examples/perl5/callback/runme.pl create mode 100644 Examples/perl5/extend/Makefile create mode 100644 Examples/perl5/extend/example.cxx create mode 100644 Examples/perl5/extend/example.h create mode 100644 Examples/perl5/extend/example.i create mode 100644 Examples/perl5/extend/index.html create mode 100644 Examples/perl5/extend/runme.pl diff --git a/Examples/perl5/callback/Makefile b/Examples/perl5/callback/Makefile new file mode 100644 index 000000000..544d13642 --- /dev/null +++ b/Examples/perl5/callback/Makefile @@ -0,0 +1,20 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +CXXSRCS = example.cxx +TARGET = example +INTERFACE = example.i +LIBS = -lm + +check: build + $(MAKE) -f $(TOP)/Makefile perl5_run + +build: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5_cpp + +static: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_cpp_static + +clean: + $(MAKE) -f $(TOP)/Makefile perl5_clean diff --git a/Examples/perl5/callback/example.cxx b/Examples/perl5/callback/example.cxx new file mode 100644 index 000000000..450d75608 --- /dev/null +++ b/Examples/perl5/callback/example.cxx @@ -0,0 +1,4 @@ +/* File : example.cxx */ + +#include "example.h" + diff --git a/Examples/perl5/callback/example.h b/Examples/perl5/callback/example.h new file mode 100644 index 000000000..1a0e8c432 --- /dev/null +++ b/Examples/perl5/callback/example.h @@ -0,0 +1,23 @@ +/* File : example.h */ + +#include +#include + +class Callback { +public: + virtual ~Callback() { std::cout << "Callback::~Callback()" << std:: endl; } + virtual void run() { std::cout << "Callback::run()" << std::endl; } +}; + + +class Caller { +private: + Callback *_callback; +public: + Caller(): _callback(0) {} + ~Caller() { delCallback(); } + void delCallback() { delete _callback; _callback = 0; } + void setCallback(Callback *cb) { delCallback(); _callback = cb; } + void call() { if (_callback) _callback->run(); } +}; + diff --git a/Examples/perl5/callback/example.i b/Examples/perl5/callback/example.i new file mode 100644 index 000000000..5f9072e61 --- /dev/null +++ b/Examples/perl5/callback/example.i @@ -0,0 +1,17 @@ +/* File : example.i */ +%module(directors="1") example +%{ +#include "example.h" +%} + +%include "std_string.i" + +/* turn on director wrapping Callback */ +%feature("director") Callback; + +/* Caller::setCallback(Callback *cb) gives ownership of the cb to the + * Caller object. The wrapper code should understand this. */ +%apply SWIGTYPE *DISOWN { Callback *cb }; + +%include "example.h" + diff --git a/Examples/perl5/callback/index.html b/Examples/perl5/callback/index.html new file mode 100644 index 000000000..82f5e972a --- /dev/null +++ b/Examples/perl5/callback/index.html @@ -0,0 +1,20 @@ + + +SWIG:Examples:perl5:callback + + + + + +SWIG/Examples/perl/callback/ +
    + +

    Implementing C++ callbacks in Perl

    + +

    +This example illustrates how to use directors to implement C++ callbacks. +

    + +
    + + diff --git a/Examples/perl5/callback/runme.pl b/Examples/perl5/callback/runme.pl new file mode 100644 index 000000000..9471d74e8 --- /dev/null +++ b/Examples/perl5/callback/runme.pl @@ -0,0 +1,40 @@ +#!/usr/bin/perl +use strict; +use warnings; +use example; + +{ + package PerlCallback; + use base 'example::Callback'; + sub run { + print "PerlCallback.run()\n"; + } +} + +print "Adding and calling a normal C++ callback\n"; +print "----------------------------------------\n"; + +my $caller = example::Caller->new(); +my $callback = example::Callback->new(); + +$caller->setCallback($callback); +$caller->call(); +$caller->delCallback(); + +$callback = PerlCallback->new(); + +print "\n"; +print "Adding and calling a Perl callback\n"; +print "------------------------------------\n"; + +$caller->setCallback($callback); +$caller->call(); +$caller->delCallback(); + +# Note that letting go of $callback will not attempt to destroy the +# object, ownership passed to $caller in the ->setCallback() call, and +# $callback was already destroyed in ->delCallback(). +undef $callback; + +print "\n"; +print "perl exit\n"; diff --git a/Examples/perl5/check.list b/Examples/perl5/check.list index e15f02e18..925bd263f 100644 --- a/Examples/perl5/check.list +++ b/Examples/perl5/check.list @@ -4,7 +4,6 @@ constants constants2 funcptr import -java multimap multiple_inheritance pointer @@ -12,3 +11,5 @@ reference simple value variables +callback +extend diff --git a/Examples/perl5/extend/Makefile b/Examples/perl5/extend/Makefile new file mode 100644 index 000000000..544d13642 --- /dev/null +++ b/Examples/perl5/extend/Makefile @@ -0,0 +1,20 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +CXXSRCS = example.cxx +TARGET = example +INTERFACE = example.i +LIBS = -lm + +check: build + $(MAKE) -f $(TOP)/Makefile perl5_run + +build: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5_cpp + +static: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_cpp_static + +clean: + $(MAKE) -f $(TOP)/Makefile perl5_clean diff --git a/Examples/perl5/extend/example.cxx b/Examples/perl5/extend/example.cxx new file mode 100644 index 000000000..450d75608 --- /dev/null +++ b/Examples/perl5/extend/example.cxx @@ -0,0 +1,4 @@ +/* File : example.cxx */ + +#include "example.h" + diff --git a/Examples/perl5/extend/example.h b/Examples/perl5/extend/example.h new file mode 100644 index 000000000..b27ab9711 --- /dev/null +++ b/Examples/perl5/extend/example.h @@ -0,0 +1,56 @@ +/* File : example.h */ + +#include +#include +#include +#include +#include + +class Employee { +private: + std::string name; +public: + Employee(const char* n): name(n) {} + virtual std::string getTitle() { return getPosition() + " " + getName(); } + virtual std::string getName() { return name; } + virtual std::string getPosition() const { return "Employee"; } + virtual ~Employee() { printf("~Employee() @ %p\n", this); } +}; + + +class Manager: public Employee { +public: + Manager(const char* n): Employee(n) {} + virtual std::string getPosition() const { return "Manager"; } +}; + + +class EmployeeList { + std::vector list; +public: + EmployeeList() { + list.push_back(new Employee("Bob")); + list.push_back(new Employee("Jane")); + list.push_back(new Manager("Ted")); + } + void addEmployee(Employee *p) { + list.push_back(p); + std::cout << "New employee added. Current employees are:" << std::endl; + std::vector::iterator i; + for (i=list.begin(); i!=list.end(); i++) { + std::cout << " " << (*i)->getTitle() << std::endl; + } + } + const Employee *get_item(int i) { + return list[i]; + } + ~EmployeeList() { + std::vector::iterator i; + std::cout << "~EmployeeList, deleting " << list.size() << " employees." << std::endl; + for (i=list.begin(); i!=list.end(); i++) { + delete *i; + } + std::cout << "~EmployeeList empty." << std::endl; + } +}; + diff --git a/Examples/perl5/extend/example.i b/Examples/perl5/extend/example.i new file mode 100644 index 000000000..f5e142b88 --- /dev/null +++ b/Examples/perl5/extend/example.i @@ -0,0 +1,20 @@ +/* File : example.i */ +%module(directors="1") example +%{ +#include "example.h" +%} + +%include "std_vector.i" +%include "std_string.i" + +/* turn on director wrapping for Manager */ +%feature("director") Employee; +%feature("director") Manager; + +/* EmployeeList::addEmployee(Employee *p) gives ownership of the + * employee to the EmployeeList object. The wrapper code should + * understand this. */ +%apply SWIGTYPE *DISOWN { Employee *p }; + +%include "example.h" + diff --git a/Examples/perl5/extend/index.html b/Examples/perl5/extend/index.html new file mode 100644 index 000000000..e9d886bcf --- /dev/null +++ b/Examples/perl5/extend/index.html @@ -0,0 +1,19 @@ + + +SWIG:Examples:perl5:extend + + + + + +SWIG/Examples/perl5/extend/ +
    + +

    Extending a simple C++ class

    + +

    +This example illustrates the extending of a C++ class with cross language polymorphism. + +


    + + diff --git a/Examples/perl5/extend/runme.pl b/Examples/perl5/extend/runme.pl new file mode 100644 index 000000000..43c9ce125 --- /dev/null +++ b/Examples/perl5/extend/runme.pl @@ -0,0 +1,65 @@ +#!/usr/bin/perl +use strict; +use warnings; +use example; +# This file illustrates the cross language polymorphism using directors. + +{ + # CEO class, which overrides Employee::getPosition(). + package CEO; + use base 'example::Manager'; + sub getPosition { + return 'CEO'; + } +} + + +# Create an instance of CEO, a class derived from the Java proxy of the +# underlying C++ class. The calls to getName() and getPosition() are standard, +# the call to getTitle() uses the director wrappers to call CEO.getPosition(). +my $e = CEO->new('Alice'); +print "${\ $e->getName } is a ${\ $e->getPosition() }\n"; +print "Just call her \"${\ $e->getTitle() }\"\n"; +print "----------------------\n"; + + +# Create a new EmployeeList instance. This class does not have a C++ +# director wrapper, but can be used freely with other classes that do. + +my $list = example::EmployeeList->new(); + +$list->addEmployee($e); +print "----------------------\n"; + +# 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 +# methods of all these instances are treated the same. For items 0, 1, and +# 2, all methods resolve in C++. For item 3, our CEO, getTitle calls +# getPosition which resolves in Perl. The call to getPosition is +# slightly different, however, because of the overidden getPosition() call, since +# now the object reference has been "laundered" by passing through +# EmployeeList as an Employee*. Previously, Perl resolved the call +# immediately in CEO, but now Perl thinks the object is an instance of +# class Employee. So the call passes through the +# Employee proxy class and on to the C wrappers and C++ director, +# eventually ending up back at the Perl CEO implementation of getPosition(). +# The call to getTitle() for item 3 runs the C++ Employee::getTitle() +# method, which in turn calls getPosition(). This virtual method call +# passes down through the C++ director class to the Perl implementation +# in CEO. All this routing takes place transparently. + +print "(position, title) for items 0-3:\n"; + +print " ${\ $list->get_item(0)->getPosition() }, \"${\ $list->get_item(0)->getTitle() }\"\n"; +print " ${\ $list->get_item(1)->getPosition() }, \"${\ $list->get_item(1)->getTitle() }\"\n"; +print " ${\ $list->get_item(2)->getPosition() }, \"${\ $list->get_item(2)->getTitle() }\"\n"; +print " ${\ $list->get_item(3)->getPosition() }, \"${\ $list->get_item(3)->getTitle() }\"\n"; +print "----------------------\n"; + +# Time to delete the EmployeeList, which will delete all the Employee* +# items it contains. The last item is our CEO, which gets destroyed as well. +undef $list; +print "----------------------\n"; + +# All done. +print "perl exit\n"; diff --git a/Examples/perl5/index.html b/Examples/perl5/index.html index db46023c4..23c8ff658 100644 --- a/Examples/perl5/index.html +++ b/Examples/perl5/index.html @@ -20,6 +20,8 @@ certain C declarations are turned into constants.
  • reference. C++ references.
  • pointer. Simple pointer handling.
  • funcptr. Pointers to functions. +
  • callback. C++ callbacks using directors. +
  • extend. Extending a simple C++ class.

    Compilation Issues

    From 35dc86f064382f4f85b79c4138cc1222beab9011 Mon Sep 17 00:00:00 2001 From: Robert Stone Date: Tue, 12 Nov 2013 14:13:30 -0800 Subject: [PATCH 192/481] steals python director docs and adapts to perl5 --- Doc/Manual/Perl5.html | 342 +++++++++++++++++++++++++++++++++++++++++ Lib/perl5/director.swg | 2 +- 2 files changed, 343 insertions(+), 1 deletion(-) diff --git a/Doc/Manual/Perl5.html b/Doc/Manual/Perl5.html index 49e8965fa..00284783f 100644 --- a/Doc/Manual/Perl5.html +++ b/Doc/Manual/Perl5.html @@ -68,6 +68,15 @@
  • Modifying the proxy methods
  • Adding additional Perl code +
  • Cross language polymorphism +
  • @@ -2993,6 +3002,339 @@ set_transform($im, $a); +

    31.11 Cross language polymorphism

    + + +

    +Proxy classes provide a more natural, object-oriented way to access +extension classes. As described above, each proxy instance has an +associated C++ instance, and method calls to the proxy are passed to the +C++ instance transparently via C wrapper functions. +

    + +

    +This arrangement is asymmetric in the sense that no corresponding +mechanism exists to pass method calls down the inheritance chain from +C++ to Perl. In particular, if a C++ class has been extended in Perl +(by extending the proxy class), these extensions will not be visible +from C++ code. Virtual method calls from C++ are thus not able access +the lowest implementation in the inheritance chain. +

    + +

    +Changes have been made to SWIG to address this problem and +make the relationship between C++ classes and proxy classes more +symmetric. To achieve this goal, new classes called directors are +introduced at the bottom of the C++ inheritance chain. The job of the +directors is to route method calls correctly, either to C++ +implementations higher in the inheritance chain or to Perl +implementations lower in the inheritance chain. The upshot is that C++ +classes can be extended in Perl and from C++ these extensions look +exactly like native C++ classes. Neither C++ code nor Perl code needs +to know where a particular method is implemented: the combination of +proxy classes, director classes, and C wrapper functions takes care of +all the cross-language method routing transparently. +

    + +

    31.11.1 Enabling directors

    + + +

    +The director feature is disabled by default. To use directors you +must make two changes to the interface file. First, add the "directors" +option to the %module directive, like this: +

    + +
    +
    +%module(directors="1") modulename
    +
    +
    + +

    +Without this option no director code will be generated. Second, you +must use the %feature("director") directive to tell SWIG which classes +and methods should get directors. The %feature directive can be applied +globally, to specific classes, and to specific methods, like this: +

    + +
    +
    +// generate directors for all classes that have virtual methods
    +%feature("director");         
    +
    +// generate directors for all virtual methods in class Foo
    +%feature("director") Foo;      
    +
    +
    + +

    +You can use the %feature("nodirector") directive to turn off +directors for specific classes or methods. So for example, +

    + +
    +
    +%feature("director") Foo;
    +%feature("nodirector") Foo::bar;
    +
    +
    + +

    +will generate directors for all virtual methods of class Foo except +bar(). +

    + +

    +Directors can also be generated implicitly through inheritance. +In the following, class Bar will get a director class that handles +the methods one() and two() (but not three()): +

    + +
    +
    +%feature("director") Foo;
    +class Foo {
    +public:
    +    Foo(int foo);
    +    virtual void one();
    +    virtual void two();
    +};
    +
    +class Bar: public Foo {
    +public:
    +    virtual void three();
    +};
    +
    +
    + +

    +then at the Perl side you can define +

    + +
    +
    +use mymodule;
    +
    +package MyFoo;
    +use base 'mymodule::Foo';
    +
    +sub one {
    +  print "one from Perl\n";
    +}
    +
    +
    + + +

    31.11.2 Director classes

    + + + + + +

    +For each class that has directors enabled, SWIG generates a new class +that derives from both the class in question and a special +Swig::Director class. These new classes, referred to as director +classes, can be loosely thought of as the C++ equivalent of the Perl +proxy classes. The director classes store a pointer to their underlying +Perl object and handle various issues related to object ownership. +

    + +

    +For simplicity let's ignore the Swig::Director class and refer to the +original C++ class as the director's base class. By default, a director +class extends all virtual methods in the inheritance chain of its base +class (see the preceding section for how to modify this behavior). +Thus all virtual method calls, whether they originate in C++ or in +Perl via proxy classes, eventually end up in at the implementation in +the director class. The job of the director methods is to route these +method calls to the appropriate place in the inheritance chain. By +"appropriate place" we mean the method that would have been called if +the C++ base class and its extensions in Perl were seamlessly +integrated. That seamless integration is exactly what the director +classes provide, transparently skipping over all the messy extension API +glue that binds the two languages together. +

    + +

    +In reality, the "appropriate place" is one of only two possibilities: +C++ or Perl. Once this decision is made, the rest is fairly easy. If +the correct implementation is in C++, then the lowest implementation of +the method in the C++ inheritance chain is called explicitly. If the +correct implementation is in Perl, the Perl API is used to call the +method of the underlying Perl object (after which the usual virtual +method resolution in Perl automatically finds the right +implementation). +

    + +

    +Now how does the director decide which language should handle the method call? +The basic rule is to handle the method in Perl, unless there's a good +reason not to. The reason for this is simple: Perl has the most +"extended" implementation of the method. This assertion is guaranteed, +since at a minimum the Perl proxy class implements the method. If the +method in question has been extended by a class derived from the proxy +class, that extended implementation will execute exactly as it should. +If not, the proxy class will route the method call into a C wrapper +function, expecting that the method will be resolved in C++. The wrapper +will call the virtual method of the C++ instance, and since the director +extends this the call will end up right back in the director method. Now +comes the "good reason not to" part. If the director method were to blindly +call the Perl method again, it would get stuck in an infinite loop. We avoid this +situation by adding special code to the C wrapper function that tells +the director method to not do this. The C wrapper function compares the +pointer to the Perl object that called the wrapper function to the +pointer stored by the director. If these are the same, then the C +wrapper function tells the director to resolve the method by calling up +the C++ inheritance chain, preventing an infinite loop. +

    + +

    +One more point needs to be made about the relationship between director +classes and proxy classes. When a proxy class instance is created in +Perl, SWIG creates an instance of the original C++ class. +This is exactly what happens without directors and +is true even if directors are enabled for the particular class in +question. When a class derived from a proxy class is created, +however, SWIG then creates an instance of the corresponding C++ director +class. The reason for this difference is that user-defined subclasses +may override or extend methods of the original class, so the director +class is needed to route calls to these methods correctly. For +unmodified proxy classes, all methods are ultimately implemented in C++ +so there is no need for the extra overhead involved with routing the +calls through Perl. +

    + +

    31.11.3 Ownership and object destruction

    + + +

    +Memory management issues are slightly more complicated with directors +than for proxy classes alone. Perl instances hold a pointer to the +associated C++ director object, and the director in turn holds a pointer +back to a Perl object. By default, proxy classes own their C++ +director object and take care of deleting it when they are garbage +collected. +

    + +

    +This relationship can be reversed by calling the special +DISOWN() method of the proxy class. After calling this +method the director +class increments the reference count of the Perl object. When the +director class is deleted it decrements the reference count. Assuming no +outstanding references to the Perl object remain, the Perl object +will be destroyed at the same time. This is a good thing, since +directors and proxies refer to each other and so must be created and +destroyed together. Destroying one without destroying the other will +likely cause your program to segfault. +

    + +

    31.11.4 Exception unrolling

    + + +

    +With directors routing method calls to Perl, and proxies routing them +to C++, the handling of exceptions is an important concern. By default, the +directors ignore exceptions that occur during method calls that are +resolved in Perl. To handle such exceptions correctly, it is necessary +to temporarily translate them into C++ exceptions. This can be done with +the %feature("director:except") directive. The following code should +suffice in most cases: +

    + +
    +
    +%feature("director:except") {
    +    if ($error != NULL) {
    +        throw Swig::DirectorMethodException();
    +    }
    +}
    +
    +
    + +

    +This code will check the Perl error state after each method call from +a director into Perl, and throw a C++ exception if an error occurred. +This exception can be caught in C++ to implement an error handler. +

    + +

    +It may be the case that a method call originates in Perl, travels up +to C++ through a proxy class, and then back into Perl via a director +method. If an exception occurs in Perl at this point, it would be nice +for that exception to find its way back to the original caller. This can +be done by combining a normal %exception directive with the +director:except handler shown above. Here is an example of a +suitable exception handler: +

    + +
    +
    +%exception {
    +    try { $action }
    +    catch (Swig::DirectorException &e) { SWIG_fail; }
    +}
    +
    +
    + +

    +The class Swig::DirectorException used in this example is actually a +base class of Swig::DirectorMethodException, so it will trap this +exception. Because the Perl error state is still set when +Swig::DirectorMethodException is thrown, Perl will register the +exception as soon as the C wrapper function returns. +

    + +

    31.11.5 Overhead and code bloat

    + + +

    +Enabling directors for a class will generate a new director method for +every virtual method in the class' inheritance chain. This alone can +generate a lot of code bloat for large hierarchies. Method arguments +that require complex conversions to and from target language types can +result in large director methods. For this reason it is recommended that +you selectively enable directors only for specific classes that are +likely to be extended in Perl and used in C++. +

    + +

    +Compared to classes that do not use directors, the call routing in the +director methods does add some overhead. In particular, at least one +dynamic cast and one extra function call occurs per method call from +Perl. Relative to the speed of Perl execution this is probably +completely negligible. For worst case routing, a method call that +ultimately resolves in C++ may take one extra detour through Perl in +order to ensure that the method does not have an extended Perl +implementation. This could result in a noticeable overhead in some cases. +

    + +

    +Although directors make it natural to mix native C++ objects with Perl +objects (as director objects) via a common base class pointer, one +should be aware of the obvious fact that method calls to Perl objects +will be much slower than calls to C++ objects. This situation can be +optimized by selectively enabling director methods (using the %feature +directive) for only those methods that are likely to be extended in +Perl. +

    + +

    31.11.6 Typemaps

    + + +

    +Typemaps for input and output of most of the basic types from director +classes have been written. These are roughly the reverse of the usual +input and output typemaps used by the wrapper code. The typemap +operation names are 'directorin', 'directorout', and 'directorargout'. +The director code does not currently use any of the other kinds of typemaps. +It is not clear at this point which kinds are appropriate and +need to be supported. +

    + + diff --git a/Lib/perl5/director.swg b/Lib/perl5/director.swg index 937b727a4..6b03fc26c 100644 --- a/Lib/perl5/director.swg +++ b/Lib/perl5/director.swg @@ -202,7 +202,7 @@ namespace Swig { protected: SV *err; public: - DirectorMethodException(SV *sv) + DirectorMethodException(SV *sv = sv_mortalcopy(ERRSV)) : err(sv) { SvREFCNT_inc(err); From 3e91ae7db7829f1a45ffd443514f5f19a14e7cf8 Mon Sep 17 00:00:00 2001 From: Robert Stone Date: Tue, 12 Nov 2013 18:43:56 -0800 Subject: [PATCH 193/481] mitigate ConvertPtr director cost when directors are not enabled --- Lib/perl5/perlrun.swg | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Lib/perl5/perlrun.swg b/Lib/perl5/perlrun.swg index 4e31c4754..876fae268 100644 --- a/Lib/perl5/perlrun.swg +++ b/Lib/perl5/perlrun.swg @@ -289,7 +289,11 @@ SWIG_Perl_ConvertPtrAndOwn(SWIG_MAYBE_PERL_OBJECT SV *sv, void **ptr, swig_type_ /* Now see if the types match */ char *_c = HvNAME(SvSTASH(SvRV(sv))); tc = SWIG_TypeProxyCheck(_c,_t); +#ifdef SWIG_DIRECTORS if (!tc && !sv_derived_from(sv,SWIG_Perl_TypeProxyName(_t))) { +#else + if (!tc) { +#endif return SWIG_ERROR; } { From 7d80d9b59eef51e78d794bf68e53c899c3213b65 Mon Sep 17 00:00:00 2001 From: Robert Stone Date: Wed, 13 Nov 2013 12:38:04 -0800 Subject: [PATCH 194/481] eliminate dead director code and convert remaining blocks --- Lib/perl5/director.swg | 127 --------------------------------------- Source/Modules/perl5.cxx | 100 +++++++----------------------- 2 files changed, 23 insertions(+), 204 deletions(-) diff --git a/Lib/perl5/director.swg b/Lib/perl5/director.swg index 6b03fc26c..5acc4fd15 100644 --- a/Lib/perl5/director.swg +++ b/Lib/perl5/director.swg @@ -17,41 +17,6 @@ #include -/* - Use -DSWIG_PYTHON_DIRECTOR_NO_VTABLE if you don't want to generate a 'virtual - table', and avoid multiple GetAttr calls to retrieve the python - methods. -*/ - -#ifndef SWIG_PERL_DIRECTOR_NO_VTABLE -#ifndef SWIG_PERL_DIRECTOR_VTABLE -#define SWIG_PERL_DIRECTOR_VTABLE -#endif -#endif - - - -/* - Use -DSWIG_DIRECTOR_NO_UEH if you prefer to avoid the use of the - Undefined Exception Handler provided by swig. -*/ -#ifndef SWIG_DIRECTOR_NO_UEH -#ifndef SWIG_DIRECTOR_UEH -#define SWIG_DIRECTOR_UEH -#endif -#endif - - -/* - Use -DSWIG_DIRECTOR_STATIC if you prefer to avoid the use of the - 'Swig' namespace. This could be useful for multi-modules projects. -*/ -#ifdef SWIG_DIRECTOR_STATIC -/* Force anonymous (static) namespace */ -#define Swig -#endif - - /* Use -DSWIG_DIRECTOR_NORTTI if you prefer to avoid the use of the native C++ RTTI and dynamic_cast<>. But be aware that directors @@ -267,77 +232,6 @@ namespace Swig { throw DirectorPureVirtualException(name); } }; -// /* unknown exception handler */ -// class UnknownExceptionHandler -// { -//#ifdef SWIG_DIRECTOR_UEH -// static void handler() { -// try { -// throw; -// } catch (DirectorException& e) { -// std::cerr << "SWIG Director exception caught:" << std::endl -// << e.getMessage() << std::endl; -// } catch (std::exception& e) { -// std::cerr << "std::exception caught: "<< e.what() << std::endl; -// } catch (...) { -// std::cerr << "Unknown exception caught." << std::endl; -// } -// -// //std::cerr << std::endl -// // << "Python interpreter traceback:" << std::endl; -// //PyErr_Print(); -// //std::cerr << std::endl; -// -// std::cerr << "This exception was caught by the SWIG unexpected exception handler." << std::endl -// << "Try using %feature(\"director:except\") to avoid reaching this point." << std::endl -// << std::endl -// << "Exception is being re-thrown, program will likely abort/terminate." << std::endl; -// throw; -// } -// -// public: -// -// std::unexpected_handler old; -// UnknownExceptionHandler(std::unexpected_handler nh = handler) -// { -// old = std::set_unexpected(nh); -// } -// -// ~UnknownExceptionHandler() -// { -// std::set_unexpected(old); -// } -//#endif -// }; - -#if defined(SWIG_PYTHON_THREADS) -/* __THREAD__ is the old macro to activate some thread support */ -# if !defined(__THREAD__) -# define __THREAD__ 1 -# endif -#endif - -#ifdef __THREAD__ -# include "pythread.h" - class Guard - { - PyThread_type_lock & mutex_; - - public: - Guard(PyThread_type_lock & mutex) : mutex_(mutex) - { - PyThread_acquire_lock(mutex_, WAIT_LOCK); - } - - ~Guard() - { - PyThread_release_lock(mutex_); - } - }; -# define SWIG_GUARD(mutex) Guard _guard(mutex) -#else -# define SWIG_GUARD(mutex) -#endif /* director base class */ class Director { @@ -410,16 +304,12 @@ namespace Swig { private: typedef std::map swig_ownership_map; mutable swig_ownership_map swig_owner; -#ifdef __THREAD__ - static PyThread_type_lock swig_mutex_own; -#endif public: template void swig_acquire_ownership_array(Type *vptr) const { if (vptr) { - SWIG_GUARD(swig_mutex_own); swig_owner[vptr] = new GCArray_T(vptr); } } @@ -428,7 +318,6 @@ namespace Swig { void swig_acquire_ownership(Type *vptr) const { if (vptr) { - SWIG_GUARD(swig_mutex_own); swig_owner[vptr] = new GCItem_T(vptr); } } @@ -436,7 +325,6 @@ namespace Swig { void swig_acquire_ownership_obj(void *vptr, int own) const { if (vptr && own) { - SWIG_GUARD(swig_mutex_own); swig_owner[vptr] = new GCItem_Object(own); } } @@ -445,7 +333,6 @@ namespace Swig { { int own = 0; if (vptr) { - SWIG_GUARD(swig_mutex_own); swig_ownership_map::iterator iter = swig_owner.find(vptr); if (iter != swig_owner.end()) { own = iter->second->get_own(); @@ -455,22 +342,8 @@ namespace Swig { return own; } - //template - //static PyObject* swig_pyobj_disown(PyObject *pyobj, PyObject *SWIGUNUSEDPARM(args)) - //{ - // SwigPyObject *sobj = (SwigPyObject *)pyobj; - // sobj->own = 0; - // Director *d = SWIG_DIRECTOR_CAST(reinterpret_cast(sobj->ptr)); - // if (d) - // d->swig_disown(); - // return PyWeakref_NewProxy(pyobj, NULL); - //} - }; -#ifdef __THREAD__ - PyThread_type_lock Director::swig_mutex_own = PyThread_allocate_lock(); -#endif } #endif /* __cplusplus */ diff --git a/Source/Modules/perl5.cxx b/Source/Modules/perl5.cxx index 182835645..06b4c4ae9 100644 --- a/Source/Modules/perl5.cxx +++ b/Source/Modules/perl5.cxx @@ -1707,12 +1707,8 @@ public: String *saved_nc = none_comparison; none_comparison = NewStringf("strcmp(SvPV_nolen(ST(0)), \"%s::%s\") != 0", module, class_name); String *saved_director_prot_ctor_code = director_prot_ctor_code; - director_prot_ctor_code = NewStringf( - "if ($comparison) { /* subclassed */\n" - " $director_new\n" - "} else {\n" - " SWIG_exception_fail(SWIG_RuntimeError, \"accessing abstract class or protected constructor\");\n" - "}\n"); + director_prot_ctor_code = NewStringf( "if ($comparison) { /* subclassed */\n" " $director_new\n" "} else {\n" " + SWIG_exception_fail(SWIG_RuntimeError, \"accessing abstract class or protected constructor\");\n" "}\n"); Language::constructorHandler(n); Delete(none_comparison); none_comparison = saved_nc; @@ -2084,7 +2080,6 @@ public: int status = SWIG_OK; int idx; bool ignored_method = GetFlag(n, "feature:ignore") ? true : false; - int addfail = 0; if (Cmp(storage, "virtual") == 0) { if (Cmp(value, "0") == 0) { @@ -2157,11 +2152,6 @@ public: } } - //if (builtin) { - // Printv(w->code, "PyObject *self = NULL;\n", NIL); - // Printv(w->code, "(void)self;\n", NIL); - //} - if (ignored_method) { if (!pure_virtual) { if (!is_void) @@ -2175,7 +2165,6 @@ public: } } else { /* attach typemaps to arguments (C/C++ -> Perl) */ - String *arglist = NewString(""); String *parse_args = NewString(""); String *pstack = NewString(""); @@ -2211,7 +2200,6 @@ public: /* build argument list and type conversion string */ idx = 0; p = l; - int use_parse = 0; while (p) { if (checkAttribute(p, "tmap:in:numinputs", "0")) { p = Getattr(p, "tmap:in:next"); @@ -2232,35 +2220,20 @@ public: String *pname = Getattr(p, "name"); String *ptype = Getattr(p, "type"); - Putc(',', arglist); if ((tm = Getattr(p, "tmap:directorin")) != 0) { - String *parse = Getattr(p, "tmap:directorin:parse"); - if (!parse) { - sprintf(source, "obj%d", idx++); - String *input = NewString(source); - Setattr(p, "emit:directorinput", input); - Replaceall(tm, "$input", input); - Delete(input); - Replaceall(tm, "$owner", "0"); - Replaceall(tm, "$shadow", "0"); - /* Wrapper_add_localv(w, source, "SV *", source, "= 0", NIL); */ - Printv(wrap_args, "SV *", source, ";\n", NIL); + sprintf(source, "obj%d", idx++); + String *input = NewString(source); + Setattr(p, "emit:directorinput", input); + Replaceall(tm, "$input", input); + Delete(input); + Replaceall(tm, "$owner", "0"); + Replaceall(tm, "$shadow", "0"); + /* Wrapper_add_localv(w, source, "SV *", source, "= 0", NIL); */ + Printv(wrap_args, "SV *", source, ";\n", NIL); - Printv(wrap_args, tm, "\n", NIL); - Printv(arglist, "(PyObject *)", source, NIL); - Putc('O', parse_args); - Printv(pstack, "XPUSHs(", source, ");\n", NIL); - } else { - use_parse = 1; - Append(parse_args, parse); - Setattr(p, "emit:directorinput", pname); - Replaceall(tm, "$input", pname); - Replaceall(tm, "$owner", "0"); - Replaceall(tm, "$shadow", "0"); - if (Len(tm) == 0) - Append(tm, pname); - Append(arglist, tm); - } + Printv(wrap_args, tm, "\n", NIL); + Putc('O', parse_args); + Printv(pstack, "XPUSHs(", source, ");\n", NIL); p = Getattr(p, "tmap:directorin:next"); continue; } else if (Cmp(ptype, "void")) { @@ -2303,23 +2276,19 @@ public: if (target) { String *director = NewStringf("director_%s", mangle); Wrapper_add_localv(w, director, "Swig::Director *", director, "= 0", NIL); - Wrapper_add_localv(w, source, "swig::SwigVar_PyObject", source, "= 0", NIL); + Wrapper_add_localv(w, source, "SV *", source, "= 0", NIL); Printf(wrap_args, "%s = SWIG_DIRECTOR_CAST(%s);\n", director, nonconst); Printf(wrap_args, "if (!%s) {\n", director); - Printf(wrap_args, "%s = SWIG_InternalNewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle); + Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle); Append(wrap_args, "} else {\n"); Printf(wrap_args, "%s = %s->swig_get_self();\n", source, director); - Printf(wrap_args, "Py_INCREF((PyObject *)%s);\n", source); + Printf(wrap_args, "SvREFCNT_inc((SV *)%s);\n", source); Append(wrap_args, "}\n"); Delete(director); - Printv(arglist, source, NIL); } else { Wrapper_add_localv(w, source, "SV *", source, "= 0", NIL); Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle); Printf(pstack, "XPUSHs(sv_2mortal(%s));\n", source); - //Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE_p_%s, 0);\n", - // source, nonconst, base); - Printv(arglist, source, NIL); } Putc('O', parse_args); Delete(mangle); @@ -2338,13 +2307,6 @@ public: /* add the method name as a PyString */ String *pyname = Getattr(n, "sym:name"); - //int allow_thread = threads_enable(n); - // - //if (allow_thread) { - // thread_begin_block(n, w->code); - // Append(w->code, "{\n"); - //} - /* wrap complex arguments to PyObjects */ Printv(w->code, wrap_args, NIL); @@ -2374,7 +2336,7 @@ public: Append(w->code, "if (SvTRUE(ERRSV)) {\n"); Append(w->code, " PUTBACK;\n FREETMPS;\n LEAVE;\n"); if ((tm) && Len(tm) && (Strcmp(tm, "1") != 0)) { - Replaceall(tm, "$error", "error"); + Replaceall(tm, "$error", "ERRSV"); Printv(w->code, Str(tm), "\n", NIL); } else { Printf(w->code, " Swig::DirectorMethodException::raise(ERRSV);\n", classname, pyname); @@ -2395,9 +2357,9 @@ public: String *outarg = NewString(""); if (outputs > 1) { - Wrapper_add_local(w, "output", "PyObject *output"); - Printf(w->code, "if (!PyTuple_Check(%s)) {\n", Swig_cresult_name()); - Printf(w->code, " Swig::DirectorTypeMismatchException::raise(\"Python method %s.%sfailed to return a tuple.\");\n", classname, pyname); + Wrapper_add_local(w, "output", "SV *output"); + Printf(w->code, "if (count != %d) {\n", outputs); + Printf(w->code, " Swig::DirectorTypeMismatchException::raise(\"Perl method %s.%sfailed to return a list.\");\n", classname, pyname); Append(w->code, "}\n"); } @@ -2410,7 +2372,7 @@ public: tm = Swig_typemap_lookup("directorout", n, Swig_cresult_name(), w); if (tm != 0) { if (outputs > 1) { - Printf(w->code, "output = PyTuple_GetItem(%s, %d);\n", Swig_cresult_name(), idx++); + Printf(w->code, "output = POPs;\n"); Replaceall(tm, "$input", "output"); } else { Replaceall(tm, "$input", Swig_cresult_name()); @@ -2425,14 +2387,10 @@ public: } else { Replaceall(tm, "$disown", "0"); } - //if (Getattr(n, "tmap:directorout:implicitconv")) { - // Replaceall(tm, "$implicitconv", get_implicitconv_flag(n)); - //} Replaceall(tm, "$result", "c_result"); Printv(w->code, tm, "\n", NIL); Delete(tm); } else { - Swig_print_node(n); 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)); @@ -2444,7 +2402,7 @@ public: for (p = l; p;) { if ((tm = Getattr(p, "tmap:directorargout")) != 0) { if (outputs > 1) { - Printf(w->code, "output = PyTuple_GetItem(%s, %d);\n", Swig_cresult_name(), idx++); + Printf(w->code, "output = POPs;\n"); Replaceall(tm, "$result", "output"); } else { Replaceall(tm, "$result", Swig_cresult_name()); @@ -2457,14 +2415,7 @@ public: } } - /* any existing helper functions to handle this? */ - //if (allow_thread) { - // Append(w->code, "}\n"); - // thread_end_block(n, w->code); - //} - Delete(parse_args); - Delete(arglist); Delete(cleanup); Delete(outarg); } @@ -2487,11 +2438,6 @@ public: } } - if (addfail) { - Append(w->code, "fail:\n"); - Printf(w->code, " Swig::DirectorMethodException::raise(\"Error detected when calling '%s->%s'\");\n", classname, Getattr(n, "sym:name")); - } - Append(w->code, "}\n"); // We expose protected methods via an extra public inline method which makes a straight call to the wrapped class' method From 055cbc85de4625e6b53e840cd753e0d01bae5d9e Mon Sep 17 00:00:00 2001 From: Robert Stone Date: Wed, 13 Nov 2013 15:04:18 -0800 Subject: [PATCH 195/481] fix string mangled by tidy --- Source/Modules/perl5.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Source/Modules/perl5.cxx b/Source/Modules/perl5.cxx index 06b4c4ae9..f59994cd7 100644 --- a/Source/Modules/perl5.cxx +++ b/Source/Modules/perl5.cxx @@ -1707,8 +1707,8 @@ public: String *saved_nc = none_comparison; none_comparison = NewStringf("strcmp(SvPV_nolen(ST(0)), \"%s::%s\") != 0", module, class_name); String *saved_director_prot_ctor_code = director_prot_ctor_code; - director_prot_ctor_code = NewStringf( "if ($comparison) { /* subclassed */\n" " $director_new\n" "} else {\n" " - SWIG_exception_fail(SWIG_RuntimeError, \"accessing abstract class or protected constructor\");\n" "}\n"); + director_prot_ctor_code = NewStringf( "if ($comparison) { /* subclassed */\n" " $director_new\n" "} else {\n" + "SWIG_exception_fail(SWIG_RuntimeError, \"accessing abstract class or protected constructor\");\n" "}\n"); Language::constructorHandler(n); Delete(none_comparison); none_comparison = saved_nc; From e0789366e7dccf28c31c04e9d82d35abead5f78c Mon Sep 17 00:00:00 2001 From: Robert Stone Date: Thu, 14 Nov 2013 07:29:28 -0800 Subject: [PATCH 196/481] prefer polymorphism on existing destructor over custom destructor method --- Doc/Manual/Perl5.html | 24 +++++++++++++++++++ .../perl5/director_finalizer_runme.pl | 5 ++-- Source/Modules/perl5.cxx | 15 ++++++------ 3 files changed, 35 insertions(+), 9 deletions(-) diff --git a/Doc/Manual/Perl5.html b/Doc/Manual/Perl5.html index 00284783f..db8c0e602 100644 --- a/Doc/Manual/Perl5.html +++ b/Doc/Manual/Perl5.html @@ -3231,6 +3231,30 @@ destroyed together. Destroying one without destroying the other will likely cause your program to segfault.

    +

    +Also note that due to the proxy implementation, the DESTROY() +method on directors can be called for several reasons, many of which +have little to do with the teardown of an object instance. To help +disambiguate this, a second argument is added to the DESTROY() +call when a C++ director object is being released. So, to avoid running +your clean-up code when an object is not really going away, or after it +has already been reclaimed, it is suggested that custom destructors in +Perl subclasses looks something like: +

    + +
    +
    +sub DESTROY {
    +  my($self, $final) = @_;
    +  if($final) {
    +    # real teardown code
    +  }
    +  shift->SUPER::DESTROY(@_);
    +}
    +
    +
    + +

    31.11.4 Exception unrolling

    diff --git a/Examples/test-suite/perl5/director_finalizer_runme.pl b/Examples/test-suite/perl5/director_finalizer_runme.pl index bb6e1fa71..bcb4002ec 100644 --- a/Examples/test-suite/perl5/director_finalizer_runme.pl +++ b/Examples/test-suite/perl5/director_finalizer_runme.pl @@ -7,8 +7,9 @@ require_ok('director_finalizer'); { package MyFoo; use base 'director_finalizer::Foo'; - sub DIRECTOR_DESTROY { my($self) = @_; - $self->orStatus(2); + sub DESTROY { my($self, $final) = @_; + $self->orStatus(2) if $final; + shift->SUPER::DESTROY(@_); } } diff --git a/Source/Modules/perl5.cxx b/Source/Modules/perl5.cxx index f59994cd7..530ed07ed 100644 --- a/Source/Modules/perl5.cxx +++ b/Source/Modules/perl5.cxx @@ -1529,11 +1529,11 @@ public: Delete(get_attr); Printv(pm, "sub FETCH {\n", tab4, "my ($self,$field) = @_;\n", tab4, "my $member_func = \"swig_${field}_get\";\n", tab4, - "if (not $self->can(\"$member_func\")) {\n", tab4, tab4, "my $h = ", cmodule, "::", mrename, "($self);\n", tab4, tab4, - "return $h->{$field} if $h;\n", tab4, "}\n", tab4, "return $self->$member_func;\n", "}\n", "\n", "sub STORE {\n", tab4, - "my ($self,$field,$newval) = @_;\n", tab4, "my $member_func = \"swig_${field}_set\";\n", tab4, - "if (not $self->can(\"$member_func\")) {\n", tab4, tab4, "my $h = ", cmodule, "::", mrename, "($self);\n", tab4, tab4, - "return $h->{$field} = $newval if $h;\n", tab4, "}\n", tab4, "return $self->$member_func($newval);\n", "}\n", NIL); + "if (not $self->can($member_func)) {\n", tab8, "my $h = ", cmodule, "::", mrename, "($self);\n", tab8, "return $h->{$field} if $h;\n", + tab4, "}\n", tab4, "return $self->$member_func;\n", "}\n", "\n", "sub STORE {\n", tab4, "my ($self,$field,$newval) = @_;\n", tab4, + "my $member_func = \"swig_${field}_set\";\n", tab4, "if (not $self->can($member_func)) {\n", tab8, "my $h = ", cmodule, "::", mrename, + "($self);\n", tab8, "return $h->{$field} = $newval if $h;\n", tab4, "}\n", tab4, "return $self->$member_func($newval);\n", "}\n", NIL); + Delete(mrename); } } @@ -2493,8 +2493,9 @@ public: String *mangle = SwigType_manglestr(ptype); Printv(body, tab4, "dSP;\n", tab4, "SV *self = SWIG_NewPointerObj(SWIG_as_voidptr(this), SWIGTYPE", mangle, ", SWIG_SHADOW);\n", tab4, "\n", tab4, - "sv_bless(self, gv_stashpv(swig_get_class(), 0));\n", tab4, "ENTER;\n", tab4, "SAVETMPS;\n", tab4, "PUSHMARK(SP);\n", tab4, "XPUSHs(self);\n", - tab4, "PUTBACK;\n", tab4, "call_method(\"DIRECTOR_DESTROY\", G_EVAL | G_VOID);\n", tab4, "FREETMPS;\n", tab4, "LEAVE;\n", NIL); + "sv_bless(self, gv_stashpv(swig_get_class(), 0));\n", tab4, "ENTER;\n", tab4, "SAVETMPS;\n", tab4, "PUSHMARK(SP);\n", tab4, + "XPUSHs(self);\n", tab4, "XPUSHs(&PL_sv_yes);\n", tab4, "PUTBACK;\n", tab4, "call_method(\"DESTROY\", G_EVAL | G_VOID);\n", tab4, + "FREETMPS;\n", tab4, "LEAVE;\n", NIL); Delete(mangle); Delete(ptype); From 43aefba9eed6fc06334ccef5e5652664aa8ea570 Mon Sep 17 00:00:00 2001 From: Robert Stone Date: Thu, 14 Nov 2013 09:22:23 -0800 Subject: [PATCH 197/481] ran "beautify-file" make target over perl5.cxx patch hunks and rewrote callback and extend examples in the style of existing examples --- Examples/perl5/callback/runme.pl | 40 +-- Examples/perl5/extend/runme.pl | 58 ++-- Source/Modules/perl5.cxx | 439 +++++++++++++++---------------- 3 files changed, 277 insertions(+), 260 deletions(-) diff --git a/Examples/perl5/callback/runme.pl b/Examples/perl5/callback/runme.pl index 9471d74e8..a6b80d988 100644 --- a/Examples/perl5/callback/runme.pl +++ b/Examples/perl5/callback/runme.pl @@ -1,40 +1,48 @@ -#!/usr/bin/perl -use strict; -use warnings; +# file: runme.pl + +# This file illustrates the cross language polymorphism using directors. + use example; + { - package PerlCallback; + package PlCallback; use base 'example::Callback'; sub run { - print "PerlCallback.run()\n"; + print "PlCallback->run()\n"; } } +# Create an Caller instance + +$caller = example::Caller->new(); + +# 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\n"; print "----------------------------------------\n"; -my $caller = example::Caller->new(); -my $callback = example::Callback->new(); - +$callback = example::Callback->new(); +$callback->DISOWN(); $caller->setCallback($callback); $caller->call(); $caller->delCallback(); -$callback = PerlCallback->new(); - -print "\n"; +print print "Adding and calling a Perl callback\n"; -print "------------------------------------\n"; +print "----------------------------------\n"; +# Add a Perl callback (caller owns the callback, so we +# disown it first by calling DISOWN). + +$callback = PlCallback->new(); +$callback->DISOWN(); $caller->setCallback($callback); $caller->call(); $caller->delCallback(); -# Note that letting go of $callback will not attempt to destroy the -# object, ownership passed to $caller in the ->setCallback() call, and -# $callback was already destroyed in ->delCallback(). -undef $callback; +# All done. print "\n"; print "perl exit\n"; diff --git a/Examples/perl5/extend/runme.pl b/Examples/perl5/extend/runme.pl index 43c9ce125..76ee849a4 100644 --- a/Examples/perl5/extend/runme.pl +++ b/Examples/perl5/extend/runme.pl @@ -1,48 +1,56 @@ -#!/usr/bin/perl -use strict; -use warnings; -use example; +# file: runme.pl + # This file illustrates the cross language polymorphism using directors. +use example; + + +# CEO class, which overrides Employee::getPosition(). + { - # CEO class, which overrides Employee::getPosition(). package CEO; use base 'example::Manager'; sub getPosition { - return 'CEO'; + return "CEO"; } } -# Create an instance of CEO, a class derived from the Java proxy of the -# underlying C++ class. The calls to getName() and getPosition() are standard, -# the call to getTitle() uses the director wrappers to call CEO.getPosition(). -my $e = CEO->new('Alice'); -print "${\ $e->getName } is a ${\ $e->getPosition() }\n"; -print "Just call her \"${\ $e->getTitle() }\"\n"; +# Create an instance of our employee extension class, CEO. The calls to +# getName() and getPosition() are standard, the call to getTitle() uses +# the director wrappers to call CEO->getPosition. $e = CEO->new("Alice") + +$e = CEO->new("Alice"); +print $e->getName(), " is a ", $e->getPosition(), "\n"; +printf "Just call her \"%s\"\n", $e->getTitle(); print "----------------------\n"; # Create a new EmployeeList instance. This class does not have a C++ # director wrapper, but can be used freely with other classes that do. -my $list = example::EmployeeList->new(); +$list = example::EmployeeList->new(); +# EmployeeList owns its items, so we must surrender ownership of objects +# we add. This involves calling the DISOWN method to tell the +# C++ director to start reference counting. + +$e->DISOWN(); $list->addEmployee($e); print "----------------------\n"; # 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 # methods of all these instances are treated the same. For items 0, 1, and -# 2, all methods resolve in C++. For item 3, our CEO, getTitle calls +# 2, both all methods resolve in C++. For item 3, our CEO, getTitle calls # getPosition which resolves in Perl. The call to getPosition is -# slightly different, however, because of the overidden getPosition() call, since +# slightly different, however, from the $e->getPosition() call above, since # now the object reference has been "laundered" by passing through # EmployeeList as an Employee*. Previously, Perl resolved the call # immediately in CEO, but now Perl thinks the object is an instance of -# class Employee. So the call passes through the +# class Employee (actually EmployeePtr). So the call passes through the # Employee proxy class and on to the C wrappers and C++ director, -# eventually ending up back at the Perl CEO implementation of getPosition(). +# eventually ending up back at the CEO implementation of getPosition(). # The call to getTitle() for item 3 runs the C++ Employee::getTitle() # method, which in turn calls getPosition(). This virtual method call # passes down through the C++ director class to the Perl implementation @@ -50,16 +58,22 @@ print "----------------------\n"; print "(position, title) for items 0-3:\n"; -print " ${\ $list->get_item(0)->getPosition() }, \"${\ $list->get_item(0)->getTitle() }\"\n"; -print " ${\ $list->get_item(1)->getPosition() }, \"${\ $list->get_item(1)->getTitle() }\"\n"; -print " ${\ $list->get_item(2)->getPosition() }, \"${\ $list->get_item(2)->getTitle() }\"\n"; -print " ${\ $list->get_item(3)->getPosition() }, \"${\ $list->get_item(3)->getTitle() }\"\n"; +printf " %s, \"%s\"\n", $list->get_item(0)->getPosition(), $list->get_item(0)->getTitle(); +printf " %s, \"%s\"\n", $list->get_item(1)->getPosition(), $list->get_item(1)->getTitle(); +printf " %s, \"%s\"\n", $list->get_item(2)->getPosition(), $list->get_item(2)->getTitle(); +printf " %s, \"%s\"\n", $list->get_item(3)->getPosition(), $list->get_item(3)->getTitle(); print "----------------------\n"; # Time to delete the EmployeeList, which will delete all the Employee* -# items it contains. The last item is our CEO, which gets destroyed as well. +# items it contains. The last item is our CEO, which gets destroyed as its +# reference count goes to zero. The Perl destructor runs, and is still +# able to call self.getName() since the underlying C++ object still +# exists. After this destructor runs the remaining C++ destructors run as +# usual to destroy the object. + undef $list; print "----------------------\n"; # All done. + print "perl exit\n"; diff --git a/Source/Modules/perl5.cxx b/Source/Modules/perl5.cxx index 530ed07ed..d7a131aa2 100644 --- a/Source/Modules/perl5.cxx +++ b/Source/Modules/perl5.cxx @@ -238,47 +238,42 @@ public: { Node *mod = Getattr(n, "module"); if (mod) { - Node *options = Getattr(mod, "options"); - if (options) { - int dirprot = 0; - if (Getattr(options, "dirprot")) - dirprot = 1; - if (Getattr(options, "nodirprot")) - dirprot = 0; - if (Getattr(options, "directors")) { - int allow = 1; - if (export_all) { - Printv(stderr, - "*** directors are not supported with -exportall\n", NIL); - allow = 0; - } - if (staticoption) { - Printv(stderr, - "*** directors are not supported with -static\n", NIL); - allow = 0; - } - if (!blessed) { - Printv(stderr, - "*** directors are not supported with -noproxy\n", NIL); - allow = 0; - } - if (no_pmfile) { - Printv(stderr, - "*** directors are not supported with -nopm\n", NIL); - allow = 0; - } - if (compat) { - Printv(stderr, - "*** directors are not supported with -compat\n", NIL); - allow = 0; - } - if (allow) { - allow_directors(); - if (dirprot) - allow_dirprot(); - } - } - } + Node *options = Getattr(mod, "options"); + if (options) { + int dirprot = 0; + if (Getattr(options, "dirprot")) + dirprot = 1; + if (Getattr(options, "nodirprot")) + dirprot = 0; + if (Getattr(options, "directors")) { + int allow = 1; + if (export_all) { + Printv(stderr, "*** directors are not supported with -exportall\n", NIL); + allow = 0; + } + if (staticoption) { + Printv(stderr, "*** directors are not supported with -static\n", NIL); + allow = 0; + } + if (!blessed) { + Printv(stderr, "*** directors are not supported with -noproxy\n", NIL); + allow = 0; + } + if (no_pmfile) { + Printv(stderr, "*** directors are not supported with -nopm\n", NIL); + allow = 0; + } + if (compat) { + Printv(stderr, "*** directors are not supported with -compat\n", NIL); + allow = 0; + } + if (allow) { + allow_directors(); + if (dirprot) + allow_dirprot(); + } + } + } } } @@ -301,8 +296,8 @@ public: if (directorsEnabled()) { f_runtime_h = NewFile(outfile_h, "w", SWIG_output_files()); if (!f_runtime_h) { - FileErrorDisplay(outfile_h); - SWIG_exit(EXIT_FAILURE); + FileErrorDisplay(outfile_h); + SWIG_exit(EXIT_FAILURE); } } @@ -1477,8 +1472,7 @@ public: String *director_disown; if (Getattr(n, "perl5:directordisown")) { - director_disown = NewStringf("%s%s($self);\n", - tab4, Getattr(n, "perl5:directordisown")); + director_disown = NewStringf("%s%s($self);\n", tab4, Getattr(n, "perl5:directordisown")); } else { director_disown = NewString(""); } @@ -1511,7 +1505,8 @@ public: type = NewString("SV"); SwigType_add_pointer(type); String *action = NewString(""); - Printv(action, "{\n", " Swig::Director *director = SWIG_DIRECTOR_CAST(arg1);\n", " result = sv_newmortal();\n" " if (director) sv_setsv(result, director->swig_get_self());\n", "}\n", NIL); + Printv(action, "{\n", " Swig::Director *director = SWIG_DIRECTOR_CAST(arg1);\n", + " result = sv_newmortal();\n" " if (director) sv_setsv(result, director->swig_get_self());\n", "}\n", NIL); Setfile(get_attr, Getfile(n)); Setline(get_attr, Getline(n)); Setattr(get_attr, "wrap:action", action); @@ -1534,7 +1529,7 @@ public: "my $member_func = \"swig_${field}_set\";\n", tab4, "if (not $self->can($member_func)) {\n", tab8, "my $h = ", cmodule, "::", mrename, "($self);\n", tab8, "return $h->{$field} = $newval if $h;\n", tab4, "}\n", tab4, "return $self->$member_func($newval);\n", "}\n", NIL); - Delete(mrename); + Delete(mrename); } } return SWIG_OK; @@ -1707,8 +1702,8 @@ public: String *saved_nc = none_comparison; none_comparison = NewStringf("strcmp(SvPV_nolen(ST(0)), \"%s::%s\") != 0", module, class_name); String *saved_director_prot_ctor_code = director_prot_ctor_code; - director_prot_ctor_code = NewStringf( "if ($comparison) { /* subclassed */\n" " $director_new\n" "} else {\n" - "SWIG_exception_fail(SWIG_RuntimeError, \"accessing abstract class or protected constructor\");\n" "}\n"); + director_prot_ctor_code = NewStringf("if ($comparison) { /* subclassed */\n" " $director_new\n" "} else {\n" + "SWIG_exception_fail(SWIG_RuntimeError, \"accessing abstract class or protected constructor\");\n" "}\n"); Language::constructorHandler(n); Delete(none_comparison); none_comparison = saved_nc; @@ -1732,7 +1727,7 @@ public: Printv(pcode, "sub ", Swig_name_construct(NSPACE_TODO, symname), " {\n", NIL); } - const char *pkg = getCurrentClass() && Swig_directorclass(getCurrentClass()) ? "$_[0]" : "shift"; + const char *pkg = getCurrentClass() && Swig_directorclass(getCurrentClass())? "$_[0]" : "shift"; Printv(pcode, tab4, "my $pkg = ", pkg, ";\n", tab4, "my $self = ", cmodule, "::", Swig_name_construct(NSPACE_TODO, symname), "(@_);\n", tab4, "bless $self, $pkg if defined($self);\n", "}\n\n", NIL); @@ -2083,7 +2078,7 @@ public: if (Cmp(storage, "virtual") == 0) { if (Cmp(value, "0") == 0) { - pure_virtual = true; + pure_virtual = true; } } @@ -2116,18 +2111,18 @@ public: Append(declaration, " throw("); if (throw_parm_list) - Swig_typemap_attach_parms("throws", throw_parm_list, 0); + Swig_typemap_attach_parms("throws", throw_parm_list, 0); for (p = throw_parm_list; p; p = nextSibling(p)) { - if (Getattr(p, "tmap:throws")) { - if (gencomma++) { - Append(w->def, ", "); - Append(declaration, ", "); - } - String *str = SwigType_str(Getattr(p, "type"), 0); - Append(w->def, str); - Append(declaration, str); - Delete(str); - } + if (Getattr(p, "tmap:throws")) { + if (gencomma++) { + Append(w->def, ", "); + Append(declaration, ", "); + } + String *str = SwigType_str(Getattr(p, "type"), 0); + Append(w->def, str); + Append(declaration, str); + Delete(str); + } } Append(w->def, ")"); @@ -2143,9 +2138,9 @@ public: */ if (!is_void) { if (!(ignored_method && !pure_virtual)) { - String *cres = SwigType_lstr(returntype, "c_result"); - Printf(w->code, "%s;\n", cres); - Delete(cres); + String *cres = SwigType_lstr(returntype, "c_result"); + Printf(w->code, "%s;\n", cres); + Delete(cres); String *pres = NewStringf("SV *%s", Swig_cresult_name()); Wrapper_add_local(w, Swig_cresult_name(), pres); Delete(pres); @@ -2154,14 +2149,14 @@ public: if (ignored_method) { if (!pure_virtual) { - if (!is_void) - Printf(w->code, "return "); - String *super_call = Swig_method_call(super, l); - Printf(w->code, "%s;\n", super_call); - Delete(super_call); + if (!is_void) + Printf(w->code, "return "); + String *super_call = Swig_method_call(super, l); + Printf(w->code, "%s;\n", super_call); + 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)); + Printf(w->code, "Swig::DirectorPureVirtualException::raise(\"Attempted to invoke pure virtual method %s::%s\");\n", SwigType_namestr(c_classname), + SwigType_namestr(name)); } } else { /* attach typemaps to arguments (C/C++ -> Perl) */ @@ -2195,32 +2190,32 @@ public: int outputs = 0; if (!is_void) - outputs++; + outputs++; /* build argument list and type conversion string */ idx = 0; p = l; while (p) { - if (checkAttribute(p, "tmap:in:numinputs", "0")) { - p = Getattr(p, "tmap:in:next"); - continue; - } + if (checkAttribute(p, "tmap:in:numinputs", "0")) { + p = Getattr(p, "tmap:in:next"); + continue; + } - /* old style? caused segfaults without the p!=0 check - in the for() condition, and seems dangerous in the - while loop as well. - while (Getattr(p, "tmap:ignore")) { - p = Getattr(p, "tmap:ignore:next"); - } - */ + /* old style? caused segfaults without the p!=0 check + in the for() condition, and seems dangerous in the + while loop as well. + while (Getattr(p, "tmap:ignore")) { + p = Getattr(p, "tmap:ignore:next"); + } + */ - if (Getattr(p, "tmap:directorargout") != 0) - outputs++; + if (Getattr(p, "tmap:directorargout") != 0) + outputs++; - String *pname = Getattr(p, "name"); - String *ptype = Getattr(p, "type"); + String *pname = Getattr(p, "name"); + String *ptype = Getattr(p, "type"); - if ((tm = Getattr(p, "tmap:directorin")) != 0) { + if ((tm = Getattr(p, "tmap:directorin")) != 0) { sprintf(source, "obj%d", idx++); String *input = NewString(source); Setattr(p, "emit:directorinput", input); @@ -2234,74 +2229,74 @@ public: Printv(wrap_args, tm, "\n", NIL); Putc('O', parse_args); Printv(pstack, "XPUSHs(", source, ");\n", NIL); - p = Getattr(p, "tmap:directorin:next"); - continue; - } else if (Cmp(ptype, "void")) { - /* special handling for pointers to other C++ director classes. - * ideally this would be left to a typemap, but there is currently no - * way to selectively apply the dynamic_cast<> to classes that have - * directors. in other words, the type "SwigDirector_$1_lname" only exists - * for classes with directors. we avoid the problem here by checking - * module.wrap::directormap, but it's not clear how to get a typemap to - * do something similar. perhaps a new default typemap (in addition - * to SWIGTYPE) called DIRECTORTYPE? - */ - if (SwigType_ispointer(ptype) || SwigType_isreference(ptype)) { - Node *module = Getattr(parent, "module"); - Node *target = Swig_directormap(module, ptype); - sprintf(source, "obj%d", idx++); - String *nonconst = 0; - /* strip pointer/reference --- should move to Swig/stype.c */ - String *nptype = NewString(Char(ptype) + 2); - /* name as pointer */ - String *ppname = Copy(pname); - if (SwigType_isreference(ptype)) { - Insert(ppname, 0, "&"); - } - /* if necessary, cast away const since Python doesn't support it! */ - if (SwigType_isconst(nptype)) { - nonconst = NewStringf("nc_tmp_%s", pname); - String *nonconst_i = NewStringf("= const_cast< %s >(%s)", SwigType_lstr(ptype, 0), ppname); - Wrapper_add_localv(w, nonconst, SwigType_lstr(ptype, 0), nonconst, nonconst_i, NIL); - Delete(nonconst_i); - Swig_warning(WARN_LANG_DISCARD_CONST, input_file, line_number, - "Target language argument '%s' discards const in director method %s::%s.\n", - SwigType_str(ptype, pname), SwigType_namestr(c_classname), SwigType_namestr(name)); - } else { - nonconst = Copy(ppname); - } - Delete(nptype); - Delete(ppname); - String *mangle = SwigType_manglestr(ptype); - if (target) { - String *director = NewStringf("director_%s", mangle); - Wrapper_add_localv(w, director, "Swig::Director *", director, "= 0", NIL); - Wrapper_add_localv(w, source, "SV *", source, "= 0", NIL); - Printf(wrap_args, "%s = SWIG_DIRECTOR_CAST(%s);\n", director, nonconst); - Printf(wrap_args, "if (!%s) {\n", director); - Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle); - Append(wrap_args, "} else {\n"); - Printf(wrap_args, "%s = %s->swig_get_self();\n", source, director); - Printf(wrap_args, "SvREFCNT_inc((SV *)%s);\n", source); - Append(wrap_args, "}\n"); - Delete(director); - } else { - Wrapper_add_localv(w, source, "SV *", source, "= 0", NIL); - Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle); - Printf(pstack, "XPUSHs(sv_2mortal(%s));\n", source); - } - Putc('O', parse_args); - Delete(mangle); - Delete(nonconst); - } else { - Swig_warning(WARN_TYPEMAP_DIRECTORIN_UNDEF, input_file, line_number, - "Unable to use type %s as a function argument in director method %s::%s (skipping method).\n", SwigType_str(ptype, 0), - SwigType_namestr(c_classname), SwigType_namestr(name)); - status = SWIG_NOWRAP; - break; - } - } - p = nextSibling(p); + p = Getattr(p, "tmap:directorin:next"); + continue; + } else if (Cmp(ptype, "void")) { + /* special handling for pointers to other C++ director classes. + * ideally this would be left to a typemap, but there is currently no + * way to selectively apply the dynamic_cast<> to classes that have + * directors. in other words, the type "SwigDirector_$1_lname" only exists + * for classes with directors. we avoid the problem here by checking + * module.wrap::directormap, but it's not clear how to get a typemap to + * do something similar. perhaps a new default typemap (in addition + * to SWIGTYPE) called DIRECTORTYPE? + */ + if (SwigType_ispointer(ptype) || SwigType_isreference(ptype)) { + Node *module = Getattr(parent, "module"); + Node *target = Swig_directormap(module, ptype); + sprintf(source, "obj%d", idx++); + String *nonconst = 0; + /* strip pointer/reference --- should move to Swig/stype.c */ + String *nptype = NewString(Char(ptype) + 2); + /* name as pointer */ + String *ppname = Copy(pname); + if (SwigType_isreference(ptype)) { + Insert(ppname, 0, "&"); + } + /* if necessary, cast away const since Python doesn't support it! */ + if (SwigType_isconst(nptype)) { + nonconst = NewStringf("nc_tmp_%s", pname); + String *nonconst_i = NewStringf("= const_cast< %s >(%s)", SwigType_lstr(ptype, 0), ppname); + Wrapper_add_localv(w, nonconst, SwigType_lstr(ptype, 0), nonconst, nonconst_i, NIL); + Delete(nonconst_i); + Swig_warning(WARN_LANG_DISCARD_CONST, input_file, line_number, + "Target language argument '%s' discards const in director method %s::%s.\n", + SwigType_str(ptype, pname), SwigType_namestr(c_classname), SwigType_namestr(name)); + } else { + nonconst = Copy(ppname); + } + Delete(nptype); + Delete(ppname); + String *mangle = SwigType_manglestr(ptype); + if (target) { + String *director = NewStringf("director_%s", mangle); + Wrapper_add_localv(w, director, "Swig::Director *", director, "= 0", NIL); + Wrapper_add_localv(w, source, "SV *", source, "= 0", NIL); + Printf(wrap_args, "%s = SWIG_DIRECTOR_CAST(%s);\n", director, nonconst); + Printf(wrap_args, "if (!%s) {\n", director); + Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle); + Append(wrap_args, "} else {\n"); + Printf(wrap_args, "%s = %s->swig_get_self();\n", source, director); + Printf(wrap_args, "SvREFCNT_inc((SV *)%s);\n", source); + Append(wrap_args, "}\n"); + Delete(director); + } else { + Wrapper_add_localv(w, source, "SV *", source, "= 0", NIL); + Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle); + Printf(pstack, "XPUSHs(sv_2mortal(%s));\n", source); + } + Putc('O', parse_args); + Delete(mangle); + Delete(nonconst); + } else { + Swig_warning(WARN_TYPEMAP_DIRECTORIN_UNDEF, input_file, line_number, + "Unable to use type %s as a function argument in director method %s::%s (skipping method).\n", SwigType_str(ptype, 0), + SwigType_namestr(c_classname), SwigType_namestr(name)); + status = SWIG_NOWRAP; + break; + } + } + p = nextSibling(p); } /* add the method name as a PyString */ @@ -2312,7 +2307,7 @@ public: /* pass the method call on to the Python object */ if (dirprot_mode() && !is_public(n)) { - Printf(w->code, "swig_set_inner(\"%s\", true);\n", name); + Printf(w->code, "swig_set_inner(\"%s\", true);\n", name); } Append(w->code, "ENTER;\n"); @@ -2324,22 +2319,22 @@ public: Printf(w->code, "call_method(\"%s\", G_EVAL | G_SCALAR);\n", pyname); if (dirprot_mode() && !is_public(n)) - Printf(w->code, "swig_set_inner(\"%s\", false);\n", name); + Printf(w->code, "swig_set_inner(\"%s\", false);\n", name); /* 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); + tm = Getattr(n, "feature:director:except"); + if (tm) + tm = Copy(tm); } Append(w->code, "if (SvTRUE(ERRSV)) {\n"); Append(w->code, " PUTBACK;\n FREETMPS;\n LEAVE;\n"); if ((tm) && Len(tm) && (Strcmp(tm, "1") != 0)) { - Replaceall(tm, "$error", "ERRSV"); - Printv(w->code, Str(tm), "\n", NIL); + 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", classname, pyname); } Append(w->code, "}\n"); Delete(tm); @@ -2357,62 +2352,62 @@ public: String *outarg = NewString(""); if (outputs > 1) { - Wrapper_add_local(w, "output", "SV *output"); - Printf(w->code, "if (count != %d) {\n", outputs); - Printf(w->code, " Swig::DirectorTypeMismatchException::raise(\"Perl method %s.%sfailed to return a list.\");\n", classname, pyname); - Append(w->code, "}\n"); + Wrapper_add_local(w, "output", "SV *output"); + Printf(w->code, "if (count != %d) {\n", outputs); + Printf(w->code, " Swig::DirectorTypeMismatchException::raise(\"Perl method %s.%sfailed to return a list.\");\n", classname, pyname); + Append(w->code, "}\n"); } idx = 0; /* marshal return value */ if (!is_void) { - Append(w->code, "SPAGAIN;\n"); + Append(w->code, "SPAGAIN;\n"); Printf(w->code, "%s = POPs;\n", Swig_cresult_name()); - tm = Swig_typemap_lookup("directorout", n, Swig_cresult_name(), w); - if (tm != 0) { - if (outputs > 1) { - Printf(w->code, "output = POPs;\n"); - Replaceall(tm, "$input", "output"); - } else { - Replaceall(tm, "$input", Swig_cresult_name()); - } - char temp[24]; - sprintf(temp, "%d", idx); - Replaceall(tm, "$argnum", temp); + tm = Swig_typemap_lookup("directorout", n, Swig_cresult_name(), w); + if (tm != 0) { + if (outputs > 1) { + Printf(w->code, "output = POPs;\n"); + Replaceall(tm, "$input", "output"); + } else { + Replaceall(tm, "$input", Swig_cresult_name()); + } + char temp[24]; + sprintf(temp, "%d", idx); + Replaceall(tm, "$argnum", temp); - /* TODO check this */ - if (Getattr(n, "wrap:disown")) { - Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); - } else { - Replaceall(tm, "$disown", "0"); - } - Replaceall(tm, "$result", "c_result"); - Printv(w->code, tm, "\n", NIL); - 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)); - status = SWIG_ERROR; - } + /* TODO check this */ + if (Getattr(n, "wrap:disown")) { + Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); + } else { + Replaceall(tm, "$disown", "0"); + } + Replaceall(tm, "$result", "c_result"); + Printv(w->code, tm, "\n", NIL); + 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)); + status = SWIG_ERROR; + } } /* marshal outputs */ for (p = l; p;) { - if ((tm = Getattr(p, "tmap:directorargout")) != 0) { - if (outputs > 1) { - Printf(w->code, "output = POPs;\n"); - Replaceall(tm, "$result", "output"); - } else { - Replaceall(tm, "$result", Swig_cresult_name()); - } - Replaceall(tm, "$input", Getattr(p, "emit:directorinput")); - Printv(w->code, tm, "\n", NIL); - p = Getattr(p, "tmap:directorargout:next"); - } else { - p = nextSibling(p); - } + if ((tm = Getattr(p, "tmap:directorargout")) != 0) { + if (outputs > 1) { + Printf(w->code, "output = POPs;\n"); + Replaceall(tm, "$result", "output"); + } else { + Replaceall(tm, "$result", Swig_cresult_name()); + } + Replaceall(tm, "$input", Getattr(p, "emit:directorinput")); + Printv(w->code, tm, "\n", NIL); + p = Getattr(p, "tmap:directorargout:next"); + } else { + p = nextSibling(p); + } } Delete(parse_args); @@ -2428,13 +2423,13 @@ public: if (!is_void) { if (!(ignored_method && !pure_virtual)) { - String *rettype = SwigType_str(returntype, 0); - if (!SwigType_isreference(returntype)) { - Printf(w->code, "return (%s) c_result;\n", rettype); - } else { - Printf(w->code, "return (%s) *c_result;\n", rettype); - } - Delete(rettype); + String *rettype = SwigType_str(returntype, 0); + if (!SwigType_isreference(returntype)) { + Printf(w->code, "return (%s) c_result;\n", rettype); + } else { + Printf(w->code, "return (%s) *c_result;\n", rettype); + } + Delete(rettype); } } @@ -2448,7 +2443,7 @@ public: Replaceall(inline_extra_method, name, extra_method_name); Replaceall(inline_extra_method, ";\n", " {\n "); if (!is_void) - Printf(inline_extra_method, "return "); + Printf(inline_extra_method, "return "); String *methodcall = Swig_method_call(super, l); Printv(inline_extra_method, methodcall, ";\n }\n", NIL); Delete(methodcall); @@ -2458,10 +2453,10 @@ public: /* emit the director method */ if (status == SWIG_OK) { if (!Getattr(n, "defaultargs")) { - Replaceall(w->code, "$symname", symname); - Wrapper_print(w, f_directors); - Printv(f_directors_h, declaration, NIL); - Printv(f_directors_h, inline_extra_method, NIL); + Replaceall(w->code, "$symname", symname); + Wrapper_print(w, f_directors); + Printv(f_directors_h, declaration, NIL); + Printv(f_directors_h, inline_extra_method, NIL); } } @@ -2476,7 +2471,7 @@ public: member_func = 1; rv = Language::classDirectorDisown(n); member_func = 0; - if(rv == SWIG_OK && Swig_directorclass(n)) { + if (rv == SWIG_OK && Swig_directorclass(n)) { String *symname = Getattr(n, "sym:name"); String *disown = Swig_name_disown(NSPACE_TODO, symname); Setattr(n, "perl5:directordisown", NewStringf("%s::%s", cmodule, disown)); From 81ce0a723e151e570c7990fb9a0ccef3976f0c81 Mon Sep 17 00:00:00 2001 From: Robert Stone Date: Thu, 14 Nov 2013 11:19:11 -0800 Subject: [PATCH 198/481] fix "long long" tests for perl v5.6 --- Examples/test-suite/perl5/li_typemaps_runme.pl | 18 +++++++++++------- .../perl5/reference_global_vars_runme.pl | 11 ++++++----- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/Examples/test-suite/perl5/li_typemaps_runme.pl b/Examples/test-suite/perl5/li_typemaps_runme.pl index c182cdbb1..a573b89a0 100644 --- a/Examples/test-suite/perl5/li_typemaps_runme.pl +++ b/Examples/test-suite/perl5/li_typemaps_runme.pl @@ -41,8 +41,8 @@ batch('schar', -0x80, 0, 1, 12, 0x7f); use Math::BigInt qw(); # the pack dance is to get plain old NVs out of the # Math::BigInt objects. - my $inf = unpack 'd', pack 'd', Math::BigInt->binf(); - my $nan = unpack 'd', pack 'd', Math::BigInt->bnan(); + my $inf = unpack 'd', pack 'd', Math::BigInt->new('Inf'); + my $nan = unpack 'd', pack 'd', Math::BigInt->new('NaN'); batch('float', -(2 - 2 ** -23) * 2 ** 127, -1, -2 ** -149, 0, 2 ** -149, 1, @@ -63,12 +63,16 @@ batch('schar', -0x80, 0, 1, 12, 0x7f); batch('longlong', -1, 0, 1, 12); batch('ulonglong', 0, 1, 12); SKIP: { - my $a = "8000000000000000"; - my $b = "7fffffffffffffff"; - my $c = "ffffffffffffffff"; + use Math::BigInt qw(); skip "not a 64bit Perl", 18 unless eval { pack 'q', 1 }; - batch('longlong', -hex($a), hex($b)); - batch('ulonglong', hex($c)); + my $a = unpack 'q', pack 'q', + Math::BigInt->new('-9223372036854775808'); + my $b = unpack 'q', pack 'q', + Math::BigInt->new('9223372036854775807'); + my $c = unpack 'Q', pack 'Q', + Math::BigInt->new('18446744073709551615'); + batch('longlong', $a, $b); + batch('ulonglong', $c); } my($foo, $int) = li_typemaps::out_foo(10); diff --git a/Examples/test-suite/perl5/reference_global_vars_runme.pl b/Examples/test-suite/perl5/reference_global_vars_runme.pl index dfbcf15bb..89d73b03d 100755 --- a/Examples/test-suite/perl5/reference_global_vars_runme.pl +++ b/Examples/test-suite/perl5/reference_global_vars_runme.pl @@ -53,12 +53,13 @@ $cvar->{var_unsigned_long} = createref_unsigned_long(10); is(value_unsigned_long($cvar->{var_unsigned_long}), 10); SKIP: { - my $a = "6FFFFFFFFFFFFFF8"; + use Math::BigInt qw(); skip "64 bit int support", 1 unless eval { pack 'q', 1 }; - # using hex() here instead of a literal because non 64bit Perls will - # be noisy about big constants. - $cvar->{var_long_long} = createref_long_long(hex $a); - is(value_long_long($cvar->{var_long_long}), hex $a); + # the pack dance is to get plain old IVs out of the + # Math::BigInt objects. + my $a = unpack 'q', pack 'q', Math::BigInt->new('8070450532247928824'); + $cvar->{var_long_long} = createref_long_long($a); + is(value_long_long($cvar->{var_long_long}), $a); } #ull = abs(0xFFFFFFF2FFFFFFF0) From 16d40c14f946055f7516697091c5758cba9de883 Mon Sep 17 00:00:00 2001 From: Robert Stone Date: Fri, 15 Nov 2013 10:49:34 -0800 Subject: [PATCH 199/481] try adding travis ci to this branch --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 26758304f..0a3aa1893 100644 --- a/.travis.yml +++ b/.travis.yml @@ -56,3 +56,4 @@ script: branches: only: - master + - perl5-directors-minimal From e566c5fa7f4b8af527c9f13f6eabd84bfc38a897 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 16 Nov 2013 00:13:38 +0000 Subject: [PATCH 200/481] Add support for parsing C++11 =delete and =default Although this was documented as working, it wasn't implemented %typemap(default) failed without the idstring changes Add some C tests using the C++ keyword delete --- Doc/Manual/CPlusPlus11.html | 22 +++++--- Examples/test-suite/c_delete.i | 14 +++++ Examples/test-suite/c_delete_function.i | 7 +++ Examples/test-suite/common.mk | 2 + Examples/test-suite/cpp11_default_delete.i | 64 ++++++++++++++++++--- Source/CParse/cscanner.c | 3 + Source/CParse/parser.y | 66 ++++++++++++++++++++-- Source/Modules/allocate.cxx | 26 ++++++--- 8 files changed, 173 insertions(+), 31 deletions(-) create mode 100644 Examples/test-suite/c_delete.i create mode 100644 Examples/test-suite/c_delete_function.i diff --git a/Doc/Manual/CPlusPlus11.html b/Doc/Manual/CPlusPlus11.html index 3caec748e..95d748791 100644 --- a/Doc/Manual/CPlusPlus11.html +++ b/Doc/Manual/CPlusPlus11.html @@ -33,7 +33,7 @@
  • New string literals
  • User-defined literals
  • Thread-local storage -
  • Defaulting/deleting of standard functions on C++ objects +
  • Defaulting/deleting of standard functions on C++ objects
  • Type long long int
  • Static assertions
  • Allow sizeof to work on members of classes without an explicit object @@ -739,23 +739,27 @@ A variable will be thread local if accessed from different threads from the targ same way that it will be thread local if accessed from C++ code.

    -

    7.2.21 Defaulting/deleting of standard functions on C++ objects

    +

    7.2.21 Explicitly defaulted functions and deleted functions

    -

    SWIG correctly parses the = delete and = default -keywords. For example:

    +

    SWIG handles explicitly defaulted functions, that is, = default added to a function declaration. Deleted definitions, which are also called deleted functions, have = delete added to the function declaration. +For example:

     struct NonCopyable {
       NonCopyable& operator=(const NonCopyable&) = delete; /* Removes operator= */
    -  NonCopyable(const NonCopyable&) = delete;            /* Removed copy constructor */
    -  NonCopyable() = default;                             /* Explicitly allows the empty constructor */
    -  void *operator new(std::size_t) = delete;            /* Removes new NonCopyable */
    +  NonCopyable(const NonCopyable&) = delete;                /* Removed copy constructor */
    +  NonCopyable() = default;                                     /* Explicitly allows the empty constructor */
    +  void *operator new(std::size_t) = delete;                    /* Removes new NonCopyable */
     };
     
    -

    This feature is specific to C++ only. The defaulting/deleting is currently ignored, because SWIG -automatically produces wrappers for special constructors and operators specific to the target language.

    +

    +Wrappers for deleted functions will not be available in the target language. +Wrappers for defaulted functions will of course be available in the target language. +Explicitly defaulted functions have no direct effect for SWIG wrapping as the declaration is handled +much like any other method declaration parsed by SWIG. +

    7.2.22 Type long long int

    diff --git a/Examples/test-suite/c_delete.i b/Examples/test-suite/c_delete.i new file mode 100644 index 000000000..d47032095 --- /dev/null +++ b/Examples/test-suite/c_delete.i @@ -0,0 +1,14 @@ +%module c_delete + +/* check C++ delete keyword is okay in C wrappers */ + +%inline %{ +struct delete { + int delete; +}; +%} + +%rename(DeleteGlobalVariable) delete; +%inline %{ +int delete = 0; +%} diff --git a/Examples/test-suite/c_delete_function.i b/Examples/test-suite/c_delete_function.i new file mode 100644 index 000000000..e1fba7495 --- /dev/null +++ b/Examples/test-suite/c_delete_function.i @@ -0,0 +1,7 @@ +%module c_delete_function + +/* check C++ delete keyword is okay in C wrappers */ + +%inline %{ +double delete(double d) { return d; } +%} diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index e25d36715..0d360830d 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -552,6 +552,8 @@ endif C_TEST_CASES += \ arrays \ bom_utf8 \ + c_delete \ + c_delete_function \ char_constant \ const_const \ constant_expr \ diff --git a/Examples/test-suite/cpp11_default_delete.i b/Examples/test-suite/cpp11_default_delete.i index be4cc6cc9..49a677060 100644 --- a/Examples/test-suite/cpp11_default_delete.i +++ b/Examples/test-suite/cpp11_default_delete.i @@ -1,9 +1,12 @@ -/* This testcase checks whether SWIG correctly parses the default and delete - keywords which keep or remove default C++ object construction functions. */ +/* This testcase checks whether SWIG correctly parses C++11 explicitly defaulted functions and deleted functions */ %module cpp11_default_delete -%{ -#include +%warnfilter(SWIGWARN_LANG_OVERLOAD_IGNORED, SWIGWARN_LANG_OVERLOAD_SHADOW) trivial::trivial(trivial&&); +%warnfilter(SWIGWARN_LANG_OVERLOAD_IGNORED, SWIGWARN_LANG_OVERLOAD_SHADOW) trivial::operator =(trivial&&); + +%rename(Assignment) *::operator=; + +%inline %{ class NonCopyable { public: @@ -14,11 +17,56 @@ public: }; struct A1 { - void f(int i); - void f(double i) = delete; /* Don't cast double to int. Compiler returns an error */ + void func(int i) {} + A1() = default; + ~A1() = default; + void func(double i) = delete; /* Don't cast double to int. Compiler returns an error */ +private: + A1(const A1&); }; +A1::A1(const A1&) = default; + struct A2 { - void f(int i); - template void f(T) = delete; /* Only accept int */ + void func(int i) {} + virtual void fff(int) = delete; + virtual ~A2() = default; + template void func(T) = delete; +}; + +struct trivial { + trivial() = default; + trivial(const trivial&) = default; + trivial(trivial&&) = default; + trivial& operator=(const trivial&) = default; + trivial& operator=(trivial&&) = default; + ~trivial() = default; +}; + +struct nontrivial1 { + nontrivial1(); +}; +nontrivial1::nontrivial1() = default; + +struct sometype { + sometype() = delete; + sometype(int) = delete; + sometype(double); +}; +sometype::sometype(double) {} + +/* Not working with prerelease of gcc-4.8 +struct nonew { + void *operator new(std::size_t) = delete; + void *operator new[](std::size_t) = delete; +}; +*/ + +struct moveonly { + moveonly() = default; + moveonly(const moveonly&) = delete; + moveonly(moveonly&&) = default; + moveonly& operator=(const moveonly&) = delete; + moveonly& operator=(moveonly&&) = default; + ~moveonly() = default; }; %} diff --git a/Source/CParse/cscanner.c b/Source/CParse/cscanner.c index e91dfb3d3..8b484f8a7 100644 --- a/Source/CParse/cscanner.c +++ b/Source/CParse/cscanner.c @@ -728,6 +728,9 @@ int yylex(void) { if (strcmp(yytext, "delete") == 0) { return (DELETE_KW); } + if (strcmp(yytext, "default") == 0) { + return (DEFAULT); + } if (strcmp(yytext, "using") == 0) { return (USING); } diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index ce0c91c43..1328d6e0d 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -447,6 +447,14 @@ static void add_symbols(Node *n) { n = nextSibling(n); continue; } + if (cparse_cplusplus) { + String *value = Getattr(n, "value"); + if (value && Strcmp(value, "delete") == 0) { + /* C++11 deleted definition / deleted function */ + SetFlag(n,"deleted"); + SetFlag(n,"feature:ignore"); + } + } if (only_csymbol || GetFlag(n,"feature:ignore")) { /* Only add to C symbol table and continue */ Swig_symbol_add(0, n); @@ -1715,7 +1723,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %token NATIVE INLINE %token TYPEMAP EXCEPT ECHO APPLY CLEAR SWIGTEMPLATE FRAGMENT %token WARN -%token LESSTHAN GREATERTHAN DELETE_KW +%token LESSTHAN GREATERTHAN DELETE_KW DEFAULT %token LESSTHANOREQUALTO GREATERTHANOREQUALTO EQUALTO NOTEQUALTO %token ARROW %token QUESTIONMARK @@ -1775,7 +1783,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %type ellipsis variadic; %type type rawtype type_right anon_bitfield_type decltype ; %type base_list inherit raw_inherit; -%type definetype def_args etype; +%type definetype def_args etype default_delete deleted_definition explicit_default; %type expr exprnum exprcompound valexpr; %type ename ; %type template_decl; @@ -4696,6 +4704,8 @@ cpp_constructor_decl : storage_class type LPAREN parms RPAREN ctor_end { Delete(code); } SetFlag($$,"feature:new"); + if ($6.defarg) + Setattr($$,"value",$6.defarg); } else { $$ = 0; } @@ -4723,6 +4733,8 @@ cpp_destructor_decl : NOT idtemplate LPAREN parms RPAREN cpp_end { } Setattr($$,"throws",$6.throws); Setattr($$,"throw",$6.throwf); + if ($6.val) + Setattr($$,"value",$6.val); add_symbols($$); } @@ -4738,9 +4750,8 @@ cpp_destructor_decl : NOT idtemplate LPAREN parms RPAREN cpp_end { Delete(name); Setattr($$,"throws",$7.throws); Setattr($$,"throw",$7.throwf); - if ($7.val) { - Setattr($$,"value","0"); - } + if ($7.val) + Setattr($$,"value",$7.val); if (Len(scanner_ccode)) { String *code = Copy(scanner_ccode); Setattr($$,"code",code); @@ -4982,11 +4993,19 @@ cpp_swig_directive: pragma_directive { $$ = $1; } cpp_end : cpp_const SEMI { Clear(scanner_ccode); + $$.val = 0; + $$.throws = $1.throws; + $$.throwf = $1.throwf; + } + | cpp_const EQUAL default_delete SEMI { + Clear(scanner_ccode); + $$.val = $3.val; $$.throws = $1.throws; $$.throwf = $1.throwf; } | cpp_const LBRACE { skip_balanced('{','}'); + $$.val = 0; $$.throws = $1.throws; $$.throwf = $1.throwf; } @@ -6143,11 +6162,15 @@ definetype : { /* scanner_check_typedef(); */ } expr { } else if ($$.type != T_CHAR && $$.type != T_WSTRING && $$.type != T_WCHAR) { $$.rawval = 0; } + $$.qualifier = 0; $$.bitfield = 0; $$.throws = 0; $$.throwf = 0; scanner_ignore_typedef(); } + | default_delete { + $$ = $1; + } /* | string { $$.val = NewString($1); @@ -6160,6 +6183,38 @@ definetype : { /* scanner_check_typedef(); */ } expr { */ ; +default_delete : deleted_definition { + $$ = $1; + } + | explicit_default { + $$ = $1; + } + ; + +/* For C++ deleted definition '= delete' */ +deleted_definition : DELETE_KW { + $$.val = NewString("delete"); + $$.rawval = 0; + $$.type = T_STRING; + $$.qualifier = 0; + $$.bitfield = 0; + $$.throws = 0; + $$.throwf = 0; + } + ; + +/* For C++ explicitly defaulted functions '= default' */ +explicit_default : DEFAULT { + $$.val = NewString("default"); + $$.rawval = 0; + $$.type = T_STRING; + $$.qualifier = 0; + $$.bitfield = 0; + $$.throws = 0; + $$.throwf = 0; + } + ; + /* Some stuff for handling enums */ ename : ID { $$ = $1; } @@ -6711,6 +6766,7 @@ template_decl : LESSTHAN valparms GREATERTHAN { ; idstring : ID { $$ = $1; } + | default_delete { $$ = $1.val; } | string { $$ = $1; } ; diff --git a/Source/Modules/allocate.cxx b/Source/Modules/allocate.cxx index dee044bf3..b7daae59c 100644 --- a/Source/Modules/allocate.cxx +++ b/Source/Modules/allocate.cxx @@ -659,7 +659,7 @@ Allocate(): } if (!Getattr(n, "allocate:has_destructor")) { - /* No destructor was defined. We need to check a few things here too */ + /* No destructor was defined */ List *bases = Getattr(n, "allbases"); int allows_destruct = 1; @@ -676,13 +676,13 @@ Allocate(): } if (!Getattr(n, "allocate:has_assign")) { - /* No destructor was defined. We need to check a few things here too */ + /* No assignment operator was defined */ List *bases = Getattr(n, "allbases"); int allows_assign = 1; for (int i = 0; i < Len(bases); i++) { Node *n = Getitem(bases, i); - /* If base class does not allow default destructor, we don't allow it either */ + /* If base class does not allow assignment, we don't allow it either */ if (Getattr(n, "allocate:has_assign")) { allows_assign = !Getattr(n, "allocate:noassign"); } @@ -693,13 +693,13 @@ Allocate(): } if (!Getattr(n, "allocate:has_new")) { - /* No destructor was defined. We need to check a few things here too */ + /* No new operator was defined */ List *bases = Getattr(n, "allbases"); int allows_new = 1; for (int i = 0; i < Len(bases); i++) { Node *n = Getitem(bases, i); - /* If base class does not allow default destructor, we don't allow it either */ + /* If base class does not allow new operator, we don't allow it either */ if (Getattr(n, "allocate:has_new")) { allows_new = !Getattr(n, "allocate:nonew"); } @@ -779,18 +779,26 @@ Allocate(): if (cplus_mode != PUBLIC) { if (Strcmp(name, "operator =") == 0) { /* Look for a private assignment operator */ - Setattr(inclass, "allocate:has_assign", "1"); + if (!GetFlag(n, "deleted")) + Setattr(inclass, "allocate:has_assign", "1"); Setattr(inclass, "allocate:noassign", "1"); } else if (Strcmp(name, "operator new") == 0) { /* Look for a private new operator */ - Setattr(inclass, "allocate:has_new", "1"); + if (!GetFlag(n, "deleted")) + Setattr(inclass, "allocate:has_new", "1"); Setattr(inclass, "allocate:nonew", "1"); } } else { if (Strcmp(name, "operator =") == 0) { - Setattr(inclass, "allocate:has_assign", "1"); + if (!GetFlag(n, "deleted")) + Setattr(inclass, "allocate:has_assign", "1"); + else + Setattr(inclass, "allocate:noassign", "1"); } else if (Strcmp(name, "operator new") == 0) { - Setattr(inclass, "allocate:has_new", "1"); + if (!GetFlag(n, "deleted")) + Setattr(inclass, "allocate:has_new", "1"); + else + Setattr(inclass, "allocate:nonew", "1"); } /* Look for smart pointer operator */ if ((Strcmp(name, "operator ->") == 0) && (!GetFlag(n, "feature:ignore"))) { From 7a8dd4bb2d9b34f511596940f2721c1257fccc6b Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Wed, 20 Nov 2013 22:24:13 +0000 Subject: [PATCH 201/481] Correct html references --- Doc/Manual/CPlusPlus11.html | 144 ++++++++++++++++++------------------ 1 file changed, 73 insertions(+), 71 deletions(-) diff --git a/Doc/Manual/CPlusPlus11.html b/Doc/Manual/CPlusPlus11.html index 95d748791..30b88d6fa 100644 --- a/Doc/Manual/CPlusPlus11.html +++ b/Doc/Manual/CPlusPlus11.html @@ -10,45 +10,45 @@
    @@ -56,7 +56,7 @@ -

    7.1 Introduction

    +

    7.1 Introduction

    This chapter gives you a brief overview about the SWIG @@ -68,10 +68,10 @@ Google Summer of Code 2009 period.

    new STL types (unordered_ containers, result_of, tuples) are not supported yet.

    -

    7.2 Core language changes

    +

    7.2 Core language changes

    -

    7.2.1 Rvalue reference and move semantics

    +

    7.2.1 Rvalue reference and move semantics

    SWIG correctly parses the new operator && the same as the reference operator &.

    @@ -87,7 +87,7 @@ class MyClass { }; -

    7.2.2 Generalized constant expressions

    +

    7.2.2 Generalized constant expressions

    SWIG correctly parses the keyword constexpr, but ignores its functionality. Constant functions cannot be used as constants.

    @@ -105,7 +105,7 @@ constexpr int myConstFunc() { return MY_CONST; } const int a = MY_CONST; // ok -

    7.2.3 Extern template

    +

    7.2.3 Extern template

    SWIG correctly parses the keywords extern template. However, the explicit template instantiation is not used by SWIG, a %template is still required.

    @@ -123,7 +123,8 @@ public: }; -

    7.2.4 Initializer lists

    +

    7.2.4 Initializer lists

    +

    Initializer lists are very much a C++ compiler construct and are not very accessible from wrappers as @@ -254,7 +255,7 @@ Note that the default typemap for std::initializer_list does nothing bu and hence any user supplied typemaps will override it and suppress the warning.

    -

    7.2.5 Uniform initialization

    +

    7.2.5 Uniform initialization

    The curly brackets {} for member initialization are fully @@ -287,7 +288,7 @@ AltStruct var2{2, 4.3}; // calls the constructor 142.15 -

    7.2.6 Type inference

    +

    7.2.6 Type inference

    SWIG supports decltype() with some limitations. Single @@ -304,13 +305,13 @@ int i; int j; decltype(i+j) k; // syntax error -

    7.2.7 Range-based for-loop

    +

    7.2.7 Range-based for-loop

    This feature is part of the implementation block only. SWIG ignores it.

    -

    7.2.8 Lambda functions and expressions

    +

    7.2.8 Lambda functions and expressions

    SWIG correctly parses most of the Lambda functions syntax. For example:

    @@ -336,7 +337,7 @@ auto six = [](int x, int y) { return x+y; }(4, 2); Better support should be available in a later release.

    -

    7.2.9 Alternate function syntax

    +

    7.2.9 Alternate function syntax

    SWIG fully supports the new definition of functions. For example:

    @@ -371,7 +372,7 @@ auto SomeStruct::FuncName(int x, int y) -> int { auto square(float a, float b) -> decltype(a); -

    7.2.10 Object construction improvement

    +

    7.2.10 Object construction improvement

    @@ -412,12 +413,12 @@ class DerivedClass: public BaseClass { }; -

    7.2.11 Null pointer constant

    +

    7.2.11 Null pointer constant

    The nullptr constant is largely unimportant in wrappers. In the few places it has an effect, it is treated like NULL.

    -

    7.2.12 Strongly typed enumerations

    +

    7.2.12 Strongly typed enumerations

    SWIG parses the new enum class syntax and forward declarator for the enums:

    @@ -468,7 +469,7 @@ class AllColors { }; -

    7.2.13 Double angle brackets

    +

    7.2.13 Double angle brackets

    SWIG correctly parses the symbols >> as closing the @@ -479,7 +480,7 @@ shift operator >> otherwise.

    std::vector<std::vector<int>> myIntTable; -

    7.2.14 Explicit conversion operators

    +

    7.2.14 Explicit conversion operators

    SWIG correctly parses the keyword explicit both for operators and constructors. @@ -515,7 +516,8 @@ SWIG target languages, because all use their own facilities (eg. classes Cloneab to achieve particular copy and compare behaviours.

    -

    7.2.15 Alias templates

    +

    7.2.15 Alias templates

    +

    The following is an example of an alias template: @@ -567,7 +569,7 @@ example.i:17: Warning 341: The 'using' keyword in type aliasing is not fully sup typedef void (*PFD)(double); // The old style -

    7.2.16 Unrestricted unions

    +

    7.2.16 Unrestricted unions

    SWIG fully supports any type inside a union even if it does not @@ -593,7 +595,7 @@ union P { } p1; -

    7.2.17 Variadic templates

    +

    7.2.17 Variadic templates

    SWIG supports the variadic templates syntax (inside the <> @@ -628,7 +630,7 @@ const int SIZE = sizeof...(ClassName<int, int>); In the above example SIZE is of course wrapped as a constant.

    -

    7.2.18 New string literals

    +

    7.2.18 New string literals

    SWIG supports unicode string constants and raw string literals.

    @@ -652,7 +654,7 @@ const char32_t *ii = UR"XXX(I'm a "raw UTF-32" \ string.)XXX";

    Note: SWIG currently incorrectly parses the odd number of double quotes inside the string due to SWIG's C++ preprocessor.

    -

    7.2.19 User-defined literals

    +

    7.2.19 User-defined literals

    @@ -719,7 +721,7 @@ OutputType var2 = 1234_suffix; OutputType var3 = 3.1416_suffix; -

    7.2.20 Thread-local storage

    +

    7.2.20 Thread-local storage

    SWIG correctly parses the thread_local keyword. For example, variable @@ -761,12 +763,12 @@ Explicitly defaulted functions have no direct effect for SWIG wrapping as the de much like any other method declaration parsed by SWIG.

    -

    7.2.22 Type long long int

    +

    7.2.22 Type long long int

    SWIG correctly parses and uses the new long long type already introduced in C99 some time ago.

    -

    7.2.23 Static assertions

    +

    7.2.23 Static assertions

    SWIG correctly parses and calls the new static_assert function.

    @@ -778,7 +780,7 @@ struct Check { }; -

    7.2.24 Allow sizeof to work on members of classes without an explicit object

    +

    7.2.24 Allow sizeof to work on members of classes without an explicit object

    SWIG correctly calls the sizeof() on types as well as on the @@ -798,28 +800,28 @@ const int SIZE = sizeof(A::member); // does not work with C++03. Okay with C++11 8 -

    7.3 Standard library changes

    +

    7.3 Standard library changes

    -

    7.3.1 Threading facilities

    +

    7.3.1 Threading facilities

    SWIG does not currently wrap or use any of the new threading classes introduced (thread, mutex, locks, condition variables, task). The main reason is that SWIG target languages offer their own threading facilities that do not rely on C++.

    -

    7.3.2 Tuple types and hash tables

    +

    7.3.2 Tuple types and hash tables

    SWIG does not wrap the new tuple types and the unordered_ container classes yet. Variadic template support is working so it is possible to include the tuple header file; it is parsed without any problems.

    -

    7.3.3 Regular expressions

    +

    7.3.3 Regular expressions

    SWIG does not wrap the new C++11 regular expressions classes, because the SWIG target languages use their own facilities for this.

    -

    7.3.4 General-purpose smart pointers

    +

    7.3.4 General-purpose smart pointers

    @@ -827,12 +829,12 @@ SWIG provides special smart pointer handling for std::tr1::shared_ptr i There is no special smart pointer handling available for std::weak_ptr and std::unique_ptr.

    -

    7.3.5 Extensible random number facility

    +

    7.3.5 Extensible random number facility

    This feature extends and standardizes the standard library only and does not effect the C++ language and SWIG.

    -

    7.3.6 Wrapper reference

    +

    7.3.6 Wrapper reference

    The new ref and cref classes are used to instantiate a parameter as a reference of a template function. For example:

    @@ -857,7 +859,7 @@ int main() {

    The ref and cref classes are not wrapped by SWIG because the SWIG target languages do not support referencing.

    -

    7.3.7 Polymorphous wrappers for function objects

    +

    7.3.7 Polymorphous wrappers for function objects

    @@ -888,7 +890,7 @@ t = Test() b = t(1,2) # invoke C++ function object -

    7.3.8 Type traits for metaprogramming

    +

    7.3.8 Type traits for metaprogramming

    The new C++ metaprogramming is useful at compile time and is aimed specifically for C++ development:

    @@ -913,7 +915,7 @@ template< class T1, class T2 > int elaborate( T1 A, T2 B ) {

    SWIG correctly parses the template specialization, template types and values inside the <> block and the new helper functions: is_convertible, is_integral, is_const etc. However, SWIG still explicitly requires concrete types when using the %template directive, so the C++ metaprogramming features are not really of interest at runtime in the target languages.

    -

    7.3.9 Uniform method for computing return type of function objects

    +

    7.3.9 Uniform method for computing return type of function objects

    SWIG does not wrap the new result_of class introduced in the <functional> header and map the result_of::type to the concrete type yet. For example:

    From cdefaaf794398655de5e93c4aa9f20fdb01e2283 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 21 Nov 2013 20:20:34 +0000 Subject: [PATCH 202/481] Fixes for c_delete and c_delete_function tests --- Examples/test-suite/c_delete.i | 6 ++++++ Examples/test-suite/c_delete_function.i | 4 ++++ Lib/csharp/csharpkw.swg | 3 +++ 3 files changed, 13 insertions(+) diff --git a/Examples/test-suite/c_delete.i b/Examples/test-suite/c_delete.i index d47032095..632340629 100644 --- a/Examples/test-suite/c_delete.i +++ b/Examples/test-suite/c_delete.i @@ -2,6 +2,10 @@ /* check C++ delete keyword is okay in C wrappers */ +#pragma SWIG nowarn=SWIGWARN_PARSE_KEYWORD + +#if !defined(SWIGOCTAVE) /* Octave compiles wrappers as C++ */ + %inline %{ struct delete { int delete; @@ -12,3 +16,5 @@ struct delete { %inline %{ int delete = 0; %} + +#endif diff --git a/Examples/test-suite/c_delete_function.i b/Examples/test-suite/c_delete_function.i index e1fba7495..3739ceadc 100644 --- a/Examples/test-suite/c_delete_function.i +++ b/Examples/test-suite/c_delete_function.i @@ -2,6 +2,10 @@ /* check C++ delete keyword is okay in C wrappers */ +#if !defined(SWIGOCTAVE) /* Octave compiles wrappers as C++ */ + %inline %{ double delete(double d) { return d; } %} + +#endif diff --git a/Lib/csharp/csharpkw.swg b/Lib/csharp/csharpkw.swg index 9a6d979f1..43ca5993b 100644 --- a/Lib/csharp/csharpkw.swg +++ b/Lib/csharp/csharpkw.swg @@ -4,6 +4,8 @@ /* Warnings for C# keywords */ #define CSHARPKW(x) %keywordwarn("'" `x` "' is a C# keyword, renaming to '_" `x` "'",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` + /* from http://www.jaggersoft.com/csharp_grammar.html#1.7%20Keywords @@ -88,6 +90,7 @@ CSHARPKW(void); CSHARPKW(volatile); CSHARPKW(while); +CSHARPCLASSKW(delete); #undef CSHARPKW From f4ada30a7e6f0b15ed4a1446675980b6df15b631 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 21 Nov 2013 19:31:59 +0000 Subject: [PATCH 203/481] Add support for C++11 noexcept specification in exception specifications --- Doc/Manual/CPlusPlus11.html | 23 +++++- Examples/test-suite/common.mk | 1 + Examples/test-suite/cpp11_noexcept.i | 48 +++++++++++++ Source/CParse/cscanner.c | 2 + Source/CParse/parser.y | 104 ++++++++++++++++++++------- 5 files changed, 151 insertions(+), 27 deletions(-) create mode 100644 Examples/test-suite/cpp11_noexcept.i diff --git a/Doc/Manual/CPlusPlus11.html b/Doc/Manual/CPlusPlus11.html index 30b88d6fa..0d2f22aff 100644 --- a/Doc/Manual/CPlusPlus11.html +++ b/Doc/Manual/CPlusPlus11.html @@ -37,6 +37,7 @@
  • Type long long int
  • Static assertions
  • Allow sizeof to work on members of classes without an explicit object +
  • Exception specifications and noexcept
  • Standard library changes
      @@ -583,7 +584,7 @@ struct point { int x_, y_; }; -#include // For placement 'new' in the constructor below +#include <new> // For placement 'new' in the constructor below union P { int z; double w; @@ -800,6 +801,23 @@ const int SIZE = sizeof(A::member); // does not work with C++03. Okay with C++11 8 +

      7.2.25 Exception specifications and noexcept

      + + +

      +C++11 added in the noexcept specification to exception specifications to indicate that a function simply may or may not throw an exception, without actually naming any exception. +SWIG understands these, although there isn't any useful way that this information can be taken advantage of by target languages, +so it is as good as ignored during the wrapping process. +Below are some examples of noexcept in function declarations: +

      + +
      +static void noex1() noexcept;
      +int noex2(int) noexcept(true);
      +int noex3(int, bool) noexcept(false);
      +
      + +

      7.3 Standard library changes

      @@ -885,7 +903,7 @@ Example of supported usage of the plain functor from Python is shown below. It does not involve std::function.

      -
      +
       t = Test()
       b = t(1,2) # invoke C++ function object
       
      @@ -944,5 +962,6 @@ typename std::result_of<Fun(Arg)>::type test_result_impl(Fun fun, Arg arg)

      Instead, please use decltype() where possible for now.

      + diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 0d360830d..e5127fd0c 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -491,6 +491,7 @@ CPP11_TEST_CASES = \ cpp11_initializer_list \ cpp11_initializer_list_extend \ cpp11_lambda_functions \ + cpp11_noexcept \ cpp11_null_pointer_constant \ cpp11_raw_string_literals \ cpp11_rvalue_reference \ diff --git a/Examples/test-suite/cpp11_noexcept.i b/Examples/test-suite/cpp11_noexcept.i new file mode 100644 index 000000000..27476fa70 --- /dev/null +++ b/Examples/test-suite/cpp11_noexcept.i @@ -0,0 +1,48 @@ +%module cpp11_noexcept + +%ignore NoExceptClass(NoExceptClass&&); +%rename(Assignment) NoExceptClass::operator=; + +%inline %{ + +extern "C" void global_noexcept(int, bool) noexcept; + +struct NoExceptClass { + static const bool VeryTrue = true; + + NoExceptClass() noexcept {} + NoExceptClass(const NoExceptClass&) noexcept {} + NoExceptClass(NoExceptClass&&) noexcept {} + NoExceptClass& operator=(const NoExceptClass&) noexcept {} + ~NoExceptClass() noexcept {} + + void noex0() noexcept {} + void noex1() noexcept(sizeof(int) == 4) {} + void noex2() noexcept(true) {} + void noex3() noexcept(false) {} + void noex4() noexcept(VeryTrue) {} + + template void template_noexcept(T) noexcept {} + + void noo1() const noexcept {} + static void noo2() noexcept {} + virtual void noo3() const noexcept {} + virtual void noo4() const noexcept = delete; + virtual void noo5() const throw() = delete; +}; + +struct NoExceptAbstract { + virtual void noo4() const noexcept = 0; + virtual ~NoExceptAbstract() noexcept = 0; +}; + +struct NoExceptDefaultDelete { +// NoExceptDefaultDelete() noexcept = default; +// NoExceptDefaultDelete(const NoExceptDefaultDelete&) noexcept = delete; + NoExceptDefaultDelete(NoExceptDefaultDelete&&) = delete; + NoExceptDefaultDelete& operator=(const NoExceptDefaultDelete&) = delete; + ~NoExceptDefaultDelete() noexcept = default; +}; + +%} + diff --git a/Source/CParse/cscanner.c b/Source/CParse/cscanner.c index 8b484f8a7..c04ce4688 100644 --- a/Source/CParse/cscanner.c +++ b/Source/CParse/cscanner.c @@ -705,6 +705,8 @@ int yylex(void) { } if (strcmp(yytext, "throw") == 0) return (THROW); + if (strcmp(yytext, "noexcept") == 0) + return (NOEXCEPT); if (strcmp(yytext, "try") == 0) return (yylex()); if (strcmp(yytext, "catch") == 0) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 1328d6e0d..bb1b5c1cc 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1669,6 +1669,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { String *bitfield; Parm *throws; String *throwf; + String *nexcept; } dtype; struct { char *type; @@ -1683,6 +1684,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { short have_parms; ParmList *throws; String *throwf; + String *nexcept; } decl; Parm *tparms; struct { @@ -1716,7 +1718,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %token ILLEGAL CONSTANT %token NAME RENAME NAMEWARN EXTEND PRAGMA FEATURE VARARGS %token ENUM -%token CLASS TYPENAME PRIVATE PUBLIC PROTECTED COLON STATIC VIRTUAL FRIEND THROW CATCH EXPLICIT AUTO +%token CLASS TYPENAME PRIVATE PUBLIC PROTECTED COLON STATIC VIRTUAL FRIEND THROW CATCH EXPLICIT AUTO NOEXCEPT %token STATIC_ASSERT CONSTEXPR THREAD_LOCAL DECLTYPE /* C++11 keywords */ %token USING %token NAMESPACE @@ -1771,7 +1773,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %type kwargs options; /* Misc */ -%type initializer cpp_const ; +%type initializer cpp_const exception_specification; %type storage_class; %type parms ptail rawparms varargs_parms ; %type templateparameters templateparameterstail; @@ -3234,6 +3236,7 @@ c_decl : storage_class type declarator initializer c_decl_tail { Setattr($$,"value",$4.val); Setattr($$,"throws",$4.throws); Setattr($$,"throw",$4.throwf); + Setattr($$,"noexcept",$4.nexcept); if (!$5) { if (Len(scanner_ccode)) { String *code = Copy(scanner_ccode); @@ -3293,6 +3296,7 @@ c_decl : storage_class type declarator initializer c_decl_tail { Setattr($$,"value",$6.val); Setattr($$,"throws",$6.throws); Setattr($$,"throw",$6.throwf); + Setattr($$,"noexcept",$6.nexcept); if (!$7) { if (Len(scanner_ccode)) { String *code = Copy(scanner_ccode); @@ -3352,6 +3356,7 @@ c_decl_tail : SEMI { Setattr($$,"value",$3.val); Setattr($$,"throws",$3.throws); Setattr($$,"throw",$3.throwf); + Setattr($$,"noexcept",$3.nexcept); if ($3.bitfield) { Setattr($$,"bitfield", $3.bitfield); } @@ -3376,24 +3381,28 @@ initializer : def_args { $$.qualifier = 0; $$.throws = 0; $$.throwf = 0; + $$.nexcept = 0; } | type_qualifier def_args { $$ = $2; $$.qualifier = $1; $$.throws = 0; $$.throwf = 0; + $$.nexcept = 0; } - | THROW LPAREN parms RPAREN def_args { - $$ = $5; + | exception_specification def_args { + $$ = $2; $$.qualifier = 0; - $$.throws = $3; - $$.throwf = NewString("1"); + $$.throws = $1.throws; + $$.throwf = $1.throwf; + $$.nexcept = $1.nexcept; } - | type_qualifier THROW LPAREN parms RPAREN def_args { - $$ = $6; + | type_qualifier exception_specification def_args { + $$ = $3; $$.qualifier = $1; - $$.throws = $4; - $$.throwf = NewString("1"); + $$.throws = $2.throws; + $$.throwf = $2.throwf; + $$.nexcept = $2.nexcept; } ; @@ -3669,6 +3678,7 @@ c_constructor_decl : storage_class type LPAREN parms RPAREN ctor_end { } Setattr($$,"throws",$6.throws); Setattr($$,"throw",$6.throwf); + Setattr($$,"noexcept",$6.nexcept); err = 0; } } @@ -4698,6 +4708,7 @@ cpp_constructor_decl : storage_class type LPAREN parms RPAREN ctor_end { Setattr($$,"decl",decl); Setattr($$,"throws",$6.throws); Setattr($$,"throw",$6.throwf); + Setattr($$,"noexcept",$6.nexcept); if (Len(scanner_ccode)) { String *code = Copy(scanner_ccode); Setattr($$,"code",code); @@ -4733,6 +4744,7 @@ cpp_destructor_decl : NOT idtemplate LPAREN parms RPAREN cpp_end { } Setattr($$,"throws",$6.throws); Setattr($$,"throw",$6.throwf); + Setattr($$,"noexcept",$6.nexcept); if ($6.val) Setattr($$,"value",$6.val); add_symbols($$); @@ -4750,6 +4762,7 @@ cpp_destructor_decl : NOT idtemplate LPAREN parms RPAREN cpp_end { Delete(name); Setattr($$,"throws",$7.throws); Setattr($$,"throw",$7.throwf); + Setattr($$,"noexcept",$7.nexcept); if ($7.val) Setattr($$,"value",$7.val); if (Len(scanner_ccode)) { @@ -4996,18 +5009,21 @@ cpp_end : cpp_const SEMI { $$.val = 0; $$.throws = $1.throws; $$.throwf = $1.throwf; + $$.nexcept = $1.nexcept; } | cpp_const EQUAL default_delete SEMI { Clear(scanner_ccode); $$.val = $3.val; $$.throws = $1.throws; $$.throwf = $1.throwf; + $$.nexcept = $1.nexcept; } | cpp_const LBRACE { skip_balanced('{','}'); $$.val = 0; $$.throws = $1.throws; $$.throwf = $1.throwf; + $$.nexcept = $1.nexcept; } ; @@ -5018,6 +5034,7 @@ cpp_vend : cpp_const SEMI { $$.bitfield = 0; $$.throws = $1.throws; $$.throwf = $1.throwf; + $$.nexcept = $1.nexcept; } | cpp_const EQUAL definetype SEMI { Clear(scanner_ccode); @@ -5026,6 +5043,7 @@ cpp_vend : cpp_const SEMI { $$.bitfield = 0; $$.throws = $1.throws; $$.throwf = $1.throwf; + $$.nexcept = $1.nexcept; } | cpp_const LBRACE { skip_balanced('{','}'); @@ -5034,6 +5052,7 @@ cpp_vend : cpp_const SEMI { $$.bitfield = 0; $$.throws = $1.throws; $$.throwf = $1.throwf; + $$.nexcept = $1.nexcept; } ; @@ -5085,6 +5104,7 @@ storage_class : EXTERN { $$ = "extern"; } | FRIEND { $$ = "friend"; } | EXPLICIT { $$ = "explicit"; } | CONSTEXPR { $$ = "constexpr"; } + | STATIC CONSTEXPR { $$ = "static constexpr"; } | THREAD_LOCAL { $$ = "thread_local"; } | THREAD_LOCAL STATIC { $$ = "static thread_local"; } | STATIC THREAD_LOCAL { $$ = "static thread_local"; } @@ -5222,6 +5242,7 @@ def_args : EQUAL definetype { $$.bitfield = 0; $$.throws = 0; $$.throwf = 0; + $$.nexcept = 0; } } | EQUAL definetype LBRACKET expr RBRACKET { @@ -5234,6 +5255,7 @@ def_args : EQUAL definetype { $$.bitfield = 0; $$.throws = 0; $$.throwf = 0; + $$.nexcept = 0; } else { $$.val = NewStringf("%s[%s]",$2.val,$4.val); } @@ -5246,6 +5268,7 @@ def_args : EQUAL definetype { $$.bitfield = 0; $$.throws = 0; $$.throwf = 0; + $$.nexcept = 0; } | COLON expr { $$.val = 0; @@ -5254,6 +5277,7 @@ def_args : EQUAL definetype { $$.bitfield = $2.val; $$.throws = 0; $$.throwf = 0; + $$.nexcept = 0; } | empty { $$.val = 0; @@ -5262,6 +5286,7 @@ def_args : EQUAL definetype { $$.bitfield = 0; $$.throws = 0; $$.throwf = 0; + $$.nexcept = 0; } ; @@ -6166,6 +6191,7 @@ definetype : { /* scanner_check_typedef(); */ } expr { $$.bitfield = 0; $$.throws = 0; $$.throwf = 0; + $$.nexcept = 0; scanner_ignore_typedef(); } | default_delete { @@ -6179,6 +6205,7 @@ definetype : { /* scanner_check_typedef(); */ } expr { $$.bitfield = 0; $$.throws = 0; $$.throwf = 0; + $$.nexcept = 0; } */ ; @@ -6200,6 +6227,7 @@ deleted_definition : DELETE_KW { $$.bitfield = 0; $$.throws = 0; $$.throwf = 0; + $$.nexcept = 0; } ; @@ -6212,6 +6240,7 @@ explicit_default : DEFAULT { $$.bitfield = 0; $$.throws = 0; $$.throwf = 0; + $$.nexcept = 0; } ; @@ -6331,6 +6360,7 @@ valexpr : exprnum { $$ = $1; } $$.bitfield = 0; $$.throws = 0; $$.throwf = 0; + $$.nexcept = 0; } | WCHARCONST { $$.val = NewString($1); @@ -6343,6 +6373,7 @@ valexpr : exprnum { $$ = $1; } $$.bitfield = 0; $$.throws = 0; $$.throwf = 0; + $$.nexcept = 0; } /* grouping */ @@ -6668,25 +6699,43 @@ opt_virtual : VIRTUAL | empty ; -cpp_const : type_qualifier { - $$.qualifier = $1; - $$.throws = 0; - $$.throwf = 0; - } - | THROW LPAREN parms RPAREN { - $$.qualifier = 0; +exception_specification : THROW LPAREN parms RPAREN { $$.throws = $3; $$.throwf = NewString("1"); - } - | type_qualifier THROW LPAREN parms RPAREN { - $$.qualifier = $1; - $$.throws = $4; - $$.throwf = NewString("1"); - } - | empty { - $$.qualifier = 0; + $$.nexcept = 0; + } + | NOEXCEPT { $$.throws = 0; $$.throwf = 0; + $$.nexcept = NewString("true"); + } + + | NOEXCEPT LPAREN expr RPAREN { + $$.throws = 0; + $$.throwf = 0; + $$.nexcept = $3.val; + } + ; + +cpp_const : type_qualifier { + $$.throws = 0; + $$.throwf = 0; + $$.nexcept = 0; + $$.qualifier = $1; + } + | exception_specification { + $$ = $1; + $$.qualifier = 0; + } + | type_qualifier exception_specification { + $$ = $2; + $$.qualifier = $1; + } + | empty { + $$.throws = 0; + $$.throwf = 0; + $$.nexcept = 0; + $$.qualifier = 0; } ; @@ -6696,6 +6745,7 @@ ctor_end : cpp_const ctor_initializer SEMI { $$.defarg = 0; $$.throws = $1.throws; $$.throwf = $1.throwf; + $$.nexcept = $1.nexcept; } | cpp_const ctor_initializer LBRACE { skip_balanced('{','}'); @@ -6703,6 +6753,7 @@ ctor_end : cpp_const ctor_initializer SEMI { $$.defarg = 0; $$.throws = $1.throws; $$.throwf = $1.throwf; + $$.nexcept = $1.nexcept; } | LPAREN parms RPAREN SEMI { Clear(scanner_ccode); @@ -6711,6 +6762,7 @@ ctor_end : cpp_const ctor_initializer SEMI { $$.defarg = 0; $$.throws = 0; $$.throwf = 0; + $$.nexcept = 0; } | LPAREN parms RPAREN LBRACE { skip_balanced('{','}'); @@ -6719,12 +6771,14 @@ ctor_end : cpp_const ctor_initializer SEMI { $$.defarg = 0; $$.throws = 0; $$.throwf = 0; + $$.nexcept = 0; } | EQUAL definetype SEMI { $$.have_parms = 0; $$.defarg = $2.val; $$.throws = 0; $$.throwf = 0; + $$.nexcept = 0; } ; From 97a9f5896a00acaf0ad73d763a938d5783425228 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 21 Nov 2013 20:22:57 +0000 Subject: [PATCH 204/481] Show date in Travis builds --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 26758304f..70cbb2f27 100644 --- a/.travis.yml +++ b/.travis.yml @@ -33,6 +33,7 @@ matrix: allow_failures: # None before_install: + - date -u - lsb_release -a - uname -a - sudo apt-get -qq update From fcd0480364ba932cf5e9eabb34c7c048f146e758 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 22 Nov 2013 00:12:33 +0000 Subject: [PATCH 205/481] Fix some cases of C++11 exception specifications on constructors with =default or =delete --- Examples/test-suite/cpp11_default_delete.i | 9 +++++++++ Examples/test-suite/cpp11_noexcept.i | 5 +++-- Source/CParse/parser.y | 7 +++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/Examples/test-suite/cpp11_default_delete.i b/Examples/test-suite/cpp11_default_delete.i index 49a677060..79c02cddc 100644 --- a/Examples/test-suite/cpp11_default_delete.i +++ b/Examples/test-suite/cpp11_default_delete.i @@ -69,4 +69,13 @@ struct moveonly { moveonly& operator=(moveonly&&) = default; ~moveonly() = default; }; + +struct ConstructorThrow { + ConstructorThrow() throw() = default; + ConstructorThrow(const ConstructorThrow&) throw() = delete; + ConstructorThrow(ConstructorThrow&&) throw() = delete; + ConstructorThrow& operator=(const ConstructorThrow&) throw() = delete; + ~ConstructorThrow() throw() = default; +}; + %} diff --git a/Examples/test-suite/cpp11_noexcept.i b/Examples/test-suite/cpp11_noexcept.i index 27476fa70..6fed5b8df 100644 --- a/Examples/test-suite/cpp11_noexcept.i +++ b/Examples/test-suite/cpp11_noexcept.i @@ -37,8 +37,9 @@ struct NoExceptAbstract { }; struct NoExceptDefaultDelete { -// NoExceptDefaultDelete() noexcept = default; -// NoExceptDefaultDelete(const NoExceptDefaultDelete&) noexcept = delete; + template NoExceptDefaultDelete(T) noexcept = delete; + NoExceptDefaultDelete() noexcept = default; + NoExceptDefaultDelete(const NoExceptDefaultDelete&) noexcept = delete; NoExceptDefaultDelete(NoExceptDefaultDelete&&) = delete; NoExceptDefaultDelete& operator=(const NoExceptDefaultDelete&) = delete; ~NoExceptDefaultDelete() noexcept = default; diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index bb1b5c1cc..caac88e4d 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -6780,6 +6780,13 @@ ctor_end : cpp_const ctor_initializer SEMI { $$.throwf = 0; $$.nexcept = 0; } + | exception_specification EQUAL default_delete SEMI { + $$.have_parms = 0; + $$.defarg = $3.val; + $$.throws = $1.throws; + $$.throwf = $1.throwf; + $$.nexcept = $1.nexcept; + } ; ctor_initializer : COLON mem_initializer_list From b63c4839fe60b8192809ef94d078ef07305144c5 Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Thu, 28 Nov 2013 07:32:23 +0000 Subject: [PATCH 206/481] Nested classes support Closes #89 Squash merge branch 'master' of https://github.com/wkalinin/swig into wkalinin-nested By Vladimir Kalinin * 'master' of https://github.com/wkalinin/swig: CPlusPlusOut mode for Octave nested class illustration fixed "Abstract" flag for nested classes added an example enabled anonymous nested structs runtime test porting warnings disabled porting fixes java runtime tests ported nested class closing bracket offset fixed removed double nested template (not supported by %template parsing) template_nested test extended parent field made public property access fixed replaced tabs with spaces warning W-reorder deprecated warnings removed, derived_nested runtime test added optimized string indenting Nested classes indenting nested classes docs fixed the order in which flattened inner classes are added after the outer Private nested classes were getting into the type table. Java getProxyName() fix for nested classes fixes the case when nested classes is forward declared Fix for a case when a nested class inherits from the same base as the outer. (Base class constructor declaration is found first in this case) merge fix nested C struct first immediate declaration incorrectly renamed sample fixed tests updated to reflect nested classes support Java nested classes support (1) flattening should remove the link to the outer class access mode correctly set/restored for nested classes nested templates should be skipped while flattening (template nodes themselves, not expanded versions) also non-public nested classes should be ignored If nested classes are not supported, default behaviour is flattening, not ignoring flag "nested" is preserved, so, the nested classes can be ignored by user nested workaround test updated template instantiated within a class is marked as nested for ignoring purposes %ignore not applied to the nested classed, because "nested" flag is set too late typedef name takes precedence over the real name (reason?) unnamed structs should be processed for all the languages nested C struct instances are wrapped as "immutable" tree building typedef declaration for unnamed C structures fixed nested classes "flattening" fixed %ignoring nested classes renamed "nested" attribute to "nested:outer" added "nested" flag, to be used with $ignore (it is not removed while flattening) added nestedClassesSupported() function to the Language interface renamed "nested" attribute to "nested:outer" added "nested" flag, to be used with $ignore (it is not removed while flattening) added nestedClassesSupported() function to the Language interface tree iteration fix dirclassname variable names unified memory issue fixed merge error ignore unnamed structs for C++ unnamed nested C structs naming & unnesting class added to classes hash under typedef name private nested classes skipped test updated due to nested templates support anonymous structs with inheritance fixed nested_class test to allow anonymous structs w/o declarator tests updated: nested workaround removed from namespace_class.i propagated nested template declaration to the C++ file injected members scope nested tempplates fixes, nested structures in "C" mode parsing added utility function "appendSibling" (like "appendChild") nested unnamed structures parsing fixes, access mode restored on nested class end, tdname is properly patched with outer class name prefix memory management fixes nested templates (1) Nested unnamed structs Nested class support (1) Nested class support (1) --- Doc/Manual/SWIGPlus.html | 144 +-- Examples/csharp/class/example.cxx | 2 +- Examples/csharp/class/example.h | 8 +- Examples/csharp/class/runme.cs | 6 +- Examples/java/class/example.cxx | 2 +- Examples/java/class/example.h | 8 +- Examples/java/class/runme.java | 6 +- Examples/test-suite/derived_nested.i | 10 +- .../test-suite/java/nested_class_runme.java | 62 +- .../test-suite/java/nested_structs_runme.java | 14 +- .../java/template_nested_runme.java | 4 + Examples/test-suite/namespace_class.i | 10 - Examples/test-suite/namespace_union.i | 2 - Examples/test-suite/nested_class.i | 24 +- Examples/test-suite/nested_comment.i | 2 - Examples/test-suite/nested_workaround.i | 20 +- Examples/test-suite/template_nested.i | 19 +- .../test-suite/template_nested_typemaps.i | 6 +- Examples/test-suite/union_scope.i | 1 - Lib/swig.swg | 2 +- Source/CParse/cparse.h | 1 + Source/CParse/cscanner.c | 4 + Source/CParse/parser.y | 960 +++++------------- Source/Include/swigwarn.h | 2 - Source/Modules/allocate.cxx | 6 +- Source/Modules/contract.cxx | 6 +- Source/Modules/csharp.cxx | 231 +++-- Source/Modules/java.cxx | 196 ++-- Source/Modules/lang.cxx | 95 +- Source/Modules/main.cxx | 45 +- Source/Modules/octave.cxx | 1 + Source/Modules/swigmod.h | 13 + Source/Modules/typepass.cxx | 457 ++++++++- Source/Swig/naming.c | 65 ++ Source/Swig/scanner.c | 103 ++ Source/Swig/swig.h | 2 + Source/Swig/swigscan.h | 1 + Source/Swig/swigtree.h | 1 + Source/Swig/tree.c | 19 + 39 files changed, 1449 insertions(+), 1111 deletions(-) diff --git a/Doc/Manual/SWIGPlus.html b/Doc/Manual/SWIGPlus.html index 2713725d7..2ec98f33a 100644 --- a/Doc/Manual/SWIGPlus.html +++ b/Doc/Manual/SWIGPlus.html @@ -185,7 +185,6 @@ The following C++ features are not currently supported:

      • Overloaded versions of certain operators (new, delete, etc.) -
      • Nested classes, see Nested classes for workarounds.

      @@ -4965,143 +4964,40 @@ public:

      6.27 Nested classes

      -

      -There is some support for nested structs and unions when wrapping C code, -see Nested structures for further details. -The added complexity of C++ compared to C means this approach does not work well for -C++ code (when using the -c++ command line option). -For C++, a nested class is treated much like an opaque pointer, so anything useful within the nested class, such as its -methods and variables, are not accessible from the target language. -True nested class support may be added to SWIG in the future, however, -until then some of the following workarounds can be applied to improve the situation. +If the target language supports the nested classes concept (like Java), the nested C++ classes +are wrapped as nested target language proxy classes. (In case of Java - "static" nested classes.) +Only public nested classes are wrapped. Otherwise there is little difference between nested and +normal classes.

      -

      -It might be possible to use partial class information as often you can accept that the nested class is not needed, -especially if it is not actually used in any methods you need from the target language. -Imagine you are wrapping the following Outer class which contains a nested class Inner. -The easiest thing to do is turn a blind eye to the warning that SWIG generates, or simply suppress it: +If the target language doesn't support nested classes directly, or the support is not implemented in the +language module (like for python currently), then the visible nested classes are moved to the same name +space as the containing class (nesting hierarchy is "flattened"). The same behaviour may be turned on for +C# and Java by the %feature ("flatnested"); If there is a class with the same name in the outer namespace +the inner class (or the global one) may be renamed or ignored:

      -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::Inner;
      -
      -class Outer {
      -public:
      -  class Inner {
      -    public:
      -      ...
      -  };
      -  Inner getInner();
      -  void useInner(const Inner& inner);
      -  ...
      -};
      -
      -
      - -

      -Note that if Inner can be used as an opaque type, the default wrapping approach suffices. -For example, if the nested class does not need to be created from the target language, but can be obtained via a method -call, such as the getInner() method above, the returned value can then be passed around, such as passed into the -useInner() method. -

      - -

      -With some more effort the above situation can be improved somewhat and a nested class can be constructed and used -from the target language much like any other non-nested class. Assuming we have the Outer class in a header file: -

      - -
      -
      -// File outer.h
      -class Outer {
      -public:
      -  class Inner {
      -    public:
      -      int var;
      -      Inner(int v = 0) : var(v) {}
      -  };
      -  Inner getInner();
      -  void useInner(const Inner& inner);
      -};
      -
      -
      - -

      -The following interface file works around the nested class limitations by redefining the nested class as a global class. -A typedef for the compiler and the nestedworkaround -feature flag is also required in -order for the generated wrappers to compile. This flag simply removes all the type information from SWIG, so SWIG treats -the nested class as if it had not been parsed at all. -

      - -
      -
      -// File : example.i
      -%module example
      -
      -// Redefine nested class in global scope in order for SWIG to generate
      -// a proxy class. Only SWIG parses this definition.
      -class Inner {
      +%rename (Bar_Foo) Bar::Foo;
      +class Foo {};
      +class Bar {
         public:
      -    int var;
      -    Inner(int v = 0) : var(v) {}
      -};
      -
      -%nestedworkaround Outer::Inner;
      -
      -%{
      -#include "outer.h"
      -%}
      -%include "outer.h"
      -
      -// We've fooled SWIG into thinking that Inner is a global class, so now we need
      -// to trick the C++ compiler into understanding this apparent global type.
      -%{
      -typedef Outer::Inner Inner;
      -%}
      -
      -
      - -

      -The downside to this approach is a more complex interface file and having to maintain two definitions of Inner, -the real one and the one in the interface file that SWIG parses. -However, the upside is that all the methods/variables in the nested class are available from the target language -as a proxy class is generated instead of treating the nested class as an opaque type. -The proxy class can be constructed from the target language and passed into any methods accepting the nested class. -Also note that the original header file is parsed unmodified. -

      - -

      -Finally, conditional compilation can be used as a workaround to comment out nested class definitions in the actual headers, -assuming you are able to modify them. -

      - -
      -
      -// File outer.h
      -class Outer {
      -public:
      -#ifndef SWIG
      -  class Inner {
      -    public:
      -      ...
      -  };
      -#endif
      -  ...
      +  class Foo {};
       };
       
      -

      -This workaround used to be common when SWIG could not deal with nested classes particulary well. -This should just be a last resort for unusual corner cases now as SWIG can parse nested classes and even handle nested template classes fairly well. -

      -Compatibility Note: SWIG-1.3.40 and earlier versions did not have the nestedworkaround feature +Compatibility Note: +In SWIG 2.0 and earlier, nested classes were treated as opaque pointers. +Also there was a workaround, implementing approximately the same behaviour as the +%feature ("flatnested") with an additional help from the user: +nested class had to be manually redeclared in the global scope, typedef name and %feature nestedworkaround +added for the inner class. +SWIG-1.3.40 and earlier versions did not have the nestedworkaround feature and the generated code resulting from parsing nested classes did not always compile. Nested class warnings could also not be suppressed using %warnfilter.

      diff --git a/Examples/csharp/class/example.cxx b/Examples/csharp/class/example.cxx index 1e8e203dd..9b23ea4e6 100644 --- a/Examples/csharp/class/example.cxx +++ b/Examples/csharp/class/example.cxx @@ -9,7 +9,7 @@ void Shape::move(double dx, double dy) { y += dy; } -int Shape::nshapes = 0; +int Shape::Counter::nshapes = 0; double Circle::area(void) { return M_PI*radius*radius; diff --git a/Examples/csharp/class/example.h b/Examples/csharp/class/example.h index 46d901361..430cf47dc 100644 --- a/Examples/csharp/class/example.h +++ b/Examples/csharp/class/example.h @@ -2,17 +2,19 @@ class Shape { public: + struct Counter{ + static int nshapes; + }; Shape() { - nshapes++; + Counter::nshapes++; } virtual ~Shape() { - nshapes--; + Counter::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 { diff --git a/Examples/csharp/class/runme.cs b/Examples/csharp/class/runme.cs index 9088031d6..2b500da5c 100644 --- a/Examples/csharp/class/runme.cs +++ b/Examples/csharp/class/runme.cs @@ -17,9 +17,9 @@ public class runme Console.WriteLine( " Created circle " + c ); Console.WriteLine( " Created square " + s ); - // ----- Access a static member ----- + // ----- Access a static member of a nested class ----- - Console.WriteLine( "\nA total of " + Shape.nshapes + " shapes were created" ); + Console.WriteLine( "\nA total of " + Shape.Counter.nshapes + " shapes were created" ); // ----- Member data access ----- @@ -60,7 +60,7 @@ public class runme // Note: when this using scope is exited the C# Dispose() methods // are called which in turn call the C++ destructors - Console.WriteLine( Shape.nshapes + " shapes remain" ); + Console.WriteLine( Shape.Counter.nshapes + " shapes remain" ); Console.WriteLine( "Goodbye" ); } } diff --git a/Examples/java/class/example.cxx b/Examples/java/class/example.cxx index 1e8e203dd..9b23ea4e6 100644 --- a/Examples/java/class/example.cxx +++ b/Examples/java/class/example.cxx @@ -9,7 +9,7 @@ void Shape::move(double dx, double dy) { y += dy; } -int Shape::nshapes = 0; +int Shape::Counter::nshapes = 0; double Circle::area(void) { return M_PI*radius*radius; diff --git a/Examples/java/class/example.h b/Examples/java/class/example.h index 46d901361..430cf47dc 100644 --- a/Examples/java/class/example.h +++ b/Examples/java/class/example.h @@ -2,17 +2,19 @@ class Shape { public: + struct Counter{ + static int nshapes; + }; Shape() { - nshapes++; + Counter::nshapes++; } virtual ~Shape() { - nshapes--; + Counter::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 { diff --git a/Examples/java/class/runme.java b/Examples/java/class/runme.java index e1ea0d71c..90844ba23 100644 --- a/Examples/java/class/runme.java +++ b/Examples/java/class/runme.java @@ -21,9 +21,9 @@ public class runme { Square s = new Square(10); System.out.println( " Created square " + s ); - // ----- Access a static member ----- + // ----- Access a static member of a nested class ----- - System.out.println( "\nA total of " + Shape.getNshapes() + " shapes were created" ); + System.out.println( "\nA total of " + Shape.Counter.getNshapes() + " shapes were created" ); // ----- Member data access ----- @@ -64,7 +64,7 @@ public class runme { c.delete(); s.delete(); - System.out.println( Shape.getNshapes() + " shapes remain" ); + System.out.println( Shape.Counter.getNshapes() + " shapes remain" ); System.out.println( "Goodbye" ); } } diff --git a/Examples/test-suite/derived_nested.i b/Examples/test-suite/derived_nested.i index 29114d5a0..e374cf70f 100644 --- a/Examples/test-suite/derived_nested.i +++ b/Examples/test-suite/derived_nested.i @@ -3,14 +3,12 @@ This was reported in bug #909389 */ %module derived_nested -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) BB::CC; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) BB::DD; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) BB::EE; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) BB::FF; - %inline %{ -class A { int x; }; +class A { +public: + int x; +}; class B { class C { int y; }; //generates a warning class D : public A { int z; }; //ok diff --git a/Examples/test-suite/java/nested_class_runme.java b/Examples/test-suite/java/nested_class_runme.java index f1c67a0af..f75613e65 100644 --- a/Examples/test-suite/java/nested_class_runme.java +++ b/Examples/test-suite/java/nested_class_runme.java @@ -14,59 +14,59 @@ public class nested_class_runme { public static void main(String argv[]) { Outer outer = new Outer(); - SWIGTYPE_p_Outer__InnerStruct1 is1 = outer.makeInnerStruct1(); - SWIGTYPE_p_Outer__InnerClass1 ic1 = outer.makeInnerClass1(); - SWIGTYPE_p_Outer__InnerUnion1 iu1 = outer.makeInnerUnion1(); + Outer.InnerStruct1 is1 = outer.makeInnerStruct1(); + Outer.InnerClass1 ic1 = outer.makeInnerClass1(); + Outer.InnerUnion1 iu1 = outer.makeInnerUnion1(); - SWIGTYPE_p_Outer__InnerStruct2 is2 = outer.makeInnerStruct2(); - SWIGTYPE_p_Outer__InnerClass2 ic2 = outer.makeInnerClass2(); - SWIGTYPE_p_Outer__InnerUnion2 iu2 = outer.makeInnerUnion2(); + Outer.InnerStruct2 is2 = outer.makeInnerStruct2(); + Outer.InnerClass2 ic2 = outer.makeInnerClass2(); + Outer.InnerUnion2 iu2 = outer.makeInnerUnion2(); - SWIGTYPE_p_Outer__InnerClass4Typedef ic4 = outer.makeInnerClass4Typedef(); - SWIGTYPE_p_Outer__InnerStruct4Typedef is4 = outer.makeInnerStruct4Typedef(); - SWIGTYPE_p_Outer__InnerUnion4Typedef iu4 = outer.makeInnerUnion4Typedef(); + Outer.InnerClass4Typedef ic4 = outer.makeInnerClass4Typedef(); + Outer.InnerStruct4Typedef is4 = outer.makeInnerStruct4Typedef(); + Outer.InnerUnion4Typedef iu4 = outer.makeInnerUnion4Typedef(); - SWIGTYPE_p_Outer__InnerClass5 ic5 = outer.makeInnerClass5(); - SWIGTYPE_p_Outer__InnerStruct5 is5 = outer.makeInnerStruct5(); - SWIGTYPE_p_Outer__InnerUnion5 iu5 = outer.makeInnerUnion5(); + Outer.InnerClass5Typedef ic5 = outer.makeInnerClass5(); + Outer.InnerStruct5Typedef is5 = outer.makeInnerStruct5(); + Outer.InnerUnion5Typedef iu5 = outer.makeInnerUnion5(); ic5 = outer.makeInnerClass5Typedef(); is5 = outer.makeInnerStruct5Typedef(); iu5 = outer.makeInnerUnion5Typedef(); { - SWIGTYPE_p_Outer__InnerMultiple im1 = outer.getMultipleInstance1(); - SWIGTYPE_p_Outer__InnerMultiple im2 = outer.getMultipleInstance2(); - SWIGTYPE_p_Outer__InnerMultiple im3 = outer.getMultipleInstance3(); - SWIGTYPE_p_Outer__InnerMultiple im4 = outer.getMultipleInstance4(); + Outer.InnerMultiple im1 = outer.getMultipleInstance1(); + Outer.InnerMultiple im2 = outer.getMultipleInstance2(); + Outer.InnerMultiple im3 = outer.getMultipleInstance3(); + Outer.InnerMultiple im4 = outer.getMultipleInstance4(); } { - SWIGTYPE_p_Outer__InnerMultipleDerived im1 = outer.getMultipleDerivedInstance1(); - SWIGTYPE_p_Outer__InnerMultipleDerived im2 = outer.getMultipleDerivedInstance2(); - SWIGTYPE_p_Outer__InnerMultipleDerived im3 = outer.getMultipleDerivedInstance3(); - SWIGTYPE_p_Outer__InnerMultipleDerived im4 = outer.getMultipleDerivedInstance4(); + Outer.InnerMultipleDerived im1 = outer.getMultipleDerivedInstance1(); + Outer.InnerMultipleDerived im2 = outer.getMultipleDerivedInstance2(); + Outer.InnerMultipleDerived im3 = outer.getMultipleDerivedInstance3(); + Outer.InnerMultipleDerived im4 = outer.getMultipleDerivedInstance4(); } { - SWIGTYPE_p_Outer__InnerMultipleDerived im1 = outer.getMultipleDerivedInstance1(); - SWIGTYPE_p_Outer__InnerMultipleDerived im2 = outer.getMultipleDerivedInstance2(); - SWIGTYPE_p_Outer__InnerMultipleDerived im3 = outer.getMultipleDerivedInstance3(); - SWIGTYPE_p_Outer__InnerMultipleDerived im4 = outer.getMultipleDerivedInstance4(); + Outer.InnerMultipleDerived im1 = outer.getMultipleDerivedInstance1(); + Outer.InnerMultipleDerived im2 = outer.getMultipleDerivedInstance2(); + Outer.InnerMultipleDerived im3 = outer.getMultipleDerivedInstance3(); + Outer.InnerMultipleDerived im4 = outer.getMultipleDerivedInstance4(); } { - SWIGTYPE_p_Outer__InnerMultipleAnonTypedef1 mat1 = outer.makeInnerMultipleAnonTypedef1(); - SWIGTYPE_p_Outer__InnerMultipleAnonTypedef2 mat2 = outer.makeInnerMultipleAnonTypedef2(); - SWIGTYPE_p_Outer__InnerMultipleAnonTypedef3 mat3 = outer.makeInnerMultipleAnonTypedef3(); + Outer.InnerMultipleAnonTypedef1 mat1 = outer.makeInnerMultipleAnonTypedef1(); + Outer.InnerMultipleAnonTypedef1 mat2 = outer.makeInnerMultipleAnonTypedef2(); + SWIGTYPE_p_p_Outer__InnerMultipleAnonTypedef1 mat3 = outer.makeInnerMultipleAnonTypedef3(); - SWIGTYPE_p_Outer__InnerMultipleNamedTypedef mnt = outer.makeInnerMultipleNamedTypedef(); - SWIGTYPE_p_Outer__InnerMultipleNamedTypedef mnt1 = outer.makeInnerMultipleNamedTypedef1(); - SWIGTYPE_p_Outer__InnerMultipleNamedTypedef mnt2 = outer.makeInnerMultipleNamedTypedef2(); + Outer.InnerMultipleNamedTypedef1 mnt = outer.makeInnerMultipleNamedTypedef(); + Outer.InnerMultipleNamedTypedef1 mnt1 = outer.makeInnerMultipleNamedTypedef1(); + Outer.InnerMultipleNamedTypedef1 mnt2 = outer.makeInnerMultipleNamedTypedef2(); SWIGTYPE_p_p_Outer__InnerMultipleNamedTypedef mnt3 = outer.makeInnerMultipleNamedTypedef3(); } { - SWIGTYPE_p_Outer__InnerSameName isn = outer.makeInnerSameName(); + Outer.InnerSameName isn = outer.makeInnerSameName(); } } } diff --git a/Examples/test-suite/java/nested_structs_runme.java b/Examples/test-suite/java/nested_structs_runme.java index 6e103cd12..4b713395a 100644 --- a/Examples/test-suite/java/nested_structs_runme.java +++ b/Examples/test-suite/java/nested_structs_runme.java @@ -17,18 +17,18 @@ public class nested_structs_runme { nested_structs.setValues(outer, 10); Outer_inner1 inner1 = outer.getInner1(); - Outer_inner2 inner2 = outer.getInner2(); - Outer_inner3 inner3 = outer.getInner3(); - Outer_inner4 inner4 = outer.getInner4(); + Outer_inner1 inner2 = outer.getInner2(); + Outer_inner1 inner3 = outer.getInner3(); + Outer_inner1 inner4 = outer.getInner4(); if (inner1.getVal() != 10) throw new RuntimeException("failed inner1"); if (inner2.getVal() != 20) throw new RuntimeException("failed inner2"); if (inner3.getVal() != 20) throw new RuntimeException("failed inner3"); if (inner4.getVal() != 40) throw new RuntimeException("failed inner4"); - Outer_inside1 inside1 = outer.getInside1(); - Outer_inside2 inside2 = outer.getInside2(); - Outer_inside3 inside3 = outer.getInside3(); - Outer_inside4 inside4 = outer.getInside4(); + Named inside1 = outer.getInside1(); + Named inside2 = outer.getInside2(); + Named inside3 = outer.getInside3(); + Named inside4 = outer.getInside4(); if (inside1.getVal() != 100) throw new RuntimeException("failed inside1"); if (inside2.getVal() != 200) throw new RuntimeException("failed inside2"); if (inside3.getVal() != 200) throw new RuntimeException("failed inside3"); diff --git a/Examples/test-suite/java/template_nested_runme.java b/Examples/test-suite/java/template_nested_runme.java index 407821674..422e7ea9e 100644 --- a/Examples/test-suite/java/template_nested_runme.java +++ b/Examples/test-suite/java/template_nested_runme.java @@ -25,6 +25,10 @@ public class template_nested_runme { T_NestedOuterTemplateDouble tn = new T_NestedOuterTemplateDouble(); if (tn.hohum(-12.3) != -12.3) throw new RuntimeException("it failed"); + OuterClass.T_OuterClassInner1Int inner1 = new OuterClass().useInner1(new OuterClass.T_OuterClassInner1Int()); + OuterClass.T_OuterClassInner2NormalClass inner2 = new OuterClass.T_OuterClassInner2NormalClass(); + inner2.setEmbeddedVar(2); + OuterClass.T_OuterClassInner2NormalClass inner22 = new OuterClass().useInner2Again(inner2); } } diff --git a/Examples/test-suite/namespace_class.i b/Examples/test-suite/namespace_class.i index aea5362d1..113bbeb35 100644 --- a/Examples/test-suite/namespace_class.i +++ b/Examples/test-suite/namespace_class.i @@ -1,6 +1,5 @@ %module namespace_class -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Ala::Ola; #ifdef SWIGD %warnfilter(SWIGWARN_IGNORE_OPERATOR_LT); @@ -216,9 +215,6 @@ namespace a %} -// %copyctor doesn't work with nested class workaround -%nocopyctor; - %inline %{ class Ala { public : @@ -236,12 +232,6 @@ namespace a }; %} -%rename(Ala__Ola) Ala::Ola; -class Ala::Ola { -public: - Ola() {} - void eek() {} -}; %template(hi) Ala::hi; diff --git a/Examples/test-suite/namespace_union.i b/Examples/test-suite/namespace_union.i index 85885f399..84e38b4d5 100644 --- a/Examples/test-suite/namespace_union.i +++ b/Examples/test-suite/namespace_union.i @@ -1,7 +1,5 @@ %module namespace_union -#pragma SWIG nowarn=SWIGWARN_PARSE_UNNAMED_NESTED_CLASS - %inline %{ namespace SpatialIndex { diff --git a/Examples/test-suite/nested_class.i b/Examples/test-suite/nested_class.i index d67440ac9..0d418192d 100644 --- a/Examples/test-suite/nested_class.i +++ b/Examples/test-suite/nested_class.i @@ -1,25 +1,5 @@ %module nested_class -#pragma SWIG nowarn=SWIGWARN_PARSE_UNNAMED_NESTED_CLASS -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerStruct1; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerClass1; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerUnion1; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerClass2; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerStruct2; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerUnion2; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerClass4Typedef; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerStruct4Typedef; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerUnion4Typedef; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerClass5; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerStruct5; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerUnion5; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerMultiple; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerMultipleDerived; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerMultipleAnonTypedef1; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerMultipleNamedTypedef; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerSameName; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer2::IgnoreMe; - %inline %{ struct Outer { typedef int Integer; @@ -39,7 +19,7 @@ struct Outer { }; /////////////////////////////////////////// -#ifdef SWIG +#if defined(__GNUC__) || defined(_MSC_VER) || defined(SWIG) /* some compilers do not accept these */ class { public: @@ -154,7 +134,7 @@ struct Outer { Integer xx; } MultipleInstanceAnonDerived1, MultipleInstanceAnonDerived2, *MultipleInstanceAnonDerived3, MultipleInstanceAnonDerived4[2]; -#ifdef SWIG +#if defined(__GNUC__) || defined(_MSC_VER) || defined(SWIG) /* some compilers do not accept these */ struct : public InnerMultiple { Integer xx; diff --git a/Examples/test-suite/nested_comment.i b/Examples/test-suite/nested_comment.i index 99d0ffb43..df160b157 100644 --- a/Examples/test-suite/nested_comment.i +++ b/Examples/test-suite/nested_comment.i @@ -1,7 +1,5 @@ %module nested_comment -#pragma SWIG nowarn=SWIGWARN_PARSE_UNNAMED_NESTED_CLASS - // this example shows a problem with 'dump_nested' (parser.y). // bug #949654 diff --git a/Examples/test-suite/nested_workaround.i b/Examples/test-suite/nested_workaround.i index 9727dacee..bb69a5bbd 100644 --- a/Examples/test-suite/nested_workaround.i +++ b/Examples/test-suite/nested_workaround.i @@ -1,14 +1,6 @@ %module nested_workaround -// Similar to "Nested classes" documentation example. - -class Inner { - int val; - public: - Inner(int v = 0) : val(v) {} - void setValue(int v) { val = v; } - int getValue() const { return val; } -}; -%nestedworkaround Outer::Inner; +// "flatnested" emulates deprecated feature "nested_workaround" for the languages not supporting nested classes +%feature ("flatnested"); %inline %{ class Outer { @@ -28,11 +20,3 @@ public: } }; %} - -// We've fooled SWIG into thinking that Inner is a global class, so now we need -// to trick the C++ compiler into understanding this apparent global type. -%{ -typedef Outer::Inner Inner; -%} - - diff --git a/Examples/test-suite/template_nested.i b/Examples/test-suite/template_nested.i index 1bb1c686a..bbca9502c 100644 --- a/Examples/test-suite/template_nested.i +++ b/Examples/test-suite/template_nested.i @@ -2,13 +2,6 @@ // Test nested templates - that is template classes and template methods within a class. -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) ns::OuterClass::Inner1; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) ns::OuterClass::Inner2; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) ns::OuterTemplate::NestedInnerTemplate1; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) ns::OuterTemplate::NestedInnerTemplate2; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) ns::OuterTemplate::NestedInnerTemplate3; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) ns::OuterTemplate::NestedStruct; - namespace ns { template struct ForwardTemplate; } @@ -33,7 +26,13 @@ namespace ns { template struct NormalTemplate { void tmethod(T t) {} }; +} +%} +%template(T_NormalTemplateNormalClass) ns::NormalTemplate; +%template(T_NormalTemplateInt) ns::NormalTemplate; +%inline %{ +namespace ns { class OuterClass { public: template struct Inner1 { @@ -70,6 +69,7 @@ namespace ns { }; }; Inner2 useInner2(const Inner2& inner) { return inner; } + Inner2 useInner2Again(const Inner2& inner) { return inner; } int iii; }; struct ABC { @@ -108,9 +108,10 @@ namespace ns { %} -%template(T_NormalTemplateNormalClass) ns::NormalTemplate; %template(T_OuterTMethodNormalClass) ns::OuterClass::InnerTMethod; %template(T_TemplateFuncs1Int) ns::TemplateFuncs::templateMethod1; %template(T_TemplateFuncs2Double) ns::TemplateFuncs::templateMethod2; %template(T_NestedOuterTemplateDouble) ns::OuterTemplate; - +%template(T_OuterClassInner1Int) ns::OuterClass::Inner1; +%template(T_OuterClassInner2NormalClass) ns::OuterClass::Inner2; +%template(T_OuterClassInner2Int) ns::OuterClass::Inner2; diff --git a/Examples/test-suite/template_nested_typemaps.i b/Examples/test-suite/template_nested_typemaps.i index 54f5bc503..b40e7e291 100644 --- a/Examples/test-suite/template_nested_typemaps.i +++ b/Examples/test-suite/template_nested_typemaps.i @@ -4,18 +4,22 @@ // Testing that the typemaps invoked within a class via %template are picked up by appropriate methods +%inline %{ template struct Typemap { +#ifdef SWIG %typemap(in) T { $1 = -99; } +#endif }; template <> struct Typemap { // Note explicit specialization +#ifdef SWIG %typemap(in) short { $1 = -77; } +#endif }; -%inline %{ int globalInt1(int s) { return s; } short globalShort1(short s) { return s; } diff --git a/Examples/test-suite/union_scope.i b/Examples/test-suite/union_scope.i index b7307cb29..67093eff6 100644 --- a/Examples/test-suite/union_scope.i +++ b/Examples/test-suite/union_scope.i @@ -2,7 +2,6 @@ %warnfilter(SWIGWARN_RUBY_WRONG_NAME) nRState; // Ruby, wrong class name %warnfilter(SWIGWARN_RUBY_WRONG_NAME) nRState_rstate; // Ruby, wrong class name -#pragma SWIG nowarn=SWIGWARN_PARSE_UNNAMED_NESTED_CLASS %inline %{ class nRState { diff --git a/Lib/swig.swg b/Lib/swig.swg index ad6b7b64b..a63169b3e 100644 --- a/Lib/swig.swg +++ b/Lib/swig.swg @@ -302,7 +302,7 @@ static int NAME(TYPE x) { %define %$ismemberset "match$memberset"="1" %enddef %define %$classname %$ismember,"match$parentNode$name" %enddef - +%define %$isnested "match$nested"="1" %enddef /* ----------------------------------------------------------------------------- * Include all the warnings labels and macros * ----------------------------------------------------------------------------- */ diff --git a/Source/CParse/cparse.h b/Source/CParse/cparse.h index 922bbfcdc..19bf3f3f0 100644 --- a/Source/CParse/cparse.h +++ b/Source/CParse/cparse.h @@ -31,6 +31,7 @@ extern "C" { extern void scanner_file(File *); extern void scanner_next_token(int); extern void skip_balanced(int startchar, int endchar); + extern String *get_raw_text_balanced(int startchar, int endchar); extern void skip_decl(void); extern void scanner_check_typedef(void); extern void scanner_ignore_typedef(void); diff --git a/Source/CParse/cscanner.c b/Source/CParse/cscanner.c index c04ce4688..68b305c90 100644 --- a/Source/CParse/cscanner.c +++ b/Source/CParse/cscanner.c @@ -118,6 +118,10 @@ void skip_balanced(int startchar, int endchar) { return; } +String* get_raw_text_balanced(int startchar, int endchar) { + return Scanner_get_raw_text_balanced(scan, startchar, endchar); +} + /* ---------------------------------------------------------------------------- * void skip_decl(void) * diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index caac88e4d..ef7eb81ba 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -51,7 +51,7 @@ static Node *module_node = 0; static String *Classprefix = 0; static String *Namespaceprefix = 0; static int inclass = 0; -static int nested_template = 0; /* template class/function definition within a class */ +static Node *currentOuterClass = 0; /*for nested classes*/ static char *last_cpptype = 0; static int inherit_list = 0; static Parm *template_parameters = 0; @@ -59,10 +59,7 @@ static int extendmode = 0; static int compact_default_args = 0; static int template_reduce = 0; static int cparse_externc = 0; - -static int max_class_levels = 0; -static int class_level = 0; -static Node **class_decl = NULL; +extern int CPlusPlusOut; /* ----------------------------------------------------------------------------- * Assist Functions @@ -165,7 +162,6 @@ static Node *copy_node(Node *n) { static char *typemap_lang = 0; /* Current language setting */ static int cplus_mode = 0; -static String *class_rename = 0; /* C++ modes */ @@ -237,6 +233,25 @@ static String *feature_identifier_fix(String *s) { } } +static void set_access_mode(Node* n) { + if (cplus_mode == CPLUS_PUBLIC) + Setattr(n, "access", "public"); + else if (cplus_mode == CPLUS_PROTECTED) + Setattr(n, "access", "protected"); + else + Setattr(n, "access", "private"); +} + +static void restore_access_mode(Node* n) { + char* mode = Char(Getattr(n, "access")); + if (strcmp(mode, "private") == 0) + cplus_mode = CPLUS_PRIVATE; + else if (strcmp(mode, "protected") == 0) + cplus_mode = CPLUS_PROTECTED; + else + cplus_mode = CPLUS_PUBLIC; +} + /* Generate the symbol table name for an object */ /* This is a bit of a mess. Need to clean up */ static String *add_oldname = 0; @@ -283,13 +298,6 @@ static void add_symbols(Node *n) { String *decl; String *wrn = 0; - if (nested_template) { - if (!(n && Equal(nodeType(n), "template"))) { - return; - } - /* continue if template function, but not template class, declared within a class */ - } - if (inclass && n) { cparse_normalize_void(n); } @@ -349,9 +357,6 @@ static void add_symbols(Node *n) { Delete(prefix); } - /* - if (!Getattr(n,"parentNode") && class_level) set_parentNode(n,class_decl[class_level - 1]); - */ Setattr(n,"ismember","1"); } } @@ -793,53 +798,31 @@ static String *make_class_name(String *name) { return nname; } -static List *make_inherit_list(String *clsname, List *names) { - int i, ilen; - String *derived; - List *bases = NewList(); - - if (Namespaceprefix) derived = NewStringf("%s::%s", Namespaceprefix,clsname); - else derived = NewString(clsname); - - ilen = Len(names); - for (i = 0; i < ilen; i++) { - Node *s; - String *base; - String *n = Getitem(names,i); - /* Try to figure out where this symbol is */ - s = Swig_symbol_clookup(n,0); - if (s) { - while (s && (Strcmp(nodeType(s),"class") != 0)) { - /* Not a class. Could be a typedef though. */ - String *storage = Getattr(s,"storage"); - if (storage && (Strcmp(storage,"typedef") == 0)) { - String *nn = Getattr(s,"type"); - s = Swig_symbol_clookup(nn,Getattr(s,"sym:symtab")); - } else { - break; - } - } - if (s && ((Strcmp(nodeType(s),"class") == 0) || (Strcmp(nodeType(s),"template") == 0))) { - String *q = Swig_symbol_qualified(s); - Append(bases,s); - if (q) { - base = NewStringf("%s::%s", q, Getattr(s,"name")); - Delete(q); - } else { - base = NewString(Getattr(s,"name")); - } - } else { - base = NewString(n); - } - } else { - base = NewString(n); - } - if (base) { - Swig_name_inherit(base,derived); - Delete(base); +/* Use typedef name as class name */ +void add_typedef_name(Node* n, Node* decl, String* oldName, Symtab *cscope, String* scpname) +{ + String* class_rename = 0; + SwigType *decltype = Getattr(decl,"decl"); + if (!decltype || !Len(decltype)) { + String *cname; + String *tdscopename; + String *class_scope = Swig_symbol_qualifiedscopename(cscope); + String *name = Getattr(decl,"name"); + cname = Copy(name); + Setattr(n,"tdname",cname); + tdscopename = class_scope ? NewStringf("%s::%s", class_scope, name) : Copy(name); + class_rename = Getattr(n, "class_rename"); + if (class_rename && (Strcmp(class_rename,oldName) == 0)) + Setattr(n, "class_rename", NewString(name)); + if (!classes_typedefs) classes_typedefs = NewHash(); + if (!Equal(scpname, tdscopename) && !Getattr(classes_typedefs, tdscopename)) { + Setattr(classes_typedefs, tdscopename, n); } + Setattr(n,"decl",decltype); + Delete(class_scope); + Delete(cname); + Delete(tdscopename); } - return bases; } /* If the class name is qualified. We need to create or lookup namespace entries */ @@ -1059,352 +1042,33 @@ static String *resolve_create_node_scope(String *cname) { return cname; } - - -/* Structures for handling code fragments built for nested classes */ - -typedef struct Nested { - String *code; /* Associated code fragment */ - int line; /* line number where it starts */ - const char *name; /* Name associated with this nested class */ - const char *kind; /* Kind of class */ - int unnamed; /* unnamed class */ - SwigType *type; /* Datatype associated with the name */ - struct Nested *next; /* Next code fragment in list */ -} Nested; - -/* Some internal variables for saving nested class information */ - -static Nested *nested_list = 0; - -/* Add a function to the nested list */ - -static void add_nested(Nested *n) { - if (!nested_list) { - nested_list = n; - } else { - Nested *n1 = nested_list; - while (n1->next) - n1 = n1->next; - n1->next = n; - } -} - -/* ----------------------------------------------------------------------------- - * nested_new_struct() - * - * Nested struct handling for C code only creates a global struct from the nested struct. - * - * Nested structure. This is a sick "hack". If we encounter - * a nested structure, we're going to grab the text of its definition and - * feed it back into the scanner. In the meantime, we need to grab - * variable declaration information and generate the associated wrapper - * code later. Yikes! - * - * This really only works in a limited sense. Since we use the - * code attached to the nested class to generate both C code - * it can't have any SWIG directives in it. It also needs to be parsable - * by SWIG or this whole thing is going to puke. - * ----------------------------------------------------------------------------- */ - -static void nested_new_struct(const char *kind, String *struct_code, Node *cpp_opt_declarators) { - String *name; - String *decl; - - /* Create a new global struct declaration which is just a copy of the nested struct */ - Nested *nested = (Nested *) malloc(sizeof(Nested)); - Nested *n = nested; - - name = Getattr(cpp_opt_declarators, "name"); - decl = Getattr(cpp_opt_declarators, "decl"); - - n->code = NewStringEmpty(); - Printv(n->code, "typedef ", kind, " ", struct_code, " $classname_", name, ";\n", NIL); - n->name = Swig_copy_string(Char(name)); - n->line = cparse_start_line; - n->type = NewStringEmpty(); - n->kind = kind; - n->unnamed = 0; - SwigType_push(n->type, decl); - n->next = 0; - - /* Repeat for any multiple instances of the nested struct */ - { - Node *p = cpp_opt_declarators; - p = nextSibling(p); - while (p) { - Nested *nn = (Nested *) malloc(sizeof(Nested)); - - name = Getattr(p, "name"); - decl = Getattr(p, "decl"); - - nn->code = NewStringEmpty(); - Printv(nn->code, "typedef ", kind, " ", struct_code, " $classname_", name, ";\n", NIL); - nn->name = Swig_copy_string(Char(name)); - nn->line = cparse_start_line; - nn->type = NewStringEmpty(); - nn->kind = kind; - nn->unnamed = 0; - SwigType_push(nn->type, decl); - nn->next = 0; - n->next = nn; - n = nn; - p = nextSibling(p); - } - } - - add_nested(nested); -} - -/* ----------------------------------------------------------------------------- - * nested_forward_declaration() - * - * Nested struct handling for C++ code only. - * - * Treat the nested class/struct/union as a forward declaration until a proper - * nested class solution is implemented. - * ----------------------------------------------------------------------------- */ - -static Node *nested_forward_declaration(const char *storage, const char *kind, String *sname, String *name, Node *cpp_opt_declarators) { - Node *nn = 0; - int warned = 0; - - if (sname) { - /* Add forward declaration of the nested type */ - Node *n = new_node("classforward"); - Setattr(n, "kind", kind); - Setattr(n, "name", sname); - Setattr(n, "storage", storage); - Setattr(n, "sym:weak", "1"); - add_symbols(n); - nn = n; - } - - /* Add any variable instances. Also add in any further typedefs of the nested type. - Note that anonymous typedefs (eg typedef struct {...} a, b;) are treated as class forward declarations */ - if (cpp_opt_declarators) { - int storage_typedef = (storage && (strcmp(storage, "typedef") == 0)); - int variable_of_anonymous_type = !sname && !storage_typedef; - if (!variable_of_anonymous_type) { - int anonymous_typedef = !sname && (storage && (strcmp(storage, "typedef") == 0)); - Node *n = cpp_opt_declarators; - SwigType *type = name; - while (n) { - Setattr(n, "type", type); - Setattr(n, "storage", storage); - if (anonymous_typedef) { - Setattr(n, "nodeType", "classforward"); - Setattr(n, "sym:weak", "1"); - } - n = nextSibling(n); - } - add_symbols(cpp_opt_declarators); - - if (nn) { - set_nextSibling(nn, cpp_opt_declarators); - } else { - nn = cpp_opt_declarators; +/* look for simple typedef name in typedef list */ +String* try_to_find_a_name_for_unnamed_structure(char* storage, Node* decls) { + String* name = 0; + Node* n = decls; + if (storage && (strcmp(storage,"typedef") == 0)) { + for (; n; n = nextSibling(n)) { + if (!Len(Getattr(n, "decl"))) { + name = Copy(Getattr(n, "name")); + break; } } } - - if (nn && Equal(nodeType(nn), "classforward")) { - Node *n = nn; - if (GetFlag(n, "feature:nestedworkaround")) { - Swig_symbol_remove(n); - nn = 0; - warned = 1; - } else { - SWIG_WARN_NODE_BEGIN(n); - Swig_warning(WARN_PARSE_NAMED_NESTED_CLASS, cparse_file, cparse_line,"Nested %s not currently supported (%s ignored)\n", kind, sname ? sname : name); - SWIG_WARN_NODE_END(n); - warned = 1; - } - } - - if (!warned) - Swig_warning(WARN_PARSE_UNNAMED_NESTED_CLASS, cparse_file, cparse_line, "Nested %s not currently supported (ignored).\n", kind); - - return nn; + return name; } -/* Strips C-style and C++-style comments from string in-place. */ -static void strip_comments(char *string) { - int state = 0; /* - * 0 - not in comment - * 1 - in c-style comment - * 2 - in c++-style comment - * 3 - in string - * 4 - after reading / not in comments - * 5 - after reading * in c-style comments - * 6 - after reading \ in strings - */ - char * c = string; - while (*c) { - switch (state) { - case 0: - if (*c == '\"') - state = 3; - else if (*c == '/') - state = 4; - break; - case 1: - if (*c == '*') - state = 5; - *c = ' '; - break; - case 2: - if (*c == '\n') - state = 0; - else - *c = ' '; - break; - case 3: - if (*c == '\"') - state = 0; - else if (*c == '\\') - state = 6; - break; - case 4: - if (*c == '/') { - *(c-1) = ' '; - *c = ' '; - state = 2; - } else if (*c == '*') { - *(c-1) = ' '; - *c = ' '; - state = 1; - } else - state = 0; - break; - case 5: - if (*c == '/') - state = 0; - else - state = 1; - *c = ' '; - break; - case 6: - state = 3; - break; - } - ++c; +/* traverse copied tree segment, and update outer class links*/ +void update_nested_classes(Node* n) +{ + Node* c = firstChild(n); + while (c) { + if (Getattr(c, "nested:outer")) + Setattr(c, "nested:outer", n); + update_nested_classes(c); + c = nextSibling(c); } } -/* Dump all of the nested class declarations to the inline processor - * However. We need to do a few name replacements and other munging - * first. This function must be called before closing a class! */ - -static Node *dump_nested(const char *parent) { - Nested *n,*n1; - Node *ret = 0; - Node *last = 0; - n = nested_list; - if (!parent) { - nested_list = 0; - return 0; - } - while (n) { - Node *retx; - SwigType *nt; - /* Token replace the name of the parent class */ - Replace(n->code, "$classname", parent, DOH_REPLACE_ANY); - - /* Fix up the name of the datatype (for building typedefs and other stuff) */ - Append(n->type,parent); - Append(n->type,"_"); - Append(n->type,n->name); - - /* Add the appropriate declaration to the C++ processor */ - retx = new_node("cdecl"); - Setattr(retx,"name",n->name); - nt = Copy(n->type); - Setattr(retx,"type",nt); - Delete(nt); - Setattr(retx,"nested",parent); - if (n->unnamed) { - Setattr(retx,"unnamed","1"); - } - - add_symbols(retx); - if (ret) { - set_nextSibling(last, retx); - Delete(retx); - } else { - ret = retx; - } - last = retx; - - /* Strip comments - further code may break in presence of comments. */ - strip_comments(Char(n->code)); - - /* Make all SWIG created typedef structs/unions/classes unnamed else - redefinition errors occur - nasty hack alert.*/ - - { - const char* types_array[3] = {"struct", "union", "class"}; - int i; - for (i=0; i<3; i++) { - char* code_ptr = Char(n->code); - while (code_ptr) { - /* Replace struct name (as in 'struct name {...}' ) with whitespace - name will be between struct and opening brace */ - - code_ptr = strstr(code_ptr, types_array[i]); - if (code_ptr) { - char *open_bracket_pos; - code_ptr += strlen(types_array[i]); - open_bracket_pos = strchr(code_ptr, '{'); - if (open_bracket_pos) { - /* Make sure we don't have something like struct A a; */ - char* semi_colon_pos = strchr(code_ptr, ';'); - if (!(semi_colon_pos && (semi_colon_pos < open_bracket_pos))) - while (code_ptr < open_bracket_pos) - *code_ptr++ = ' '; - } - } - } - } - } - - { - /* Remove SWIG directive %constant which may be left in the SWIG created typedefs */ - char* code_ptr = Char(n->code); - while (code_ptr) { - code_ptr = strstr(code_ptr, "%constant"); - if (code_ptr) { - char* directive_end_pos = strchr(code_ptr, ';'); - if (directive_end_pos) { - while (code_ptr <= directive_end_pos) - *code_ptr++ = ' '; - } - } - } - } - { - Node *newnode = new_node("insert"); - String *code = NewStringEmpty(); - Wrapper_pretty_print(n->code, code); - Setattr(newnode,"code", code); - Delete(code); - set_nextSibling(last, newnode); - Delete(newnode); - last = newnode; - } - - /* Dump the code to the scanner */ - start_inline(Char(Getattr(last, "code")),n->line); - - n1 = n->next; - Delete(n->code); - free(n); - n = n1; - } - nested_list = 0; - return ret; -} - Node *Swig_cparse(File *f) { scanner_file(f); top = 0; @@ -1768,7 +1432,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %type cpp_declaration cpp_class_decl cpp_forward_class_decl cpp_template_decl cpp_alternate_rettype; %type cpp_members cpp_member; %type cpp_constructor_decl cpp_destructor_decl cpp_protection_decl cpp_conversion_operator cpp_static_assert; -%type cpp_swig_directive cpp_temp_possible cpp_nested cpp_opt_declarators ; +%type cpp_swig_directive cpp_temp_possible /*cpp_nested*/ cpp_opt_declarators ; %type cpp_using_decl cpp_namespace_decl cpp_catch_decl cpp_lambda_decl; %type kwargs options; @@ -2999,6 +2663,7 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va } templnode = copy_node(nn); + update_nested_classes(templnode); /* We need to set the node name based on name used to instantiate */ Setattr(templnode,"name",tname); Delete(tname); @@ -3007,7 +2672,7 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va } else { Setattr(templnode,"sym:typename","1"); } - if ($3 && !inclass) { + if ($3) { /* Comment this out for 1.3.28. We need to re-enable it later but first we need to @@ -3026,16 +2691,15 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va Setattr(templnode,"sym:name",nname); Delete(nname); Setattr(templnode,"feature:onlychildren", "typemap,typemapitem,typemapcopy,typedef,types,fragment"); - - if ($3) { - Swig_warning(WARN_PARSE_NESTED_TEMPLATE, cparse_file, cparse_line, "Named nested template instantiations not supported. Processing as if no name was given to %%template().\n"); - } } Delattr(templnode,"templatetype"); Setattr(templnode,"template",nn); Setfile(templnode,cparse_file); Setline(templnode,cparse_line); Delete(temparms); + if (currentOuterClass) { + SetFlag(templnode, "nested"); + } add_symbols_copy(templnode); @@ -3051,7 +2715,7 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va csyms = Swig_symbol_current(); Swig_symbol_setscope(Getattr(templnode,"symtab")); if (baselist) { - List *bases = make_inherit_list(Getattr(templnode,"name"),baselist); + List *bases = Swig_make_inherit_list(Getattr(templnode,"name"),baselist, Namespaceprefix); if (bases) { Iterator s; for (s = First(bases); s.item; s = Next(s)) { @@ -3704,10 +3368,10 @@ cpp_declaration : cpp_class_decl { $$ = $1; } /* A simple class/struct/union definition */ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { - if (nested_template == 0) { String *prefix; List *bases = 0; Node *scope = 0; + String *code; $$ = new_node("class"); Setline($$,cparse_start_line); Setattr($$,"kind",$2); @@ -3719,41 +3383,27 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { Setattr($$,"allows_typedef","1"); /* preserve the current scope */ - prev_symtab = Swig_symbol_current(); + Setattr($$,"prev_symtab",Swig_symbol_current()); /* If the class name is qualified. We need to create or lookup namespace/scope entries */ scope = resolve_create_node_scope($3); Setfile(scope,cparse_file); Setline(scope,cparse_line); $3 = scope; - - /* support for old nested classes "pseudo" support, such as: - - %rename(Ala__Ola) Ala::Ola; - class Ala::Ola { - public: - Ola() {} - }; - - this should disappear when a proper implementation is added. - */ - if (nscope_inner && Strcmp(nodeType(nscope_inner),"namespace") != 0) { - if (Namespaceprefix) { - String *name = NewStringf("%s::%s", Namespaceprefix, $3); - $3 = name; - Namespaceprefix = 0; - nscope_inner = 0; - } - } Setattr($$,"name",$3); - Delete(class_rename); - class_rename = make_name($$,$3,0); + if (currentOuterClass) { + SetFlag($$, "nested"); + Setattr($$, "nested:outer", currentOuterClass); + set_access_mode($$); + } + /* save yyrename to the class attribute, to be used later in add_symbols()*/ + Setattr($$, "class_rename", make_name($$, $3, 0)); + Setattr($$, "Classprefix", $3); Classprefix = NewString($3); /* Deal with inheritance */ - if ($4) { - bases = make_inherit_list($3,Getattr($4,"public")); - } + if ($4) + bases = Swig_make_inherit_list($3,Getattr($4,"public"),Namespaceprefix); prefix = SwigType_istemplate_templateprefix($3); if (prefix) { String *fbase, *tbase; @@ -3775,18 +3425,7 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { } Swig_symbol_newscope(); Swig_symbol_setscopename($3); - if (bases) { - Iterator s; - for (s = First(bases); s.item; s = Next(s)) { - Symtab *st = Getattr(s.item,"symtab"); - if (st) { - Setfile(st,Getfile(s.item)); - Setline(st,Getline(s.item)); - Swig_symbol_inherit(st); - } - } - Delete(bases); - } + Swig_inherit_base_symbols(bases); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); cparse_start_line = cparse_line; @@ -3805,31 +3444,27 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { Delete(tpname); } } - if (class_level >= max_class_levels) { - if (!max_class_levels) { - max_class_levels = 16; - } else { - max_class_levels *= 2; - } - class_decl = (Node**) realloc(class_decl, sizeof(Node*) * max_class_levels); - if (!class_decl) { - Swig_error(cparse_file, cparse_line, "realloc() failed\n"); - } - } - class_decl[class_level++] = $$; Delete(prefix); inclass = 1; - } + currentOuterClass = $$; + if (CPlusPlusOut) { /* save the structure declaration to declare it in global scope for C++ to see*/ + code = get_raw_text_balanced('{', '}'); + Setattr($$, "code", code); + Delete(code); + } } cpp_members RBRACE cpp_opt_declarators { - (void) $6; - if (nested_template == 0) { Node *p; SwigType *ty; - Symtab *cscope = prev_symtab; + Symtab *cscope; Node *am = 0; String *scpname = 0; - $$ = class_decl[--class_level]; - inclass = 0; + (void) $6; + $$ = currentOuterClass; + currentOuterClass = Getattr($$, "nested:outer"); + if (!currentOuterClass) + inclass = 0; + cscope = Getattr($$, "prev_symtab"); + Delattr($$, "prev_symtab"); /* Check for pure-abstract class */ Setattr($$,"abstracts", pure_abstracts($7)); @@ -3855,7 +3490,10 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { p = $9; if (p) { - set_nextSibling($$,p); + if (!cparse_cplusplus && currentOuterClass) + appendChild(currentOuterClass, p); + else + appendSibling($$, p); } if (cparse_cplusplus && !cparse_externc) { @@ -3866,41 +3504,14 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { while (p) { Setattr(p,"storage",$1); Setattr(p,"type",ty); + if (!cparse_cplusplus) { + SetFlag(p,"hasconsttype"); + SetFlag(p,"feature:immutable"); + } p = nextSibling(p); } - /* Class typedefs */ - { - String *name = $3; - if ($9) { - SwigType *decltype = Getattr($9,"decl"); - if (Cmp($1,"typedef") == 0) { - if (!decltype || !Len(decltype)) { - String *cname; - String *tdscopename; - String *class_scope = Swig_symbol_qualifiedscopename(cscope); - name = Getattr($9,"name"); - cname = Copy(name); - Setattr($$,"tdname",cname); - tdscopename = class_scope ? NewStringf("%s::%s", class_scope, name) : Copy(name); - - /* Use typedef name as class name */ - if (class_rename && (Strcmp(class_rename,$3) == 0)) { - Delete(class_rename); - class_rename = NewString(name); - } - if (!classes_typedefs) classes_typedefs = NewHash(); - if (!Equal(scpname, tdscopename) && !Getattr(classes_typedefs, tdscopename)) { - Setattr(classes_typedefs, tdscopename, $$); - } - Setattr($$,"decl",decltype); - Delete(class_scope); - Delete(cname); - Delete(tdscopename); - } - } - } - appendChild($$,dump_nested(Char(name))); - } + if ($9 && Cmp($1,"typedef") == 0) + add_typedef_name($$, $9, $3, cscope, scpname); Delete(scpname); if (cplus_mode != CPLUS_PUBLIC) { @@ -3912,10 +3523,13 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { appendChild($$,pa); Delete(pa); } + if (currentOuterClass) + restore_access_mode($$); Setattr($$,"symtab",Swig_symbol_popscope()); - Classprefix = 0; + Classprefix = Getattr($$,"Classprefix"); + Delattr($$,"Classprefix"); if (nscope_inner) { /* this is tricky */ /* we add the declaration in the original namespace */ @@ -3932,37 +3546,59 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { add_symbols($9); } else { Delete(yyrename); - yyrename = Copy(class_rename); + yyrename = 0; Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); - - add_symbols($$); - add_symbols($9); + if (!cparse_cplusplus && currentOuterClass) { /* nested C structs go into global scope*/ + Node* outer = currentOuterClass; + while (Getattr(outer, "nested:outer")) + outer = Getattr(outer, "nested:outer"); + appendSibling(outer, $$); + add_symbols($9); + set_scope_to_global(); + Delete(Namespaceprefix); + Namespaceprefix = Swig_symbol_qualifiedscopename(0); + yyrename = Copy(Getattr($$, "class_rename")); + add_symbols($$); + if (!CPlusPlusOut) + Delattr($$, "nested:outer"); + Delattr($$, "class_rename"); + $$ = 0; + } else { + yyrename = Copy(Getattr($$, "class_rename")); + add_symbols($$); + add_symbols($9); + Delattr($$, "class_rename"); + } } Swig_symbol_setscope(cscope); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); - } else { - $$ = new_node("class"); - Setattr($$,"kind",$2); - Setattr($$,"name",NewString($3)); - SetFlag($$,"nestedtemplateclass"); - } } /* An unnamed struct, possibly with a typedef */ - | storage_class cpptype LBRACE { + | storage_class cpptype inherit LBRACE { String *unnamed; + String *code; unnamed = make_unnamed(); $$ = new_node("class"); Setline($$,cparse_start_line); Setattr($$,"kind",$2); + if ($3) { + Setattr($$,"baselist", Getattr($3,"public")); + Setattr($$,"protectedbaselist", Getattr($3,"protected")); + Setattr($$,"privatebaselist", Getattr($3,"private")); + } Setattr($$,"storage",$1); Setattr($$,"unnamed",unnamed); Setattr($$,"allows_typedef","1"); - Delete(class_rename); - class_rename = make_name($$,0,0); + if (currentOuterClass) { + SetFlag($$, "nested"); + Setattr($$, "nested:outer", currentOuterClass); + set_access_mode($$); + } + Setattr($$, "class_rename", make_name($$,0,0)); if (strcmp($2,"class") == 0) { cplus_mode = CPLUS_PRIVATE; } else { @@ -3970,108 +3606,111 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { } Swig_symbol_newscope(); cparse_start_line = cparse_line; - if (class_level >= max_class_levels) { - if (!max_class_levels) { - max_class_levels = 16; - } else { - max_class_levels *= 2; - } - class_decl = (Node**) realloc(class_decl, sizeof(Node*) * max_class_levels); - if (!class_decl) { - Swig_error(cparse_file, cparse_line, "realloc() failed\n"); - } - } - class_decl[class_level++] = $$; + currentOuterClass = $$; inclass = 1; Classprefix = NewStringEmpty(); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); - } cpp_members RBRACE declarator initializer c_decl_tail { + /* save the structure declaration to make a typedef for it later*/ + code = get_raw_text_balanced('{', '}'); + Setattr($$, "code", code); + Delete(code); + } cpp_members RBRACE cpp_opt_declarators { String *unnamed; + List *bases = 0; + String *name = 0; Node *n; - (void) $4; Classprefix = 0; - $$ = class_decl[--class_level]; - inclass = 0; + $$ = currentOuterClass; + currentOuterClass = Getattr($$, "nested:outer"); + if (!currentOuterClass) + inclass = 0; + else + restore_access_mode($$); unnamed = Getattr($$,"unnamed"); - - /* Check for pure-abstract class */ - Setattr($$,"abstracts", pure_abstracts($5)); - - n = new_node("cdecl"); - Setattr(n,"name",$7.id); - Setattr(n,"unnamed",unnamed); - Setattr(n,"type",unnamed); - Setattr(n,"decl",$7.type); - Setattr(n,"parms",$7.parms); - Setattr(n,"storage",$1); - if ($9) { - Node *p = $9; - set_nextSibling(n,p); - while (p) { - String *type = Copy(unnamed); - Setattr(p,"name",$7.id); - Setattr(p,"unnamed",unnamed); - Setattr(p,"type",type); - Delete(type); - Setattr(p,"storage",$1); - p = nextSibling(p); - } - } - set_nextSibling($$,n); - Delete(n); - { + /* Check for pure-abstract class */ + Setattr($$,"abstracts", pure_abstracts($6)); + n = $8; + if (n) { + appendSibling($$,n); /* If a proper typedef name was given, we'll use it to set the scope name */ - String *name = 0; - if ($1 && (strcmp($1,"typedef") == 0)) { - if (!Len($7.type)) { - String *scpname = 0; - name = $7.id; - Setattr($$,"tdname",name); - Setattr($$,"name",name); - Swig_symbol_setscopename(name); + name = try_to_find_a_name_for_unnamed_structure($1, n); + if (name) { + String *scpname = 0; + SwigType *ty; + Setattr($$,"tdname",name); + Setattr($$,"name",name); + Swig_symbol_setscopename(name); + if ($3) + bases = Swig_make_inherit_list(name,Getattr($3,"public"),Namespaceprefix); + Swig_inherit_base_symbols(bases); /* If a proper name was given, we use that as the typedef, not unnamed */ - Clear(unnamed); - Append(unnamed, name); - - n = nextSibling(n); - set_nextSibling($$,n); - - /* Check for previous extensions */ - if (extendhash) { - String *clsname = Swig_symbol_qualifiedscopename(0); - Node *am = Getattr(extendhash,clsname); - if (am) { - /* Merge the extension into the symbol table */ - merge_extensions($$,am); - append_previous_extension($$,am); - Delattr(extendhash,clsname); - } - Delete(clsname); - } - if (!classes) classes = NewHash(); - scpname = Swig_symbol_qualifiedscopename(0); - Setattr(classes,scpname,$$); - Delete(scpname); + Clear(unnamed); + Append(unnamed, name); + if (cparse_cplusplus && !cparse_externc) { + ty = NewString(name); } else { - Swig_symbol_setscopename(""); + ty = NewStringf("%s %s", $2,name); } + while (n) { + Setattr(n,"storage",$1); + Setattr(n, "type", ty); + if (!cparse_cplusplus) { + SetFlag(n,"hasconsttype"); + SetFlag(n,"feature:immutable"); + } + n = nextSibling(n); + } + n = $8; + /* Check for previous extensions */ + if (extendhash) { + String *clsname = Swig_symbol_qualifiedscopename(0); + Node *am = Getattr(extendhash,clsname); + if (am) { + /* Merge the extension into the symbol table */ + merge_extensions($$,am); + append_previous_extension($$,am); + Delattr(extendhash,clsname); + } + Delete(clsname); + } + if (!classes) classes = NewHash(); + scpname = Swig_symbol_qualifiedscopename(0); + Setattr(classes,scpname,$$); + Delete(scpname); + } else { /* no suitable name was found for a struct */ + Setattr($$, "nested:unnamed", Getattr(n, "name")); /* save the name of the first declarator for later use in name generation*/ + while (n) { /* attach unnamed struct to the declarators, so that they would receive proper type later*/ + Setattr(n, "nested:unnamedtype", $$); + Setattr(n, "storage", $1); + n = nextSibling(n); + } + n = $8; + Swig_symbol_setscopename(""); } - appendChild($$,$5); - appendChild($$,dump_nested(Char(name))); + appendChild($$,$6); + /* Pop the scope */ + Setattr($$,"symtab",Swig_symbol_popscope()); + if (name) { + Delete(yyrename); + yyrename = Copy(Getattr($$, "class_rename")); + Delete(Namespaceprefix); + Namespaceprefix = Swig_symbol_qualifiedscopename(0); + add_symbols($$); + add_symbols(n); + Delattr($$, "class_rename"); + }else if (cparse_cplusplus) + $$ = 0; /* ignore unnamed structs for C++ */ + Delete(unnamed); + } else { /* unnamed struct w/o declarator*/ + Swig_symbol_popscope(); + Delete(Namespaceprefix); + Namespaceprefix = Swig_symbol_qualifiedscopename(0); + add_symbols($6); + Delete($$); + $$ = $6; /* pass member list to outer class/namespace (instead of self)*/ } - /* Pop the scope */ - Setattr($$,"symtab",Swig_symbol_popscope()); - if (class_rename) { - Delete(yyrename); - yyrename = NewString(class_rename); - } - Delete(Namespaceprefix); - Namespaceprefix = Swig_symbol_qualifiedscopename(0); - add_symbols($$); - add_symbols(n); - Delete(unnamed); } ; @@ -4107,41 +3746,10 @@ cpp_forward_class_decl : storage_class cpptype idcolon SEMI { ------------------------------------------------------------ */ cpp_template_decl : TEMPLATE LESSTHAN template_parms GREATERTHAN { + if (currentOuterClass) + Setattr(currentOuterClass, "template_parameters", template_parameters); template_parameters = $3; - if (inclass) - nested_template++; - } cpp_temp_possible { - - /* Don't ignore templated functions declared within a class, unless the templated function is within a nested class */ - if (nested_template <= 1) { - int is_nested_template_class = $6 && GetFlag($6, "nestedtemplateclass"); - if (is_nested_template_class) { - $$ = 0; - /* Nested template classes would probably better be ignored like ordinary nested classes using cpp_nested, but that introduces shift/reduce conflicts */ - if (cplus_mode == CPLUS_PUBLIC) { - /* Treat the nested class/struct/union as a forward declaration until a proper nested class solution is implemented */ - String *kind = Getattr($6, "kind"); - String *name = Getattr($6, "name"); - $$ = new_node("template"); - Setattr($$,"kind",kind); - Setattr($$,"name",name); - Setattr($$,"sym:weak", "1"); - Setattr($$,"templatetype","classforward"); - Setattr($$,"templateparms", $3); - add_symbols($$); - - if (GetFlag($$, "feature:nestedworkaround")) { - Swig_symbol_remove($$); - $$ = 0; - } else { - SWIG_WARN_NODE_BEGIN($$); - Swig_warning(WARN_PARSE_NAMED_NESTED_CLASS, cparse_file, cparse_line, "Nested template %s not currently supported (%s ignored).\n", kind, name); - SWIG_WARN_NODE_END($$); - } - } - Delete($6); - } else { String *tname = 0; int error = 0; @@ -4387,13 +3995,10 @@ cpp_template_decl : TEMPLATE LESSTHAN template_parms GREATERTHAN { Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); if (error) $$ = 0; - } - } else { - $$ = 0; - } - template_parameters = 0; - if (inclass) - nested_template--; + if (currentOuterClass) + template_parameters = Getattr(currentOuterClass, "template_parameters"); + else + template_parameters = 0; } /* Explicit template instantiation */ @@ -4622,6 +4227,8 @@ cpp_members : cpp_member cpp_members { p = nextSibling(p); } set_nextSibling(pp,$2); + if ($2) + set_previousSibling($2, pp); } else { $$ = $2; } @@ -4678,7 +4285,8 @@ cpp_member : c_declaration { $$ = $1; } | cpp_swig_directive { $$ = $1; } | cpp_conversion_operator { $$ = $1; } | cpp_forward_class_decl { $$ = $1; } - | cpp_nested { $$ = $1; } + | cpp_class_decl { $$ = $1; } +/* | cpp_nested { $$ = $1; }*/ | storage_class idcolon SEMI { $$ = 0; } | cpp_using_decl { $$ = $1; } | cpp_template_decl { $$ = $1; } @@ -4906,82 +4514,6 @@ cpp_protection_decl : PUBLIC COLON { cplus_mode = CPLUS_PROTECTED; } ; - - -/* ------------------------------------------------------------ - Named nested structs: - struct sname { }; - struct sname { } id; - struct sname : bases { }; - struct sname : bases { } id; - typedef sname struct { } td; - typedef sname struct : bases { } td; - - Adding inheritance, ie replacing 'ID' with 'idcolon inherit' - added one shift/reduce - ------------------------------------------------------------ */ - -cpp_nested : storage_class cpptype idcolon inherit LBRACE { - cparse_start_line = cparse_line; - skip_balanced('{','}'); - $$ = NewString(scanner_ccode); /* copied as initializers overwrite scanner_ccode */ - } cpp_opt_declarators { - $$ = 0; - if (cplus_mode == CPLUS_PUBLIC) { - if (cparse_cplusplus) { - String *name = Copy($3); - $$ = nested_forward_declaration($1, $2, $3, name, $7); - } else if ($7) { - nested_new_struct($2, $6, $7); - } - } - Delete($6); - } - -/* ------------------------------------------------------------ - Unnamed/anonymous nested structs: - struct { }; - struct { } id; - struct : bases { }; - struct : bases { } id; - typedef struct { } td; - typedef struct : bases { } td; - ------------------------------------------------------------ */ - - | storage_class cpptype inherit LBRACE { - cparse_start_line = cparse_line; - skip_balanced('{','}'); - $$ = NewString(scanner_ccode); /* copied as initializers overwrite scanner_ccode */ - } cpp_opt_declarators { - $$ = 0; - if (cplus_mode == CPLUS_PUBLIC) { - if (cparse_cplusplus) { - String *name = $6 ? Copy(Getattr($6, "name")) : 0; - $$ = nested_forward_declaration($1, $2, 0, name, $6); - } else { - if ($6) { - nested_new_struct($2, $5, $6); - } else { - Swig_warning(WARN_PARSE_UNNAMED_NESTED_CLASS, cparse_file, cparse_line, "Nested %s not currently supported (ignored).\n", $2); - } - } - } - Delete($5); - } - - -/* This unfortunately introduces 4 shift/reduce conflicts, so instead the somewhat hacky nested_template is used for ignore nested template classes. */ -/* - | TEMPLATE LESSTHAN template_parms GREATERTHAN cpptype idcolon LBRACE { cparse_start_line = cparse_line; skip_balanced('{','}'); - } SEMI { - $$ = 0; - if (cplus_mode == CPLUS_PUBLIC) { - Swig_warning(WARN_PARSE_NAMED_NESTED_CLASS, cparse_file, cparse_line,"Nested %s not currently supported (%s ignored)\n", $5, $6); - } - } -*/ - ; - /* These directives can be included inside a class definition */ cpp_swig_directive: pragma_directive { $$ = $1; } diff --git a/Source/Include/swigwarn.h b/Source/Include/swigwarn.h index 65ff70dd9..7b535f748 100644 --- a/Source/Include/swigwarn.h +++ b/Source/Include/swigwarn.h @@ -75,7 +75,6 @@ #define WARN_PARSE_PRIVATE_INHERIT 309 #define WARN_PARSE_TEMPLATE_REPEAT 310 #define WARN_PARSE_TEMPLATE_PARTIAL 311 -#define WARN_PARSE_UNNAMED_NESTED_CLASS 312 #define WARN_PARSE_UNDEFINED_EXTERN 313 #define WARN_PARSE_KEYWORD 314 #define WARN_PARSE_USING_UNDEF 315 @@ -88,7 +87,6 @@ #define WARN_PARSE_REDUNDANT 322 #define WARN_PARSE_REC_INHERITANCE 323 #define WARN_PARSE_NESTED_TEMPLATE 324 -#define WARN_PARSE_NAMED_NESTED_CLASS 325 #define WARN_PARSE_EXTEND_NAME 326 #define WARN_CPP11_LAMBDA 340 diff --git a/Source/Modules/allocate.cxx b/Source/Modules/allocate.cxx index b7daae59c..4e71711d6 100644 --- a/Source/Modules/allocate.cxx +++ b/Source/Modules/allocate.cxx @@ -559,6 +559,8 @@ Allocate(): virtual int classDeclaration(Node *n) { Symtab *symtab = Swig_symbol_current(); Swig_symbol_setscope(Getattr(n, "symtab")); + Node* oldInclass = inclass; + AccessMode oldAcessMode = cplus_mode; if (!CPlusPlus) { /* Always have default constructors/destructors in C */ @@ -580,7 +582,6 @@ Allocate(): } } } - inclass = n; String *kind = Getattr(n, "kind"); if (Strcmp(kind, "class") == 0) { @@ -728,7 +729,8 @@ Allocate(): /* Only care about default behavior. Remove temporary values */ Setattr(n, "allocate:visit", "1"); - inclass = 0; + inclass = oldInclass; + cplus_mode = oldAcessMode; Swig_symbol_setscope(symtab); return SWIG_OK; } diff --git a/Source/Modules/contract.cxx b/Source/Modules/contract.cxx index ffd799cfd..981a21883 100644 --- a/Source/Modules/contract.cxx +++ b/Source/Modules/contract.cxx @@ -342,11 +342,13 @@ int Contracts::namespaceDeclaration(Node *n) { int Contracts::classDeclaration(Node *n) { int ret = SWIG_OK; + int oldInClass = InClass; + Node* oldClass = CurrentClass; InClass = 1; CurrentClass = n; emit_children(n); - InClass = 0; - CurrentClass = 0; + InClass = oldInClass; + CurrentClass = oldClass; return ret; } diff --git a/Source/Modules/csharp.cxx b/Source/Modules/csharp.cxx index 6b9219750..a0332f1ae 100644 --- a/Source/Modules/csharp.cxx +++ b/Source/Modules/csharp.cxx @@ -18,6 +18,8 @@ /* Hash type used for upcalls from C/C++ */ typedef DOH UpcallData; +// insert N tabs before each new line in s +void Swig_offset_string(String* s, int N); class CSHARP:public Language { static const char *usage; @@ -53,7 +55,6 @@ class CSHARP:public Language { String *proxy_class_code; String *module_class_code; String *proxy_class_name; // proxy class name - String *full_proxy_class_name;// fully qualified proxy class name when using nspace feature, otherwise same as proxy_class_name String *full_imclass_name; // fully qualified intermediary class name when using nspace feature, otherwise same as imclass_name String *variable_name; //Name of a variable being wrapped String *proxy_class_constants_code; @@ -87,6 +88,7 @@ class CSHARP:public Language { int n_directors; int first_class_dmethod; int curr_class_dmethod; + int nesting_depth; enum EnumFeature { SimpleEnum, TypeunsafeEnum, TypesafeEnum, ProperEnum }; @@ -125,7 +127,6 @@ public: proxy_class_code(NULL), module_class_code(NULL), proxy_class_name(NULL), - full_proxy_class_name(NULL), full_imclass_name(NULL), variable_name(NULL), proxy_class_constants_code(NULL), @@ -156,7 +157,8 @@ public: n_dmethods(0), n_directors(0), first_class_dmethod(0), - curr_class_dmethod(0) { + curr_class_dmethod(0), + nesting_depth(0){ /* for now, multiple inheritance in directors is disabled, this should be easy to implement though */ director_multiple_inheritance = 0; @@ -179,7 +181,13 @@ public: proxyname = Getattr(n, "proxyname"); if (!proxyname) { String *nspace = Getattr(n, "sym:nspace"); - String *symname = Getattr(n, "sym:name"); + String *symname = Copy(Getattr(n, "sym:name")); + if (!GetFlag(n, "feature:flatnested")) { + for (Node* outer_class = Getattr(n, "nested:outer");outer_class;outer_class = Getattr(outer_class, "nested:outer")) { + Push(symname, "."); + Push(symname, Getattr(outer_class, "sym:name")); + } + } if (nspace) { if (namespce) proxyname = NewStringf("%s.%s.%s", namespce, nspace, symname); @@ -190,12 +198,33 @@ public: } Setattr(n, "proxyname", proxyname); Delete(proxyname); + Delete(symname); } } } return proxyname; } + /* ----------------------------------------------------------------------------- + * directorClassName() + * ----------------------------------------------------------------------------- */ + + String *directorClassName(Node *n) { + String *dirclassname; + const char *attrib = "director:classname"; + + if (!(dirclassname = Getattr(n, attrib))) { + String *classname = getClassPrefix(); + + dirclassname = NewStringf("SwigDirector_%s", classname); + Setattr(n, attrib, dirclassname); + } + else + dirclassname = Copy(dirclassname); + + return dirclassname; + } + /* ------------------------------------------------------------ * main() * ------------------------------------------------------------ */ @@ -1025,7 +1054,7 @@ public: */ if (proxy_flag && wrapping_member_flag && !enum_constant_flag) { // Capitalize the first letter in the variable in the getter/setter function name - bool getter_flag = Cmp(symname, Swig_name_set(getNSpace(), Swig_name_member(0, proxy_class_name, variable_name))) != 0; + bool getter_flag = Cmp(symname, Swig_name_set(getNSpace(), Swig_name_member(0, getClassPrefix(), variable_name))) != 0; String *getter_setter_name = NewString(""); if (!getter_flag) @@ -1589,6 +1618,7 @@ public: String *c_baseclassname = NULL; SwigType *typemap_lookup_type = Getattr(n, "classtypeobj"); bool feature_director = Swig_directorclass(n) ? true : false; + bool has_outerclass = Getattr(n, "nested:outer") != 0 && !GetFlag(n, "feature:flatnested"); // Inheritance from pure C# classes Node *attributes = NewHash(); @@ -1648,7 +1678,8 @@ public: // Pure C# interfaces const String *pure_interfaces = typemapLookup(n, derived ? "csinterfaces_derived" : "csinterfaces", typemap_lookup_type, WARN_NONE); // Start writing the proxy class - Printv(proxy_class_def, typemapLookup(n, "csimports", typemap_lookup_type, WARN_NONE), // Import statements + if (!has_outerclass) + Printv(proxy_class_def, typemapLookup(n, "csimports", typemap_lookup_type, WARN_NONE), // Import statements "\n", NIL); // Class attributes @@ -1719,7 +1750,7 @@ public: Printf(proxy_class_code, " if (SwigDerivedClassHasMethod(\"%s\", swigMethodTypes%s))\n", method, methid); Printf(proxy_class_code, " swigDelegate%s = new SwigDelegate%s_%s(SwigDirector%s);\n", methid, proxy_class_name, methid, overname); } - String *director_connect_method_name = Swig_name_member(getNSpace(), proxy_class_name, "director_connect"); + String *director_connect_method_name = Swig_name_member(getNSpace(), getClassPrefix(), "director_connect"); Printf(proxy_class_code, " %s.%s(swigCPtr", imclass_name, director_connect_method_name); for (i = first_class_dmethod; i < curr_class_dmethod; ++i) { UpcallData *udata = Getitem(dmethods_seq, i); @@ -1795,7 +1826,7 @@ public: // Add code to do C++ casting to base class (only for classes in an inheritance hierarchy) if (derived) { String *smartptr = Getattr(n, "feature:smartptr"); - String *upcast_method = Swig_name_member(getNSpace(), proxy_class_name, smartptr != 0 ? "SWIGSmartPtrUpcast" : "SWIGUpcast"); + String *upcast_method = Swig_name_member(getNSpace(), getClassPrefix(), smartptr != 0 ? "SWIGSmartPtrUpcast" : "SWIGUpcast"); String *wname = Swig_name_wrapper(upcast_method); Printv(imclass_cppcasts_code, "\n [global::System.Runtime.InteropServices.DllImport(\"", dllimport, "\", EntryPoint=\"", wname, "\")]\n", NIL); @@ -1846,11 +1877,35 @@ public: String *nspace = getNSpace(); File *f_proxy = NULL; + // save class local variables + String* old_proxy_class_name = proxy_class_name; + String* old_full_imclass_name = full_imclass_name; + String* old_destructor_call = destructor_call; + String* old_proxy_class_constants_code = proxy_class_constants_code; + String* old_proxy_class_def = proxy_class_def; + String* old_proxy_class_code = proxy_class_code; + if (proxy_flag) { proxy_class_name = NewString(Getattr(n, "sym:name")); + if (Node* outer = Getattr(n, "nested:outer")) { + String* outerClassesPrefix = Copy(Getattr(outer, "sym:name")); + for (outer = Getattr(outer, "nested:outer"); outer != 0; outer = Getattr(outer, "nested:outer")) { + Push(outerClassesPrefix, "::"); + Push(outerClassesPrefix, Getattr(outer, "sym:name")); + } + String* fnspace = nspace ? NewStringf("%s::%s", nspace, outerClassesPrefix) : outerClassesPrefix; + if (!addSymbol(proxy_class_name, n, fnspace)) + return SWIG_ERROR; + if (nspace) + Delete(fnspace); + Delete(outerClassesPrefix); + } + else { + if (!addSymbol(proxy_class_name, n, nspace)) + return SWIG_ERROR; + } if (!nspace) { - full_proxy_class_name = NewStringf("%s", proxy_class_name); full_imclass_name = NewStringf("%s", imclass_name); if (Cmp(proxy_class_name, imclass_name) == 0) { Printf(stderr, "Class name cannot be equal to intermediary class name: %s\n", proxy_class_name); @@ -1863,36 +1918,34 @@ public: } } else { if (namespce) { - full_proxy_class_name = NewStringf("%s.%s.%s", namespce, nspace, proxy_class_name); full_imclass_name = NewStringf("%s.%s", namespce, imclass_name); } else { - full_proxy_class_name = NewStringf("%s.%s", nspace, proxy_class_name); full_imclass_name = NewStringf("%s", imclass_name); } } - if (!addSymbol(proxy_class_name, n, nspace)) - return SWIG_ERROR; + // inner class doesn't need this prologue + if (!Getattr(n, "nested:outer")) { + String *output_directory = outputDirectory(nspace); + String *filen = NewStringf("%s%s.cs", output_directory, proxy_class_name); + f_proxy = NewFile(filen, "w", SWIG_output_files()); + if (!f_proxy) { + FileErrorDisplay(filen); + SWIG_exit(EXIT_FAILURE); + } + Append(filenames_list, Copy(filen)); + Delete(filen); + filen = NULL; - String *output_directory = outputDirectory(nspace); - String *filen = NewStringf("%s%s.cs", output_directory, proxy_class_name); - f_proxy = NewFile(filen, "w", SWIG_output_files()); - if (!f_proxy) { - FileErrorDisplay(filen); - SWIG_exit(EXIT_FAILURE); + // Start writing out the proxy class file + emitBanner(f_proxy); + + addOpenNamespace(nspace, f_proxy); } - Append(filenames_list, Copy(filen)); - Delete(filen); - filen = NULL; - - // Start writing out the proxy class file - emitBanner(f_proxy); - - addOpenNamespace(nspace, f_proxy); - - Clear(proxy_class_def); - Clear(proxy_class_code); - + else + ++nesting_depth; + proxy_class_def = NewString(""); + proxy_class_code = NewString(""); destructor_call = NewString(""); proxy_class_constants_code = NewString(""); } @@ -1903,7 +1956,7 @@ public: emitProxyClassDefAndCPPCasts(n); - String *csclazzname = Swig_name_member(getNSpace(), proxy_class_name, ""); // mangled full proxy class name + String *csclazzname = Swig_name_member(getNSpace(), getClassPrefix(), ""); // mangled full proxy class name Replaceall(proxy_class_def, "$csclassname", proxy_class_name); Replaceall(proxy_class_code, "$csclassname", proxy_class_name); @@ -1924,17 +1977,36 @@ public: Replaceall(proxy_class_def, "$dllimport", dllimport); Replaceall(proxy_class_code, "$dllimport", dllimport); Replaceall(proxy_class_constants_code, "$dllimport", dllimport); - - Printv(f_proxy, proxy_class_def, proxy_class_code, NIL); + bool has_outerclass = Getattr(n, "nested:outer") != 0 && !GetFlag(n, "feature:flatnested"); + if (!has_outerclass) + Printv(f_proxy, proxy_class_def, proxy_class_code, NIL); + else { + Swig_offset_string(proxy_class_def, nesting_depth); + Append(old_proxy_class_code, proxy_class_def); + Swig_offset_string(proxy_class_code, nesting_depth); + Append(old_proxy_class_code, proxy_class_code); + } // Write out all the constants - if (Len(proxy_class_constants_code) != 0) - Printv(f_proxy, proxy_class_constants_code, NIL); - - Printf(f_proxy, "}\n"); - addCloseNamespace(nspace, f_proxy); - Delete(f_proxy); - f_proxy = NULL; + if (Len(proxy_class_constants_code) != 0) { + if (!has_outerclass) + Printv(f_proxy, proxy_class_constants_code, NIL); + else { + Swig_offset_string(proxy_class_constants_code, nesting_depth); + Append(old_proxy_class_code, proxy_class_constants_code); + } + } + if (!has_outerclass) { + Printf(f_proxy, "}\n"); + addCloseNamespace(nspace, f_proxy); + Delete(f_proxy); + f_proxy = NULL; + } else { + for (int i = 0; i < nesting_depth; ++i) + Append(old_proxy_class_code, " "); + Append(old_proxy_class_code, "}\n"); + --nesting_depth; + } /* Output the downcast method, if necessary. Note: There's no other really good place to put this code, since Abstract Base Classes (ABCs) can and should have @@ -1971,17 +2043,18 @@ public: Delete(csclazzname); Delete(proxy_class_name); - proxy_class_name = NULL; - Delete(full_proxy_class_name); - full_proxy_class_name = NULL; + proxy_class_name = old_proxy_class_name; Delete(full_imclass_name); - full_imclass_name = NULL; + full_imclass_name = old_full_imclass_name; Delete(destructor_call); - destructor_call = NULL; + destructor_call = old_destructor_call; Delete(proxy_class_constants_code); - proxy_class_constants_code = NULL; + proxy_class_constants_code = old_proxy_class_constants_code; + Delete(proxy_class_def); + proxy_class_def = old_proxy_class_def; + Delete(proxy_class_code); + proxy_class_code = old_proxy_class_code; } - return SWIG_OK; } @@ -1994,7 +2067,7 @@ public: if (proxy_flag) { String *overloaded_name = getOverloadedName(n); - String *intermediary_function_name = Swig_name_member(getNSpace(), proxy_class_name, overloaded_name); + String *intermediary_function_name = Swig_name_member(getNSpace(), getClassPrefix(), overloaded_name); Setattr(n, "proxyfuncname", Getattr(n, "sym:name")); Setattr(n, "imfuncname", intermediary_function_name); proxyClassFunctionHandler(n); @@ -2014,7 +2087,7 @@ public: if (proxy_flag) { String *overloaded_name = getOverloadedName(n); - String *intermediary_function_name = Swig_name_member(getNSpace(), proxy_class_name, overloaded_name); + String *intermediary_function_name = Swig_name_member(getNSpace(), getClassPrefix(), overloaded_name); Setattr(n, "proxyfuncname", Getattr(n, "sym:name")); Setattr(n, "imfuncname", intermediary_function_name); proxyClassFunctionHandler(n); @@ -2094,7 +2167,7 @@ public: if (wrapping_member_flag && !enum_constant_flag) { // Properties - setter_flag = (Cmp(Getattr(n, "sym:name"), Swig_name_set(getNSpace(), Swig_name_member(0, proxy_class_name, variable_name))) == 0); + setter_flag = (Cmp(Getattr(n, "sym:name"), Swig_name_set(getNSpace(), Swig_name_member(0, getClassPrefix(), variable_name))) == 0); if (setter_flag) Swig_typemap_attach_parms("csvarin", l, NULL); } @@ -2264,7 +2337,7 @@ public: Node *explicit_n = Getattr(n, "explicitcallnode"); if (explicit_n) { String *ex_overloaded_name = getOverloadedName(explicit_n); - String *ex_intermediary_function_name = Swig_name_member(getNSpace(), proxy_class_name, ex_overloaded_name); + String *ex_intermediary_function_name = Swig_name_member(getNSpace(), getClassPrefix(), ex_overloaded_name); String *ex_imcall = Copy(imcall); Replaceall(ex_imcall, "$imfuncname", ex_intermediary_function_name); @@ -3376,14 +3449,21 @@ public: // Output the director connect method: String *norm_name = SwigType_namestr(Getattr(n, "name")); - String *swig_director_connect = Swig_name_member(getNSpace(), proxy_class_name, "director_connect"); + String *dirclassname = directorClassName(n); + String *swig_director_connect = Swig_name_member(getNSpace(), getClassPrefix(), "director_connect"); String *wname = Swig_name_wrapper(swig_director_connect); String *sym_name = Getattr(n, "sym:name"); String *qualified_classname = Copy(sym_name); String *nspace = getNSpace(); String *dirClassName = directorClassName(n); String *smartptr = Getattr(n, "feature:smartptr"); + if (!GetFlag(n, "feature:flatnested")) { + for (Node* outer_class = Getattr(n, "nested:outer"); outer_class; outer_class = Getattr(outer_class, "nested:outer")) { + Push(qualified_classname, "."); + Push(qualified_classname, Getattr(outer_class, "sym:name")); + } + } if (nspace) Insert(qualified_classname, 0, NewStringf("%s.", nspace)); @@ -3415,7 +3495,7 @@ public: Printf(code_wrap->def, ", "); if (i != first_class_dmethod) Printf(code_wrap->code, ", "); - Printf(code_wrap->def, "%s::SWIG_Callback%s_t callback%s", dirClassName, methid, methid); + Printf(code_wrap->def, "%s::SWIG_Callback%s_t callback%s", dirclassname, methid, methid); Printf(code_wrap->code, "callback%s", methid); Printf(imclass_class_code, ", %s.SwigDelegate%s_%s delegate%s", qualified_classname, sym_name, methid, methid); } @@ -3432,7 +3512,7 @@ public: Delete(wname); Delete(swig_director_connect); Delete(qualified_classname); - Delete(dirClassName); + Delete(dirclassname); } /* --------------------------------------------------------------- @@ -3485,7 +3565,7 @@ public: // we're consistent with the sym:overload name in functionWrapper. (?? when // does the overloaded method name get set?) - imclass_dmethod = NewStringf("SwigDirector_%s", Swig_name_member(getNSpace(), classname, overloaded_name)); + imclass_dmethod = NewStringf("SwigDirector_%s", Swig_name_member(getNSpace(), getClassPrefix(), overloaded_name)); qualified_return = SwigType_rcaststr(returntype, "c_result"); @@ -3931,6 +4011,7 @@ public: Delete(proxy_method_types); Delete(callback_def); Delete(callback_code); + Delete(dirclassname); DelWrapper(w); return status; @@ -3970,13 +4051,11 @@ public: String *basetype = Getattr(parent, "classtype"); String *target = Swig_method_decl(0, decl, dirclassname, parms, 0, 0); String *call = Swig_csuperclass_call(0, basetype, superparms); - String *classtype = SwigType_namestr(Getattr(n, "name")); Printf(f_directors, "%s::%s : %s, %s {\n", dirclassname, target, call, Getattr(parent, "director:ctor")); Printf(f_directors, " swig_init_callbacks();\n"); Printf(f_directors, "}\n\n"); - Delete(classtype); Delete(target); Delete(call); } @@ -4047,6 +4126,26 @@ public: return Language::classDirectorInit(n); } + int classDeclaration(Node *n) { + String *old_director_callback_typedefs = director_callback_typedefs; + String *old_director_callbacks = director_callbacks; + String *old_director_delegate_callback = director_delegate_callback; + String *old_director_delegate_definitions = director_delegate_definitions; + String *old_director_delegate_instances = director_delegate_instances; + String *old_director_method_types = director_method_types; + String *old_director_connect_parms = director_connect_parms; + int ret = Language::classDeclaration(n); + // these variables are deleted in emitProxyClassDefAndCPPCasts, hence no Delete here + director_callback_typedefs = old_director_callback_typedefs; + director_callbacks = old_director_callbacks; + director_delegate_callback = old_director_delegate_callback; + director_delegate_definitions = old_director_delegate_definitions; + director_delegate_instances = old_director_delegate_instances; + director_method_types = old_director_method_types; + director_connect_parms = old_director_connect_parms; + return ret; + } + /* ---------------------------------------------------------------------- * classDirectorDestructor() * ---------------------------------------------------------------------- */ @@ -4079,7 +4178,7 @@ public: int classDirectorEnd(Node *n) { int i; - String *director_classname = directorClassName(n); + String *dirclassname = directorClassName(n); Wrapper *w = NewWrapper(); @@ -4089,7 +4188,7 @@ public: Printf(f_directors_h, " void swig_connect_director("); - Printf(w->def, "void %s::swig_connect_director(", director_classname); + Printf(w->def, "void %s::swig_connect_director(", dirclassname); for (i = first_class_dmethod; i < curr_class_dmethod; ++i) { UpcallData *udata = Getitem(dmethods_seq, i); @@ -4116,7 +4215,7 @@ public: Printf(f_directors_h, "};\n\n"); Printf(w->code, "}\n\n"); - Printf(w->code, "void %s::swig_init_callbacks() {\n", director_classname); + Printf(w->code, "void %s::swig_init_callbacks() {\n", dirclassname); for (i = first_class_dmethod; i < curr_class_dmethod; ++i) { UpcallData *udata = Getitem(dmethods_seq, i); String *overname = Getattr(udata, "overname"); @@ -4127,6 +4226,7 @@ public: Wrapper_print(w, f_directors); DelWrapper(w); + Delete(dirclassname); return Language::classDirectorEnd(n); } @@ -4159,8 +4259,8 @@ public: String *base = Getattr(n, "classtype"); String *class_ctor = NewString("Swig::Director()"); - String *directorname = directorClassName(n); - String *declaration = Swig_class_declaration(n, directorname); + String *dirclassname = directorClassName(n); + String *declaration = Swig_class_declaration(n, dirclassname); Printf(declaration, " : public %s, public Swig::Director", base); @@ -4168,9 +4268,12 @@ public: Setattr(n, "director:decl", declaration); Setattr(n, "director:ctor", class_ctor); - Delete(directorname); + Delete(dirclassname); } + bool nestedClassesSupported() const { + return true; + } }; /* class CSHARP */ /* ----------------------------------------------------------------------------- diff --git a/Source/Modules/java.cxx b/Source/Modules/java.cxx index 6576ad544..a286b5f8e 100644 --- a/Source/Modules/java.cxx +++ b/Source/Modules/java.cxx @@ -18,6 +18,8 @@ /* Hash type used for upcalls from C/C++ */ typedef DOH UpcallData; +// insert N tabs before each new line in s +void Swig_offset_string(String* s, int N); class JAVA:public Language { static const char *usage; @@ -86,6 +88,7 @@ class JAVA:public Language { int n_directors; int first_class_dmethod; int curr_class_dmethod; + int nesting_depth; enum EnumFeature { SimpleEnum, TypeunsafeEnum, TypesafeEnum, ProperEnum }; @@ -154,7 +157,8 @@ public: n_dmethods(0), n_directors(0), first_class_dmethod(0), - curr_class_dmethod(0) { + curr_class_dmethod(0), + nesting_depth(0){ /* for now, multiple inheritance in directors is disabled, this should be easy to implement though */ director_multiple_inheritance = 0; @@ -204,7 +208,13 @@ public: proxyname = Getattr(n, "proxyname"); if (!proxyname || jnidescriptor) { String *nspace = Getattr(n, "sym:nspace"); - String *symname = Getattr(n, "sym:name"); + String *symname = Copy(Getattr(n, "sym:name")); + if (!GetFlag(n, "feature:flatnested")) { + for (Node* outer_class = Getattr(n, "nested:outer");outer_class;outer_class = Getattr(outer_class, "nested:outer")) { + Push(symname, "."); + Push(symname, Getattr(outer_class, "sym:name")); + } + } if (nspace) { if (package && !jnidescriptor) proxyname = NewStringf("%s.%s.%s", package, nspace, symname); @@ -217,6 +227,7 @@ public: Setattr(n, "proxyname", proxyname); // Cache it Delete(proxyname); } + Delete(symname); } } } @@ -1134,7 +1145,7 @@ public: */ if (proxy_flag && wrapping_member_flag && !enum_constant_flag) { // Capitalize the first letter in the variable to create a JavaBean type getter/setter function name - bool getter_flag = Cmp(symname, Swig_name_set(getNSpace(), Swig_name_member(0, proxy_class_name, variable_name))) != 0; + bool getter_flag = Cmp(symname, Swig_name_set(getNSpace(), Swig_name_member(0, getClassPrefix(), variable_name))) != 0; String *getter_setter_name = NewString(""); if (!getter_flag) @@ -1713,6 +1724,7 @@ public: String *c_baseclassname = NULL; SwigType *typemap_lookup_type = Getattr(n, "classtypeobj"); bool feature_director = Swig_directorclass(n) ? true : false; + bool has_outerclass = Getattr(n, "nested:outer") != 0 && !GetFlag(n, "feature:flatnested"); // Inheritance from pure Java classes Node *attributes = NewHash(); @@ -1773,8 +1785,11 @@ public: const String *pure_interfaces = typemapLookup(n, "javainterfaces", typemap_lookup_type, WARN_NONE); // Start writing the proxy class - Printv(proxy_class_def, typemapLookup(n, "javaimports", typemap_lookup_type, WARN_NONE), // Import statements - "\n", typemapLookup(n, "javaclassmodifiers", typemap_lookup_type, WARN_JAVA_TYPEMAP_CLASSMOD_UNDEF), // Class modifiers + if (!has_outerclass) // Import statements + Printv(proxy_class_def, typemapLookup(n, "javaimports", typemap_lookup_type, WARN_NONE),"\n", NIL); + else + Printv(proxy_class_def, "static ", NIL); // C++ nested classes correspond to static java classes + Printv(proxy_class_def, typemapLookup(n, "javaclassmodifiers", typemap_lookup_type, WARN_JAVA_TYPEMAP_CLASSMOD_UNDEF), // Class modifiers " $javaclassname", // Class name and bases (*Char(wanted_base)) ? " extends " : "", wanted_base, *Char(pure_interfaces) ? // Pure Java interfaces " implements " : "", pure_interfaces, " {", derived ? typemapLookup(n, "javabody_derived", typemap_lookup_type, WARN_JAVA_TYPEMAP_JAVABODY_UNDEF) : // main body of class @@ -1825,7 +1840,7 @@ public: /* Also insert the swigTakeOwnership and swigReleaseOwnership methods */ if (feature_director) { String *destruct_jnicall, *release_jnicall, *take_jnicall; - String *changeown_method_name = Swig_name_member(getNSpace(), proxy_class_name, "change_ownership"); + String *changeown_method_name = Swig_name_member(getNSpace(), getClassPrefix(), "change_ownership"); destruct_jnicall = NewStringf("%s()", destruct_methodname); release_jnicall = NewStringf("%s.%s(this, swigCPtr, false)", full_imclass_name, changeown_method_name); @@ -1851,7 +1866,7 @@ public: // Add code to do C++ casting to base class (only for classes in an inheritance hierarchy) if (derived) { String *smartptr = Getattr(n, "feature:smartptr"); - String *upcast_method = Swig_name_member(getNSpace(), proxy_class_name, smartptr != 0 ? "SWIGSmartPtrUpcast" : "SWIGUpcast"); + String *upcast_method = Swig_name_member(getNSpace(), getClassPrefix(), smartptr != 0 ? "SWIGSmartPtrUpcast" : "SWIGUpcast"); String *jniname = makeValidJniName(upcast_method); String *wname = Swig_name_wrapper(jniname); Printf(imclass_cppcasts_code, " public final static native long %s(long jarg1);\n", upcast_method); @@ -1908,13 +1923,29 @@ public: virtual int classHandler(Node *n) { File *f_proxy = NULL; + String* old_proxy_class_name = proxy_class_name; + String* old_full_proxy_class_name = full_proxy_class_name; + String* old_full_imclass_name = full_imclass_name; + String* old_destructor_call = destructor_call; + String* old_destructor_throws_clause = destructor_throws_clause; + String* old_proxy_class_constants_code = proxy_class_constants_code; + String* old_proxy_class_def = proxy_class_def; + String* old_proxy_class_code = proxy_class_code; if (proxy_flag) { proxy_class_name = NewString(Getattr(n, "sym:name")); String *nspace = getNSpace(); constructIntermediateClassName(n); + String* outerClassesPrefix = 0; + if (Node* outer = Getattr(n, "nested:outer")) { + outerClassesPrefix = Copy(Getattr(outer, "sym:name")); + for (outer = Getattr(outer, "nested:outer"); outer != 0; outer = Getattr(outer, "nested:outer")) { + Push(outerClassesPrefix, "."); + Push(outerClassesPrefix, Getattr(outer, "sym:name")); + } + } if (!nspace) { - full_proxy_class_name = NewStringf("%s", proxy_class_name); + full_proxy_class_name = outerClassesPrefix ? NewStringf("%s.%s", outerClassesPrefix, proxy_class_name) : NewStringf("%s", proxy_class_name); if (Cmp(proxy_class_name, imclass_name) == 0) { Printf(stderr, "Class name cannot be equal to intermediary class name: %s\n", proxy_class_name); @@ -1926,54 +1957,73 @@ public: SWIG_exit(EXIT_FAILURE); } } else { - if (package) - full_proxy_class_name = NewStringf("%s.%s.%s", package, nspace, proxy_class_name); - else - full_proxy_class_name = NewStringf("%s.%s", nspace, proxy_class_name); + if (outerClassesPrefix) { + if (package) + full_proxy_class_name = NewStringf("%s.%s.%s.%s", package, nspace, outerClassesPrefix, proxy_class_name); + else + full_proxy_class_name = NewStringf("%s.%s.%s", nspace, outerClassesPrefix, proxy_class_name); + }else { + if (package) + full_proxy_class_name = NewStringf("%s.%s.%s", package, nspace, proxy_class_name); + else + full_proxy_class_name = NewStringf("%s.%s", nspace, proxy_class_name); + } } - if (!addSymbol(proxy_class_name, n, nspace)) - return SWIG_ERROR; - - String *output_directory = outputDirectory(nspace); - String *filen = NewStringf("%s%s.java", output_directory, proxy_class_name); - f_proxy = NewFile(filen, "w", SWIG_output_files()); - if (!f_proxy) { - FileErrorDisplay(filen); - SWIG_exit(EXIT_FAILURE); - } - Append(filenames_list, Copy(filen)); - Delete(filen); - filen = NULL; - - // Start writing out the proxy class file - emitBanner(f_proxy); - - if (package || nspace) { - Printf(f_proxy, "package "); - if (package) - Printv(f_proxy, package, nspace ? "." : "", NIL); + if (outerClassesPrefix) { + Replaceall(outerClassesPrefix, ".", "::"); + String* fnspace = nspace ? NewStringf("%s::%s", nspace, outerClassesPrefix) : outerClassesPrefix; + if (!addSymbol(proxy_class_name, n, fnspace)) + return SWIG_ERROR; if (nspace) - Printv(f_proxy, nspace, NIL); - Printf(f_proxy, ";\n"); + Delete(fnspace); + Delete(outerClassesPrefix); + } + else { + if (!addSymbol(proxy_class_name, n, nspace)) + return SWIG_ERROR; } - Clear(proxy_class_def); - Clear(proxy_class_code); + if (!Getattr(n, "nested:outer")) { + String *output_directory = outputDirectory(nspace); + String *filen = NewStringf("%s%s.java", output_directory, proxy_class_name); + f_proxy = NewFile(filen, "w", SWIG_output_files()); + if (!f_proxy) { + FileErrorDisplay(filen); + SWIG_exit(EXIT_FAILURE); + } + Append(filenames_list, Copy(filen)); + Delete(filen); + Delete(output_directory); + // Start writing out the proxy class file + emitBanner(f_proxy); + + if (package || nspace) { + Printf(f_proxy, "package "); + if (package) + Printv(f_proxy, package, nspace ? "." : "", NIL); + if (nspace) + Printv(f_proxy, nspace, NIL); + Printf(f_proxy, ";\n"); + } + } + else + ++nesting_depth; + + proxy_class_def = NewString(""); + proxy_class_code = NewString(""); destructor_call = NewString(""); destructor_throws_clause = NewString(""); proxy_class_constants_code = NewString(""); - Delete(output_directory); } - Language::classHandler(n); if (proxy_flag) { emitProxyClassDefAndCPPCasts(n); - String *javaclazzname = Swig_name_member(getNSpace(), proxy_class_name, ""); // mangled full proxy class name + String *javaclazzname = Swig_name_member(getNSpace(), getClassPrefix(), ""); // mangled full proxy class name Replaceall(proxy_class_def, "$javaclassname", proxy_class_name); Replaceall(proxy_class_code, "$javaclassname", proxy_class_name); @@ -1991,22 +2041,43 @@ public: Replaceall(proxy_class_code, "$imclassname", full_imclass_name); Replaceall(proxy_class_constants_code, "$imclassname", full_imclass_name); - Printv(f_proxy, proxy_class_def, proxy_class_code, NIL); + bool has_outerclass = Getattr(n, "nested:outer") != 0 && !GetFlag(n, "feature:flatnested"); + if (!has_outerclass) + Printv(f_proxy, proxy_class_def, proxy_class_code, NIL); + else { + Swig_offset_string(proxy_class_def, nesting_depth); + Append(old_proxy_class_code, proxy_class_def); + Swig_offset_string(proxy_class_code, nesting_depth); + Append(old_proxy_class_code, proxy_class_code); + } // Write out all the constants - if (Len(proxy_class_constants_code) != 0) - Printv(f_proxy, proxy_class_constants_code, NIL); + if (Len(proxy_class_constants_code) != 0) { + if (!has_outerclass) + Printv(f_proxy, proxy_class_constants_code, NIL); + else { + Swig_offset_string(proxy_class_constants_code, nesting_depth); + Append(old_proxy_class_code, proxy_class_constants_code); + } + } - Printf(f_proxy, "}\n"); - Delete(f_proxy); - f_proxy = NULL; + if (!has_outerclass) { + Printf(f_proxy, "}\n"); + Delete(f_proxy); + f_proxy = NULL; + } else { + for (int i = 0; i < nesting_depth; ++i) + Append(old_proxy_class_code, " "); + Append(old_proxy_class_code, "}\n"); + --nesting_depth; + } /* Output the downcast method, if necessary. Note: There's no other really good place to put this code, since Abstract Base Classes (ABCs) can and should have downcasts, making the constructorHandler() a bad place (because ABCs don't get to have constructors emitted.) */ if (GetFlag(n, "feature:javadowncast")) { - String *downcast_method = Swig_name_member(getNSpace(), proxy_class_name, "SWIGDowncast"); + String *downcast_method = Swig_name_member(getNSpace(), getClassPrefix(), "SWIGDowncast"); String *jniname = makeValidJniName(downcast_method); String *wname = Swig_name_wrapper(jniname); @@ -2038,17 +2109,21 @@ public: Delete(javaclazzname); Delete(proxy_class_name); - proxy_class_name = NULL; + proxy_class_name = old_proxy_class_name; Delete(full_proxy_class_name); - full_proxy_class_name = NULL; + full_proxy_class_name = old_full_proxy_class_name; Delete(full_imclass_name); - full_imclass_name = NULL; + full_imclass_name = old_full_imclass_name; Delete(destructor_call); - destructor_call = NULL; + destructor_call = old_destructor_call; Delete(destructor_throws_clause); - destructor_throws_clause = NULL; + destructor_throws_clause = old_destructor_throws_clause; Delete(proxy_class_constants_code); - proxy_class_constants_code = NULL; + proxy_class_constants_code = old_proxy_class_constants_code; + Delete(proxy_class_def); + proxy_class_def = old_proxy_class_def; + Delete(proxy_class_code); + proxy_class_code = old_proxy_class_code; } return SWIG_OK; @@ -2064,7 +2139,7 @@ public: if (proxy_flag) { String *overloaded_name = getOverloadedName(n); - String *intermediary_function_name = Swig_name_member(getNSpace(), proxy_class_name, overloaded_name); + String *intermediary_function_name = Swig_name_member(getNSpace(), getClassPrefix(), overloaded_name); Setattr(n, "proxyfuncname", Getattr(n, "sym:name")); Setattr(n, "imfuncname", intermediary_function_name); proxyClassFunctionHandler(n); @@ -2086,7 +2161,7 @@ public: if (proxy_flag) { String *overloaded_name = getOverloadedName(n); - String *intermediary_function_name = Swig_name_member(getNSpace(), proxy_class_name, overloaded_name); + String *intermediary_function_name = Swig_name_member(getNSpace(), getClassPrefix(), overloaded_name); Setattr(n, "proxyfuncname", Getattr(n, "sym:name")); Setattr(n, "imfuncname", intermediary_function_name); proxyClassFunctionHandler(n); @@ -2162,7 +2237,7 @@ public: if (wrapping_member_flag && !enum_constant_flag) { // For wrapping member variables (Javabean setter) - setter_flag = (Cmp(Getattr(n, "sym:name"), Swig_name_set(getNSpace(), Swig_name_member(0, proxy_class_name, variable_name))) == 0); + setter_flag = (Cmp(Getattr(n, "sym:name"), Swig_name_set(getNSpace(), Swig_name_member(0, getClassPrefix(), variable_name))) == 0); } /* Start generating the proxy function */ @@ -2316,7 +2391,7 @@ public: Node *explicit_n = Getattr(n, "explicitcallnode"); if (explicit_n) { String *ex_overloaded_name = getOverloadedName(explicit_n); - String *ex_intermediary_function_name = Swig_name_member(getNSpace(), proxy_class_name, ex_overloaded_name); + String *ex_intermediary_function_name = Swig_name_member(getNSpace(), getClassPrefix(), ex_overloaded_name); String *ex_imcall = Copy(imcall); Replaceall(ex_imcall, "$imfuncname", ex_intermediary_function_name); @@ -3399,7 +3474,7 @@ public: // Output the director connect method: String *jni_imclass_name = makeValidJniName(imclass_name); String *norm_name = SwigType_namestr(Getattr(n, "name")); - String *swig_director_connect = Swig_name_member(getNSpace(), proxy_class_name, "director_connect"); + String *swig_director_connect = Swig_name_member(getNSpace(), getClassPrefix(), "director_connect"); String *swig_director_connect_jni = makeValidJniName(swig_director_connect); String *smartptr = Getattr(n, "feature:smartptr"); String *dirClassName = directorClassName(n); @@ -3439,7 +3514,7 @@ public: Delete(swig_director_connect); // Output the swigReleaseOwnership, swigTakeOwnership methods: - String *changeown_method_name = Swig_name_member(getNSpace(), proxy_class_name, "change_ownership"); + String *changeown_method_name = Swig_name_member(getNSpace(), getClassPrefix(), "change_ownership"); String *changeown_jnimethod_name = makeValidJniName(changeown_method_name); Printf(imclass_class_code, " public final static native void %s(%s obj, long cptr, boolean take_or_release);\n", changeown_method_name, full_proxy_class_name); @@ -4519,6 +4594,9 @@ public: Setattr(n, "director:ctor", class_ctor); } + bool nestedClassesSupported() const { + return true; + } }; /* class JAVA */ /* ----------------------------------------------------------------------------- diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index e50a50a6d..89cc17a83 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -355,7 +355,7 @@ Language::~Language() { String *dirclassname; String *nspace = NewString(Getattr(n, "sym:nspace")); const char *attrib = "director:classname"; - String *classname = Getattr(n, "sym:name"); + String *classname = getClassPrefix(); Replace(nspace, NSPACE_SEPARATOR, "_", DOH_REPLACE_ANY); if (Len(nspace) > 0) @@ -1015,8 +1015,6 @@ int Language::cDeclaration(Node *n) { /* Some kind of variable declaration */ String *declaration = Copy(decl); Delattr(n, "decl"); - if (Getattr(n, "nested")) - SetFlag(n, "feature:immutable"); if (!CurrentClass) { if (Swig_storage_isextern(n) || ForceExtern) { if (AddExtern) { @@ -2362,6 +2360,15 @@ int Language::classDeclaration(Node *n) { return SWIG_NOWRAP; } + // save class local variables for nested classes support + int oldInClass = InClass; + String *oldClassType = ClassType; + String *oldClassPrefix = ClassPrefix; + String *oldClassName = ClassName; + String *oldDirectorClassName = DirectorClassName; + String *oldNSpace = NSpace; + Node* oldCurrentClass = CurrentClass; + String *kind = Getattr(n, "kind"); String *name = Getattr(n, "name"); String *tdname = Getattr(n, "tdname"); @@ -2370,6 +2377,8 @@ int Language::classDeclaration(Node *n) { int strip = CPlusPlus ? 1 : unnamed && tdname; + if (cplus_mode != PUBLIC) + return SWIG_NOWRAP; if (!name) { Swig_warning(WARN_LANG_CLASS_UNNAMED, input_file, line_number, "Can't generate wrappers for unnamed struct/class.\n"); return SWIG_NOWRAP; @@ -2380,15 +2389,21 @@ int Language::classDeclaration(Node *n) { Swig_warning(WARN_LANG_IDENTIFIER, input_file, line_number, "Can't wrap class %s unless renamed to a valid identifier.\n", SwigType_namestr(symname)); return SWIG_NOWRAP; } - + AccessMode oldAccessMode = cplus_mode; + Node* outerClass = Getattr(n, "nested:outer"); + if (outerClass && oldAccessMode != Dispatcher::PUBLIC) + return SWIG_NOWRAP; + ClassName = Copy(name); + ClassPrefix = Copy(symname); if (Cmp(kind, "class") == 0) { cplus_mode = PRIVATE; } else { cplus_mode = PUBLIC; } - - ClassName = Copy(name); - ClassPrefix = Copy(symname); + for (; outerClass; outerClass = Getattr(outerClass, "nested:outer")) { + Push(ClassPrefix, "_"); + Push(ClassPrefix, Getattr(outerClass, "sym:name")); + } if (strip) { ClassType = Copy(name); } else { @@ -2399,9 +2414,8 @@ int Language::classDeclaration(Node *n) { InClass = 1; CurrentClass = n; - - String *oldNSpace = NSpace; NSpace = Getattr(n, "sym:nspace"); + int oldAbstract = Abstract; /* Call classHandler() here */ if (!ImportMode) { @@ -2443,25 +2457,27 @@ int Language::classDeclaration(Node *n) { classDirector(n); } /* check for abstract after resolving directors */ - Abstract = abstractClassTest(n); + Abstract = abstractClassTest(n); classHandler(n); } else { Abstract = abstractClassTest(n); Language::classHandler(n); } + Abstract = oldAbstract; + cplus_mode = oldAccessMode; NSpace = oldNSpace; - InClass = 0; - CurrentClass = 0; + InClass = oldInClass; + CurrentClass = oldCurrentClass; Delete(ClassType); - ClassType = 0; + ClassType = oldClassType; Delete(ClassPrefix); - ClassPrefix = 0; + ClassPrefix = oldClassPrefix; Delete(ClassName); - ClassName = 0; + ClassName = oldClassName; Delete(DirectorClassName); - DirectorClassName = 0; + DirectorClassName = oldDirectorClassName; return SWIG_OK; } @@ -2640,7 +2656,7 @@ int Language::constructorDeclaration(Node *n) { String *scope = Swig_scopename_check(ClassName) ? Swig_scopename_prefix(ClassName) : 0; String *actual_name = scope ? NewStringf("%s::%s", scope, name) : NewString(name); Delete(scope); - if (!Equal(actual_name, expected_name) && !(Getattr(n, "template"))) { + if (!Equal(actual_name, expected_name) && !SwigType_istemplate(expected_name)) { bool illegal_name = true; if (Extend) { // Check for typedef names used as a constructor name in %extend. This is deprecated except for anonymous @@ -3426,6 +3442,9 @@ bool Language::extraDirectorProtectedCPPMethodsRequired() const { return true; } +bool Language::nestedClassesSupported() const { + return false; +} /* ----------------------------------------------------------------------------- * Language::is_wrapping_class() * ----------------------------------------------------------------------------- */ @@ -3612,3 +3631,45 @@ Language *Language::instance() { Hash *Language::getClassHash() const { return classhash; } + +// insert N tabs before each new line in s +void Swig_offset_string(String* s, int N) +{ + // count a number of lines in s + int lines = 1; + int L = Len(s); + char* start = strchr(Char(s), '\n'); + while (start) { + ++lines; + start = strchr(start + 1, '\n'); + } + // do not count pending new line + if ((Char(s))[L-1] == '\n') + --lines; + // allocate a temporary storage for a padded string + char* res = (char*)malloc(L + lines * N * 2 + 1); + res[L + lines * N * 2] = 0; + + // copy lines to res, prepending tabs to each line + char* p = res; // output pointer + start = Char(s); // start of a current line + char* end = strchr(start, '\n'); // end of a current line + while (end) { + memset(p, ' ', N*2); + p += N*2; + memcpy(p, start, end - start + 1); + p += end - start + 1; + start = end + 1; + end = strchr(start, '\n'); + } + // process the last line + if (*start) { + memset(p, ' ', N*2); + p += N*2; + strcpy(p, start); + } + // replace 's' contents with 'res' + Clear(s); + Append(s, res); + free(res); +} diff --git a/Source/Modules/main.cxx b/Source/Modules/main.cxx index 4076b9206..e2ed6a675 100644 --- a/Source/Modules/main.cxx +++ b/Source/Modules/main.cxx @@ -29,6 +29,10 @@ static Language *lang = 0; // Language method int CPlusPlus = 0; +extern "C" +{ + int CPlusPlusOut = 0; // generate C++ declarations for C code +}; int Extend = 0; // Extend flag int ForceExtern = 0; // Force extern mode int GenerateDefault = 1; // Generate default constructors @@ -483,6 +487,9 @@ void SWIG_getoptions(int argc, char *argv[]) { Preprocessor_define((DOH *) "__cplusplus __cplusplus", 0); Swig_cparse_cplusplus(1); Swig_mark_arg(i); + } else if (strcmp(argv[i], "-c++out") == 0) { + CPlusPlusOut = 1; + Swig_mark_arg(i); } else if (strcmp(argv[i], "-fcompact") == 0) { Wrapper_compact_print_mode_set(1); Swig_mark_arg(i); @@ -855,8 +862,27 @@ void SWIG_getoptions(int argc, char *argv[]) { } } - - +void Swig_flatten_nested() { + String* name = NewString(""); + String* fname = NewString("feature:flatnested"); + String* val = NewString("1"); + Swig_feature_set(Swig_cparse_features(),name,0,fname, val, 0); + Delete(fname); + Delete(name); + Delete(val); + /* + String* name = NewStringEmpty(); + Hash* newname = NewHash(); + Setattr(newname, "name", "$ignore"); + Hash* match = NewHash(); + Setattr(match, "name", "match$nested"); + Setattr(match, "value", "1"); + set_nextSibling(newname, match); + Swig_name_rename_add(0, name, 0, newname, 0); + Delete(name); + Delete(match); + Delete(newname);*/ +} int SWIG_main(int argc, char *argv[], Language *l) { @@ -1151,6 +1177,10 @@ int SWIG_main(int argc, char *argv[], Language *l) { fflush(stdout); } + // add "ignore" directive if nested classes are not supported + if (!lang->nestedClassesSupported()) + Swig_flatten_nested(); + Node *top = Swig_cparse(cpps); if (dump_top & STAGE1) { @@ -1161,6 +1191,11 @@ int SWIG_main(int argc, char *argv[], Language *l) { Printf(stdout, "debug-module stage 1\n"); Swig_print_tree(Getattr(top, "module")); } + if (!CPlusPlus) { + if (Verbose) + Printf(stdout, "Processing unnamed structs...\n"); + Swig_name_unnamed_c_structs(top); + } if (Verbose) { Printf(stdout, "Processing types...\n"); @@ -1181,6 +1216,12 @@ int SWIG_main(int argc, char *argv[], Language *l) { } Swig_default_allocators(top); + if (CPlusPlus) { + if (Verbose) + Printf(stdout, "Processing nested classes...\n"); + Swig_process_nested_classes(top); + } + if (dump_top & STAGE3) { Printf(stdout, "debug-top stage 3\n"); Swig_print_tree(top); diff --git a/Source/Modules/octave.cxx b/Source/Modules/octave.cxx index 65a1ad701..1c0192d07 100644 --- a/Source/Modules/octave.cxx +++ b/Source/Modules/octave.cxx @@ -86,6 +86,7 @@ public: director_multiple_inheritance = 1; director_language = 1; docs = NewHash(); + CPlusPlusOut = 1; } virtual void main(int argc, char *argv[]) { diff --git a/Source/Modules/swigmod.h b/Source/Modules/swigmod.h index 3a7e8a8d6..61e5f8c13 100644 --- a/Source/Modules/swigmod.h +++ b/Source/Modules/swigmod.h @@ -32,6 +32,7 @@ extern String *input_file; extern int line_number; extern int start_line; extern int CPlusPlus; // C++ mode +extern "C" int CPlusPlusOut; // generate C++ declarations for C code (currently used for Octave) extern int Extend; // Extend mode extern int Verbose; extern int IsVirtual; @@ -297,6 +298,16 @@ protected: /* Some language modules require additional wrappers for virtual methods not declared in sub-classes */ virtual bool extraDirectorProtectedCPPMethodsRequired() const; +public: + /* Does target language support nested classes? Default is 'false'. If 'false' is returned, then + %rename("$ignore", %$isnested) statement will be issued at the top, and the nested classes + will be ignored. Note that even if the target language does not support the notion of class + nesting, the language module may nevertheless return true from this function, and use + %feature "flatnested" to move nested classes to the global scope, instead of ignoring them. + */ + virtual bool nestedClassesSupported() const; + +protected: /* Identifies if a protected members that are generated when the allprotected option is used. This does not include protected virtual methods as they are turned on with the dirprot option. */ bool isNonVirtualProtectedAccess(Node *n) const; @@ -410,5 +421,7 @@ int Swig_contract_mode_get(); void Swig_browser(Node *n, int); void Swig_default_allocators(Node *n); void Swig_process_types(Node *n); +void Swig_process_nested_classes(Node *n); +void Swig_name_unnamed_c_structs(Node *n); #endif diff --git a/Source/Modules/typepass.cxx b/Source/Modules/typepass.cxx index 7eebfe80b..e5c6d2c05 100644 --- a/Source/Modules/typepass.cxx +++ b/Source/Modules/typepass.cxx @@ -178,6 +178,20 @@ class TypePass:private Dispatcher { } continue; } + // A case when both outer and nested classes inherit from the same parent. Constructor may be found instead of the class itself. + } else if (GetFlag(cls, "nested") && checkAttribute(bcls, "nodeType", "constructor")) { + bcls = Getattr(bcls, "parentNode"); + if (Getattr(bcls, "typepass:visit")) { + if (!Getattr(bcls, "feature:onlychildren")) { + if (!ilist) + ilist = alist = NewList(); + Append(ilist, bcls); + } else { + Swig_warning(WARN_TYPE_UNDEFINED_CLASS, Getfile(bname), Getline(bname), "Base class '%s' has no name as it is an empty template instantiated with '%%template()'. Ignored.\n", SwigType_namestr(bname)); + Swig_warning(WARN_TYPE_UNDEFINED_CLASS, Getfile(bcls), Getline(bcls), "The %%template directive must be written before '%s' is used as a base class and be declared with a name.\n", SwigType_namestr(bname)); + } + } + break; } if (Strcmp(nodeType(bcls), "classforward") != 0) { Swig_error(Getfile(bname), Getline(bname), "'%s' is not a valid base class.\n", SwigType_namestr(bname)); @@ -463,6 +477,18 @@ class TypePass:private Dispatcher { SwigType_typedef(unnamed, tdname); } + // name of the outer class should already be patched to contain it's outer classes names, but not to contain namespaces + // namespace name (if present) is added after processing child nodes + if (Getattr(n, "nested:outer") && name) { + String* outerName = Getattr(Getattr(n, "nested:outer"), "name"); + name = NewStringf("%s::%s", outerName, name); + Setattr(n, "name", name); + if (tdname) { + tdname = NewStringf("%s::%s", outerName, tdname); + Setattr(n, "tdname", tdname); + } + } + if (nsname && name) { nname = NewStringf("%s::%s", nsname, name); String *tdname = Getattr(n, "tdname"); @@ -479,7 +505,7 @@ class TypePass:private Dispatcher { SwigType_attach_symtab(Getattr(n, "symtab")); /* Inherit type definitions into the class */ - if (name) { + if (name && !(GetFlag(n, "nested") && GetFlag(n, "feature:flatnested") && !checkAttribute(n, "access", "public"))) { cplus_inherit_types(n, 0, nname ? nname : (fname ? fname : name)); } @@ -1258,3 +1284,432 @@ void Swig_process_types(Node *n) { return; TypePass::pass(n); } + +// Nested classes processing section +static Hash* classhash = 0; + +static String *make_name(Node *n, String *name,SwigType *decl) { + int destructor = name && (*(Char(name)) == '~'); + if (String* yyrename = Getattr(n, "class_rename")) { + String *s = NewString(yyrename); + Delattr(n, "class_rename"); + if (destructor && (*(Char(s)) != '~')) { + Insert(s,0,"~"); + } + return s; + } + + if (!name) return 0; + return Swig_name_make(n,0,name,decl,0); +} + +// C version of add_symbols() +static void add_symbols_c(Node *n) { + String *decl; + String *wrn = 0; + String *symname = 0; + int iscdecl = Cmp(nodeType(n),"cdecl") == 0; + Setattr(n,"ismember","1"); + Setattr(n,"access", "public"); + if (Getattr(n,"sym:name")) + return; + decl = Getattr(n,"decl"); + if (!SwigType_isfunction(decl)) { + String *name = Getattr(n,"name"); + String *makename = Getattr(n,"parser:makename"); + if (iscdecl) { + String *storage = Getattr(n, "storage"); + if (Cmp(storage,"typedef") == 0) { + Setattr(n,"kind","typedef"); + } else { + SwigType *type = Getattr(n,"type"); + String *value = Getattr(n,"value"); + Setattr(n,"kind","variable"); + if (value && Len(value)) { + Setattr(n,"hasvalue","1"); + } + if (type) { + SwigType *ty; + SwigType *tmp = 0; + if (decl) { + ty = tmp = Copy(type); + SwigType_push(ty,decl); + } else { + ty = type; + } + if (!SwigType_ismutable(ty)) { + SetFlag(n,"hasconsttype"); + SetFlag(n,"feature:immutable"); + } + if (tmp) Delete(tmp); + } + if (!type) { + Printf(stderr,"notype name %s\n", name); + } + } + } + Swig_features_get(Swig_cparse_features(), 0, name, 0, n); + if (makename) { + symname = make_name(n, makename, 0); + Delattr(n,"parser:makename"); /* temporary information, don't leave it hanging around */ + } else { + makename = name; + symname = make_name(n, makename, 0); + } + + if (!symname) { + symname = Copy(Getattr(n,"unnamed")); + } + if (symname) { + wrn = Swig_name_warning(n, 0, symname,0); + } + } else { + String *name = Getattr(n,"name"); + SwigType *fdecl = Copy(decl); + SwigType *fun = SwigType_pop_function(fdecl); + if (iscdecl) { + Setattr(n,"kind","function"); + } + + Swig_features_get(Swig_cparse_features(),0,name,fun,n); + + symname = make_name(n, name, fun); + wrn = Swig_name_warning(n, 0, symname,fun); + + Delete(fdecl); + Delete(fun); + + } + if (!symname) + return; + if (GetFlag(n,"feature:ignore")) { + /* Only add to C symbol table and continue */ + Swig_symbol_add(0, n); + } else if (strncmp(Char(symname),"$ignore",7) == 0) { + char *c = Char(symname)+7; + SetFlag(n,"feature:ignore"); + if (strlen(c)) { + SWIG_WARN_NODE_BEGIN(n); + Swig_warning(0,Getfile(n), Getline(n), "%s\n",c+1); + SWIG_WARN_NODE_END(n); + } + Swig_symbol_add(0, n); + } else { + Node *c; + if ((wrn) && (Len(wrn))) { + String *metaname = symname; + if (!Getmeta(metaname,"already_warned")) { + SWIG_WARN_NODE_BEGIN(n); + Swig_warning(0,Getfile(n),Getline(n), "%s\n", wrn); + SWIG_WARN_NODE_END(n); + Setmeta(metaname,"already_warned","1"); + } + } + c = Swig_symbol_add(symname,n); + + if (c != n) { + /* symbol conflict attempting to add in the new symbol */ + if (Getattr(n,"sym:weak")) { + Setattr(n,"sym:name",symname); + } else { + String *e = NewStringEmpty(); + String *en = NewStringEmpty(); + String *ec = NewStringEmpty(); + int redefined = Swig_need_redefined_warn(n,c,true); + if (redefined) { + Printf(en,"Identifier '%s' redefined (ignored)",symname); + Printf(ec,"previous definition of '%s'",symname); + } else { + Printf(en,"Redundant redeclaration of '%s'",symname); + Printf(ec,"previous declaration of '%s'",symname); + } + if (Cmp(symname,Getattr(n,"name"))) { + Printf(en," (Renamed from '%s')", SwigType_namestr(Getattr(n,"name"))); + } + Printf(en,","); + if (Cmp(symname,Getattr(c,"name"))) { + Printf(ec," (Renamed from '%s')", SwigType_namestr(Getattr(c,"name"))); + } + Printf(ec,"."); + SWIG_WARN_NODE_BEGIN(n); + if (redefined) { + Swig_warning(WARN_PARSE_REDEFINED,Getfile(n),Getline(n),"%s\n",en); + Swig_warning(WARN_PARSE_REDEFINED,Getfile(c),Getline(c),"%s\n",ec); + } else { + Swig_warning(WARN_PARSE_REDUNDANT,Getfile(n),Getline(n),"%s\n",en); + Swig_warning(WARN_PARSE_REDUNDANT,Getfile(c),Getline(c),"%s\n",ec); + } + SWIG_WARN_NODE_END(n); + Printf(e,"%s:%d:%s\n%s:%d:%s\n",Getfile(n),Getline(n),en, + Getfile(c),Getline(c),ec); + Setattr(n,"error",e); + Delete(e); + Delete(en); + Delete(ec); + } + } + } + Delete(symname); +} + +/* Strips C-style and C++-style comments from string in-place. */ +static void strip_comments(char *string) { + int state = 0; /* + * 0 - not in comment + * 1 - in c-style comment + * 2 - in c++-style comment + * 3 - in string + * 4 - after reading / not in comments + * 5 - after reading * in c-style comments + * 6 - after reading \ in strings + */ + char * c = string; + while (*c) { + switch (state) { + case 0: + if (*c == '\"') + state = 3; + else if (*c == '/') + state = 4; + break; + case 1: + if (*c == '*') + state = 5; + *c = ' '; + break; + case 2: + if (*c == '\n') + state = 0; + else + *c = ' '; + break; + case 3: + if (*c == '\"') + state = 0; + else if (*c == '\\') + state = 6; + break; + case 4: + if (*c == '/') { + *(c-1) = ' '; + *c = ' '; + state = 2; + } else if (*c == '*') { + *(c-1) = ' '; + *c = ' '; + state = 1; + } else + state = 0; + break; + case 5: + if (*c == '/') + state = 0; + else + state = 1; + *c = ' '; + break; + case 6: + state = 3; + break; + } + ++c; + } +} + +// Create an %insert with a typedef to make a new name visible to C +// the code is moved from parser.y, dump_nested() function with minor changes +static Node* create_insert(Node* n, bool noTypedef = false) { + // format a typedef + String* ccode = Getattr(n, "code"); + Push(ccode, " "); + if (noTypedef) { + Push(ccode, Getattr(n, "name")); + Push(ccode, " "); + Push(ccode, Getattr(n, "kind")); + } else { + Push(ccode, Getattr(n, "kind")); + Push(ccode, "typedef "); + Append(ccode, " "); + Append(ccode, Getattr(n, "tdname")); + } + Append(ccode, ";"); + + + /* Strip comments - further code may break in presence of comments. */ + strip_comments(Char(ccode)); + + /* Make all SWIG created typedef structs/unions/classes unnamed else + redefinition errors occur - nasty hack alert.*/ + if (!noTypedef) { + const char* types_array[3] = {"struct", "union", "class"}; + for (int i = 0; i < 3; i++) { + char* code_ptr = Char(ccode); + while (code_ptr) { + /* Replace struct name (as in 'struct name {...}' ) with whitespace + name will be between struct and opening brace */ + + code_ptr = strstr(code_ptr, types_array[i]); + if (code_ptr) { + char *open_bracket_pos; + code_ptr += strlen(types_array[i]); + open_bracket_pos = strchr(code_ptr, '{'); + if (open_bracket_pos) { + /* Make sure we don't have something like struct A a; */ + char* semi_colon_pos = strchr(code_ptr, ';'); + if (!(semi_colon_pos && (semi_colon_pos < open_bracket_pos))) + while (code_ptr < open_bracket_pos) + *code_ptr++ = ' '; + } + } + } + } + } + { + /* Remove SWIG directive %constant which may be left in the SWIG created typedefs */ + char* code_ptr = Char(ccode); + while (code_ptr) { + code_ptr = strstr(code_ptr, "%constant"); + if (code_ptr) { + char* directive_end_pos = strchr(code_ptr, ';'); + if (directive_end_pos) { + while (code_ptr <= directive_end_pos) + *code_ptr++ = ' '; + } + } + } + } + Node *newnode = NewHash(); + set_nodeType(newnode ,"insert"); + Setfile(newnode ,Getfile(n)); + Setline(newnode ,Getline(n)); + String *code = NewStringEmpty(); + Wrapper_pretty_print(ccode, code); + Setattr(newnode, "code", code); + Delete(code); + Delattr(n, "code"); + return newnode; +} + +static void insertNodeAfter(Node *n, Node* c) +{ + Node* g = parentNode(n); + set_parentNode(c, g); + Node* ns = nextSibling(n); + if (Node* outer = Getattr(c, "nested:outer")) { + while (ns && outer == Getattr(ns, "nested:outer")) { + n = ns; + ns = nextSibling(n); + } + } + if (!ns) { + set_lastChild(g, c); + } + else { + set_nextSibling(c, ns); + set_previousSibling(ns, c); + } + set_nextSibling(n, c); + set_previousSibling(c, n); +} + +void Swig_name_unnamed_c_structs(Node *n) { + if (!classhash) + classhash = Getattr(n, "classes"); + Node* c = firstChild(n); + while (c) { + Node* next = nextSibling(c); + if (String* declName = Getattr(c, "nested:unnamed")) { + if (Node* outer = Getattr(c, "nested:outer")) { + // generate a name + String* name = NewStringf("%s_%s", Getattr(outer, "name"), declName); + Delattr(c, "nested:unnamed"); + // set the name to the class and symbol table + Setattr(c, "tdname", name); + Setattr(c, "name", name); + Swig_symbol_setscope(Getattr(c,"symtab")); + Swig_symbol_setscopename(name); + // now that we have a name - gather base symbols + if (List* publicBases = Getattr(c,"baselist")) { + List* bases = Swig_make_inherit_list(name, publicBases, 0); + Swig_inherit_base_symbols(bases); + Delete(bases); + } + Setattr(classhash,name,c); + Swig_symbol_popscope(); + // process declarations following this type (assign correct new type) + SwigType* ty = Copy(name); + Node* decl = nextSibling(c); + List* declList = NewList(); + while (decl && Getattr(decl, "nested:unnamedtype") == c) { + Setattr(decl, "type", ty); + Append(declList, decl); + Delattr(decl, "nested:unnamedtype"); + SetFlag(decl, "feature:immutable"); + add_symbols_c(decl); + decl = nextSibling(decl); + } + Delete(ty); + // Check for extensions +/* // TODO: we can save extensions hash like class hash and move check_extensions() after nesting processing + if (extendhash) { + if (Node *am = Getattr(extendhash, name)) { + // Merge the extension into the symbol table + merge_extensions(c, am); + append_previous_extension(c, am); + Delattr(extendhash, clsname); + } + }*/ + Swig_symbol_setscope(Swig_symbol_global_scope()); + add_symbols_c(c); + + Node* ins = create_insert(c); + insertNodeAfter(c, ins); + removeNode(c); + insertNodeAfter(n, c); + Delete(ins); + Delattr(c, "nested:outer"); + }else { + // global unnamed struct - ignore it + c = next; + continue; + } + } else if (CPlusPlusOut) { + if (Getattr(c, "nested:outer")) { + Node* ins = create_insert(c, true); + insertNodeAfter(c, ins); + Delete(ins); + Delattr(c, "nested:outer"); + } + } + // process children + Swig_name_unnamed_c_structs(c); + c = next; + } +} +static void remove_outer_class_reference(Node *n) +{ + for (Node* c = firstChild(n); c; c = nextSibling(c)) { + if (GetFlag(c, "feature:flatnested")) { + Delattr(c, "nested:outer"); + remove_outer_class_reference(c); + } + } +} +void Swig_process_nested_classes(Node *n) { + Node* c = firstChild(n); + while (c) { + Node* next = nextSibling(c); + if (!Getattr(c,"templatetype")) { + if (GetFlag(c, "nested") && GetFlag(c, "feature:flatnested")) { + removeNode(c); + if (!checkAttribute(c, "access", "public")) + SetFlag(c, "feature:ignore"); + else + insertNodeAfter(n, c); + } + Swig_process_nested_classes(c); + } + c = next; + } + remove_outer_class_reference(n); +} diff --git a/Source/Swig/naming.c b/Source/Swig/naming.c index 119f816dc..d860a8b00 100644 --- a/Source/Swig/naming.c +++ b/Source/Swig/naming.c @@ -1648,6 +1648,71 @@ void Swig_name_inherit(String *base, String *derived) { Swig_name_object_inherit(Swig_cparse_features(), base, derived); } +void Swig_inherit_base_symbols(List* bases) { + if (bases) { + Iterator s; + for (s = First(bases); s.item; s = Next(s)) { + Symtab *st = Getattr(s.item,"symtab"); + if (st) { + Setfile(st,Getfile(s.item)); + Setline(st,Getline(s.item)); + Swig_symbol_inherit(st); + } + } + Delete(bases); + } +} + +List *Swig_make_inherit_list(String *clsname, List *names, String* Namespaceprefix) { + int i, ilen; + String *derived; + List *bases = NewList(); + + if (Namespaceprefix) derived = NewStringf("%s::%s", Namespaceprefix,clsname); + else derived = NewString(clsname); + + ilen = Len(names); + for (i = 0; i < ilen; i++) { + Node *s; + String *base; + String *n = Getitem(names,i); + /* Try to figure out where this symbol is */ + s = Swig_symbol_clookup(n,0); + if (s) { + while (s && (Strcmp(nodeType(s),"class") != 0)) { + /* Not a class. Could be a typedef though. */ + String *storage = Getattr(s,"storage"); + if (storage && (Strcmp(storage,"typedef") == 0)) { + String *nn = Getattr(s,"type"); + s = Swig_symbol_clookup(nn,Getattr(s,"sym:symtab")); + } else { + break; + } + } + if (s && ((Strcmp(nodeType(s),"class") == 0) || (Strcmp(nodeType(s),"template") == 0))) { + String *q = Swig_symbol_qualified(s); + Append(bases,s); + if (q) { + base = NewStringf("%s::%s", q, Getattr(s,"name")); + Delete(q); + } else { + base = NewString(Getattr(s,"name")); + } + } else { + base = NewString(n); + } + } else { + base = NewString(n); + } + if (base) { + Swig_name_inherit(base,derived); + Delete(base); + } + } + return bases; +} + + /* ----------------------------------------------------------------------------- * void Swig_name_str() * diff --git a/Source/Swig/scanner.c b/Source/Swig/scanner.c index 181d9aa74..39eaaf4d4 100644 --- a/Source/Swig/scanner.c +++ b/Source/Swig/scanner.c @@ -1545,7 +1545,110 @@ int Scanner_skip_balanced(Scanner * s, int startchar, int endchar) { Delete(locator); return 0; } +/* returns raw text between 2 braces, does not change scanner state in any way*/ +String* Scanner_get_raw_text_balanced(Scanner* s, int startchar, int endchar) +{ + String* result = 0; + char c; + int old_line = s->line; + String* old_text = Copy(s->text); + int position = Tell(s->str); + int num_levels = 1; + int state = 0; + char temp[2] = { 0, 0 }; + temp[0] = (char) startchar; + Clear(s->text); + Setfile(s->text, Getfile(s->str)); + Setline(s->text, s->line); + Append(s->text, temp); + while (num_levels > 0) { + if ((c = nextchar(s)) == 0) { + Clear(s->text); + Append(s->text, old_text); + Delete(old_text); + s->line = old_line; + return 0; + } + switch (state) { + case 0: + if (c == startchar) + num_levels++; + else if (c == endchar) + num_levels--; + else if (c == '/') + state = 10; + else if (c == '\"') + state = 20; + else if (c == '\'') + state = 30; + break; + case 10: + if (c == '/') + state = 11; + else if (c == '*') + state = 12; + else if (c == startchar) { + state = 0; + num_levels++; + } + else + state = 0; + break; + case 11: + if (c == '\n') + state = 0; + else + state = 11; + break; + case 12: /* first character inside C comment */ + if (c == '*') + state = 14; + else + state = 13; + break; + case 13: + if (c == '*') + state = 14; + break; + case 14: /* possible end of C comment */ + if (c == '*') + state = 14; + else if (c == '/') + state = 0; + else + state = 13; + break; + case 20: + if (c == '\"') + state = 0; + else if (c == '\\') + state = 21; + break; + case 21: + state = 20; + break; + case 30: + if (c == '\'') + state = 0; + else if (c == '\\') + state = 31; + break; + case 31: + state = 30; + break; + default: + break; + } + } + Seek(s->str, position, SEEK_SET); + result = Copy(s->text); + Clear(s->text); + Append(s->text, old_text); + Delete(old_text); + s->line = old_line; + return result; +} /* ----------------------------------------------------------------------------- * Scanner_isoperator() * diff --git a/Source/Swig/swig.h b/Source/Swig/swig.h index b730ab04d..9a4163c2c 100644 --- a/Source/Swig/swig.h +++ b/Source/Swig/swig.h @@ -286,6 +286,8 @@ extern int ParmList_is_compactdefargs(ParmList *p); extern Hash *Swig_name_namewarn_get(Node *n, String *prefix, String *name, SwigType *decl); extern void Swig_name_rename_add(String *prefix, String *name, SwigType *decl, Hash *namewrn, ParmList *declaratorparms); extern void Swig_name_inherit(String *base, String *derived); + extern List *Swig_make_inherit_list(String *clsname, List *names, String* Namespaceprefix); + extern void Swig_inherit_base_symbols(List* bases); extern int Swig_need_protected(Node *n); extern int Swig_need_name_warning(Node *n); extern int Swig_need_redefined_warn(Node *a, Node *b, int InClass); diff --git a/Source/Swig/swigscan.h b/Source/Swig/swigscan.h index 017ef58d5..6a181f86f 100644 --- a/Source/Swig/swigscan.h +++ b/Source/Swig/swigscan.h @@ -22,6 +22,7 @@ extern int Scanner_token(Scanner *); extern String *Scanner_text(Scanner *); extern void Scanner_skip_line(Scanner *); extern int Scanner_skip_balanced(Scanner *, int startchar, int endchar); +extern String *Scanner_get_raw_text_balanced(Scanner *, int startchar, int endchar); extern void Scanner_set_location(Scanner *, String *file, int line); extern String *Scanner_file(Scanner *); extern int Scanner_line(Scanner *); diff --git a/Source/Swig/swigtree.h b/Source/Swig/swigtree.h index 5decb79e3..4973400d7 100644 --- a/Source/Swig/swigtree.h +++ b/Source/Swig/swigtree.h @@ -38,6 +38,7 @@ extern void appendChild(Node *node, Node *child); extern void prependChild(Node *node, Node *child); extern void removeNode(Node *node); extern Node *copyNode(Node *node); +extern void appendSibling(Node *node, Node *chd); /* Node restoration/restore functions */ diff --git a/Source/Swig/tree.c b/Source/Swig/tree.c index 784d3ab84..79f708d33 100644 --- a/Source/Swig/tree.c +++ b/Source/Swig/tree.c @@ -171,6 +171,25 @@ void prependChild(Node *node, Node *chd) { } } +void appendSibling(Node *node, Node *chd) +{ + Node *parent; + Node* lc = node; + while(nextSibling(lc)) + lc = nextSibling(lc); + set_nextSibling(lc, chd); + set_previousSibling(chd, lc); + parent = parentNode(node); + if (parent) { + while (chd) { + lc = chd; + set_parentNode(chd, parent); + chd = nextSibling(chd); + } + set_lastChild(parent, lc); + } +} + /* ----------------------------------------------------------------------------- * removeNode() * From 44a883a05700d3c74ce6e13aa70a49c4533052d2 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 28 Nov 2013 21:01:02 +0000 Subject: [PATCH 207/481] Cosmetics/code beautification of nested class support --- Source/CParse/cscanner.c | 8 +- Source/CParse/parser.y | 42 +++--- Source/Modules/allocate.cxx | 2 +- Source/Modules/contract.cxx | 2 +- Source/Modules/csharp.cxx | 27 ++-- Source/Modules/java.cxx | 28 ++-- Source/Modules/lang.cxx | 16 +-- Source/Modules/main.cxx | 16 +-- Source/Modules/typepass.cxx | 277 ++++++++++++++++++------------------ Source/Swig/naming.c | 46 +++--- Source/Swig/scanner.c | 15 +- Source/Swig/swig.h | 4 +- Source/Swig/tree.c | 7 +- 13 files changed, 249 insertions(+), 241 deletions(-) diff --git a/Source/CParse/cscanner.c b/Source/CParse/cscanner.c index 68b305c90..ee2c49cd4 100644 --- a/Source/CParse/cscanner.c +++ b/Source/CParse/cscanner.c @@ -118,7 +118,13 @@ void skip_balanced(int startchar, int endchar) { return; } -String* get_raw_text_balanced(int startchar, int endchar) { +/* ----------------------------------------------------------------------------- + * get_raw_text_balanced() + * + * Returns raw text between 2 braces + * ----------------------------------------------------------------------------- */ + +String *get_raw_text_balanced(int startchar, int endchar) { return Scanner_get_raw_text_balanced(scan, startchar, endchar); } diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index ef7eb81ba..09385f1c0 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -51,7 +51,7 @@ static Node *module_node = 0; static String *Classprefix = 0; static String *Namespaceprefix = 0; static int inclass = 0; -static Node *currentOuterClass = 0; /*for nested classes*/ +static Node *currentOuterClass = 0; /* for nested classes */ static char *last_cpptype = 0; static int inherit_list = 0; static Parm *template_parameters = 0; @@ -233,7 +233,7 @@ static String *feature_identifier_fix(String *s) { } } -static void set_access_mode(Node* n) { +static void set_access_mode(Node *n) { if (cplus_mode == CPLUS_PUBLIC) Setattr(n, "access", "public"); else if (cplus_mode == CPLUS_PROTECTED) @@ -242,7 +242,7 @@ static void set_access_mode(Node* n) { Setattr(n, "access", "private"); } -static void restore_access_mode(Node* n) { +static void restore_access_mode(Node *n) { char* mode = Char(Getattr(n, "access")); if (strcmp(mode, "private") == 0) cplus_mode = CPLUS_PRIVATE; @@ -799,26 +799,26 @@ static String *make_class_name(String *name) { } /* Use typedef name as class name */ -void add_typedef_name(Node* n, Node* decl, String* oldName, Symtab *cscope, String* scpname) -{ - String* class_rename = 0; - SwigType *decltype = Getattr(decl,"decl"); + +void add_typedef_name(Node *n, Node *decl, String *oldName, Symtab *cscope, String *scpname) { + String *class_rename = 0; + SwigType *decltype = Getattr(decl, "decl"); if (!decltype || !Len(decltype)) { String *cname; String *tdscopename; String *class_scope = Swig_symbol_qualifiedscopename(cscope); - String *name = Getattr(decl,"name"); + String *name = Getattr(decl, "name"); cname = Copy(name); - Setattr(n,"tdname",cname); + Setattr(n, "tdname", cname); tdscopename = class_scope ? NewStringf("%s::%s", class_scope, name) : Copy(name); class_rename = Getattr(n, "class_rename"); - if (class_rename && (Strcmp(class_rename,oldName) == 0)) + if (class_rename && (Strcmp(class_rename, oldName) == 0)) Setattr(n, "class_rename", NewString(name)); if (!classes_typedefs) classes_typedefs = NewHash(); if (!Equal(scpname, tdscopename) && !Getattr(classes_typedefs, tdscopename)) { Setattr(classes_typedefs, tdscopename, n); } - Setattr(n,"decl",decltype); + Setattr(n, "decl", decltype); Delete(class_scope); Delete(cname); Delete(tdscopename); @@ -1043,10 +1043,10 @@ static String *resolve_create_node_scope(String *cname) { } /* look for simple typedef name in typedef list */ -String* try_to_find_a_name_for_unnamed_structure(char* storage, Node* decls) { - String* name = 0; - Node* n = decls; - if (storage && (strcmp(storage,"typedef") == 0)) { +String *try_to_find_a_name_for_unnamed_structure(char *storage, Node *decls) { + String *name = 0; + Node *n = decls; + if (storage && (strcmp(storage, "typedef") == 0)) { for (; n; n = nextSibling(n)) { if (!Len(Getattr(n, "decl"))) { name = Copy(Getattr(n, "name")); @@ -1058,9 +1058,9 @@ String* try_to_find_a_name_for_unnamed_structure(char* storage, Node* decls) { } /* traverse copied tree segment, and update outer class links*/ -void update_nested_classes(Node* n) +void update_nested_classes(Node *n) { - Node* c = firstChild(n); + Node *c = firstChild(n); while (c) { if (Getattr(c, "nested:outer")) Setattr(c, "nested:outer", n); @@ -1432,7 +1432,7 @@ static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { %type cpp_declaration cpp_class_decl cpp_forward_class_decl cpp_template_decl cpp_alternate_rettype; %type cpp_members cpp_member; %type cpp_constructor_decl cpp_destructor_decl cpp_protection_decl cpp_conversion_operator cpp_static_assert; -%type cpp_swig_directive cpp_temp_possible /*cpp_nested*/ cpp_opt_declarators ; +%type cpp_swig_directive cpp_temp_possible cpp_opt_declarators ; %type cpp_using_decl cpp_namespace_decl cpp_catch_decl cpp_lambda_decl; %type kwargs options; @@ -3447,7 +3447,8 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { Delete(prefix); inclass = 1; currentOuterClass = $$; - if (CPlusPlusOut) { /* save the structure declaration to declare it in global scope for C++ to see*/ + if (CPlusPlusOut) { + /* save the structure declaration to declare it in global scope for C++ to see */ code = get_raw_text_balanced('{', '}'); Setattr($$, "code", code); Delete(code); @@ -3550,7 +3551,7 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); if (!cparse_cplusplus && currentOuterClass) { /* nested C structs go into global scope*/ - Node* outer = currentOuterClass; + Node *outer = currentOuterClass; while (Getattr(outer, "nested:outer")) outer = Getattr(outer, "nested:outer"); appendSibling(outer, $$); @@ -4286,7 +4287,6 @@ cpp_member : c_declaration { $$ = $1; } | cpp_conversion_operator { $$ = $1; } | cpp_forward_class_decl { $$ = $1; } | cpp_class_decl { $$ = $1; } -/* | cpp_nested { $$ = $1; }*/ | storage_class idcolon SEMI { $$ = 0; } | cpp_using_decl { $$ = $1; } | cpp_template_decl { $$ = $1; } diff --git a/Source/Modules/allocate.cxx b/Source/Modules/allocate.cxx index 4e71711d6..7f1d13678 100644 --- a/Source/Modules/allocate.cxx +++ b/Source/Modules/allocate.cxx @@ -559,7 +559,7 @@ Allocate(): virtual int classDeclaration(Node *n) { Symtab *symtab = Swig_symbol_current(); Swig_symbol_setscope(Getattr(n, "symtab")); - Node* oldInclass = inclass; + Node *oldInclass = inclass; AccessMode oldAcessMode = cplus_mode; if (!CPlusPlus) { diff --git a/Source/Modules/contract.cxx b/Source/Modules/contract.cxx index 981a21883..7e0eaf9e0 100644 --- a/Source/Modules/contract.cxx +++ b/Source/Modules/contract.cxx @@ -343,7 +343,7 @@ int Contracts::namespaceDeclaration(Node *n) { int Contracts::classDeclaration(Node *n) { int ret = SWIG_OK; int oldInClass = InClass; - Node* oldClass = CurrentClass; + Node *oldClass = CurrentClass; InClass = 1; CurrentClass = n; emit_children(n); diff --git a/Source/Modules/csharp.cxx b/Source/Modules/csharp.cxx index a0332f1ae..7d3a0ac07 100644 --- a/Source/Modules/csharp.cxx +++ b/Source/Modules/csharp.cxx @@ -19,7 +19,7 @@ /* Hash type used for upcalls from C/C++ */ typedef DOH UpcallData; // insert N tabs before each new line in s -void Swig_offset_string(String* s, int N); +void Swig_offset_string(String *s, int N); class CSHARP:public Language { static const char *usage; @@ -183,7 +183,7 @@ public: String *nspace = Getattr(n, "sym:nspace"); String *symname = Copy(Getattr(n, "sym:name")); if (!GetFlag(n, "feature:flatnested")) { - for (Node* outer_class = Getattr(n, "nested:outer");outer_class;outer_class = Getattr(outer_class, "nested:outer")) { + for (Node *outer_class = Getattr(n, "nested:outer"); outer_class; outer_class = Getattr(outer_class, "nested:outer")) { Push(symname, "."); Push(symname, Getattr(outer_class, "sym:name")); } @@ -1878,22 +1878,22 @@ public: String *nspace = getNSpace(); File *f_proxy = NULL; // save class local variables - String* old_proxy_class_name = proxy_class_name; - String* old_full_imclass_name = full_imclass_name; - String* old_destructor_call = destructor_call; - String* old_proxy_class_constants_code = proxy_class_constants_code; - String* old_proxy_class_def = proxy_class_def; - String* old_proxy_class_code = proxy_class_code; + String *old_proxy_class_name = proxy_class_name; + String *old_full_imclass_name = full_imclass_name; + String *old_destructor_call = destructor_call; + String *old_proxy_class_constants_code = proxy_class_constants_code; + String *old_proxy_class_def = proxy_class_def; + String *old_proxy_class_code = proxy_class_code; if (proxy_flag) { proxy_class_name = NewString(Getattr(n, "sym:name")); - if (Node* outer = Getattr(n, "nested:outer")) { - String* outerClassesPrefix = Copy(Getattr(outer, "sym:name")); + if (Node *outer = Getattr(n, "nested:outer")) { + String *outerClassesPrefix = Copy(Getattr(outer, "sym:name")); for (outer = Getattr(outer, "nested:outer"); outer != 0; outer = Getattr(outer, "nested:outer")) { Push(outerClassesPrefix, "::"); Push(outerClassesPrefix, Getattr(outer, "sym:name")); } - String* fnspace = nspace ? NewStringf("%s::%s", nspace, outerClassesPrefix) : outerClassesPrefix; + String *fnspace = nspace ? NewStringf("%s::%s", nspace, outerClassesPrefix) : outerClassesPrefix; if (!addSymbol(proxy_class_name, n, fnspace)) return SWIG_ERROR; if (nspace) @@ -3458,7 +3458,7 @@ public: String *dirClassName = directorClassName(n); String *smartptr = Getattr(n, "feature:smartptr"); if (!GetFlag(n, "feature:flatnested")) { - for (Node* outer_class = Getattr(n, "nested:outer"); outer_class; outer_class = Getattr(outer_class, "nested:outer")) { + for (Node *outer_class = Getattr(n, "nested:outer"); outer_class; outer_class = Getattr(outer_class, "nested:outer")) { Push(qualified_classname, "."); Push(qualified_classname, Getattr(outer_class, "sym:name")); @@ -4134,7 +4134,9 @@ public: String *old_director_delegate_instances = director_delegate_instances; String *old_director_method_types = director_method_types; String *old_director_connect_parms = director_connect_parms; + int ret = Language::classDeclaration(n); + // these variables are deleted in emitProxyClassDefAndCPPCasts, hence no Delete here director_callback_typedefs = old_director_callback_typedefs; director_callbacks = old_director_callbacks; @@ -4143,6 +4145,7 @@ public: director_delegate_instances = old_director_delegate_instances; director_method_types = old_director_method_types; director_connect_parms = old_director_connect_parms; + return ret; } diff --git a/Source/Modules/java.cxx b/Source/Modules/java.cxx index a286b5f8e..15199af9e 100644 --- a/Source/Modules/java.cxx +++ b/Source/Modules/java.cxx @@ -19,7 +19,7 @@ /* Hash type used for upcalls from C/C++ */ typedef DOH UpcallData; // insert N tabs before each new line in s -void Swig_offset_string(String* s, int N); +void Swig_offset_string(String *s, int N); class JAVA:public Language { static const char *usage; @@ -210,7 +210,7 @@ public: String *nspace = Getattr(n, "sym:nspace"); String *symname = Copy(Getattr(n, "sym:name")); if (!GetFlag(n, "feature:flatnested")) { - for (Node* outer_class = Getattr(n, "nested:outer");outer_class;outer_class = Getattr(outer_class, "nested:outer")) { + for (Node *outer_class = Getattr(n, "nested:outer"); outer_class; outer_class = Getattr(outer_class, "nested:outer")) { Push(symname, "."); Push(symname, Getattr(outer_class, "sym:name")); } @@ -1923,21 +1923,21 @@ public: virtual int classHandler(Node *n) { File *f_proxy = NULL; - String* old_proxy_class_name = proxy_class_name; - String* old_full_proxy_class_name = full_proxy_class_name; - String* old_full_imclass_name = full_imclass_name; - String* old_destructor_call = destructor_call; - String* old_destructor_throws_clause = destructor_throws_clause; - String* old_proxy_class_constants_code = proxy_class_constants_code; - String* old_proxy_class_def = proxy_class_def; - String* old_proxy_class_code = proxy_class_code; + String *old_proxy_class_name = proxy_class_name; + String *old_full_proxy_class_name = full_proxy_class_name; + String *old_full_imclass_name = full_imclass_name; + String *old_destructor_call = destructor_call; + String *old_destructor_throws_clause = destructor_throws_clause; + String *old_proxy_class_constants_code = proxy_class_constants_code; + String *old_proxy_class_def = proxy_class_def; + String *old_proxy_class_code = proxy_class_code; if (proxy_flag) { proxy_class_name = NewString(Getattr(n, "sym:name")); String *nspace = getNSpace(); constructIntermediateClassName(n); - String* outerClassesPrefix = 0; - if (Node* outer = Getattr(n, "nested:outer")) { + String *outerClassesPrefix = 0; + if (Node *outer = Getattr(n, "nested:outer")) { outerClassesPrefix = Copy(Getattr(outer, "sym:name")); for (outer = Getattr(outer, "nested:outer"); outer != 0; outer = Getattr(outer, "nested:outer")) { Push(outerClassesPrefix, "."); @@ -1962,7 +1962,7 @@ public: full_proxy_class_name = NewStringf("%s.%s.%s.%s", package, nspace, outerClassesPrefix, proxy_class_name); else full_proxy_class_name = NewStringf("%s.%s.%s", nspace, outerClassesPrefix, proxy_class_name); - }else { + } else { if (package) full_proxy_class_name = NewStringf("%s.%s.%s", package, nspace, proxy_class_name); else @@ -1972,7 +1972,7 @@ public: if (outerClassesPrefix) { Replaceall(outerClassesPrefix, ".", "::"); - String* fnspace = nspace ? NewStringf("%s::%s", nspace, outerClassesPrefix) : outerClassesPrefix; + String *fnspace = nspace ? NewStringf("%s::%s", nspace, outerClassesPrefix) : outerClassesPrefix; if (!addSymbol(proxy_class_name, n, fnspace)) return SWIG_ERROR; if (nspace) diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 89cc17a83..25bf7e804 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -20,7 +20,7 @@ static int director_mode = 0; static int director_protected_mode = 1; static int all_protected_mode = 0; static int naturalvar_mode = 0; -Language* Language::this_ = 0; +Language *Language::this_ = 0; /* Set director_protected_mode */ void Wrapper_director_mode_set(int flag) { @@ -2367,7 +2367,7 @@ int Language::classDeclaration(Node *n) { String *oldClassName = ClassName; String *oldDirectorClassName = DirectorClassName; String *oldNSpace = NSpace; - Node* oldCurrentClass = CurrentClass; + Node *oldCurrentClass = CurrentClass; String *kind = Getattr(n, "kind"); String *name = Getattr(n, "name"); @@ -2390,7 +2390,7 @@ int Language::classDeclaration(Node *n) { return SWIG_NOWRAP; } AccessMode oldAccessMode = cplus_mode; - Node* outerClass = Getattr(n, "nested:outer"); + Node *outerClass = Getattr(n, "nested:outer"); if (outerClass && oldAccessMode != Dispatcher::PUBLIC) return SWIG_NOWRAP; ClassName = Copy(name); @@ -3633,12 +3633,12 @@ Hash *Language::getClassHash() const { } // insert N tabs before each new line in s -void Swig_offset_string(String* s, int N) +void Swig_offset_string(String *s, int N) { // count a number of lines in s int lines = 1; int L = Len(s); - char* start = strchr(Char(s), '\n'); + char *start = strchr(Char(s), '\n'); while (start) { ++lines; start = strchr(start + 1, '\n'); @@ -3647,13 +3647,13 @@ void Swig_offset_string(String* s, int N) if ((Char(s))[L-1] == '\n') --lines; // allocate a temporary storage for a padded string - char* res = (char*)malloc(L + lines * N * 2 + 1); + char *res = (char*)malloc(L + lines * N * 2 + 1); res[L + lines * N * 2] = 0; // copy lines to res, prepending tabs to each line - char* p = res; // output pointer + char *p = res; // output pointer start = Char(s); // start of a current line - char* end = strchr(start, '\n'); // end of a current line + char *end = strchr(start, '\n'); // end of a current line while (end) { memset(p, ' ', N*2); p += N*2; diff --git a/Source/Modules/main.cxx b/Source/Modules/main.cxx index e2ed6a675..5336159af 100644 --- a/Source/Modules/main.cxx +++ b/Source/Modules/main.cxx @@ -31,8 +31,8 @@ static Language *lang = 0; // Language method int CPlusPlus = 0; extern "C" { - int CPlusPlusOut = 0; // generate C++ declarations for C code -}; + int CPlusPlusOut = 0; // Generate C++ compatible code when wrapping C code +} int Extend = 0; // Extend flag int ForceExtern = 0; // Force extern mode int GenerateDefault = 1; // Generate default constructors @@ -870,18 +870,6 @@ void Swig_flatten_nested() { Delete(fname); Delete(name); Delete(val); - /* - String* name = NewStringEmpty(); - Hash* newname = NewHash(); - Setattr(newname, "name", "$ignore"); - Hash* match = NewHash(); - Setattr(match, "name", "match$nested"); - Setattr(match, "value", "1"); - set_nextSibling(newname, match); - Swig_name_rename_add(0, name, 0, newname, 0); - Delete(name); - Delete(match); - Delete(newname);*/ } diff --git a/Source/Modules/typepass.cxx b/Source/Modules/typepass.cxx index e5c6d2c05..6954e0dd2 100644 --- a/Source/Modules/typepass.cxx +++ b/Source/Modules/typepass.cxx @@ -476,11 +476,10 @@ class TypePass:private Dispatcher { if (unnamed && tdname && (Cmp(storage, "typedef") == 0)) { SwigType_typedef(unnamed, tdname); } - // name of the outer class should already be patched to contain it's outer classes names, but not to contain namespaces // namespace name (if present) is added after processing child nodes if (Getattr(n, "nested:outer") && name) { - String* outerName = Getattr(Getattr(n, "nested:outer"), "name"); + String *outerName = Getattr(Getattr(n, "nested:outer"), "name"); name = NewStringf("%s::%s", outerName, name); Setattr(n, "name", name); if (tdname) { @@ -679,7 +678,7 @@ class TypePass:private Dispatcher { if (GetFlag(n, "conversion_operator")) { /* The call to the operator in the generated wrapper must be fully qualified in order to compile */ SwigType *name = Getattr(n, "name"); - SwigType *qualifiedname = Swig_symbol_string_qualify(name,0); + SwigType *qualifiedname = Swig_symbol_string_qualify(name, 0); Clear(name); Append(name, qualifiedname); Delete(qualifiedname); @@ -1116,8 +1115,7 @@ class TypePass:private Dispatcher { * list of overloaded methods we have just added in as child nodes to the "using" node. * The node will still exist, it is just the symbol table linked list of overloaded methods * which is hacked. */ - if (Getattr(n, "sym:overloaded")) - { + if (Getattr(n, "sym:overloaded")) { int cnt = 0; #ifdef DEBUG_OVERLOADED Node *debugnode = n; @@ -1180,7 +1178,7 @@ class TypePass:private Dispatcher { #ifdef DEBUG_OVERLOADED show_overloaded(debugnode); #endif - clean_overloaded(n); // Needed? + clean_overloaded(n); // Needed? } } } @@ -1286,21 +1284,22 @@ void Swig_process_types(Node *n) { } // Nested classes processing section -static Hash* classhash = 0; +static Hash *classhash = 0; -static String *make_name(Node *n, String *name,SwigType *decl) { +static String *make_name(Node *n, String *name, SwigType *decl) { int destructor = name && (*(Char(name)) == '~'); - if (String* yyrename = Getattr(n, "class_rename")) { + if (String *yyrename = Getattr(n, "class_rename")) { String *s = NewString(yyrename); Delattr(n, "class_rename"); - if (destructor && (*(Char(s)) != '~')) { - Insert(s,0,"~"); + if (destructor && (*(Char(s)) != '~')) { + Insert(s, 0, "~"); } return s; } - if (!name) return 0; - return Swig_name_make(n,0,name,decl,0); + if (!name) + return 0; + return Swig_name_make(n, 0, name, decl, 0); } // C version of add_symbols() @@ -1308,73 +1307,74 @@ static void add_symbols_c(Node *n) { String *decl; String *wrn = 0; String *symname = 0; - int iscdecl = Cmp(nodeType(n),"cdecl") == 0; - Setattr(n,"ismember","1"); - Setattr(n,"access", "public"); - if (Getattr(n,"sym:name")) + int iscdecl = Cmp(nodeType(n), "cdecl") == 0; + Setattr(n, "ismember", "1"); + Setattr(n, "access", "public"); + if (Getattr(n, "sym:name")) return; - decl = Getattr(n,"decl"); + decl = Getattr(n, "decl"); if (!SwigType_isfunction(decl)) { - String *name = Getattr(n,"name"); - String *makename = Getattr(n,"parser:makename"); + String *name = Getattr(n, "name"); + String *makename = Getattr(n, "parser:makename"); if (iscdecl) { String *storage = Getattr(n, "storage"); - if (Cmp(storage,"typedef") == 0) { - Setattr(n,"kind","typedef"); + if (Cmp(storage, "typedef") == 0) { + Setattr(n, "kind", "typedef"); } else { - SwigType *type = Getattr(n,"type"); - String *value = Getattr(n,"value"); - Setattr(n,"kind","variable"); + SwigType *type = Getattr(n, "type"); + String *value = Getattr(n, "value"); + Setattr(n, "kind", "variable"); if (value && Len(value)) { - Setattr(n,"hasvalue","1"); + Setattr(n, "hasvalue", "1"); } if (type) { SwigType *ty; SwigType *tmp = 0; if (decl) { ty = tmp = Copy(type); - SwigType_push(ty,decl); + SwigType_push(ty, decl); } else { ty = type; } if (!SwigType_ismutable(ty)) { - SetFlag(n,"hasconsttype"); - SetFlag(n,"feature:immutable"); + SetFlag(n, "hasconsttype"); + SetFlag(n, "feature:immutable"); } - if (tmp) Delete(tmp); + if (tmp) + Delete(tmp); } if (!type) { - Printf(stderr,"notype name %s\n", name); + Printf(stderr, "notype name %s\n", name); } } } Swig_features_get(Swig_cparse_features(), 0, name, 0, n); if (makename) { symname = make_name(n, makename, 0); - Delattr(n,"parser:makename"); /* temporary information, don't leave it hanging around */ + Delattr(n, "parser:makename"); /* temporary information, don't leave it hanging around */ } else { makename = name; symname = make_name(n, makename, 0); } if (!symname) { - symname = Copy(Getattr(n,"unnamed")); + symname = Copy(Getattr(n, "unnamed")); } if (symname) { - wrn = Swig_name_warning(n, 0, symname,0); + wrn = Swig_name_warning(n, 0, symname, 0); } } else { - String *name = Getattr(n,"name"); + String *name = Getattr(n, "name"); SwigType *fdecl = Copy(decl); SwigType *fun = SwigType_pop_function(fdecl); if (iscdecl) { - Setattr(n,"kind","function"); + Setattr(n, "kind", "function"); } - Swig_features_get(Swig_cparse_features(),0,name,fun,n); + Swig_features_get(Swig_cparse_features(), 0, name, fun, n); symname = make_name(n, name, fun); - wrn = Swig_name_warning(n, 0, symname,fun); + wrn = Swig_name_warning(n, 0, symname, fun); Delete(fdecl); Delete(fun); @@ -1382,15 +1382,15 @@ static void add_symbols_c(Node *n) { } if (!symname) return; - if (GetFlag(n,"feature:ignore")) { + if (GetFlag(n, "feature:ignore")) { /* Only add to C symbol table and continue */ Swig_symbol_add(0, n); - } else if (strncmp(Char(symname),"$ignore",7) == 0) { - char *c = Char(symname)+7; - SetFlag(n,"feature:ignore"); + } else if (strncmp(Char(symname), "$ignore", 7) == 0) { + char *c = Char(symname) + 7; + SetFlag(n, "feature:ignore"); if (strlen(c)) { SWIG_WARN_NODE_BEGIN(n); - Swig_warning(0,Getfile(n), Getline(n), "%s\n",c+1); + Swig_warning(0, Getfile(n), Getline(n), "%s\n", c + 1); SWIG_WARN_NODE_END(n); } Swig_symbol_add(0, n); @@ -1398,51 +1398,50 @@ static void add_symbols_c(Node *n) { Node *c; if ((wrn) && (Len(wrn))) { String *metaname = symname; - if (!Getmeta(metaname,"already_warned")) { + if (!Getmeta(metaname, "already_warned")) { SWIG_WARN_NODE_BEGIN(n); - Swig_warning(0,Getfile(n),Getline(n), "%s\n", wrn); + Swig_warning(0, Getfile(n), Getline(n), "%s\n", wrn); SWIG_WARN_NODE_END(n); - Setmeta(metaname,"already_warned","1"); + Setmeta(metaname, "already_warned", "1"); } } - c = Swig_symbol_add(symname,n); + c = Swig_symbol_add(symname, n); if (c != n) { /* symbol conflict attempting to add in the new symbol */ - if (Getattr(n,"sym:weak")) { - Setattr(n,"sym:name",symname); + if (Getattr(n, "sym:weak")) { + Setattr(n, "sym:name", symname); } else { String *e = NewStringEmpty(); String *en = NewStringEmpty(); String *ec = NewStringEmpty(); - int redefined = Swig_need_redefined_warn(n,c,true); + int redefined = Swig_need_redefined_warn(n, c, true); if (redefined) { - Printf(en,"Identifier '%s' redefined (ignored)",symname); - Printf(ec,"previous definition of '%s'",symname); + Printf(en, "Identifier '%s' redefined (ignored)", symname); + Printf(ec, "previous definition of '%s'", symname); } else { - Printf(en,"Redundant redeclaration of '%s'",symname); - Printf(ec,"previous declaration of '%s'",symname); + Printf(en, "Redundant redeclaration of '%s'", symname); + Printf(ec, "previous declaration of '%s'", symname); } - if (Cmp(symname,Getattr(n,"name"))) { - Printf(en," (Renamed from '%s')", SwigType_namestr(Getattr(n,"name"))); + if (Cmp(symname, Getattr(n, "name"))) { + Printf(en, " (Renamed from '%s')", SwigType_namestr(Getattr(n, "name"))); } - Printf(en,","); - if (Cmp(symname,Getattr(c,"name"))) { - Printf(ec," (Renamed from '%s')", SwigType_namestr(Getattr(c,"name"))); + Printf(en, ","); + if (Cmp(symname, Getattr(c, "name"))) { + Printf(ec, " (Renamed from '%s')", SwigType_namestr(Getattr(c, "name"))); } - Printf(ec,"."); + Printf(ec, "."); SWIG_WARN_NODE_BEGIN(n); if (redefined) { - Swig_warning(WARN_PARSE_REDEFINED,Getfile(n),Getline(n),"%s\n",en); - Swig_warning(WARN_PARSE_REDEFINED,Getfile(c),Getline(c),"%s\n",ec); + Swig_warning(WARN_PARSE_REDEFINED, Getfile(n), Getline(n), "%s\n", en); + Swig_warning(WARN_PARSE_REDEFINED, Getfile(c), Getline(c), "%s\n", ec); } else { - Swig_warning(WARN_PARSE_REDUNDANT,Getfile(n),Getline(n),"%s\n",en); - Swig_warning(WARN_PARSE_REDUNDANT,Getfile(c),Getline(c),"%s\n",ec); + Swig_warning(WARN_PARSE_REDUNDANT, Getfile(n), Getline(n), "%s\n", en); + Swig_warning(WARN_PARSE_REDUNDANT, Getfile(c), Getline(c), "%s\n", ec); } SWIG_WARN_NODE_END(n); - Printf(e,"%s:%d:%s\n%s:%d:%s\n",Getfile(n),Getline(n),en, - Getfile(c),Getline(c),ec); - Setattr(n,"error",e); + Printf(e, "%s:%d:%s\n%s:%d:%s\n", Getfile(n), Getline(n), en, Getfile(c), Getline(c), ec); + Setattr(n, "error", e); Delete(e); Delete(en); Delete(ec); @@ -1454,58 +1453,59 @@ static void add_symbols_c(Node *n) { /* Strips C-style and C++-style comments from string in-place. */ static void strip_comments(char *string) { - int state = 0; /* - * 0 - not in comment - * 1 - in c-style comment - * 2 - in c++-style comment - * 3 - in string - * 4 - after reading / not in comments - * 5 - after reading * in c-style comments - * 6 - after reading \ in strings - */ - char * c = string; + int state = 0; + /* + * 0 - not in comment + * 1 - in c-style comment + * 2 - in c++-style comment + * 3 - in string + * 4 - after reading / not in comments + * 5 - after reading * in c-style comments + * 6 - after reading \ in strings + */ + char *c = string; while (*c) { switch (state) { case 0: if (*c == '\"') - state = 3; + state = 3; else if (*c == '/') - state = 4; + state = 4; break; case 1: if (*c == '*') - state = 5; + state = 5; *c = ' '; break; case 2: if (*c == '\n') - state = 0; + state = 0; else - *c = ' '; + *c = ' '; break; case 3: if (*c == '\"') - state = 0; + state = 0; else if (*c == '\\') - state = 6; + state = 6; break; case 4: if (*c == '/') { - *(c-1) = ' '; - *c = ' '; - state = 2; + *(c - 1) = ' '; + *c = ' '; + state = 2; } else if (*c == '*') { - *(c-1) = ' '; - *c = ' '; - state = 1; + *(c - 1) = ' '; + *c = ' '; + state = 1; } else - state = 0; + state = 0; break; case 5: if (*c == '/') - state = 0; + state = 0; else - state = 1; + state = 1; *c = ' '; break; case 6: @@ -1516,11 +1516,10 @@ static void strip_comments(char *string) { } } -// Create an %insert with a typedef to make a new name visible to C -// the code is moved from parser.y, dump_nested() function with minor changes -static Node* create_insert(Node* n, bool noTypedef = false) { +// Create a %insert with a typedef to make a new name visible to C +static Node *create_insert(Node *n, bool noTypedef = false) { // format a typedef - String* ccode = Getattr(n, "code"); + String *ccode = Getattr(n, "code"); Push(ccode, " "); if (noTypedef) { Push(ccode, Getattr(n, "name")); @@ -1534,19 +1533,18 @@ static Node* create_insert(Node* n, bool noTypedef = false) { } Append(ccode, ";"); - /* Strip comments - further code may break in presence of comments. */ strip_comments(Char(ccode)); /* Make all SWIG created typedef structs/unions/classes unnamed else - redefinition errors occur - nasty hack alert.*/ + redefinition errors occur - nasty hack alert. */ if (!noTypedef) { - const char* types_array[3] = {"struct", "union", "class"}; + const char *types_array[3] = { "struct", "union", "class" }; for (int i = 0; i < 3; i++) { - char* code_ptr = Char(ccode); + char *code_ptr = Char(ccode); while (code_ptr) { /* Replace struct name (as in 'struct name {...}' ) with whitespace - name will be between struct and opening brace */ + name will be between struct and opening brace */ code_ptr = strstr(code_ptr, types_array[i]); if (code_ptr) { @@ -1555,7 +1553,7 @@ static Node* create_insert(Node* n, bool noTypedef = false) { open_bracket_pos = strchr(code_ptr, '{'); if (open_bracket_pos) { /* Make sure we don't have something like struct A a; */ - char* semi_colon_pos = strchr(code_ptr, ';'); + char *semi_colon_pos = strchr(code_ptr, ';'); if (!(semi_colon_pos && (semi_colon_pos < open_bracket_pos))) while (code_ptr < open_bracket_pos) *code_ptr++ = ' '; @@ -1566,11 +1564,11 @@ static Node* create_insert(Node* n, bool noTypedef = false) { } { /* Remove SWIG directive %constant which may be left in the SWIG created typedefs */ - char* code_ptr = Char(ccode); + char *code_ptr = Char(ccode); while (code_ptr) { code_ptr = strstr(code_ptr, "%constant"); if (code_ptr) { - char* directive_end_pos = strchr(code_ptr, ';'); + char *directive_end_pos = strchr(code_ptr, ';'); if (directive_end_pos) { while (code_ptr <= directive_end_pos) *code_ptr++ = ' '; @@ -1578,10 +1576,10 @@ static Node* create_insert(Node* n, bool noTypedef = false) { } } } - Node *newnode = NewHash(); - set_nodeType(newnode ,"insert"); - Setfile(newnode ,Getfile(n)); - Setline(newnode ,Getline(n)); + Node *newnode = NewHash(); + set_nodeType(newnode, "insert"); + Setfile(newnode, Getfile(n)); + Setline(newnode, Getline(n)); String *code = NewStringEmpty(); Wrapper_pretty_print(ccode, code); Setattr(newnode, "code", code); @@ -1590,12 +1588,11 @@ static Node* create_insert(Node* n, bool noTypedef = false) { return newnode; } -static void insertNodeAfter(Node *n, Node* c) -{ - Node* g = parentNode(n); +static void insertNodeAfter(Node *n, Node *c) { + Node *g = parentNode(n); set_parentNode(c, g); - Node* ns = nextSibling(n); - if (Node* outer = Getattr(c, "nested:outer")) { + Node *ns = nextSibling(n); + if (Node *outer = Getattr(c, "nested:outer")) { while (ns && outer == Getattr(ns, "nested:outer")) { n = ns; ns = nextSibling(n); @@ -1603,8 +1600,7 @@ static void insertNodeAfter(Node *n, Node* c) } if (!ns) { set_lastChild(g, c); - } - else { + } else { set_nextSibling(c, ns); set_previousSibling(ns, c); } @@ -1615,36 +1611,36 @@ static void insertNodeAfter(Node *n, Node* c) void Swig_name_unnamed_c_structs(Node *n) { if (!classhash) classhash = Getattr(n, "classes"); - Node* c = firstChild(n); + Node *c = firstChild(n); while (c) { - Node* next = nextSibling(c); - if (String* declName = Getattr(c, "nested:unnamed")) { - if (Node* outer = Getattr(c, "nested:outer")) { + Node *next = nextSibling(c); + if (String *declName = Getattr(c, "nested:unnamed")) { + if (Node *outer = Getattr(c, "nested:outer")) { // generate a name - String* name = NewStringf("%s_%s", Getattr(outer, "name"), declName); + String *name = NewStringf("%s_%s", Getattr(outer, "name"), declName); Delattr(c, "nested:unnamed"); // set the name to the class and symbol table Setattr(c, "tdname", name); Setattr(c, "name", name); - Swig_symbol_setscope(Getattr(c,"symtab")); + Swig_symbol_setscope(Getattr(c, "symtab")); Swig_symbol_setscopename(name); // now that we have a name - gather base symbols - if (List* publicBases = Getattr(c,"baselist")) { - List* bases = Swig_make_inherit_list(name, publicBases, 0); + if (List *publicBases = Getattr(c, "baselist")) { + List *bases = Swig_make_inherit_list(name, publicBases, 0); Swig_inherit_base_symbols(bases); Delete(bases); } - Setattr(classhash,name,c); + Setattr(classhash, name, c); Swig_symbol_popscope(); // process declarations following this type (assign correct new type) - SwigType* ty = Copy(name); - Node* decl = nextSibling(c); - List* declList = NewList(); + SwigType *ty = Copy(name); + Node *decl = nextSibling(c); + List *declList = NewList(); while (decl && Getattr(decl, "nested:unnamedtype") == c) { Setattr(decl, "type", ty); Append(declList, decl); Delattr(decl, "nested:unnamedtype"); - SetFlag(decl, "feature:immutable"); + SetFlag(decl, "feature:immutable"); add_symbols_c(decl); decl = nextSibling(decl); } @@ -1662,20 +1658,20 @@ void Swig_name_unnamed_c_structs(Node *n) { Swig_symbol_setscope(Swig_symbol_global_scope()); add_symbols_c(c); - Node* ins = create_insert(c); + Node *ins = create_insert(c); insertNodeAfter(c, ins); removeNode(c); insertNodeAfter(n, c); Delete(ins); Delattr(c, "nested:outer"); - }else { + } else { // global unnamed struct - ignore it c = next; continue; } } else if (CPlusPlusOut) { if (Getattr(c, "nested:outer")) { - Node* ins = create_insert(c, true); + Node *ins = create_insert(c, true); insertNodeAfter(c, ins); Delete(ins); Delattr(c, "nested:outer"); @@ -1686,23 +1682,24 @@ void Swig_name_unnamed_c_structs(Node *n) { c = next; } } -static void remove_outer_class_reference(Node *n) -{ - for (Node* c = firstChild(n); c; c = nextSibling(c)) { + +static void remove_outer_class_reference(Node *n) { + for (Node *c = firstChild(n); c; c = nextSibling(c)) { if (GetFlag(c, "feature:flatnested")) { Delattr(c, "nested:outer"); remove_outer_class_reference(c); } } } + void Swig_process_nested_classes(Node *n) { - Node* c = firstChild(n); + Node *c = firstChild(n); while (c) { - Node* next = nextSibling(c); - if (!Getattr(c,"templatetype")) { + Node *next = nextSibling(c); + if (!Getattr(c, "templatetype")) { if (GetFlag(c, "nested") && GetFlag(c, "feature:flatnested")) { - removeNode(c); - if (!checkAttribute(c, "access", "public")) + removeNode(c); + if (!checkAttribute(c, "access", "public")) SetFlag(c, "feature:ignore"); else insertNodeAfter(n, c); diff --git a/Source/Swig/naming.c b/Source/Swig/naming.c index d860a8b00..259676971 100644 --- a/Source/Swig/naming.c +++ b/Source/Swig/naming.c @@ -1648,14 +1648,18 @@ void Swig_name_inherit(String *base, String *derived) { Swig_name_object_inherit(Swig_cparse_features(), base, derived); } -void Swig_inherit_base_symbols(List* bases) { +/* ----------------------------------------------------------------------------- + * Swig_inherit_base_symbols() + * ----------------------------------------------------------------------------- */ + +void Swig_inherit_base_symbols(List *bases) { if (bases) { Iterator s; for (s = First(bases); s.item; s = Next(s)) { - Symtab *st = Getattr(s.item,"symtab"); + Symtab *st = Getattr(s.item, "symtab"); if (st) { - Setfile(st,Getfile(s.item)); - Setline(st,Getline(s.item)); + Setfile(st, Getfile(s.item)); + Setline(st, Getline(s.item)); Swig_symbol_inherit(st); } } @@ -1663,40 +1667,46 @@ void Swig_inherit_base_symbols(List* bases) { } } -List *Swig_make_inherit_list(String *clsname, List *names, String* Namespaceprefix) { +/* ----------------------------------------------------------------------------- + * Swig_make_inherit_list() + * ----------------------------------------------------------------------------- */ + +List *Swig_make_inherit_list(String *clsname, List *names, String *Namespaceprefix) { int i, ilen; String *derived; List *bases = NewList(); - if (Namespaceprefix) derived = NewStringf("%s::%s", Namespaceprefix,clsname); - else derived = NewString(clsname); + if (Namespaceprefix) + derived = NewStringf("%s::%s", Namespaceprefix, clsname); + else + derived = NewString(clsname); ilen = Len(names); for (i = 0; i < ilen; i++) { Node *s; String *base; - String *n = Getitem(names,i); + String *n = Getitem(names, i); /* Try to figure out where this symbol is */ s = Swig_symbol_clookup(n,0); if (s) { - while (s && (Strcmp(nodeType(s),"class") != 0)) { + while (s && (Strcmp(nodeType(s), "class") != 0)) { /* Not a class. Could be a typedef though. */ - String *storage = Getattr(s,"storage"); - if (storage && (Strcmp(storage,"typedef") == 0)) { - String *nn = Getattr(s,"type"); - s = Swig_symbol_clookup(nn,Getattr(s,"sym:symtab")); + String *storage = Getattr(s, "storage"); + if (storage && (Strcmp(storage, "typedef") == 0)) { + String *nn = Getattr(s, "type"); + s = Swig_symbol_clookup(nn, Getattr(s, "sym:symtab")); } else { break; } } - if (s && ((Strcmp(nodeType(s),"class") == 0) || (Strcmp(nodeType(s),"template") == 0))) { + if (s && ((Strcmp(nodeType(s), "class") == 0) || (Strcmp(nodeType(s), "template") == 0))) { String *q = Swig_symbol_qualified(s); - Append(bases,s); + Append(bases, s); if (q) { - base = NewStringf("%s::%s", q, Getattr(s,"name")); + base = NewStringf("%s::%s", q, Getattr(s, "name")); Delete(q); } else { - base = NewString(Getattr(s,"name")); + base = NewString(Getattr(s, "name")); } } else { base = NewString(n); @@ -1705,7 +1715,7 @@ List *Swig_make_inherit_list(String *clsname, List *names, String* Namespacepref base = NewString(n); } if (base) { - Swig_name_inherit(base,derived); + Swig_name_inherit(base, derived); Delete(base); } } diff --git a/Source/Swig/scanner.c b/Source/Swig/scanner.c index 39eaaf4d4..a32828b58 100644 --- a/Source/Swig/scanner.c +++ b/Source/Swig/scanner.c @@ -1545,13 +1545,18 @@ int Scanner_skip_balanced(Scanner * s, int startchar, int endchar) { Delete(locator); return 0; } -/* returns raw text between 2 braces, does not change scanner state in any way*/ -String* Scanner_get_raw_text_balanced(Scanner* s, int startchar, int endchar) -{ - String* result = 0; + +/* ----------------------------------------------------------------------------- + * Scanner_get_raw_text_balanced() + * + * Returns raw text between 2 braces, does not change scanner state in any way + * ----------------------------------------------------------------------------- */ + +String *Scanner_get_raw_text_balanced(Scanner *s, int startchar, int endchar) { + String *result = 0; char c; int old_line = s->line; - String* old_text = Copy(s->text); + String *old_text = Copy(s->text); int position = Tell(s->str); int num_levels = 1; diff --git a/Source/Swig/swig.h b/Source/Swig/swig.h index 9a4163c2c..95e3784d9 100644 --- a/Source/Swig/swig.h +++ b/Source/Swig/swig.h @@ -286,8 +286,8 @@ extern int ParmList_is_compactdefargs(ParmList *p); extern Hash *Swig_name_namewarn_get(Node *n, String *prefix, String *name, SwigType *decl); extern void Swig_name_rename_add(String *prefix, String *name, SwigType *decl, Hash *namewrn, ParmList *declaratorparms); extern void Swig_name_inherit(String *base, String *derived); - extern List *Swig_make_inherit_list(String *clsname, List *names, String* Namespaceprefix); - extern void Swig_inherit_base_symbols(List* bases); + extern List *Swig_make_inherit_list(String *clsname, List *names, String *Namespaceprefix); + extern void Swig_inherit_base_symbols(List *bases); extern int Swig_need_protected(Node *n); extern int Swig_need_name_warning(Node *n); extern int Swig_need_redefined_warn(Node *a, Node *b, int InClass); diff --git a/Source/Swig/tree.c b/Source/Swig/tree.c index 79f708d33..d817f1a85 100644 --- a/Source/Swig/tree.c +++ b/Source/Swig/tree.c @@ -171,11 +171,10 @@ void prependChild(Node *node, Node *chd) { } } -void appendSibling(Node *node, Node *chd) -{ +void appendSibling(Node *node, Node *chd) { Node *parent; - Node* lc = node; - while(nextSibling(lc)) + Node *lc = node; + while (nextSibling(lc)) lc = nextSibling(lc); set_nextSibling(lc, chd); set_previousSibling(chd, lc); From b65ba2a8db43b8fe377caee88fce8aa35bdfbcdb Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 29 Nov 2013 07:33:55 +0000 Subject: [PATCH 208/481] Minor code improvements --- Source/CParse/parser.y | 12 ++++++------ Source/Modules/lang.cxx | 2 +- Source/Modules/main.cxx | 12 ++++-------- Source/Swig/naming.c | 3 +-- Source/Swig/swigtree.h | 2 +- 5 files changed, 13 insertions(+), 18 deletions(-) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 09385f1c0..a97ac8fd5 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -243,10 +243,10 @@ static void set_access_mode(Node *n) { } static void restore_access_mode(Node *n) { - char* mode = Char(Getattr(n, "access")); - if (strcmp(mode, "private") == 0) + String *mode = Getattr(n, "access"); + if (Strcmp(mode, "private") == 0) cplus_mode = CPLUS_PRIVATE; - else if (strcmp(mode, "protected") == 0) + else if (Strcmp(mode, "protected") == 0) cplus_mode = CPLUS_PROTECTED; else cplus_mode = CPLUS_PUBLIC; @@ -800,7 +800,7 @@ static String *make_class_name(String *name) { /* Use typedef name as class name */ -void add_typedef_name(Node *n, Node *decl, String *oldName, Symtab *cscope, String *scpname) { +static void add_typedef_name(Node *n, Node *decl, String *oldName, Symtab *cscope, String *scpname) { String *class_rename = 0; SwigType *decltype = Getattr(decl, "decl"); if (!decltype || !Len(decltype)) { @@ -1043,7 +1043,7 @@ static String *resolve_create_node_scope(String *cname) { } /* look for simple typedef name in typedef list */ -String *try_to_find_a_name_for_unnamed_structure(char *storage, Node *decls) { +static String *try_to_find_a_name_for_unnamed_structure(const char *storage, Node *decls) { String *name = 0; Node *n = decls; if (storage && (strcmp(storage, "typedef") == 0)) { @@ -1058,7 +1058,7 @@ String *try_to_find_a_name_for_unnamed_structure(char *storage, Node *decls) { } /* traverse copied tree segment, and update outer class links*/ -void update_nested_classes(Node *n) +static void update_nested_classes(Node *n) { Node *c = firstChild(n); while (c) { diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 25bf7e804..5c701bc85 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -2391,7 +2391,7 @@ int Language::classDeclaration(Node *n) { } AccessMode oldAccessMode = cplus_mode; Node *outerClass = Getattr(n, "nested:outer"); - if (outerClass && oldAccessMode != Dispatcher::PUBLIC) + if (outerClass && oldAccessMode != PUBLIC) return SWIG_NOWRAP; ClassName = Copy(name); ClassPrefix = Copy(symname); diff --git a/Source/Modules/main.cxx b/Source/Modules/main.cxx index 5336159af..290887c6e 100644 --- a/Source/Modules/main.cxx +++ b/Source/Modules/main.cxx @@ -862,13 +862,9 @@ void SWIG_getoptions(int argc, char *argv[]) { } } -void Swig_flatten_nested() { - String* name = NewString(""); - String* fname = NewString("feature:flatnested"); - String* val = NewString("1"); - Swig_feature_set(Swig_cparse_features(),name,0,fname, val, 0); - Delete(fname); - Delete(name); +static void flatten_nested() { + String *val = NewString("1"); + Swig_feature_set(Swig_cparse_features(), "", 0, "feature:flatnested", val, 0); Delete(val); } @@ -1167,7 +1163,7 @@ int SWIG_main(int argc, char *argv[], Language *l) { // add "ignore" directive if nested classes are not supported if (!lang->nestedClassesSupported()) - Swig_flatten_nested(); + flatten_nested(); Node *top = Swig_cparse(cpps); diff --git a/Source/Swig/naming.c b/Source/Swig/naming.c index 259676971..2921b3c84 100644 --- a/Source/Swig/naming.c +++ b/Source/Swig/naming.c @@ -1683,11 +1683,10 @@ List *Swig_make_inherit_list(String *clsname, List *names, String *Namespacepref ilen = Len(names); for (i = 0; i < ilen; i++) { - Node *s; String *base; String *n = Getitem(names, i); /* Try to figure out where this symbol is */ - s = Swig_symbol_clookup(n,0); + Node *s = Swig_symbol_clookup(n, 0); if (s) { while (s && (Strcmp(nodeType(s), "class") != 0)) { /* Not a class. Could be a typedef though. */ diff --git a/Source/Swig/swigtree.h b/Source/Swig/swigtree.h index 4973400d7..acd0e5e90 100644 --- a/Source/Swig/swigtree.h +++ b/Source/Swig/swigtree.h @@ -38,7 +38,7 @@ extern void appendChild(Node *node, Node *child); extern void prependChild(Node *node, Node *child); extern void removeNode(Node *node); extern Node *copyNode(Node *node); -extern void appendSibling(Node *node, Node *chd); +extern void appendSibling(Node *node, Node *child); /* Node restoration/restore functions */ From 9e2c35f766a01aa96459e2d3ce3f63b8d5aefe2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Klaus=20K=C3=A4mpf?= Date: Fri, 29 Nov 2013 13:48:07 +0100 Subject: [PATCH 209/481] Make string encoding explitic Ruby 2.0 enforces explicit string encodings. The char_constant testcase fails because the internal (SWIG_FromCharPtrAndSize, using rb_str_new) defaults to ASCII-8BIT while the test-suite file defaults to the current shell LOCALE setting. This patch sets the char_constant_runme.rb encoding to ASCII-8BIT. --- Examples/test-suite/ruby/char_constant_runme.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Examples/test-suite/ruby/char_constant_runme.rb b/Examples/test-suite/ruby/char_constant_runme.rb index 4e9d9d59c..4c56ecbf7 100644 --- a/Examples/test-suite/ruby/char_constant_runme.rb +++ b/Examples/test-suite/ruby/char_constant_runme.rb @@ -1,5 +1,5 @@ #!/usr/bin/env ruby -# +#Encoding: ASCII-8BIT # Put description here # # From 2d518c638c008d12a7cf7e93a7711df34bd60859 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 29 Nov 2013 07:46:48 +0000 Subject: [PATCH 210/481] Add C++ nested class example This also reverts the nested class additions to the Java/C# 'class' example so that the 'class' example remains identical across different language modules --- Examples/csharp/check.list | 1 + Examples/csharp/class/example.cxx | 2 +- Examples/csharp/class/example.h | 8 +- Examples/csharp/class/runme.cs | 6 +- Examples/csharp/nested/Makefile | 19 +++ Examples/csharp/nested/example-cs.csproj | 94 +++++++++++++ Examples/csharp/nested/example-vc.vcproj | 158 ++++++++++++++++++++++ Examples/csharp/nested/example.cxx | 62 +++++++++ Examples/csharp/nested/example.h | 48 +++++++ Examples/csharp/nested/example.i | 13 ++ Examples/csharp/nested/example.sln | 30 +++++ Examples/csharp/nested/runme.cs | 27 ++++ Examples/java/check.list | 1 + Examples/java/class/example.cxx | 2 +- Examples/java/class/example.h | 8 +- Examples/java/class/runme.java | 6 +- Examples/java/nested/Makefile | 18 +++ Examples/java/nested/example.cxx | 62 +++++++++ Examples/java/nested/example.dsp | 162 +++++++++++++++++++++++ Examples/java/nested/example.h | 48 +++++++ Examples/java/nested/example.i | 13 ++ Examples/java/nested/runme.java | 32 +++++ 22 files changed, 802 insertions(+), 18 deletions(-) create mode 100644 Examples/csharp/nested/Makefile create mode 100644 Examples/csharp/nested/example-cs.csproj create mode 100644 Examples/csharp/nested/example-vc.vcproj create mode 100644 Examples/csharp/nested/example.cxx create mode 100644 Examples/csharp/nested/example.h create mode 100644 Examples/csharp/nested/example.i create mode 100644 Examples/csharp/nested/example.sln create mode 100644 Examples/csharp/nested/runme.cs create mode 100644 Examples/java/nested/Makefile create mode 100644 Examples/java/nested/example.cxx create mode 100644 Examples/java/nested/example.dsp create mode 100644 Examples/java/nested/example.h create mode 100644 Examples/java/nested/example.i create mode 100644 Examples/java/nested/runme.java diff --git a/Examples/csharp/check.list b/Examples/csharp/check.list index 5454d8531..a530a4b42 100644 --- a/Examples/csharp/check.list +++ b/Examples/csharp/check.list @@ -5,6 +5,7 @@ class enum extend funcptr +nested reference simple template diff --git a/Examples/csharp/class/example.cxx b/Examples/csharp/class/example.cxx index 9b23ea4e6..1e8e203dd 100644 --- a/Examples/csharp/class/example.cxx +++ b/Examples/csharp/class/example.cxx @@ -9,7 +9,7 @@ void Shape::move(double dx, double dy) { y += dy; } -int Shape::Counter::nshapes = 0; +int Shape::nshapes = 0; double Circle::area(void) { return M_PI*radius*radius; diff --git a/Examples/csharp/class/example.h b/Examples/csharp/class/example.h index 430cf47dc..46d901361 100644 --- a/Examples/csharp/class/example.h +++ b/Examples/csharp/class/example.h @@ -2,19 +2,17 @@ class Shape { public: - struct Counter{ - static int nshapes; - }; Shape() { - Counter::nshapes++; + nshapes++; } virtual ~Shape() { - Counter::nshapes--; + 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 { diff --git a/Examples/csharp/class/runme.cs b/Examples/csharp/class/runme.cs index 2b500da5c..9088031d6 100644 --- a/Examples/csharp/class/runme.cs +++ b/Examples/csharp/class/runme.cs @@ -17,9 +17,9 @@ public class runme Console.WriteLine( " Created circle " + c ); Console.WriteLine( " Created square " + s ); - // ----- Access a static member of a nested class ----- + // ----- Access a static member ----- - Console.WriteLine( "\nA total of " + Shape.Counter.nshapes + " shapes were created" ); + Console.WriteLine( "\nA total of " + Shape.nshapes + " shapes were created" ); // ----- Member data access ----- @@ -60,7 +60,7 @@ public class runme // Note: when this using scope is exited the C# Dispose() methods // are called which in turn call the C++ destructors - Console.WriteLine( Shape.Counter.nshapes + " shapes remain" ); + Console.WriteLine( Shape.nshapes + " shapes remain" ); Console.WriteLine( "Goodbye" ); } } diff --git a/Examples/csharp/nested/Makefile b/Examples/csharp/nested/Makefile new file mode 100644 index 000000000..bc3ce8ce8 --- /dev/null +++ b/Examples/csharp/nested/Makefile @@ -0,0 +1,19 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +CXXSRCS = example.cxx +TARGET = example +INTERFACE = example.i +SWIGOPT = +CSHARPSRCS = *.cs +CSHARPFLAGS= -nologo -out:runme.exe + +check: build + $(MAKE) -f $(TOP)/Makefile csharp_run + +build: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp_cpp + $(MAKE) -f $(TOP)/Makefile CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile + +clean: + $(MAKE) -f $(TOP)/Makefile csharp_clean diff --git a/Examples/csharp/nested/example-cs.csproj b/Examples/csharp/nested/example-cs.csproj new file mode 100644 index 000000000..8004780fb --- /dev/null +++ b/Examples/csharp/nested/example-cs.csproj @@ -0,0 +1,94 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/Examples/csharp/nested/example-vc.vcproj b/Examples/csharp/nested/example-vc.vcproj new file mode 100644 index 000000000..5788bc9c7 --- /dev/null +++ b/Examples/csharp/nested/example-vc.vcproj @@ -0,0 +1,158 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Examples/csharp/nested/example.cxx b/Examples/csharp/nested/example.cxx new file mode 100644 index 000000000..03bb74d9e --- /dev/null +++ b/Examples/csharp/nested/example.cxx @@ -0,0 +1,62 @@ +#include "example.h" + +int MotorCar::DesignOpinion::AceDesignCount = 0; +int MotorCar::DesignOpinion::TotalDesignCount = 0; + +int MotorCar::DesignOpinion::PercentScore() { + return AceDesignCount*100/TotalDesignCount; +} + +MotorCar::Wheels::Wheels(Shape shape, size_t count) : shape(shape), count(count) {} + +MotorCar::WindScreen::WindScreen(bool opaque) : opaque(opaque) {} + +MotorCar::MotorCar(const std::string &name, const Wheels &wheels, const WindScreen &windscreen) : name(name), wheels(wheels), windscreen(windscreen) {} + +MotorCar MotorCar::DesignFromComponents(const std::string &name, const Wheels &wheels, const WindScreen &windscreen) { + MotorCar car = MotorCar(name, wheels, windscreen); + DesignOpinion::TotalDesignCount++; + if (car.wheels.Opinion().itrocks && car.windscreen.Opinion().itrocks) + DesignOpinion::AceDesignCount++; + return car; +} + +MotorCar::DesignOpinion MotorCar::Wheels::Opinion() { + DesignOpinion opinion; + opinion.itrocks = true; + if (shape == Square) { + opinion.itrocks = false; + opinion.reason = "you'll have a few issues with wheel rotation"; + } + if (count <= 2) { + opinion.reason += opinion.itrocks ? "" : " and "; + opinion.itrocks = false; + opinion.reason += "a few more wheels are needed for stability"; + } + if (opinion.itrocks) + opinion.reason = "your choice of wheels was top notch"; + + return opinion; +} + +MotorCar::DesignOpinion MotorCar::WindScreen::Opinion() { + DesignOpinion opinion; + opinion.itrocks = !opaque; + opinion.reason = opinion.itrocks ? "the driver will have a commanding view out the window" : "you can't see out the windscreen"; + return opinion; +} + +std::string MotorCar::WillItWork() { + DesignOpinion wh = wheels.Opinion(); + DesignOpinion ws = windscreen.Opinion(); + std::string willit; + if (wh.itrocks && ws.itrocks) { + willit = "Great car design because " + wh.reason + " and " + ws.reason; + } else { + willit = "You need a rethink because "; + willit += wh.itrocks ? "" : wh.reason; + willit += (!wh.itrocks && !ws.itrocks) ? " and " : ""; + willit += ws.itrocks ? "" : ws.reason; + } + return willit; +} diff --git a/Examples/csharp/nested/example.h b/Examples/csharp/nested/example.h new file mode 100644 index 000000000..4fb107cb5 --- /dev/null +++ b/Examples/csharp/nested/example.h @@ -0,0 +1,48 @@ +#include + +/** Design a motor car from various components */ +struct MotorCar { + + /** Information about an opinion of the design of a car component */ + struct DesignOpinion { + bool itrocks; + std::string reason; + static int AceDesignCount; + static int TotalDesignCount; + static int PercentScore(); + }; + + /** Wheels component */ + struct Wheels { + enum Shape { Round, Square }; + Wheels(Shape shape, size_t count); + DesignOpinion Opinion(); + private: + Shape shape; + size_t count; + }; + + /** Windscreen component */ + struct WindScreen { + WindScreen(bool opaque); + DesignOpinion Opinion(); + private: + bool opaque; + }; + + /** Factory method for creating a car */ + static MotorCar DesignFromComponents(const std::string &name, const Wheels &wheels, const WindScreen &windscreen); + + std::string Name() { + return name; + } + + /** Get an overall opinion on the car design */ + std::string WillItWork(); + +private: + MotorCar(const std::string &name, const Wheels &wheels, const WindScreen &windscreen); + std::string name; + Wheels wheels; + WindScreen windscreen; +}; diff --git a/Examples/csharp/nested/example.i b/Examples/csharp/nested/example.i new file mode 100644 index 000000000..c07c1521a --- /dev/null +++ b/Examples/csharp/nested/example.i @@ -0,0 +1,13 @@ +%module example + +// This example shows how wrappers for numerous aspects of C++ nested classes work: +// Nested static and instance variables and methods and nested enums + +%include + +%{ +#include "example.h" +%} + +%include "example.h" + diff --git a/Examples/csharp/nested/example.sln b/Examples/csharp/nested/example.sln new file mode 100644 index 000000000..88995ffd3 --- /dev/null +++ b/Examples/csharp/nested/example.sln @@ -0,0 +1,30 @@ +Microsoft Visual Studio Solution File, Format Version 8.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "example-cs", "example-cs.csproj", "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}" + ProjectSection(ProjectDependencies) = postProject + {C2302635-D489-4678-96B4-70F5309DCBE6} = {C2302635-D489-4678-96B4-70F5309DCBE6} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example-vc", "example-vc.vcproj", "{C2302635-D489-4678-96B4-70F5309DCBE6}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfiguration) = preSolution + Debug = Debug + Release = Release + EndGlobalSection + GlobalSection(ProjectConfiguration) = postSolution + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.ActiveCfg = Debug|.NET + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.Build.0 = Debug|.NET + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.ActiveCfg = Release|.NET + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.Build.0 = Release|.NET + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.ActiveCfg = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.Build.0 = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release.ActiveCfg = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + EndGlobalSection + GlobalSection(ExtensibilityAddIns) = postSolution + EndGlobalSection +EndGlobal diff --git a/Examples/csharp/nested/runme.cs b/Examples/csharp/nested/runme.cs new file mode 100644 index 000000000..facaefdb7 --- /dev/null +++ b/Examples/csharp/nested/runme.cs @@ -0,0 +1,27 @@ +// This example illustrates how C++ classes can be used from C# using SWIG. +// The C# class gets mapped onto the C++ class and behaves as if it is a C# class. + +using System; + +public class runme +{ + static void Main() + { + MotorCar car1 = MotorCar.DesignFromComponents("Bumpy", new MotorCar.Wheels(MotorCar.Wheels.Shape.Square, 4), new MotorCar.WindScreen(false)); + MotorCar car2 = MotorCar.DesignFromComponents("Wobbly", new MotorCar.Wheels(MotorCar.Wheels.Shape.Round, 2), new MotorCar.WindScreen(false)); + MotorCar car3 = MotorCar.DesignFromComponents("Batty", new MotorCar.Wheels(MotorCar.Wheels.Shape.Round, 4), new MotorCar.WindScreen(true)); + MotorCar car4 = MotorCar.DesignFromComponents("Spiffing", new MotorCar.Wheels(MotorCar.Wheels.Shape.Round, 4), new MotorCar.WindScreen(false)); + + Console.WriteLine("Expert opinion on " + car1.Name() + " : \n " + car1.WillItWork()); + Console.WriteLine("Expert opinion on " + car2.Name() + " : \n " + car2.WillItWork()); + Console.WriteLine("Expert opinion on " + car3.Name() + " : \n " + car3.WillItWork()); + Console.WriteLine("Expert opinion on " + car4.Name() + " : \n " + car4.WillItWork()); + + int count = MotorCar.DesignOpinion.AceDesignCount; + int total = MotorCar.DesignOpinion.TotalDesignCount; + int percent = MotorCar.DesignOpinion.PercentScore(); + Console.WriteLine("Overall opinion rating on car design is " + count + "/" + total + " = " + percent + "%"); + + Console.WriteLine("Single square wheel thoughts: " + new MotorCar.Wheels(MotorCar.Wheels.Shape.Square, 1).Opinion().reason); + } +} diff --git a/Examples/java/check.list b/Examples/java/check.list index 9728342f2..825d04a6d 100644 --- a/Examples/java/check.list +++ b/Examples/java/check.list @@ -7,6 +7,7 @@ extend funcptr multimap native +nested pointer reference simple diff --git a/Examples/java/class/example.cxx b/Examples/java/class/example.cxx index 9b23ea4e6..1e8e203dd 100644 --- a/Examples/java/class/example.cxx +++ b/Examples/java/class/example.cxx @@ -9,7 +9,7 @@ void Shape::move(double dx, double dy) { y += dy; } -int Shape::Counter::nshapes = 0; +int Shape::nshapes = 0; double Circle::area(void) { return M_PI*radius*radius; diff --git a/Examples/java/class/example.h b/Examples/java/class/example.h index 430cf47dc..46d901361 100644 --- a/Examples/java/class/example.h +++ b/Examples/java/class/example.h @@ -2,19 +2,17 @@ class Shape { public: - struct Counter{ - static int nshapes; - }; Shape() { - Counter::nshapes++; + nshapes++; } virtual ~Shape() { - Counter::nshapes--; + 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 { diff --git a/Examples/java/class/runme.java b/Examples/java/class/runme.java index 90844ba23..e1ea0d71c 100644 --- a/Examples/java/class/runme.java +++ b/Examples/java/class/runme.java @@ -21,9 +21,9 @@ public class runme { Square s = new Square(10); System.out.println( " Created square " + s ); - // ----- Access a static member of a nested class ----- + // ----- Access a static member ----- - System.out.println( "\nA total of " + Shape.Counter.getNshapes() + " shapes were created" ); + System.out.println( "\nA total of " + Shape.getNshapes() + " shapes were created" ); // ----- Member data access ----- @@ -64,7 +64,7 @@ public class runme { c.delete(); s.delete(); - System.out.println( Shape.Counter.getNshapes() + " shapes remain" ); + System.out.println( Shape.getNshapes() + " shapes remain" ); System.out.println( "Goodbye" ); } } diff --git a/Examples/java/nested/Makefile b/Examples/java/nested/Makefile new file mode 100644 index 000000000..8f274e7cb --- /dev/null +++ b/Examples/java/nested/Makefile @@ -0,0 +1,18 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +CXXSRCS = example.cxx +TARGET = example +INTERFACE = example.i +SWIGOPT = +JAVASRCS = *.java + +check: build + $(MAKE) -f $(TOP)/Makefile java_run + +build: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp + $(MAKE) -f $(TOP)/Makefile JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile + +clean: + $(MAKE) -f $(TOP)/Makefile java_clean diff --git a/Examples/java/nested/example.cxx b/Examples/java/nested/example.cxx new file mode 100644 index 000000000..03bb74d9e --- /dev/null +++ b/Examples/java/nested/example.cxx @@ -0,0 +1,62 @@ +#include "example.h" + +int MotorCar::DesignOpinion::AceDesignCount = 0; +int MotorCar::DesignOpinion::TotalDesignCount = 0; + +int MotorCar::DesignOpinion::PercentScore() { + return AceDesignCount*100/TotalDesignCount; +} + +MotorCar::Wheels::Wheels(Shape shape, size_t count) : shape(shape), count(count) {} + +MotorCar::WindScreen::WindScreen(bool opaque) : opaque(opaque) {} + +MotorCar::MotorCar(const std::string &name, const Wheels &wheels, const WindScreen &windscreen) : name(name), wheels(wheels), windscreen(windscreen) {} + +MotorCar MotorCar::DesignFromComponents(const std::string &name, const Wheels &wheels, const WindScreen &windscreen) { + MotorCar car = MotorCar(name, wheels, windscreen); + DesignOpinion::TotalDesignCount++; + if (car.wheels.Opinion().itrocks && car.windscreen.Opinion().itrocks) + DesignOpinion::AceDesignCount++; + return car; +} + +MotorCar::DesignOpinion MotorCar::Wheels::Opinion() { + DesignOpinion opinion; + opinion.itrocks = true; + if (shape == Square) { + opinion.itrocks = false; + opinion.reason = "you'll have a few issues with wheel rotation"; + } + if (count <= 2) { + opinion.reason += opinion.itrocks ? "" : " and "; + opinion.itrocks = false; + opinion.reason += "a few more wheels are needed for stability"; + } + if (opinion.itrocks) + opinion.reason = "your choice of wheels was top notch"; + + return opinion; +} + +MotorCar::DesignOpinion MotorCar::WindScreen::Opinion() { + DesignOpinion opinion; + opinion.itrocks = !opaque; + opinion.reason = opinion.itrocks ? "the driver will have a commanding view out the window" : "you can't see out the windscreen"; + return opinion; +} + +std::string MotorCar::WillItWork() { + DesignOpinion wh = wheels.Opinion(); + DesignOpinion ws = windscreen.Opinion(); + std::string willit; + if (wh.itrocks && ws.itrocks) { + willit = "Great car design because " + wh.reason + " and " + ws.reason; + } else { + willit = "You need a rethink because "; + willit += wh.itrocks ? "" : wh.reason; + willit += (!wh.itrocks && !ws.itrocks) ? " and " : ""; + willit += ws.itrocks ? "" : ws.reason; + } + return willit; +} diff --git a/Examples/java/nested/example.dsp b/Examples/java/nested/example.dsp new file mode 100644 index 000000000..f52544b95 --- /dev/null +++ b/Examples/java/nested/example.dsp @@ -0,0 +1,162 @@ +# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 + +CFG=example - Win32 Release +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "example.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +MTL=midl.exe +RSC=rc.exe + +!IF "$(CFG)" == "example - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(JAVA_INCLUDE)" /I "$(JAVA_INCLUDE)\win32" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c +# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x809 /d "_DEBUG" +# ADD RSC /l 0x809 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /out:"example.dll" /pdbtype:sept +# Begin Special Build Tool +SOURCE="$(InputPath)" +PostBuild_Desc=Java compile post-build step +PostBuild_Cmds=echo on "%JAVA_BIN%\javac" *.java +# End Special Build Tool + +!ELSEIF "$(CFG)" == "example - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c +# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(JAVA_INCLUDE)" /I "$(JAVA_INCLUDE)\win32" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c +# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x809 /d "NDEBUG" +# ADD RSC /l 0x809 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386 /out:"example.dll" +# Begin Special Build Tool +SOURCE="$(InputPath)" +PostBuild_Desc=Java compile post-build step +PostBuild_Cmds=echo on "%JAVA_BIN%\javac" *.java +# End Special Build Tool + +!ENDIF + +# Begin Target + +# Name "example - Win32 Debug" +# Name "example - Win32 Release" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\example.cxx +# End Source File +# Begin Source File + +SOURCE=.\example_wrap.cxx +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=.\example.h +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# Begin Source File + +SOURCE=.\example.i + +!IF "$(CFG)" == "example - Win32 Debug" + +# Begin Custom Build +InputPath=.\example.i +InputName=example + +"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + echo In order to function correctly, please ensure the following environment variables are correctly set: + echo JAVA_INCLUDE: %JAVA_INCLUDE% + echo JAVA_BIN: %JAVA_BIN% + echo on + ..\..\..\swig.exe -c++ -java "$(InputPath)" + +# End Custom Build + +!ELSEIF "$(CFG)" == "example - Win32 Release" + +# Begin Custom Build +InputPath=.\example.i +InputName=example + +"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + echo In order to function correctly, please ensure the following environment variables are correctly set: + echo JAVA_INCLUDE: %JAVA_INCLUDE% + echo JAVA_BIN: %JAVA_BIN% + echo on + ..\..\..\swig.exe -c++ -java "$(InputPath)" + +# End Custom Build + +!ENDIF + +# End Source File +# End Target +# End Project diff --git a/Examples/java/nested/example.h b/Examples/java/nested/example.h new file mode 100644 index 000000000..4fb107cb5 --- /dev/null +++ b/Examples/java/nested/example.h @@ -0,0 +1,48 @@ +#include + +/** Design a motor car from various components */ +struct MotorCar { + + /** Information about an opinion of the design of a car component */ + struct DesignOpinion { + bool itrocks; + std::string reason; + static int AceDesignCount; + static int TotalDesignCount; + static int PercentScore(); + }; + + /** Wheels component */ + struct Wheels { + enum Shape { Round, Square }; + Wheels(Shape shape, size_t count); + DesignOpinion Opinion(); + private: + Shape shape; + size_t count; + }; + + /** Windscreen component */ + struct WindScreen { + WindScreen(bool opaque); + DesignOpinion Opinion(); + private: + bool opaque; + }; + + /** Factory method for creating a car */ + static MotorCar DesignFromComponents(const std::string &name, const Wheels &wheels, const WindScreen &windscreen); + + std::string Name() { + return name; + } + + /** Get an overall opinion on the car design */ + std::string WillItWork(); + +private: + MotorCar(const std::string &name, const Wheels &wheels, const WindScreen &windscreen); + std::string name; + Wheels wheels; + WindScreen windscreen; +}; diff --git a/Examples/java/nested/example.i b/Examples/java/nested/example.i new file mode 100644 index 000000000..c07c1521a --- /dev/null +++ b/Examples/java/nested/example.i @@ -0,0 +1,13 @@ +%module example + +// This example shows how wrappers for numerous aspects of C++ nested classes work: +// Nested static and instance variables and methods and nested enums + +%include + +%{ +#include "example.h" +%} + +%include "example.h" + diff --git a/Examples/java/nested/runme.java b/Examples/java/nested/runme.java new file mode 100644 index 000000000..855dbea91 --- /dev/null +++ b/Examples/java/nested/runme.java @@ -0,0 +1,32 @@ +// This example illustrates wrapping of nested C++ classes + +public class runme { + static { + try { + System.loadLibrary("example"); + } 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[]) + { + MotorCar car1 = MotorCar.DesignFromComponents("Bumpy", new MotorCar.Wheels(MotorCar.Wheels.Shape.Square, 4), new MotorCar.WindScreen(false)); + MotorCar car2 = MotorCar.DesignFromComponents("Wobbly", new MotorCar.Wheels(MotorCar.Wheels.Shape.Round, 2), new MotorCar.WindScreen(false)); + MotorCar car3 = MotorCar.DesignFromComponents("Batty", new MotorCar.Wheels(MotorCar.Wheels.Shape.Round, 4), new MotorCar.WindScreen(true)); + MotorCar car4 = MotorCar.DesignFromComponents("Spiffing", new MotorCar.Wheels(MotorCar.Wheels.Shape.Round, 4), new MotorCar.WindScreen(false)); + + System.out.println("Expert opinion on " + car1.Name() + " : \n " + car1.WillItWork()); + System.out.println("Expert opinion on " + car2.Name() + " : \n " + car2.WillItWork()); + System.out.println("Expert opinion on " + car3.Name() + " : \n " + car3.WillItWork()); + System.out.println("Expert opinion on " + car4.Name() + " : \n " + car4.WillItWork()); + + int count = MotorCar.DesignOpinion.getAceDesignCount(); + int total = MotorCar.DesignOpinion.getTotalDesignCount(); + int percent = MotorCar.DesignOpinion.PercentScore(); + System.out.println("Overall opinion rating on car design is " + count + "/" + total + " = " + percent + "%"); + + System.out.println("Single square wheel thoughts: " + new MotorCar.Wheels(MotorCar.Wheels.Shape.Square, 1).Opinion().getReason()); + } +} From 1c7054b98a1251447ab6fda7904ea0c419396018 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 30 Nov 2013 09:26:49 +0000 Subject: [PATCH 211/481] Add in Travis testing for nested branch --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 70cbb2f27..7f868ae91 100644 --- a/.travis.yml +++ b/.travis.yml @@ -57,3 +57,4 @@ script: branches: only: - master + - nested From 19f202cc163ce24756aa0493936eead05ed8ec8b Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 30 Nov 2013 18:01:24 +0000 Subject: [PATCH 212/481] C nested struct passed by value example This was causing problems in Octave as wrappers were compiled as C++. Solution has already been committed and required regenerating the inner struct into the global C++ namespace (which is where it is intended to be in C). --- Examples/test-suite/nested_structs.i | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Examples/test-suite/nested_structs.i b/Examples/test-suite/nested_structs.i index 60e34a638..add24ec17 100644 --- a/Examples/test-suite/nested_structs.i +++ b/Examples/test-suite/nested_structs.i @@ -25,3 +25,17 @@ void setValues(struct Outer *outer, int val) { } %} +/* +Below was causing problems in Octave as wrappers were compiled as C++. +Solution requires regenerating the inner struct into +the global C++ namespace (which is where it is intended to be in C). +*/ +%inline %{ +int nestedByVal(struct Named s); +int nestedByPtr(struct Named *s); +%} +%{ +int nestedByVal(struct Named s) { return s.val; } +int nestedByPtr(struct Named *s) { return s->val; } +%} + From df679071681242ec2619c82693f261f1f1c34b80 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 2 Dec 2013 07:06:29 +0000 Subject: [PATCH 213/481] Testcase of private nested class usage causing segfault Needs fixing for C#/Java --- Examples/test-suite/common.mk | 1 + Examples/test-suite/nested_private.i | 32 ++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 Examples/test-suite/nested_private.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index e5127fd0c..5c2aea787 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -84,6 +84,7 @@ CPP_TEST_BROKEN += \ extend_variable \ li_std_vector_ptr \ li_boost_shared_ptr_template \ + nested_private \ overload_complicated \ template_default_pointer \ template_expr \ diff --git a/Examples/test-suite/nested_private.i b/Examples/test-suite/nested_private.i new file mode 100644 index 000000000..a573fdd5a --- /dev/null +++ b/Examples/test-suite/nested_private.i @@ -0,0 +1,32 @@ +%module nested_private + +// segfault due to private nested class usage + +%inline %{ +#include +class MotorCar { + + struct DesignOpinion { + std::string reason; + }; + +public: + struct WindScreen { + WindScreen(bool opaque) : opaque(opaque) {} + DesignOpinion Opinion(); + private: + bool opaque; + }; + + std::string WindScreenOpinion() { + return MotorCar::WindScreen(true).Opinion().reason; + } +}; + +MotorCar::DesignOpinion MotorCar::WindScreen::Opinion() { + DesignOpinion opinion; + opinion.reason = !opaque ? "great design" : "you can't see out the windscreen"; + return opinion; +} + +%} From 9d3fc0069c5e62dff004f951e34bd75b47c397f0 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 30 Nov 2013 17:35:15 +0000 Subject: [PATCH 214/481] Add a few more types for the code beautifier --- Source/Makefile.am | 2 +- Source/Swig/typemap.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Source/Makefile.am b/Source/Makefile.am index 40fa4d9f2..0c28a95b6 100644 --- a/Source/Makefile.am +++ b/Source/Makefile.am @@ -116,7 +116,7 @@ distclean-local: # swig executable as a way of checking before and after the 'beautifying'. # Single files can be beautified with the beautify-file target, eg: 'make beautify-file INDENTFILE=chosenfile.c' -SWIGTYPEDEFS=-T bool -T File -T DohObjInfo -T Parm -T Language -T List -T Typetab -T ModuleFactory -T ErrorMessageFormat -T Symtab -T Hash -T String -T DohBase -T Node -T String_or_char -T SwigType -T Dispatcher -T Wrapper -T DohStringMethods -T DohFileMethods -T DohListMethods -T DohHashMethods -T DOH -T DohIterator -T ParmList -T FILE -T HashNode -T DOHString_or_char +SWIGTYPEDEFS=-T bool -T File -T DohObjInfo -T Parm -T Language -T List -T Typetab -T ModuleFactory -T ErrorMessageFormat -T Symtab -T Hash -T Scanner -T String -T DohBase -T Node -T String_or_char -T SwigType -T Dispatcher -T Wrapper -T DohStringMethods -T DohFileMethods -T DohListMethods -T DohHashMethods -T DOH -T DohIterator -T ParmList -T FILE -T HashNode -T DOHObj_or_char -T DOHFile -T DOHString -T DOHString_or_char -T UpcallData INDENTBAKSDIR=../IndentBaks beautify: diff --git a/Source/Swig/typemap.c b/Source/Swig/typemap.c index 981b0b436..0bfbb4bce 100644 --- a/Source/Swig/typemap.c +++ b/Source/Swig/typemap.c @@ -1200,7 +1200,7 @@ static int typemap_replace_vars(String *s, ParmList *locals, SwigType *type, Swi * creates the local variables. * ------------------------------------------------------------------------ */ -static void typemap_locals(DOHString * s, ParmList *l, Wrapper *f, int argnum) { +static void typemap_locals(String *s, ParmList *l, Wrapper *f, int argnum) { Parm *p; char *new_name; From e1a4e11beaaea4ebe9991ec47be8b559bf48e39f Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Wed, 4 Dec 2013 01:53:42 +0400 Subject: [PATCH 215/481] fixed out-of-scope nested class definitions, added a test enabled nested C structs assignment (still disabled for Octave), added Java runtime test fixed nested_private test case for Java & C# --- Examples/test-suite/common.mk | 3 ++- .../test-suite/java/nested_structs_runme.java | 7 +++++++ Examples/test-suite/nested_scope.i | 14 ++++++++++++++ Source/CParse/parser.y | 19 ++++++++++++++----- Source/Modules/csharp.cxx | 2 +- Source/Modules/java.cxx | 2 +- 6 files changed, 39 insertions(+), 8 deletions(-) create mode 100644 Examples/test-suite/nested_scope.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 5c2aea787..e444f869d 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -84,7 +84,6 @@ CPP_TEST_BROKEN += \ extend_variable \ li_std_vector_ptr \ li_boost_shared_ptr_template \ - nested_private \ overload_complicated \ template_default_pointer \ template_expr \ @@ -279,6 +278,8 @@ CPP_TEST_CASES += \ naturalvar_more \ nested_class \ nested_comment \ + nested_private \ + nested_scope \ nested_workaround \ newobject1 \ null_pointer \ diff --git a/Examples/test-suite/java/nested_structs_runme.java b/Examples/test-suite/java/nested_structs_runme.java index 4b713395a..43c5e2897 100644 --- a/Examples/test-suite/java/nested_structs_runme.java +++ b/Examples/test-suite/java/nested_structs_runme.java @@ -33,5 +33,12 @@ public class nested_structs_runme { if (inside2.getVal() != 200) throw new RuntimeException("failed inside2"); if (inside3.getVal() != 200) throw new RuntimeException("failed inside3"); if (inside4.getVal() != 400) throw new RuntimeException("failed inside4"); + + outer.getInner1().setVal(11); + if (inner1.getVal() != 11) throw new RuntimeException("failed inner1 assignment"); + Named named = new Named(); + named.setVal(22); + outer.setInside2(named); + if (outer.getInside2().getVal() != 22) throw new RuntimeException("failed inside2 assignment"); } } diff --git a/Examples/test-suite/nested_scope.i b/Examples/test-suite/nested_scope.i new file mode 100644 index 000000000..358dbbb61 --- /dev/null +++ b/Examples/test-suite/nested_scope.i @@ -0,0 +1,14 @@ +%module nested_scope + +%inline %{ +namespace ns { + struct Global { + struct Outer { + struct Nested; + }; + struct Outer::Nested { + int data; + } instance; + }; +} +%} \ No newline at end of file diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index a97ac8fd5..7a3fc1a29 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -3387,6 +3387,8 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { /* If the class name is qualified. We need to create or lookup namespace/scope entries */ scope = resolve_create_node_scope($3); + /* save nscope_inner to the class - it may be overwritten in nested classes*/ + Setattr($$, "nested:innerscope", nscope_inner); Setfile(scope,cparse_file); Setline(scope,cparse_line); $3 = scope; @@ -3462,6 +3464,10 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { (void) $6; $$ = currentOuterClass; currentOuterClass = Getattr($$, "nested:outer"); + nscope_inner = Getattr($$, "nested:innerscope"); + Delattr($$, "nested:innerscope"); + if (nscope_inner) /*actual parent class for this class*/ + Setattr($$, "nested:outer", nscope_inner); if (!currentOuterClass) inclass = 0; cscope = Getattr($$, "prev_symtab"); @@ -3490,14 +3496,16 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { if (am) append_previous_extension($$,am); p = $9; - if (p) { + if (p && !nscope_inner) { if (!cparse_cplusplus && currentOuterClass) appendChild(currentOuterClass, p); else appendSibling($$, p); } - if (cparse_cplusplus && !cparse_externc) { + if (nscope_inner) { + ty = NewString(scpname); /* if the class is declared out of scope, let the declarator use fully qualified type*/ + } else if (cparse_cplusplus && !cparse_externc) { ty = NewString($3); } else { ty = NewStringf("%s %s", $2,$3); @@ -3505,7 +3513,7 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { while (p) { Setattr(p,"storage",$1); Setattr(p,"type",ty); - if (!cparse_cplusplus) { + if (!cparse_cplusplus && currentOuterClass && (!Getattr(currentOuterClass, "name") || CPlusPlusOut)) { SetFlag(p,"hasconsttype"); SetFlag(p,"feature:immutable"); } @@ -3539,12 +3547,13 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); add_symbols($$); - if (nscope) $$ = nscope; /* but the variable definition in the current scope */ Swig_symbol_setscope(cscope); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); add_symbols($9); + nscope_inner = 0; + $$ = $9; } else { Delete(yyrename); yyrename = 0; @@ -3657,7 +3666,7 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { while (n) { Setattr(n,"storage",$1); Setattr(n, "type", ty); - if (!cparse_cplusplus) { + if (!cparse_cplusplus && currentOuterClass && (!Getattr(currentOuterClass, "name") || CPlusPlusOut)) { SetFlag(n,"hasconsttype"); SetFlag(n,"feature:immutable"); } diff --git a/Source/Modules/csharp.cxx b/Source/Modules/csharp.cxx index 7d3a0ac07..88dbfbad7 100644 --- a/Source/Modules/csharp.cxx +++ b/Source/Modules/csharp.cxx @@ -182,7 +182,7 @@ public: if (!proxyname) { String *nspace = Getattr(n, "sym:nspace"); String *symname = Copy(Getattr(n, "sym:name")); - if (!GetFlag(n, "feature:flatnested")) { + if (symname && !GetFlag(n, "feature:flatnested")) { for (Node *outer_class = Getattr(n, "nested:outer"); outer_class; outer_class = Getattr(outer_class, "nested:outer")) { Push(symname, "."); Push(symname, Getattr(outer_class, "sym:name")); diff --git a/Source/Modules/java.cxx b/Source/Modules/java.cxx index 15199af9e..f781f0c39 100644 --- a/Source/Modules/java.cxx +++ b/Source/Modules/java.cxx @@ -209,7 +209,7 @@ public: if (!proxyname || jnidescriptor) { String *nspace = Getattr(n, "sym:nspace"); String *symname = Copy(Getattr(n, "sym:name")); - if (!GetFlag(n, "feature:flatnested")) { + if (symname && !GetFlag(n, "feature:flatnested")) { for (Node *outer_class = Getattr(n, "nested:outer"); outer_class; outer_class = Getattr(outer_class, "nested:outer")) { Push(symname, "."); Push(symname, Getattr(outer_class, "sym:name")); From ed28725a15fb2b0a967e3e049a1bd43429e1a336 Mon Sep 17 00:00:00 2001 From: Vadim Zeitlin Date: Wed, 27 Nov 2013 15:44:46 +0100 Subject: [PATCH 216/481] Add std_auto_ptr.i defining typemaps for returning std::auto_ptr<>. These typemaps are currently defined for C#, Java and Python only and the tests are provided only for these languages. Also add a brief description of the new header to the documentation. --- CHANGES.current | 3 + Doc/Manual/Library.html | 51 +++++++++++++++++ Examples/test-suite/common.mk | 1 + .../csharp/li_std_auto_ptr_runme.cs | 37 ++++++++++++ .../java/li_std_auto_ptr_runme.java | 48 ++++++++++++++++ Examples/test-suite/li_std_auto_ptr.i | 56 +++++++++++++++++++ .../python/li_std_auto_ptr_runme.py | 17 ++++++ Lib/csharp/std_auto_ptr.i | 25 +++++++++ Lib/java/std_auto_ptr.i | 27 +++++++++ Lib/python/std_auto_ptr.i | 17 ++++++ 10 files changed, 282 insertions(+) create mode 100644 Examples/test-suite/csharp/li_std_auto_ptr_runme.cs create mode 100644 Examples/test-suite/java/li_std_auto_ptr_runme.java create mode 100644 Examples/test-suite/li_std_auto_ptr.i create mode 100644 Examples/test-suite/python/li_std_auto_ptr_runme.py create mode 100644 Lib/csharp/std_auto_ptr.i create mode 100644 Lib/java/std_auto_ptr.i create mode 100644 Lib/python/std_auto_ptr.i diff --git a/CHANGES.current b/CHANGES.current index c587ff07f..f3d9130a4 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,9 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2013-11-27: vadz + Add std_auto_ptr.i defining typemaps for returning std::auto_ptr<>. + 2013-11-09: wsfulton [C#] Apply patch #79 from Brant Kyser - Remove using directives from the generated C# code and fully qualify the use of all .NET diff --git a/Doc/Manual/Library.html b/Doc/Manual/Library.html index 1ae3c77a3..c23900614 100644 --- a/Doc/Manual/Library.html +++ b/Doc/Manual/Library.html @@ -31,6 +31,7 @@
    • std::vector
    • STL exceptions
    • shared_ptr smart pointer +
    • auto_ptr smart pointer
  • Utility Libraries
      @@ -1383,6 +1384,7 @@ The following table shows which C++ classes are supported and the equivalent SWI SWIG Interface library file + std::auto_ptr memory std_auto_ptr.i std::deque deque std_deque.i std::list list std_list.i std::map map std_map.i @@ -1874,6 +1876,55 @@ Adding the missing %shared_ptr macros will fix this: Note: There is currently no support for %shared_ptr and the director feature. + +

      8.4.5 auto_ptr smart pointer

      + +

      +While std::auto_ptr is deprecated in C++11, some existing code may +still be using it, so SWIG provides limited support for this class: +std_auto_ptr.i defines the typemaps which apply to the functions +returning objects of this type. Any other use of std_auto_ptr.i is not +directly supported. +

      + +

      +A typical example of use would be +

      +
      +
      +%include <std_auto_ptr.i>
      +
      +%auto_ptr(Klass)
      +%inline %{
      +class Klass {
      +public:
      +  // Factory function creating objects of this class:
      +  static std::auto_ptr<Klass> Create(int value) {
      +    return std::auto_ptr<Klass>(new Klass(value));
      +  }
      +
      +  int getValue() const { return m_value; }
      +
      +private:
      +  DerivedIntValue(int value) : m_value(value) {}
      +  int m_value;
      +};
      +%}
      +
      +
      + +

      +The returned objects can be used naturally from the target language, e.g. from +C#: +

      + +
      +
      +Klass k = Klass.Create(17);
      +int value = k.getValue();
      +
      +
      +

      8.5 Utility Libraries

      diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index e5127fd0c..e9caaedab 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -246,6 +246,7 @@ CPP_TEST_CASES += \ li_carrays \ li_cdata \ li_cpointer \ + li_std_auto_ptr \ li_stdint \ li_typemaps \ li_typemaps_apply \ diff --git a/Examples/test-suite/csharp/li_std_auto_ptr_runme.cs b/Examples/test-suite/csharp/li_std_auto_ptr_runme.cs new file mode 100644 index 000000000..bea92d2f4 --- /dev/null +++ b/Examples/test-suite/csharp/li_std_auto_ptr_runme.cs @@ -0,0 +1,37 @@ +using System; +using li_std_auto_ptrNamespace; + +public class li_std_auto_ptr_runme { + private static void WaitForGC() + { + System.GC.Collect(); + System.GC.WaitForPendingFinalizers(); + System.Threading.Thread.Sleep(10); + } + + public static void Main() + { + Klass k1 = li_std_auto_ptr.makeKlassAutoPtr("first"); + if (k1.getLabel() != "first") + throw new Exception("wrong object label"); + + Klass k2 = li_std_auto_ptr.makeKlassAutoPtr("second"); + if (Klass.getTotal_count() != 2) + throw new Exception("number of objects should be 2"); + + k1 = null; + WaitForGC(); + + if (Klass.getTotal_count() != 1) + throw new Exception("number of objects should be 1"); + + if (k2.getLabel() != "second") + throw new Exception("wrong object label"); + + k2 = null; + WaitForGC(); + + if (Klass.getTotal_count() != 0) + throw new Exception("no objects should be left"); + } +} diff --git a/Examples/test-suite/java/li_std_auto_ptr_runme.java b/Examples/test-suite/java/li_std_auto_ptr_runme.java new file mode 100644 index 000000000..eac7cacfc --- /dev/null +++ b/Examples/test-suite/java/li_std_auto_ptr_runme.java @@ -0,0 +1,48 @@ +import li_std_auto_ptr.*; + +public class li_std_auto_ptr_runme { + static { + try { + System.loadLibrary("li_std_auto_ptr"); + } 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); + } + } + + private static void WaitForGC() + { + System.gc(); + System.runFinalization(); + try { + java.lang.Thread.sleep(1); + } catch (java.lang.InterruptedException e) { + } + } + + public static void main(String argv[]) throws Throwable + { + Klass k1 = li_std_auto_ptr.makeKlassAutoPtr("first"); + if (!k1.getLabel().equals("first")) + throw new RuntimeException("wrong object label"); + + Klass k2 = li_std_auto_ptr.makeKlassAutoPtr("second"); + if (Klass.getTotal_count() != 2) + throw new RuntimeException("number of objects should be 2"); + + k1 = null; + WaitForGC(); + + if (Klass.getTotal_count() != 1) + throw new RuntimeException("number of objects should be 1"); + + if (!k2.getLabel().equals("second")) + throw new RuntimeException("wrong object label"); + + k2 = null; + WaitForGC(); + + if (Klass.getTotal_count() != 0) + throw new RuntimeException("no objects should be left"); + } +} diff --git a/Examples/test-suite/li_std_auto_ptr.i b/Examples/test-suite/li_std_auto_ptr.i new file mode 100644 index 000000000..b58a1d79d --- /dev/null +++ b/Examples/test-suite/li_std_auto_ptr.i @@ -0,0 +1,56 @@ +%module li_std_auto_ptr + +#if defined(SWIGCSHARP) || defined(SWIGJAVA) || defined(SWIGPYTHON) + +%include "std_auto_ptr.i" + +%auto_ptr(Klass) + +%inline %{ + +#include +#include +#include "swig_examples_lock.h" + +class Klass { +public: + explicit Klass(const char* label) : + m_label(label) + { + SwigExamples::Lock lock(critical_section); + total_count++; + } + + const char* getLabel() const { return m_label.c_str(); } + + ~Klass() + { + SwigExamples::Lock lock(critical_section); + total_count--; + } + + static int getTotal_count() { return total_count; } + +private: + static SwigExamples::CriticalSection critical_section; + static int total_count; + + std::string m_label; +}; + +SwigExamples::CriticalSection Klass::critical_section; +int Klass::total_count = 0; + +%} + +%template(KlassAutoPtr) std::auto_ptr; + +%inline %{ + +std::auto_ptr makeKlassAutoPtr(const char* label) { + return std::auto_ptr(new Klass(label)); +} + +%} + +#endif diff --git a/Examples/test-suite/python/li_std_auto_ptr_runme.py b/Examples/test-suite/python/li_std_auto_ptr_runme.py new file mode 100644 index 000000000..a29771479 --- /dev/null +++ b/Examples/test-suite/python/li_std_auto_ptr_runme.py @@ -0,0 +1,17 @@ +from li_std_auto_ptr import * + +k1 = makeKlassAutoPtr("first") +k2 = makeKlassAutoPtr("second") +if Klass.getTotal_count() != 2: + raise "number of objects should be 2" + +del k1 +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: + raise "no objects should be left" diff --git a/Lib/csharp/std_auto_ptr.i b/Lib/csharp/std_auto_ptr.i new file mode 100644 index 000000000..d7e5f167e --- /dev/null +++ b/Lib/csharp/std_auto_ptr.i @@ -0,0 +1,25 @@ +/* + The typemaps here allow to handle 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). + */ + +%define %auto_ptr(TYPE) +%typemap (ctype) std::auto_ptr "void *" +%typemap (imtype, out="System.IntPtr") std::auto_ptr "HandleRef" +%typemap (cstype) std::auto_ptr "$typemap(cstype, TYPE)" +%typemap (out) std::auto_ptr %{ + $result = (void *)$1.release(); +%} +%typemap(csout, excode=SWIGEXCODE) std::auto_ptr { + System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + return ret; + } +%template() std::auto_ptr; +%enddef + +namespace std { + template class auto_ptr {}; +} diff --git a/Lib/java/std_auto_ptr.i b/Lib/java/std_auto_ptr.i new file mode 100644 index 000000000..9b3cd7315 --- /dev/null +++ b/Lib/java/std_auto_ptr.i @@ -0,0 +1,27 @@ +/* + The typemaps here allow to handle 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). + */ + +%define %auto_ptr(TYPE) +%typemap (jni) std::auto_ptr "jlong" +%typemap (jtype) std::auto_ptr "long" +%typemap (jstype) std::auto_ptr "$typemap(jstype, TYPE)" + +%typemap (out) std::auto_ptr %{ + jlong lpp = 0; + *(TYPE**) &lpp = $1.release(); + $result = lpp; +%} +%typemap(javaout) std::auto_ptr { + long cPtr = $jnicall; + return (cPtr == 0) ? null : new $typemap(jstype, TYPE)(cPtr, true); + } +%template() std::auto_ptr; +%enddef + +namespace std { + template class auto_ptr {}; +} diff --git a/Lib/python/std_auto_ptr.i b/Lib/python/std_auto_ptr.i new file mode 100644 index 000000000..e310e00c8 --- /dev/null +++ b/Lib/python/std_auto_ptr.i @@ -0,0 +1,17 @@ +/* + The typemaps here allow to handle 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). + */ + +%define %auto_ptr(TYPE) +%typemap (out) std::auto_ptr %{ + %set_output(SWIG_NewPointerObj($1.release(), $descriptor(TYPE *), SWIG_POINTER_OWN | %newpointer_flags)); +%} +%template() std::auto_ptr; +%enddef + +namespace std { + template class auto_ptr {}; +} From 6624f66af5534b9284a62a7be2a3dca3952d95f6 Mon Sep 17 00:00:00 2001 From: Vadim Zeitlin Date: Tue, 3 Dec 2013 23:46:13 +0100 Subject: [PATCH 217/481] Just a correction to the last commit changelog entry. Mention the target languages affected. --- CHANGES.current | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGES.current b/CHANGES.current index f3d9130a4..a4d12239d 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -6,7 +6,7 @@ Version 3.0.0 (in progress) ============================ 2013-11-27: vadz - Add std_auto_ptr.i defining typemaps for returning std::auto_ptr<>. + [C#, Java, Python] Add std_auto_ptr.i defining typemaps for returning std::auto_ptr<>. 2013-11-09: wsfulton [C#] Apply patch #79 from Brant Kyser From b175df4e5f906741b5c0b44530b42f62b9699184 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 3 Dec 2013 23:24:17 +0000 Subject: [PATCH 218/481] C++11 alias templates seg fault fix Segfault fix when using alias templates, reported by Pierre-Henri Wuillemin --- Examples/test-suite/cpp11_template_typedefs.i | 9 +++++++++ Source/CParse/parser.y | 5 ++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/Examples/test-suite/cpp11_template_typedefs.i b/Examples/test-suite/cpp11_template_typedefs.i index ea46706a9..d6a1a3c85 100644 --- a/Examples/test-suite/cpp11_template_typedefs.i +++ b/Examples/test-suite/cpp11_template_typedefs.i @@ -2,6 +2,7 @@ %module cpp11_template_typedefs %warnfilter(SWIGWARN_CPP11_ALIAS_TEMPLATE) TypedefName; +%warnfilter(SWIGWARN_CPP11_ALIAS_TEMPLATE) MyIntKeyClass; %warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) PF; %inline %{ @@ -19,5 +20,13 @@ using TypedefName = SomeType; // type aliasing typedef void (*PFD)(double); // Old style using PF = void (*)(double); // New introduced syntax + + +// use of template aliasing +template +class MyCPP11Class { +}; +template using MyIntKeyClass = MyCPP11Class; +MyIntKeyClass intchar; %} diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index caac88e4d..1606dc249 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -3208,16 +3208,15 @@ c_declaration : c_decl { $$ = 0; /* TODO - ignored for now */ } - | TEMPLATE LESSTHAN template_parms GREATERTHAN USING idcolon EQUAL { + | TEMPLATE LESSTHAN template_parms GREATERTHAN USING idcolon EQUAL ID { skip_decl(); $$ = new_node("using"); + Setattr($$,"uname",$8); Setattr($$,"name",$6); add_symbols($$); SWIG_WARN_NODE_BEGIN($$); Swig_warning(WARN_CPP11_ALIAS_TEMPLATE, cparse_file, cparse_line, "The 'using' keyword in template aliasing is not fully supported yet.\n"); SWIG_WARN_NODE_END($$); - - $$ = 0; /* TODO - ignored for now */ } ; From 5504bd32017d9265abe43bacf9dbb7d1ecb4400a Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Wed, 4 Dec 2013 00:24:15 +0000 Subject: [PATCH 219/481] decltype fix on missing type info --- Source/CParse/parser.y | 1 + 1 file changed, 1 insertion(+) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 1606dc249..3384dcc5b 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -6033,6 +6033,7 @@ decltype : DECLTYPE LPAREN idcolon RPAREN { Node *n = Swig_symbol_clookup($3,0); if (!n) { Swig_error(cparse_file, cparse_line, "Identifier %s not defined.\n", $3); + $$ = $3; } else { $$ = Getattr(n, "type"); } From 053c605df047114557613339110367c3ee77ea4e Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Wed, 4 Dec 2013 16:21:33 +0400 Subject: [PATCH 220/481] out-of-scope template definitions fixed nested_private test disabled again --- Examples/test-suite/common.mk | 2 +- Source/CParse/parser.y | 16 +++++++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index e444f869d..a59fba18b 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -84,6 +84,7 @@ CPP_TEST_BROKEN += \ extend_variable \ li_std_vector_ptr \ li_boost_shared_ptr_template \ + nested_private \ overload_complicated \ template_default_pointer \ template_expr \ @@ -278,7 +279,6 @@ CPP_TEST_CASES += \ naturalvar_more \ nested_class \ nested_comment \ - nested_private \ nested_scope \ nested_workaround \ newobject1 \ diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 7a3fc1a29..cc0d3f4ca 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -3389,6 +3389,7 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { scope = resolve_create_node_scope($3); /* save nscope_inner to the class - it may be overwritten in nested classes*/ Setattr($$, "nested:innerscope", nscope_inner); + Setattr($$, "nested:nscope", nscope); Setfile(scope,cparse_file); Setline(scope,cparse_line); $3 = scope; @@ -3465,8 +3466,10 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { $$ = currentOuterClass; currentOuterClass = Getattr($$, "nested:outer"); nscope_inner = Getattr($$, "nested:innerscope"); + nscope = Getattr($$, "nested:nscope"); Delattr($$, "nested:innerscope"); - if (nscope_inner) /*actual parent class for this class*/ + Delattr($$, "nested:nscope"); + if (nscope_inner && Strcmp(nodeType(nscope_inner), "class") == 0) /* actual parent class for this class */ Setattr($$, "nested:outer", nscope_inner); if (!currentOuterClass) inclass = 0; @@ -3546,14 +3549,21 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { Swig_symbol_setscope(Getattr(nscope_inner,"symtab")); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); + yyrename = Copy(Getattr($$, "class_rename")); add_symbols($$); + Delattr($$, "class_rename"); /* but the variable definition in the current scope */ Swig_symbol_setscope(cscope); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); add_symbols($9); - nscope_inner = 0; - $$ = $9; + if (nscope) { + $$ = nscope; + if ($9) + appendSibling($$, $9); + } + else if (!SwigType_istemplate(ty) && template_parameters == 0) + $$ = $9; } else { Delete(yyrename); yyrename = 0; From b0afa8a95c5e1958a0f9427f8f86064bb2aa67ea Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Thu, 5 Dec 2013 20:41:22 +0400 Subject: [PATCH 221/481] nested private classes are discarded while parsing nested relate functions are moved to nested.cxx and renamed accordingly --- Source/CParse/parser.y | 94 ++++---- Source/Makefile.am | 1 + Source/Modules/main.cxx | 4 +- Source/Modules/nested.cxx | 431 ++++++++++++++++++++++++++++++++++++ Source/Modules/swigmod.h | 4 +- Source/Modules/typepass.cxx | 427 ----------------------------------- 6 files changed, 485 insertions(+), 476 deletions(-) create mode 100644 Source/Modules/nested.cxx diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index cc0d3f4ca..9dfa60099 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -3537,58 +3537,62 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { } if (currentOuterClass) restore_access_mode($$); - - Setattr($$,"symtab",Swig_symbol_popscope()); - - Classprefix = Getattr($$,"Classprefix"); - Delattr($$,"Classprefix"); - if (nscope_inner) { - /* this is tricky */ - /* we add the declaration in the original namespace */ - appendChild(nscope_inner,$$); - Swig_symbol_setscope(Getattr(nscope_inner,"symtab")); - Delete(Namespaceprefix); - Namespaceprefix = Swig_symbol_qualifiedscopename(0); - yyrename = Copy(Getattr($$, "class_rename")); - add_symbols($$); - Delattr($$, "class_rename"); - /* but the variable definition in the current scope */ - Swig_symbol_setscope(cscope); - Delete(Namespaceprefix); - Namespaceprefix = Swig_symbol_qualifiedscopename(0); - add_symbols($9); - if (nscope) { - $$ = nscope; - if ($9) - appendSibling($$, $9); - } - else if (!SwigType_istemplate(ty) && template_parameters == 0) - $$ = $9; + if (cplus_mode == CPLUS_PRIVATE) { + $$ = 0; /* skip private nested classes */ } else { - Delete(yyrename); - yyrename = 0; - Delete(Namespaceprefix); - Namespaceprefix = Swig_symbol_qualifiedscopename(0); - if (!cparse_cplusplus && currentOuterClass) { /* nested C structs go into global scope*/ - Node *outer = currentOuterClass; - while (Getattr(outer, "nested:outer")) - outer = Getattr(outer, "nested:outer"); - appendSibling(outer, $$); - add_symbols($9); - set_scope_to_global(); + Setattr($$,"symtab",Swig_symbol_popscope()); + + Classprefix = Getattr($$,"Classprefix"); + Delattr($$,"Classprefix"); + if (nscope_inner) { + /* this is tricky */ + /* we add the declaration in the original namespace */ + if (cplus_mode != CPLUS_PRIVATE) + appendChild(nscope_inner,$$); + Swig_symbol_setscope(Getattr(nscope_inner,"symtab")); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); yyrename = Copy(Getattr($$, "class_rename")); add_symbols($$); - if (!CPlusPlusOut) - Delattr($$, "nested:outer"); Delattr($$, "class_rename"); - $$ = 0; - } else { - yyrename = Copy(Getattr($$, "class_rename")); - add_symbols($$); + /* but the variable definition in the current scope */ + Swig_symbol_setscope(cscope); + Delete(Namespaceprefix); + Namespaceprefix = Swig_symbol_qualifiedscopename(0); add_symbols($9); - Delattr($$, "class_rename"); + if (nscope) { + $$ = nscope; + if ($9) + appendSibling($$, $9); + } + else if (!SwigType_istemplate(ty) && template_parameters == 0) + $$ = $9; + } else { + Delete(yyrename); + yyrename = 0; + Delete(Namespaceprefix); + Namespaceprefix = Swig_symbol_qualifiedscopename(0); + if (!cparse_cplusplus && currentOuterClass) { /* nested C structs go into global scope*/ + Node *outer = currentOuterClass; + while (Getattr(outer, "nested:outer")) + outer = Getattr(outer, "nested:outer"); + appendSibling(outer, $$); + add_symbols($9); + set_scope_to_global(); + Delete(Namespaceprefix); + Namespaceprefix = Swig_symbol_qualifiedscopename(0); + yyrename = Copy(Getattr($$, "class_rename")); + add_symbols($$); + if (!CPlusPlusOut) + Delattr($$, "nested:outer"); + Delattr($$, "class_rename"); + $$ = 0; + } else { + yyrename = Copy(Getattr($$, "class_rename")); + add_symbols($$); + add_symbols($9); + Delattr($$, "class_rename"); + } } } Swig_symbol_setscope(cscope); diff --git a/Source/Makefile.am b/Source/Makefile.am index 40fa4d9f2..8356081d6 100644 --- a/Source/Makefile.am +++ b/Source/Makefile.am @@ -54,6 +54,7 @@ eswig_SOURCES = CParse/cscanner.c \ Modules/modula3.cxx \ Modules/module.cxx \ Modules/mzscheme.cxx \ + Modules/nested.cxx \ Modules/ocaml.cxx \ Modules/octave.cxx \ Modules/overload.cxx \ diff --git a/Source/Modules/main.cxx b/Source/Modules/main.cxx index 290887c6e..62d9c0c36 100644 --- a/Source/Modules/main.cxx +++ b/Source/Modules/main.cxx @@ -1178,7 +1178,7 @@ int SWIG_main(int argc, char *argv[], Language *l) { if (!CPlusPlus) { if (Verbose) Printf(stdout, "Processing unnamed structs...\n"); - Swig_name_unnamed_c_structs(top); + Swig_nested_name_unnamed_c_structs(top); } if (Verbose) { @@ -1203,7 +1203,7 @@ int SWIG_main(int argc, char *argv[], Language *l) { if (CPlusPlus) { if (Verbose) Printf(stdout, "Processing nested classes...\n"); - Swig_process_nested_classes(top); + Swig_nested_process_classes(top); } if (dump_top & STAGE3) { diff --git a/Source/Modules/nested.cxx b/Source/Modules/nested.cxx new file mode 100644 index 000000000..4be27ebc4 --- /dev/null +++ b/Source/Modules/nested.cxx @@ -0,0 +1,431 @@ +#include "swigmod.h" +#include "cparse.h" + +// Nested classes processing section +static Hash *classhash = 0; + +static String *make_name(Node *n, String *name, SwigType *decl) { + int destructor = name && (*(Char(name)) == '~'); + if (String *yyrename = Getattr(n, "class_rename")) { + String *s = NewString(yyrename); + Delattr(n, "class_rename"); + if (destructor && (*(Char(s)) != '~')) { + Insert(s, 0, "~"); + } + return s; + } + + if (!name) + return 0; + return Swig_name_make(n, 0, name, decl, 0); +} + +// C version of add_symbols() +static void add_symbols_c(Node *n) { + String *decl; + String *wrn = 0; + String *symname = 0; + int iscdecl = Cmp(nodeType(n), "cdecl") == 0; + Setattr(n, "ismember", "1"); + Setattr(n, "access", "public"); + if (Getattr(n, "sym:name")) + return; + decl = Getattr(n, "decl"); + if (!SwigType_isfunction(decl)) { + String *name = Getattr(n, "name"); + String *makename = Getattr(n, "parser:makename"); + if (iscdecl) { + String *storage = Getattr(n, "storage"); + if (Cmp(storage, "typedef") == 0) { + Setattr(n, "kind", "typedef"); + } else { + SwigType *type = Getattr(n, "type"); + String *value = Getattr(n, "value"); + Setattr(n, "kind", "variable"); + if (value && Len(value)) { + Setattr(n, "hasvalue", "1"); + } + if (type) { + SwigType *ty; + SwigType *tmp = 0; + if (decl) { + ty = tmp = Copy(type); + SwigType_push(ty, decl); + } else { + ty = type; + } + if (!SwigType_ismutable(ty)) { + SetFlag(n, "hasconsttype"); + SetFlag(n, "feature:immutable"); + } + if (tmp) + Delete(tmp); + } + if (!type) { + Printf(stderr, "notype name %s\n", name); + } + } + } + Swig_features_get(Swig_cparse_features(), 0, name, 0, n); + if (makename) { + symname = make_name(n, makename, 0); + Delattr(n, "parser:makename"); /* temporary information, don't leave it hanging around */ + } else { + makename = name; + symname = make_name(n, makename, 0); + } + + if (!symname) { + symname = Copy(Getattr(n, "unnamed")); + } + if (symname) { + wrn = Swig_name_warning(n, 0, symname, 0); + } + } else { + String *name = Getattr(n, "name"); + SwigType *fdecl = Copy(decl); + SwigType *fun = SwigType_pop_function(fdecl); + if (iscdecl) { + Setattr(n, "kind", "function"); + } + + Swig_features_get(Swig_cparse_features(), 0, name, fun, n); + + symname = make_name(n, name, fun); + wrn = Swig_name_warning(n, 0, symname, fun); + + Delete(fdecl); + Delete(fun); + + } + if (!symname) + return; + if (GetFlag(n, "feature:ignore")) { + /* Only add to C symbol table and continue */ + Swig_symbol_add(0, n); + } else if (strncmp(Char(symname), "$ignore", 7) == 0) { + char *c = Char(symname) + 7; + SetFlag(n, "feature:ignore"); + if (strlen(c)) { + SWIG_WARN_NODE_BEGIN(n); + Swig_warning(0, Getfile(n), Getline(n), "%s\n", c + 1); + SWIG_WARN_NODE_END(n); + } + Swig_symbol_add(0, n); + } else { + Node *c; + if ((wrn) && (Len(wrn))) { + String *metaname = symname; + if (!Getmeta(metaname, "already_warned")) { + SWIG_WARN_NODE_BEGIN(n); + Swig_warning(0, Getfile(n), Getline(n), "%s\n", wrn); + SWIG_WARN_NODE_END(n); + Setmeta(metaname, "already_warned", "1"); + } + } + c = Swig_symbol_add(symname, n); + + if (c != n) { + /* symbol conflict attempting to add in the new symbol */ + if (Getattr(n, "sym:weak")) { + Setattr(n, "sym:name", symname); + } else { + String *e = NewStringEmpty(); + String *en = NewStringEmpty(); + String *ec = NewStringEmpty(); + int redefined = Swig_need_redefined_warn(n, c, true); + if (redefined) { + Printf(en, "Identifier '%s' redefined (ignored)", symname); + Printf(ec, "previous definition of '%s'", symname); + } else { + Printf(en, "Redundant redeclaration of '%s'", symname); + Printf(ec, "previous declaration of '%s'", symname); + } + if (Cmp(symname, Getattr(n, "name"))) { + Printf(en, " (Renamed from '%s')", SwigType_namestr(Getattr(n, "name"))); + } + Printf(en, ","); + if (Cmp(symname, Getattr(c, "name"))) { + Printf(ec, " (Renamed from '%s')", SwigType_namestr(Getattr(c, "name"))); + } + Printf(ec, "."); + SWIG_WARN_NODE_BEGIN(n); + if (redefined) { + Swig_warning(WARN_PARSE_REDEFINED, Getfile(n), Getline(n), "%s\n", en); + Swig_warning(WARN_PARSE_REDEFINED, Getfile(c), Getline(c), "%s\n", ec); + } else { + Swig_warning(WARN_PARSE_REDUNDANT, Getfile(n), Getline(n), "%s\n", en); + Swig_warning(WARN_PARSE_REDUNDANT, Getfile(c), Getline(c), "%s\n", ec); + } + SWIG_WARN_NODE_END(n); + Printf(e, "%s:%d:%s\n%s:%d:%s\n", Getfile(n), Getline(n), en, Getfile(c), Getline(c), ec); + Setattr(n, "error", e); + Delete(e); + Delete(en); + Delete(ec); + } + } + } + Delete(symname); +} + +/* Strips C-style and C++-style comments from string in-place. */ +static void strip_comments(char *string) { + int state = 0; + /* + * 0 - not in comment + * 1 - in c-style comment + * 2 - in c++-style comment + * 3 - in string + * 4 - after reading / not in comments + * 5 - after reading * in c-style comments + * 6 - after reading \ in strings + */ + char *c = string; + while (*c) { + switch (state) { + case 0: + if (*c == '\"') + state = 3; + else if (*c == '/') + state = 4; + break; + case 1: + if (*c == '*') + state = 5; + *c = ' '; + break; + case 2: + if (*c == '\n') + state = 0; + else + *c = ' '; + break; + case 3: + if (*c == '\"') + state = 0; + else if (*c == '\\') + state = 6; + break; + case 4: + if (*c == '/') { + *(c - 1) = ' '; + *c = ' '; + state = 2; + } else if (*c == '*') { + *(c - 1) = ' '; + *c = ' '; + state = 1; + } else + state = 0; + break; + case 5: + if (*c == '/') + state = 0; + else + state = 1; + *c = ' '; + break; + case 6: + state = 3; + break; + } + ++c; + } +} + +// Create a %insert with a typedef to make a new name visible to C +static Node *create_insert(Node *n, bool noTypedef = false) { + // format a typedef + String *ccode = Getattr(n, "code"); + Push(ccode, " "); + if (noTypedef) { + Push(ccode, Getattr(n, "name")); + Push(ccode, " "); + Push(ccode, Getattr(n, "kind")); + } else { + Push(ccode, Getattr(n, "kind")); + Push(ccode, "typedef "); + Append(ccode, " "); + Append(ccode, Getattr(n, "tdname")); + } + Append(ccode, ";"); + + /* Strip comments - further code may break in presence of comments. */ + strip_comments(Char(ccode)); + + /* Make all SWIG created typedef structs/unions/classes unnamed else + redefinition errors occur - nasty hack alert. */ + if (!noTypedef) { + const char *types_array[3] = { "struct", "union", "class" }; + for (int i = 0; i < 3; i++) { + char *code_ptr = Char(ccode); + while (code_ptr) { + /* Replace struct name (as in 'struct name {...}' ) with whitespace + name will be between struct and opening brace */ + + code_ptr = strstr(code_ptr, types_array[i]); + if (code_ptr) { + char *open_bracket_pos; + code_ptr += strlen(types_array[i]); + open_bracket_pos = strchr(code_ptr, '{'); + if (open_bracket_pos) { + /* Make sure we don't have something like struct A a; */ + char *semi_colon_pos = strchr(code_ptr, ';'); + if (!(semi_colon_pos && (semi_colon_pos < open_bracket_pos))) + while (code_ptr < open_bracket_pos) + *code_ptr++ = ' '; + } + } + } + } + } + { + /* Remove SWIG directive %constant which may be left in the SWIG created typedefs */ + char *code_ptr = Char(ccode); + while (code_ptr) { + code_ptr = strstr(code_ptr, "%constant"); + if (code_ptr) { + char *directive_end_pos = strchr(code_ptr, ';'); + if (directive_end_pos) { + while (code_ptr <= directive_end_pos) + *code_ptr++ = ' '; + } + } + } + } + Node *newnode = NewHash(); + set_nodeType(newnode, "insert"); + Setfile(newnode, Getfile(n)); + Setline(newnode, Getline(n)); + String *code = NewStringEmpty(); + Wrapper_pretty_print(ccode, code); + Setattr(newnode, "code", code); + Delete(code); + Delattr(n, "code"); + return newnode; +} + +static void insertNodeAfter(Node *n, Node *c) { + Node *g = parentNode(n); + set_parentNode(c, g); + Node *ns = nextSibling(n); + if (Node *outer = Getattr(c, "nested:outer")) { + while (ns && outer == Getattr(ns, "nested:outer")) { + n = ns; + ns = nextSibling(n); + } + } + if (!ns) { + set_lastChild(g, c); + } else { + set_nextSibling(c, ns); + set_previousSibling(ns, c); + } + set_nextSibling(n, c); + set_previousSibling(c, n); +} + +void Swig_nested_name_unnamed_c_structs(Node *n) { + if (!classhash) + classhash = Getattr(n, "classes"); + Node *c = firstChild(n); + while (c) { + Node *next = nextSibling(c); + if (String *declName = Getattr(c, "nested:unnamed")) { + if (Node *outer = Getattr(c, "nested:outer")) { + // generate a name + String *name = NewStringf("%s_%s", Getattr(outer, "name"), declName); + Delattr(c, "nested:unnamed"); + // set the name to the class and symbol table + Setattr(c, "tdname", name); + Setattr(c, "name", name); + Swig_symbol_setscope(Getattr(c, "symtab")); + Swig_symbol_setscopename(name); + // now that we have a name - gather base symbols + if (List *publicBases = Getattr(c, "baselist")) { + List *bases = Swig_make_inherit_list(name, publicBases, 0); + Swig_inherit_base_symbols(bases); + Delete(bases); + } + Setattr(classhash, name, c); + Swig_symbol_popscope(); + // process declarations following this type (assign correct new type) + SwigType *ty = Copy(name); + Node *decl = nextSibling(c); + List *declList = NewList(); + while (decl && Getattr(decl, "nested:unnamedtype") == c) { + Setattr(decl, "type", ty); + Append(declList, decl); + Delattr(decl, "nested:unnamedtype"); + SetFlag(decl, "feature:immutable"); + add_symbols_c(decl); + decl = nextSibling(decl); + } + Delete(ty); + // Check for extensions +/* // TODO: we can save extensions hash like class hash and move check_extensions() after nesting processing + if (extendhash) { + if (Node *am = Getattr(extendhash, name)) { + // Merge the extension into the symbol table + merge_extensions(c, am); + append_previous_extension(c, am); + Delattr(extendhash, clsname); + } + }*/ + Swig_symbol_setscope(Swig_symbol_global_scope()); + add_symbols_c(c); + + Node *ins = create_insert(c); + insertNodeAfter(c, ins); + removeNode(c); + insertNodeAfter(n, c); + Delete(ins); + Delattr(c, "nested:outer"); + } else { + // global unnamed struct - ignore it + c = next; + continue; + } + } else if (CPlusPlusOut) { + if (Getattr(c, "nested:outer")) { + Node *ins = create_insert(c, true); + insertNodeAfter(c, ins); + Delete(ins); + Delattr(c, "nested:outer"); + } + } + // process children + Swig_nested_name_unnamed_c_structs(c); + c = next; + } +} + +static void remove_outer_class_reference(Node *n) { + for (Node *c = firstChild(n); c; c = nextSibling(c)) { + if (GetFlag(c, "feature:flatnested")) { + Delattr(c, "nested:outer"); + remove_outer_class_reference(c); + } + } +} + +void Swig_nested_process_classes(Node *n) { + Node *c = firstChild(n); + while (c) { + Node *next = nextSibling(c); + if (!Getattr(c, "templatetype")) { + if (GetFlag(c, "nested") && GetFlag(c, "feature:flatnested")) { + removeNode(c); + if (!checkAttribute(c, "access", "public")) + SetFlag(c, "feature:ignore"); + else + insertNodeAfter(n, c); + } + Swig_nested_process_classes(c); + } + c = next; + } + remove_outer_class_reference(n); +} + diff --git a/Source/Modules/swigmod.h b/Source/Modules/swigmod.h index 61e5f8c13..41ef44e41 100644 --- a/Source/Modules/swigmod.h +++ b/Source/Modules/swigmod.h @@ -421,7 +421,7 @@ int Swig_contract_mode_get(); void Swig_browser(Node *n, int); void Swig_default_allocators(Node *n); void Swig_process_types(Node *n); -void Swig_process_nested_classes(Node *n); -void Swig_name_unnamed_c_structs(Node *n); +void Swig_nested_process_classes(Node *n); +void Swig_nested_name_unnamed_c_structs(Node *n); #endif diff --git a/Source/Modules/typepass.cxx b/Source/Modules/typepass.cxx index 6954e0dd2..3f8e33dae 100644 --- a/Source/Modules/typepass.cxx +++ b/Source/Modules/typepass.cxx @@ -1283,430 +1283,3 @@ void Swig_process_types(Node *n) { TypePass::pass(n); } -// Nested classes processing section -static Hash *classhash = 0; - -static String *make_name(Node *n, String *name, SwigType *decl) { - int destructor = name && (*(Char(name)) == '~'); - if (String *yyrename = Getattr(n, "class_rename")) { - String *s = NewString(yyrename); - Delattr(n, "class_rename"); - if (destructor && (*(Char(s)) != '~')) { - Insert(s, 0, "~"); - } - return s; - } - - if (!name) - return 0; - return Swig_name_make(n, 0, name, decl, 0); -} - -// C version of add_symbols() -static void add_symbols_c(Node *n) { - String *decl; - String *wrn = 0; - String *symname = 0; - int iscdecl = Cmp(nodeType(n), "cdecl") == 0; - Setattr(n, "ismember", "1"); - Setattr(n, "access", "public"); - if (Getattr(n, "sym:name")) - return; - decl = Getattr(n, "decl"); - if (!SwigType_isfunction(decl)) { - String *name = Getattr(n, "name"); - String *makename = Getattr(n, "parser:makename"); - if (iscdecl) { - String *storage = Getattr(n, "storage"); - if (Cmp(storage, "typedef") == 0) { - Setattr(n, "kind", "typedef"); - } else { - SwigType *type = Getattr(n, "type"); - String *value = Getattr(n, "value"); - Setattr(n, "kind", "variable"); - if (value && Len(value)) { - Setattr(n, "hasvalue", "1"); - } - if (type) { - SwigType *ty; - SwigType *tmp = 0; - if (decl) { - ty = tmp = Copy(type); - SwigType_push(ty, decl); - } else { - ty = type; - } - if (!SwigType_ismutable(ty)) { - SetFlag(n, "hasconsttype"); - SetFlag(n, "feature:immutable"); - } - if (tmp) - Delete(tmp); - } - if (!type) { - Printf(stderr, "notype name %s\n", name); - } - } - } - Swig_features_get(Swig_cparse_features(), 0, name, 0, n); - if (makename) { - symname = make_name(n, makename, 0); - Delattr(n, "parser:makename"); /* temporary information, don't leave it hanging around */ - } else { - makename = name; - symname = make_name(n, makename, 0); - } - - if (!symname) { - symname = Copy(Getattr(n, "unnamed")); - } - if (symname) { - wrn = Swig_name_warning(n, 0, symname, 0); - } - } else { - String *name = Getattr(n, "name"); - SwigType *fdecl = Copy(decl); - SwigType *fun = SwigType_pop_function(fdecl); - if (iscdecl) { - Setattr(n, "kind", "function"); - } - - Swig_features_get(Swig_cparse_features(), 0, name, fun, n); - - symname = make_name(n, name, fun); - wrn = Swig_name_warning(n, 0, symname, fun); - - Delete(fdecl); - Delete(fun); - - } - if (!symname) - return; - if (GetFlag(n, "feature:ignore")) { - /* Only add to C symbol table and continue */ - Swig_symbol_add(0, n); - } else if (strncmp(Char(symname), "$ignore", 7) == 0) { - char *c = Char(symname) + 7; - SetFlag(n, "feature:ignore"); - if (strlen(c)) { - SWIG_WARN_NODE_BEGIN(n); - Swig_warning(0, Getfile(n), Getline(n), "%s\n", c + 1); - SWIG_WARN_NODE_END(n); - } - Swig_symbol_add(0, n); - } else { - Node *c; - if ((wrn) && (Len(wrn))) { - String *metaname = symname; - if (!Getmeta(metaname, "already_warned")) { - SWIG_WARN_NODE_BEGIN(n); - Swig_warning(0, Getfile(n), Getline(n), "%s\n", wrn); - SWIG_WARN_NODE_END(n); - Setmeta(metaname, "already_warned", "1"); - } - } - c = Swig_symbol_add(symname, n); - - if (c != n) { - /* symbol conflict attempting to add in the new symbol */ - if (Getattr(n, "sym:weak")) { - Setattr(n, "sym:name", symname); - } else { - String *e = NewStringEmpty(); - String *en = NewStringEmpty(); - String *ec = NewStringEmpty(); - int redefined = Swig_need_redefined_warn(n, c, true); - if (redefined) { - Printf(en, "Identifier '%s' redefined (ignored)", symname); - Printf(ec, "previous definition of '%s'", symname); - } else { - Printf(en, "Redundant redeclaration of '%s'", symname); - Printf(ec, "previous declaration of '%s'", symname); - } - if (Cmp(symname, Getattr(n, "name"))) { - Printf(en, " (Renamed from '%s')", SwigType_namestr(Getattr(n, "name"))); - } - Printf(en, ","); - if (Cmp(symname, Getattr(c, "name"))) { - Printf(ec, " (Renamed from '%s')", SwigType_namestr(Getattr(c, "name"))); - } - Printf(ec, "."); - SWIG_WARN_NODE_BEGIN(n); - if (redefined) { - Swig_warning(WARN_PARSE_REDEFINED, Getfile(n), Getline(n), "%s\n", en); - Swig_warning(WARN_PARSE_REDEFINED, Getfile(c), Getline(c), "%s\n", ec); - } else { - Swig_warning(WARN_PARSE_REDUNDANT, Getfile(n), Getline(n), "%s\n", en); - Swig_warning(WARN_PARSE_REDUNDANT, Getfile(c), Getline(c), "%s\n", ec); - } - SWIG_WARN_NODE_END(n); - Printf(e, "%s:%d:%s\n%s:%d:%s\n", Getfile(n), Getline(n), en, Getfile(c), Getline(c), ec); - Setattr(n, "error", e); - Delete(e); - Delete(en); - Delete(ec); - } - } - } - Delete(symname); -} - -/* Strips C-style and C++-style comments from string in-place. */ -static void strip_comments(char *string) { - int state = 0; - /* - * 0 - not in comment - * 1 - in c-style comment - * 2 - in c++-style comment - * 3 - in string - * 4 - after reading / not in comments - * 5 - after reading * in c-style comments - * 6 - after reading \ in strings - */ - char *c = string; - while (*c) { - switch (state) { - case 0: - if (*c == '\"') - state = 3; - else if (*c == '/') - state = 4; - break; - case 1: - if (*c == '*') - state = 5; - *c = ' '; - break; - case 2: - if (*c == '\n') - state = 0; - else - *c = ' '; - break; - case 3: - if (*c == '\"') - state = 0; - else if (*c == '\\') - state = 6; - break; - case 4: - if (*c == '/') { - *(c - 1) = ' '; - *c = ' '; - state = 2; - } else if (*c == '*') { - *(c - 1) = ' '; - *c = ' '; - state = 1; - } else - state = 0; - break; - case 5: - if (*c == '/') - state = 0; - else - state = 1; - *c = ' '; - break; - case 6: - state = 3; - break; - } - ++c; - } -} - -// Create a %insert with a typedef to make a new name visible to C -static Node *create_insert(Node *n, bool noTypedef = false) { - // format a typedef - String *ccode = Getattr(n, "code"); - Push(ccode, " "); - if (noTypedef) { - Push(ccode, Getattr(n, "name")); - Push(ccode, " "); - Push(ccode, Getattr(n, "kind")); - } else { - Push(ccode, Getattr(n, "kind")); - Push(ccode, "typedef "); - Append(ccode, " "); - Append(ccode, Getattr(n, "tdname")); - } - Append(ccode, ";"); - - /* Strip comments - further code may break in presence of comments. */ - strip_comments(Char(ccode)); - - /* Make all SWIG created typedef structs/unions/classes unnamed else - redefinition errors occur - nasty hack alert. */ - if (!noTypedef) { - const char *types_array[3] = { "struct", "union", "class" }; - for (int i = 0; i < 3; i++) { - char *code_ptr = Char(ccode); - while (code_ptr) { - /* Replace struct name (as in 'struct name {...}' ) with whitespace - name will be between struct and opening brace */ - - code_ptr = strstr(code_ptr, types_array[i]); - if (code_ptr) { - char *open_bracket_pos; - code_ptr += strlen(types_array[i]); - open_bracket_pos = strchr(code_ptr, '{'); - if (open_bracket_pos) { - /* Make sure we don't have something like struct A a; */ - char *semi_colon_pos = strchr(code_ptr, ';'); - if (!(semi_colon_pos && (semi_colon_pos < open_bracket_pos))) - while (code_ptr < open_bracket_pos) - *code_ptr++ = ' '; - } - } - } - } - } - { - /* Remove SWIG directive %constant which may be left in the SWIG created typedefs */ - char *code_ptr = Char(ccode); - while (code_ptr) { - code_ptr = strstr(code_ptr, "%constant"); - if (code_ptr) { - char *directive_end_pos = strchr(code_ptr, ';'); - if (directive_end_pos) { - while (code_ptr <= directive_end_pos) - *code_ptr++ = ' '; - } - } - } - } - Node *newnode = NewHash(); - set_nodeType(newnode, "insert"); - Setfile(newnode, Getfile(n)); - Setline(newnode, Getline(n)); - String *code = NewStringEmpty(); - Wrapper_pretty_print(ccode, code); - Setattr(newnode, "code", code); - Delete(code); - Delattr(n, "code"); - return newnode; -} - -static void insertNodeAfter(Node *n, Node *c) { - Node *g = parentNode(n); - set_parentNode(c, g); - Node *ns = nextSibling(n); - if (Node *outer = Getattr(c, "nested:outer")) { - while (ns && outer == Getattr(ns, "nested:outer")) { - n = ns; - ns = nextSibling(n); - } - } - if (!ns) { - set_lastChild(g, c); - } else { - set_nextSibling(c, ns); - set_previousSibling(ns, c); - } - set_nextSibling(n, c); - set_previousSibling(c, n); -} - -void Swig_name_unnamed_c_structs(Node *n) { - if (!classhash) - classhash = Getattr(n, "classes"); - Node *c = firstChild(n); - while (c) { - Node *next = nextSibling(c); - if (String *declName = Getattr(c, "nested:unnamed")) { - if (Node *outer = Getattr(c, "nested:outer")) { - // generate a name - String *name = NewStringf("%s_%s", Getattr(outer, "name"), declName); - Delattr(c, "nested:unnamed"); - // set the name to the class and symbol table - Setattr(c, "tdname", name); - Setattr(c, "name", name); - Swig_symbol_setscope(Getattr(c, "symtab")); - Swig_symbol_setscopename(name); - // now that we have a name - gather base symbols - if (List *publicBases = Getattr(c, "baselist")) { - List *bases = Swig_make_inherit_list(name, publicBases, 0); - Swig_inherit_base_symbols(bases); - Delete(bases); - } - Setattr(classhash, name, c); - Swig_symbol_popscope(); - // process declarations following this type (assign correct new type) - SwigType *ty = Copy(name); - Node *decl = nextSibling(c); - List *declList = NewList(); - while (decl && Getattr(decl, "nested:unnamedtype") == c) { - Setattr(decl, "type", ty); - Append(declList, decl); - Delattr(decl, "nested:unnamedtype"); - SetFlag(decl, "feature:immutable"); - add_symbols_c(decl); - decl = nextSibling(decl); - } - Delete(ty); - // Check for extensions -/* // TODO: we can save extensions hash like class hash and move check_extensions() after nesting processing - if (extendhash) { - if (Node *am = Getattr(extendhash, name)) { - // Merge the extension into the symbol table - merge_extensions(c, am); - append_previous_extension(c, am); - Delattr(extendhash, clsname); - } - }*/ - Swig_symbol_setscope(Swig_symbol_global_scope()); - add_symbols_c(c); - - Node *ins = create_insert(c); - insertNodeAfter(c, ins); - removeNode(c); - insertNodeAfter(n, c); - Delete(ins); - Delattr(c, "nested:outer"); - } else { - // global unnamed struct - ignore it - c = next; - continue; - } - } else if (CPlusPlusOut) { - if (Getattr(c, "nested:outer")) { - Node *ins = create_insert(c, true); - insertNodeAfter(c, ins); - Delete(ins); - Delattr(c, "nested:outer"); - } - } - // process children - Swig_name_unnamed_c_structs(c); - c = next; - } -} - -static void remove_outer_class_reference(Node *n) { - for (Node *c = firstChild(n); c; c = nextSibling(c)) { - if (GetFlag(c, "feature:flatnested")) { - Delattr(c, "nested:outer"); - remove_outer_class_reference(c); - } - } -} - -void Swig_process_nested_classes(Node *n) { - Node *c = firstChild(n); - while (c) { - Node *next = nextSibling(c); - if (!Getattr(c, "templatetype")) { - if (GetFlag(c, "nested") && GetFlag(c, "feature:flatnested")) { - removeNode(c); - if (!checkAttribute(c, "access", "public")) - SetFlag(c, "feature:ignore"); - else - insertNodeAfter(n, c); - } - Swig_process_nested_classes(c); - } - c = next; - } - remove_outer_class_reference(n); -} From 7103a0684961a5b19e6ef5502823332b8936a0c2 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 5 Dec 2013 20:57:30 +0000 Subject: [PATCH 222/481] Swig_offset_string moved to misc.c --- Source/Modules/csharp.cxx | 4 +--- Source/Modules/java.cxx | 4 +--- Source/Modules/lang.cxx | 41 -------------------------------- Source/Swig/misc.c | 49 +++++++++++++++++++++++++++++++++++++++ Source/Swig/swig.h | 1 + 5 files changed, 52 insertions(+), 47 deletions(-) diff --git a/Source/Modules/csharp.cxx b/Source/Modules/csharp.cxx index 88dbfbad7..9197b4b17 100644 --- a/Source/Modules/csharp.cxx +++ b/Source/Modules/csharp.cxx @@ -18,8 +18,6 @@ /* Hash type used for upcalls from C/C++ */ typedef DOH UpcallData; -// insert N tabs before each new line in s -void Swig_offset_string(String *s, int N); class CSHARP:public Language { static const char *usage; @@ -2004,7 +2002,7 @@ public: } else { for (int i = 0; i < nesting_depth; ++i) Append(old_proxy_class_code, " "); - Append(old_proxy_class_code, "}\n"); + Append(old_proxy_class_code, "}\n\n"); --nesting_depth; } diff --git a/Source/Modules/java.cxx b/Source/Modules/java.cxx index f781f0c39..fdc678dbf 100644 --- a/Source/Modules/java.cxx +++ b/Source/Modules/java.cxx @@ -18,8 +18,6 @@ /* Hash type used for upcalls from C/C++ */ typedef DOH UpcallData; -// insert N tabs before each new line in s -void Swig_offset_string(String *s, int N); class JAVA:public Language { static const char *usage; @@ -2068,7 +2066,7 @@ public: } else { for (int i = 0; i < nesting_depth; ++i) Append(old_proxy_class_code, " "); - Append(old_proxy_class_code, "}\n"); + Append(old_proxy_class_code, "}\n\n"); --nesting_depth; } diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 5c701bc85..78c37dbb9 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -3632,44 +3632,3 @@ Hash *Language::getClassHash() const { return classhash; } -// insert N tabs before each new line in s -void Swig_offset_string(String *s, int N) -{ - // count a number of lines in s - int lines = 1; - int L = Len(s); - char *start = strchr(Char(s), '\n'); - while (start) { - ++lines; - start = strchr(start + 1, '\n'); - } - // do not count pending new line - if ((Char(s))[L-1] == '\n') - --lines; - // allocate a temporary storage for a padded string - char *res = (char*)malloc(L + lines * N * 2 + 1); - res[L + lines * N * 2] = 0; - - // copy lines to res, prepending tabs to each line - char *p = res; // output pointer - start = Char(s); // start of a current line - char *end = strchr(start, '\n'); // end of a current line - while (end) { - memset(p, ' ', N*2); - p += N*2; - memcpy(p, start, end - start + 1); - p += end - start + 1; - start = end + 1; - end = strchr(start, '\n'); - } - // process the last line - if (*start) { - memset(p, ' ', N*2); - p += N*2; - strcpy(p, start); - } - // replace 's' contents with 'res' - Clear(s); - Append(s, res); - free(res); -} diff --git a/Source/Swig/misc.c b/Source/Swig/misc.c index 769882bf8..7d8180d1c 100644 --- a/Source/Swig/misc.c +++ b/Source/Swig/misc.c @@ -1147,6 +1147,55 @@ String *Swig_string_strip(String *s) { return ns; } +/* ----------------------------------------------------------------------------- + * Swig_offset_string() + * + * Insert number tabs before each new line in s + * ----------------------------------------------------------------------------- */ + +void Swig_offset_string(String *s, int number) { + char *res; + char *p; + char *end; + /* count a number of lines in s */ + int lines = 1; + int len = Len(s); + char *start = strchr(Char(s), '\n'); + while (start) { + ++lines; + start = strchr(start + 1, '\n'); + } + /* do not count pending new line */ + if ((Char(s))[len-1] == '\n') + --lines; + /* allocate a temporary storage for a padded string */ + res = (char*)malloc(len + lines * number * 2 + 1); + res[len + lines * number * 2] = 0; + + /* copy lines to res, prepending tabs to each line */ + p = res; /* output pointer */ + start = Char(s); /* start of a current line */ + end = strchr(start, '\n'); /* end of a current line */ + while (end) { + memset(p, ' ', number*2); + p += number*2; + memcpy(p, start, end - start + 1); + p += end - start + 1; + start = end + 1; + end = strchr(start, '\n'); + } + /* process the last line */ + if (*start) { + memset(p, ' ', number*2); + p += number*2; + strcpy(p, start); + } + /* replace 's' contents with 'res' */ + Clear(s); + Append(s, res); + free(res); +} + #ifdef HAVE_PCRE #include diff --git a/Source/Swig/swig.h b/Source/Swig/swig.h index 95e3784d9..28a3ba730 100644 --- a/Source/Swig/swig.h +++ b/Source/Swig/swig.h @@ -332,6 +332,7 @@ extern int ParmList_is_compactdefargs(ParmList *p); extern String *Swig_string_lower(String *s); extern String *Swig_string_upper(String *s); extern String *Swig_string_title(String *s); + extern void Swig_offset_string(String *s, int number); extern String *Swig_pcre_version(void); extern void Swig_init(void); extern int Swig_value_wrapper_mode(int mode); From 6d97335d946a8042e84357d80ddbb67b8118696a Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 5 Dec 2013 21:21:07 +0000 Subject: [PATCH 223/481] Minor tweaks in Swig_feature_set --- Source/Modules/main.cxx | 4 +--- Source/Swig/naming.c | 2 +- Source/Swig/swig.h | 2 +- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/Source/Modules/main.cxx b/Source/Modules/main.cxx index 62d9c0c36..aa7e83ef8 100644 --- a/Source/Modules/main.cxx +++ b/Source/Modules/main.cxx @@ -863,9 +863,7 @@ void SWIG_getoptions(int argc, char *argv[]) { } static void flatten_nested() { - String *val = NewString("1"); - Swig_feature_set(Swig_cparse_features(), "", 0, "feature:flatnested", val, 0); - Delete(val); + Swig_feature_set(Swig_cparse_features(), "", 0, "feature:flatnested", "1", 0); } diff --git a/Source/Swig/naming.c b/Source/Swig/naming.c index 2921b3c84..9e2b4a436 100644 --- a/Source/Swig/naming.c +++ b/Source/Swig/naming.c @@ -774,7 +774,7 @@ void Swig_features_get(Hash *features, String *prefix, String *name, SwigType *d * concatenating the feature name plus ':' plus the attribute name. * ----------------------------------------------------------------------------- */ -void Swig_feature_set(Hash *features, const_String_or_char_ptr name, SwigType *decl, const_String_or_char_ptr featurename, String *value, Hash *featureattribs) { +void Swig_feature_set(Hash *features, const_String_or_char_ptr name, SwigType *decl, const_String_or_char_ptr featurename, const_String_or_char_ptr value, Hash *featureattribs) { Hash *n; Hash *fhash; diff --git a/Source/Swig/swig.h b/Source/Swig/swig.h index 28a3ba730..95d9189b3 100644 --- a/Source/Swig/swig.h +++ b/Source/Swig/swig.h @@ -304,7 +304,7 @@ extern int ParmList_is_compactdefargs(ParmList *p); extern DOH *Swig_name_object_get(Hash *namehash, String *prefix, String *name, SwigType *decl); extern void Swig_name_object_inherit(Hash *namehash, String *base, String *derived); extern void Swig_features_get(Hash *features, String *prefix, String *name, SwigType *decl, Node *n); - extern void Swig_feature_set(Hash *features, const_String_or_char_ptr name, SwigType *decl, const_String_or_char_ptr featurename, String *value, Hash *featureattribs); + extern void Swig_feature_set(Hash *features, const_String_or_char_ptr name, SwigType *decl, const_String_or_char_ptr featurename, const_String_or_char_ptr value, Hash *featureattribs); /* --- Misc --- */ extern char *Swig_copy_string(const char *c); From 67848e377adbc62cca118d382a587074edac21d6 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 7 Dec 2013 16:04:52 +0000 Subject: [PATCH 224/481] Fix template partial specialization detection Fixes template definitions that should be ignored and warnings introduced after nested changes: ../../../Examples/test-suite/refcount.i:63: Warning 318: Instantiation of template 'RCPtr< A >' is ambiguous, ../../../Examples/test-suite/refcount.h:159: Warning 318: instantiation 'RCPtr< T >::RCPtr' used, ../../../Examples/test-suite/refcount.h:159: Warning 318: instantiation 'RCPtr< T >::RCPtr' ignored. ../../../Examples/test-suite/refcount.h:159: Warning 318: instantiation 'RCPtr< T >::RCPtr' ignored. ../../../Examples/test-suite/refcount.h:159: Warning 318: instantiation 'RCPtr< T >::RCPtr' ignored. Different/clearer implementation of constructor detection since Classprefix is not behaving the same since nested changes were introduced. Only accept constructors if in extend mode or in a class. Also remove unused "isextension" attribute on the nodes. --- Source/CParse/parser.y | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 9dfa60099..4d978a97d 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -309,9 +309,6 @@ static void add_symbols(Node *n) { int isfriend = inclass && is_friend(n); int iscdecl = Cmp(nodeType(n),"cdecl") == 0; int only_csymbol = 0; - if (extendmode) { - Setattr(n,"isextension","1"); - } if (inclass) { String *name = Getattr(n, "name"); @@ -1594,6 +1591,7 @@ swig_directive : extend_directive { $$ = $1; } extend_directive : EXTEND options idcolon LBRACE { Node *cls; String *clsname; + extendmode = 1; cplus_mode = CPLUS_PUBLIC; if (!classes) classes = NewHash(); if (!classes_typedefs) classes_typedefs = NewHash(); @@ -1619,7 +1617,6 @@ extend_directive : EXTEND options idcolon LBRACE { Note that %extend before the class typedef never worked, only %extend after the class typdef. */ prev_symtab = Swig_symbol_setscope(Getattr(cls, "symtab")); current_class = cls; - extendmode = 1; SWIG_WARN_NODE_BEGIN(cls); Swig_warning(WARN_PARSE_EXTEND_NAME, cparse_file, cparse_line, "Deprecated %%extend name used - the %s name '%s' should be used instead of the typedef name '%s'.\n", Getattr(cls, "kind"), SwigType_namestr(Getattr(cls, "name")), $3); SWIG_WARN_NODE_END(cls); @@ -1628,7 +1625,6 @@ extend_directive : EXTEND options idcolon LBRACE { /* Previous class definition. Use its symbol table */ prev_symtab = Swig_symbol_setscope(Getattr(cls,"symtab")); current_class = cls; - extendmode = 1; } Classprefix = NewString($3); Namespaceprefix= Swig_symbol_qualifiedscopename(0); @@ -4288,7 +4284,7 @@ cpp_members : cpp_member cpp_members { cpp_member : c_declaration { $$ = $1; } | cpp_constructor_decl { $$ = $1; - if (extendmode) { + if (extendmode && current_class) { String *symname; symname= make_name($$,Getattr($$,"name"), Getattr($$,"decl")); if (Strcmp(symname,Getattr($$,"name")) == 0) { @@ -4329,7 +4325,7 @@ cpp_member : c_declaration { $$ = $1; } */ cpp_constructor_decl : storage_class type LPAREN parms RPAREN ctor_end { - if (Classprefix) { + if (inclass || extendmode) { SwigType *decl = NewStringEmpty(); $$ = new_node("constructor"); Setattr($$,"storage",$1); From 44323e14b3cb3541db5b89b43a54b443d0f4d8d1 Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Sun, 8 Dec 2013 01:46:38 +0400 Subject: [PATCH 225/481] Classprefix fixed after private nested classes some comments and spaces added --- Source/CParse/parser.y | 118 ++++++++++++++++++++--------------------- 1 file changed, 58 insertions(+), 60 deletions(-) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 9dfa60099..3900a0e09 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -3483,20 +3483,21 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { if (extendhash) { String *clsname = Swig_symbol_qualifiedscopename(0); - am = Getattr(extendhash,clsname); + am = Getattr(extendhash, clsname); if (am) { - merge_extensions($$,am); - Delattr(extendhash,clsname); + merge_extensions($$, am); + Delattr(extendhash, clsname); } Delete(clsname); } if (!classes) classes = NewHash(); scpname = Swig_symbol_qualifiedscopename(0); - Setattr(classes,scpname,$$); + Setattr(classes, scpname, $$); - appendChild($$,$7); + appendChild($$, $7); - if (am) append_previous_extension($$,am); + if (am) + append_previous_extension($$, am); p = $9; if (p && !nscope_inner) { @@ -3511,14 +3512,14 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { } else if (cparse_cplusplus && !cparse_externc) { ty = NewString($3); } else { - ty = NewStringf("%s %s", $2,$3); + ty = NewStringf("%s %s", $2, $3); } while (p) { - Setattr(p,"storage",$1); - Setattr(p,"type",ty); + Setattr(p, "storage", $1); + Setattr(p, "type" ,ty); if (!cparse_cplusplus && currentOuterClass && (!Getattr(currentOuterClass, "name") || CPlusPlusOut)) { - SetFlag(p,"hasconsttype"); - SetFlag(p,"feature:immutable"); + SetFlag(p, "hasconsttype"); + SetFlag(p, "feature:immutable"); } p = nextSibling(p); } @@ -3530,71 +3531,68 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { /* we 'open' the class at the end, to allow %template to add new members */ Node *pa = new_node("access"); - Setattr(pa,"kind","public"); + Setattr(pa, "kind", "public"); cplus_mode = CPLUS_PUBLIC; - appendChild($$,pa); + appendChild($$, pa); Delete(pa); } if (currentOuterClass) restore_access_mode($$); + Setattr($$, "symtab", Swig_symbol_popscope()); + Classprefix = Getattr($$, "Classprefix"); + Delattr($$, "Classprefix"); if (cplus_mode == CPLUS_PRIVATE) { $$ = 0; /* skip private nested classes */ + } else if (nscope_inner) { + /* this is tricky */ + /* we add the declaration in the original namespace */ + appendChild(nscope_inner, $$); + Swig_symbol_setscope(Getattr(nscope_inner, "symtab")); + Delete(Namespaceprefix); + Namespaceprefix = Swig_symbol_qualifiedscopename(0); + yyrename = Copy(Getattr($$, "class_rename")); + add_symbols($$); + Delattr($$, "class_rename"); + /* but the variable definition in the current scope */ + Swig_symbol_setscope(cscope); + Delete(Namespaceprefix); + Namespaceprefix = Swig_symbol_qualifiedscopename(0); + add_symbols($9); + if (nscope) { + $$ = nscope; /* here we return recreated namespace tower instead of the class itself */ + if ($9) + appendSibling($$, $9); + } + else if (!SwigType_istemplate(ty) && template_parameters == 0) /* for tempalte we need the class itself */ + $$ = $9; } else { - Setattr($$,"symtab",Swig_symbol_popscope()); - - Classprefix = Getattr($$,"Classprefix"); - Delattr($$,"Classprefix"); - if (nscope_inner) { - /* this is tricky */ - /* we add the declaration in the original namespace */ - if (cplus_mode != CPLUS_PRIVATE) - appendChild(nscope_inner,$$); - Swig_symbol_setscope(Getattr(nscope_inner,"symtab")); + Delete(yyrename); + yyrename = 0; + Delete(Namespaceprefix); + Namespaceprefix = Swig_symbol_qualifiedscopename(0); + if (!cparse_cplusplus && currentOuterClass) { /* nested C structs go into global scope*/ + Node *outer = currentOuterClass; + while (Getattr(outer, "nested:outer")) + outer = Getattr(outer, "nested:outer"); + appendSibling(outer, $$); + add_symbols($9); + set_scope_to_global(); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); yyrename = Copy(Getattr($$, "class_rename")); add_symbols($$); + if (!CPlusPlusOut) + Delattr($$, "nested:outer"); Delattr($$, "class_rename"); - /* but the variable definition in the current scope */ - Swig_symbol_setscope(cscope); - Delete(Namespaceprefix); - Namespaceprefix = Swig_symbol_qualifiedscopename(0); - add_symbols($9); - if (nscope) { - $$ = nscope; - if ($9) - appendSibling($$, $9); - } - else if (!SwigType_istemplate(ty) && template_parameters == 0) - $$ = $9; + $$ = 0; } else { - Delete(yyrename); - yyrename = 0; - Delete(Namespaceprefix); - Namespaceprefix = Swig_symbol_qualifiedscopename(0); - if (!cparse_cplusplus && currentOuterClass) { /* nested C structs go into global scope*/ - Node *outer = currentOuterClass; - while (Getattr(outer, "nested:outer")) - outer = Getattr(outer, "nested:outer"); - appendSibling(outer, $$); - add_symbols($9); - set_scope_to_global(); - Delete(Namespaceprefix); - Namespaceprefix = Swig_symbol_qualifiedscopename(0); - yyrename = Copy(Getattr($$, "class_rename")); - add_symbols($$); - if (!CPlusPlusOut) - Delattr($$, "nested:outer"); - Delattr($$, "class_rename"); - $$ = 0; - } else { - yyrename = Copy(Getattr($$, "class_rename")); - add_symbols($$); - add_symbols($9); - Delattr($$, "class_rename"); - } + yyrename = Copy(Getattr($$, "class_rename")); + add_symbols($$); + add_symbols($9); + Delattr($$, "class_rename"); } } + Delete(ty); Swig_symbol_setscope(cscope); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); From 2d0dc707e6975ae4476931c32f4df4e4faaa2e4e Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 8 Dec 2013 19:48:39 +0000 Subject: [PATCH 226/481] More control on output from top level Makefile Move the '-k -s' flags to a new FLAGS variable which can then be overridden on the command line. --- Makefile.in | 62 +++++++++++++++++++++++++++++------------------------ 1 file changed, 34 insertions(+), 28 deletions(-) diff --git a/Makefile.in b/Makefile.in index 9db1a7efc..aa1c3d63f 100644 --- a/Makefile.in +++ b/Makefile.in @@ -9,9 +9,16 @@ exec_prefix = @exec_prefix@ srcdir = @srcdir@ datarootdir = @datarootdir@ -############################################################################## +##################################################################### +# Make options - override these to see more output +##################################################################### + +RUNPIPE = \>/dev/null +FLAGS = -k -s + +##################################################################### # Compiler and system configuration -############################################################################## +##################################################################### SHELL = /bin/sh SWIG_LIB = @swig_lib@ @@ -23,7 +30,6 @@ SOURCE = Source CCACHE = CCache DOCS = Doc/Manual HAVE_CXX11_COMPILER = @HAVE_CXX11_COMPILER@ -RUNPIPE = \>/dev/null swig: libfiles source ccache @@ -160,7 +166,7 @@ check-%-version : echo skipping $* version; \ else \ echo showing $* version; \ - (cd Examples && $(MAKE) -s $*_version) \ + (cd Examples && $(MAKE) $(FLAGS) $*_version) \ fi # Checks examples for compilation (does not run them) @@ -224,13 +230,13 @@ check-%-examples : elif test -z "$($(strip $*_examples))"; then \ echo empty $* $(ACTION); \ else \ - $(MAKE) -k -s $($*_examples:=.actionexample) LANGUAGE=$* ACTION=$(ACTION); \ + $(MAKE) $(FLAGS) $($*_examples:=.actionexample) LANGUAGE=$* ACTION=$(ACTION); \ fi # individual example %.actionexample: @echo $(ACTION)ing Examples/$(LANGUAGE)/$* - @(cd Examples/$(LANGUAGE)/$* && $(MAKE) -s $(chk-set-env) $(ACTION) RUNPIPE=$(RUNPIPE)) + @(cd Examples/$(LANGUAGE)/$* && $(MAKE) $(FLAGS) $(chk-set-env) $(ACTION) RUNPIPE=$(RUNPIPE)) # gcj individual example java.actionexample: @@ -238,7 +244,7 @@ java.actionexample: echo "skipping Examples/$(LANGUAGE)/java $(ACTION) (gcj test)"; \ else \ echo $(ACTION)ing Examples/$(LANGUAGE)/java; \ - (cd Examples/$(LANGUAGE)/java && $(MAKE) -s $(chk-set-env) $(ACTION)) \ + (cd Examples/$(LANGUAGE)/java && $(MAKE) $(FLAGS) $(chk-set-env) $(ACTION)) \ fi # Checks testcases in the test-suite excluding those which are known to be broken @@ -279,17 +285,17 @@ check-%-test-suite: echo warning: cannot $(ACTION) $* test-suite "(no dir $$dir)";\ else \ echo $(ACTION)ing $* test-suite; \ - (cd $$dir && $(MAKE) -k -s $(ACTION) HAVE_CXX11_COMPILER=$(HAVE_CXX11_COMPILER)) \ + (cd $$dir && $(MAKE) $(FLAGS) $(ACTION) HAVE_CXX11_COMPILER=$(HAVE_CXX11_COMPILER)) \ || passed=false; \ fi; \ test $$passed = true # Partial test-suite check - it only invokes SWIG, ie no compilation and no runtime testing partialcheck-test-suite: - @$(MAKE) -k -s check-test-suite ACTION=partialcheck NOSKIP=1 + @$(MAKE) $(FLAGS) check-test-suite ACTION=partialcheck NOSKIP=1 partialcheck-%-test-suite: - @$(MAKE) -k -s check-$*-test-suite ACTION=partialcheck NOSKIP=1 + @$(MAKE) $(FLAGS) check-$*-test-suite ACTION=partialcheck NOSKIP=1 check: check-aliveness check-ccache check-versions check-examples check-test-suite @@ -319,7 +325,7 @@ all-test-suite: \ all-d-test-suite all-%-test-suite: - @$(MAKE) -k -s check-$*-test-suite ACTION=all + @$(MAKE) $(FLAGS) check-$*-test-suite ACTION=all # Run known-to-be-broken testcases in the test-suite broken-test-suite: \ @@ -347,7 +353,7 @@ broken-test-suite: \ broken-d-test-suite broken-%-test-suite: - @$(MAKE) -k -s check-$*-test-suite ACTION=broken + @$(MAKE) $(FLAGS) check-$*-test-suite ACTION=broken ##################################################################### # CLEAN @@ -359,23 +365,23 @@ clean-objects: clean-source clean-ccache clean-source: @echo cleaning Source - @cd $(SOURCE) && $(MAKE) -s clean + @cd $(SOURCE) && $(MAKE) $(FLAGS) clean @rm -f $(TARGET) clean-examples: - @$(MAKE) -k -s check-examples ACTION=clean + @$(MAKE) $(FLAGS) check-examples ACTION=clean clean-test-suite: - @$(MAKE) -k -s check-test-suite ACTION=clean NOSKIP=1 + @$(MAKE) $(FLAGS) check-test-suite ACTION=clean NOSKIP=1 clean-%-examples: - @$(MAKE) -k -s check-$*-examples ACTION=clean + @$(MAKE) $(FLAGS) check-$*-examples ACTION=clean clean-%-test-suite: - @$(MAKE) -k -s check-$*-test-suite ACTION=clean NOSKIP=1 + @$(MAKE) $(FLAGS) check-$*-test-suite ACTION=clean NOSKIP=1 clean-ccache: - test -z "$(ENABLE_CCACHE)" || (cd $(CCACHE) && $(MAKE) -s clean) + test -z "$(ENABLE_CCACHE)" || (cd $(CCACHE) && $(MAKE) $(FLAGS) clean) ##################################################################### # DISTCLEAN - clean what configure built @@ -389,20 +395,20 @@ distclean: distclean-source distclean-ccache distclean-helper distclean-source: @echo distcleaning Source - @cd $(SOURCE) && $(MAKE) -s distclean + @cd $(SOURCE) && $(MAKE) $(FLAGS) distclean @rm -f $(TARGET) distclean-test-suite: @echo distcleaning Examples/test-suite - @$(MAKE) -k -s check-test-suite ACTION=distclean NOSKIP=1 + @$(MAKE) $(FLAGS) check-test-suite ACTION=distclean NOSKIP=1 distclean-examples: @echo distcleaning Examples - @$(MAKE) -k -s clean-examples - @cd Examples && $(MAKE) -k -s distclean + @$(MAKE) $(FLAGS) clean-examples + @cd Examples && $(MAKE) $(FLAGS) distclean distclean-ccache: - @test -z "$(ENABLE_CCACHE)" || (cd $(CCACHE) && $(MAKE) -s distclean) + @test -z "$(ENABLE_CCACHE)" || (cd $(CCACHE) && $(MAKE) $(FLAGS) distclean) distclean-dead: rm -f $(DISTCLEAN-DEAD) @@ -416,15 +422,15 @@ distclean-dead: maintainer-clean: @echo maintainer-cleaning source - @cd $(SOURCE) && $(MAKE) -k -s maintainer-clean + @cd $(SOURCE) && $(MAKE) $(FLAGS) maintainer-clean @echo maintainer-cleaning CCache - @test -z "$(ENABLE_CCACHE)" || (cd $(CCACHE) && $(MAKE) -s maintainer-clean) + @test -z "$(ENABLE_CCACHE)" || (cd $(CCACHE) && $(MAKE) $(FLAGS) maintainer-clean) @echo maintainer-cleaning docs - @cd $(DOCS) && $(MAKE) -k -s maintainer-clean + @cd $(DOCS) && $(MAKE) $(FLAGS) maintainer-clean @echo maintainer-cleaning Lib files @rm -f $(srcdir)/Lib/swigwarn.swg @echo distcleaning - @$(MAKE) -k -s distclean-helper + @$(MAKE) $(FLAGS) distclean-helper ##################################################################### # Update the Lib/swigwarn.swg file @@ -492,7 +498,7 @@ install-lib: done install-ccache: - @test -z "$(ENABLE_CCACHE)" || (cd $(CCACHE) && $(MAKE) -s install) + @test -z "$(ENABLE_CCACHE)" || (cd $(CCACHE) && $(MAKE) install) ##################################################################### From c6e4dea5722eac4319306a2d09c119e312848dc8 Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Tue, 15 Oct 2013 11:25:11 +1300 Subject: [PATCH 227/481] Fix a few typos in comments and docs --- CHANGES | 6 +++--- Doc/Manual/SWIGPlus.html | 2 +- Doc/Manual/Typemaps.html | 2 +- Lib/python/pytypemaps.swg | 2 +- Lib/swig.swg | 2 +- Lib/typemaps/swigmacros.swg | 10 +++++----- Lib/typemaps/swigtypemaps.swg | 2 +- Source/Swig/typesys.c | 6 +++--- 8 files changed, 16 insertions(+), 16 deletions(-) diff --git a/CHANGES b/CHANGES index 4cc222901..da5fb1f07 100644 --- a/CHANGES +++ b/CHANGES @@ -201,7 +201,7 @@ Version 2.0.10 (27 May 2013) The macros are silently ignored. 2013-04-17: wsfulton - [C#] Pull patch #34 from BrantKyser to fix smart pointers in conjuction with directors. + [C#] Pull patch #34 from BrantKyser to fix smart pointers in conjunction with directors. 2013-04-15: kwwette [Octave] Fix bugs in output of cleanup code. @@ -5206,7 +5206,7 @@ Version 1.3.29 (March 21, 2006) 6146 _std_containers.so 174 _std_containers.so.hidden - Excecution times: + Execution times: real 0m0.050s user 0m0.039s sys 0m0.005s _std_containers.so real 0m0.039s user 0m0.026s sys 0m0.007s _std_containers.so.hidden @@ -5292,7 +5292,7 @@ Version 1.3.29 (March 21, 2006) protected methods by default. In previous releases, you needed to use the 'dirprot' - option to acheive the same. + option to achieve the same. If you want, you can disable the new default behaviour, use the 'nodirprot' option: diff --git a/Doc/Manual/SWIGPlus.html b/Doc/Manual/SWIGPlus.html index 2713725d7..2ed450c01 100644 --- a/Doc/Manual/SWIGPlus.html +++ b/Doc/Manual/SWIGPlus.html @@ -1522,7 +1522,7 @@ multiple inheritance. spirit, and target language capabilities, as possible. In most cases, this means that SWIG will parse the non-public inheritance declarations, but that will have no effect in the generated code, -besides the implicit policies derived for constructor and +besides the implicit policies derived for constructors and destructors.

      diff --git a/Doc/Manual/Typemaps.html b/Doc/Manual/Typemaps.html index 81e3fd1bb..20ad085f8 100644 --- a/Doc/Manual/Typemaps.html +++ b/Doc/Manual/Typemaps.html @@ -3956,7 +3956,7 @@ Requirements for the type system:
    • Store inheritance and type equivalence information and be able to correctly re-create the type pointer.
    • Share type information between modules.
    • -
    • Modules can be loaded in any order, irregardless of actual type +
    • Modules can be loaded in any order, regardless of actual type dependency.
    • Avoid the use of dynamically allocated memory, and library/system calls in general.
    • Provide a reasonably fast implementation, minimizing the lookup time for all diff --git a/Lib/python/pytypemaps.swg b/Lib/python/pytypemaps.swg index c64b47b05..5c6abb01e 100644 --- a/Lib/python/pytypemaps.swg +++ b/Lib/python/pytypemaps.swg @@ -9,7 +9,7 @@ #undef SWIG_TYPECHECK_BOOL %define SWIG_TYPECHECK_BOOL 10000 %enddef -/* Include fundamental fragemt definitions */ +/* Include fundamental fragment definitions */ %include /* Look for user fragments file. */ diff --git a/Lib/swig.swg b/Lib/swig.swg index ad6b7b64b..241d93f3f 100644 --- a/Lib/swig.swg +++ b/Lib/swig.swg @@ -258,7 +258,7 @@ static int NAME(TYPE x) { %rename("$ignore", %$isenumitem, %$classname="MyClass") ""; - we use the prefix '%$' to avoid clashings with other swig + we use the prefix '%$' to avoid clashes with other swig macros/directives. */ diff --git a/Lib/typemaps/swigmacros.swg b/Lib/typemaps/swigmacros.swg index c9b42facf..61470583e 100644 --- a/Lib/typemaps/swigmacros.swg +++ b/Lib/typemaps/swigmacros.swg @@ -3,16 +3,16 @@ * ----------------------------------------------------------------------------- */ /* This file implements the internal macros of the 'SWIG API', which - are useful to implement all the SWIG target languges. + are useful to implement all the SWIG target languages. Basic preprocessor macros: -------------------------- %arg(Arg) Safe argument wrap - %str(Arg) Stringtify the argument - %begin_block Begin a execution block - %end_block End a execution block - %block(Block) Execute Block as a excecution block + %str(Arg) Stringify the argument + %begin_block Begin an execution block + %end_block End an execution block + %block(Block) Execute Block as an execution block %define_as(Def, Val) Define 'Def' as 'Val', expanding Def and Val first %ifcplusplus(V1, V2) if C++ Mode; then V1; else V2; fi diff --git a/Lib/typemaps/swigtypemaps.swg b/Lib/typemaps/swigtypemaps.swg index 0e39afe4c..4e5bb2b04 100644 --- a/Lib/typemaps/swigtypemaps.swg +++ b/Lib/typemaps/swigtypemaps.swg @@ -12,7 +12,7 @@ and then include this file. Typically you will create a 'mytypemaps.swg' file in each target - languge, where you will have the following sections: + language, where you will have the following sections: === mytypemaps.swg === diff --git a/Source/Swig/typesys.c b/Source/Swig/typesys.c index 1552703c6..bcfd2feb5 100644 --- a/Source/Swig/typesys.c +++ b/Source/Swig/typesys.c @@ -1381,13 +1381,13 @@ int SwigType_type(const SwigType *t) { * * 2.- swig doesn't mark 'type' as non-assignable. * - * 3.- the user specify that the value wrapper is not needed by using - * the %feature("novaluewrapper"), in that case the user need to type + * 3.- the user specifies that the value wrapper is not needed by using + * %feature("novaluewrapper") like so: * * %feature("novaluewrapper") MyOpaqueClass; * class MyOpaqueClass; * - * Users can also force the use of the value wrapper by using the + * The user can also force the use of the value wrapper with * %feature("valuewrapper"). * ----------------------------------------------------------------------------- */ From cecd89f66f7d8e7949323358d37b78ddbf268c76 Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Thu, 12 Dec 2013 15:39:10 +1300 Subject: [PATCH 228/481] [PHP] The usage of $input in PHP directorout typemaps has been changed to be consistent with other languages. The typemaps provided by SWIG have been updated accordingly, but if you have written your own directorout typemaps, you'll need to update $input to &$input (or make equivalent changes). *** POTENTIAL INCOMPATIBILITY *** --- CHANGES.current | 9 +++++++++ Examples/test-suite/typemap_directorout.i | 18 ------------------ Lib/php/php.swg | 2 +- Lib/php/std_string.i | 8 ++++---- Lib/php/utils.i | 4 ++-- Source/Modules/php.cxx | 3 +-- 6 files changed, 17 insertions(+), 27 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index a4d12239d..597a0e853 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,15 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2013-12-12: olly + [PHP] The usage of $input in PHP directorout typemaps has been + changed to be consistent with other languages. The typemaps + provided by SWIG have been updated accordingly, but if you + have written your own directorout typemaps, you'll need to + update $input to &$input (or make equivalent changes). + + *** POTENTIAL INCOMPATIBILITY *** + 2013-11-27: vadz [C#, Java, Python] Add std_auto_ptr.i defining typemaps for returning std::auto_ptr<>. diff --git a/Examples/test-suite/typemap_directorout.i b/Examples/test-suite/typemap_directorout.i index fb0a6ab81..4a85bd47c 100644 --- a/Examples/test-suite/typemap_directorout.i +++ b/Examples/test-suite/typemap_directorout.i @@ -13,24 +13,6 @@ // Can't use the %typemap(directorout) MyType & = SWIGTYPE & approach as non-director languages don't define any directorout typemaps %typemap(directorout) MyType &Class1::foo2, MyType &foo1 %{ /* special start */ $input = 0; /* special end */ %} -#ifdef SWIGPHP -%typemap(directorout, warning="PHP directorout typemaps need fixing") MyType &Class1::foo2, MyType &foo1 %{ /* special start */ /*$input = 0;*/ /* special end */ %} -/* Patch to make $input work same as other languages. Then $input needs changing to &$input in most (maybe all) typemaps. ---- a/Source/Modules/php.cxx -+++ b/Source/Modules/php.cxx -@@ -2631,8 +2631,7 @@ done: - if (!is_void) { - tm = Swig_typemap_lookup("directorout", n, Swig_cresult_name(), w); - if (tm != 0) { -- static const String *amp_result = NewStringf("&%s", Swig_cresult_name()); -- Replaceall(tm, "$input", amp_result); -+ Replaceall(tm, "$input", Swig_cresult_name()); - char temp[24]; - sprintf(temp, "%d", idx); - Replaceall(tm, "$argnum", temp); -*/ -#endif - #ifdef SWIGCSHARP %typemap(csdirectorout) MyType & %{ WILL_NOT_COMPILE %} diff --git a/Lib/php/php.swg b/Lib/php/php.swg index 325abbcd4..afa047ef6 100644 --- a/Lib/php/php.swg +++ b/Lib/php/php.swg @@ -93,7 +93,7 @@ %typemap(directorout) SWIGTYPE ($&1_ltype tmp) { - if(SWIG_ConvertPtr(*$input, (void **) &tmp, $&1_descriptor, 0) < 0 || tmp == NULL) { + 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; diff --git a/Lib/php/std_string.i b/Lib/php/std_string.i index 10d7fdd31..aaa5dc9cd 100644 --- a/Lib/php/std_string.i +++ b/Lib/php/std_string.i @@ -33,8 +33,8 @@ namespace std { %} %typemap(directorout) string %{ - convert_to_string_ex($input); - $result.assign(Z_STRVAL_PP($input), Z_STRLEN_PP($input)); + convert_to_string_ex(&$input); + $result.assign(Z_STRVAL_P($input), Z_STRLEN_P($input)); %} %typemap(out) string %{ @@ -63,8 +63,8 @@ namespace std { %} %typemap(directorout) string & ($*1_ltype *temp) %{ - convert_to_string_ex($input); - temp = new $*1_ltype(Z_STRVAL_PP($input), Z_STRLEN_PP($input)); + convert_to_string_ex(&$input); + temp = new $*1_ltype(Z_STRVAL_P($input), Z_STRLEN_P($input)); swig_acquire_ownership(temp); $result = temp; %} diff --git a/Lib/php/utils.i b/Lib/php/utils.i index 07ac96900..c3b19a320 100644 --- a/Lib/php/utils.i +++ b/Lib/php/utils.i @@ -80,11 +80,11 @@ %} %typemap(directorout) TYPE %{ - CONVERT_IN($result,$1_ltype,$input); + CONVERT_IN($result,$1_ltype,&$input); %} %typemap(directorout) const TYPE & ($*1_ltype temp) %{ - CONVERT_IN(temp,$*1_ltype,$input); + CONVERT_IN(temp,$*1_ltype,&$input); $result = &temp; %} %enddef diff --git a/Source/Modules/php.cxx b/Source/Modules/php.cxx index def917019..a8659b9f1 100644 --- a/Source/Modules/php.cxx +++ b/Source/Modules/php.cxx @@ -2626,8 +2626,7 @@ done: if (!is_void) { tm = Swig_typemap_lookup("directorout", n, Swig_cresult_name(), w); if (tm != 0) { - static const String *amp_result = NewStringf("&%s", Swig_cresult_name()); - Replaceall(tm, "$input", amp_result); + Replaceall(tm, "$input", Swig_cresult_name()); char temp[24]; sprintf(temp, "%d", idx); Replaceall(tm, "$argnum", temp); From abeba4564401e10d908cc5240b7f748dabd3b201 Mon Sep 17 00:00:00 2001 From: Michael Bunk Date: Sat, 23 Nov 2013 19:19:37 +0100 Subject: [PATCH 229/481] Fix typos --- Doc/Manual/Introduction.html | 12 +++++------ Doc/Manual/SWIG.html | 40 ++++++++++++++++++------------------ Doc/Manual/Scripting.html | 10 ++++----- 3 files changed, 31 insertions(+), 31 deletions(-) diff --git a/Doc/Manual/Introduction.html b/Doc/Manual/Introduction.html index a8d15a5c2..d5dc778bd 100644 --- a/Doc/Manual/Introduction.html +++ b/Doc/Manual/Introduction.html @@ -38,7 +38,7 @@ SWIG is a software development tool that simplifies the task of interfacing different languages to C and C++ programs. In a nutshell, SWIG is a compiler that takes C/C++ declarations and creates -the wrappers needed to access those declarations from other languages including +the wrappers needed to access those declarations from other languages including Perl, Python, Tcl, Ruby, Guile, and Java. SWIG normally requires no modifications to existing code and can often be used to build a usable interface in only a few minutes. Possible applications @@ -49,7 +49,7 @@ of SWIG include:
    • Building interpreted interfaces to existing C programs.
    • Rapid prototyping and application development.
    • Interactive debugging. -
    • Reengineering or refactoring of legacy software into a scripting language components. +
    • Reengineering or refactoring of legacy software into scripting language components.
    • Making a graphical user interface (using Tk for example).
    • Testing of C libraries and programs (using scripts).
    • Building high performance C modules for scripting languages. @@ -98,7 +98,7 @@ of other libraries).
    • Testing is time consuming (the compile/debug cycle).
    • Not easy to reconfigure or customize without recompilation.
    • Modularization can be tricky. -
    • Security concerns (buffer overflow for instance). +
    • Security concerns (buffer overflows for instance).

    To address these limitations, many programmers have arrived at the @@ -345,7 +345,7 @@ not only parses C++, it implements the full C++ type system and it is able to understand C++ semantics. SWIG generates its wrappers with full knowledge of this information. As a result, you will find SWIG to be just as capable of dealing with nasty corner cases as it is in -wrapping simple C++ code. In fact, SWIG is able handle C++ code that +wrapping simple C++ code. In fact, SWIG is able to handle C++ code that stresses the very limits of many C++ compilers. @@ -388,8 +388,8 @@ There is growing support for SWIG in some build tools, for example 5.2.1 Basic Type Handling @@ -728,7 +728,7 @@ However, for the same conservative reasons even a constant with a simple cast wi

    -#define F_CONST (double) 5            // A floating pointer constant with cast
    +#define F_CONST (double) 5            // A floating point constant with cast
     
    @@ -750,7 +750,7 @@ enum values as assigned by the C compiler.

    The %constant directive is used to more precisely create constants corresponding to different C datatypes. Although it is not -usually not needed for simple values, it is more useful when working +usually needed for simple values, it is more useful when working with pointers and other more complex datatypes. Typically, %constant is only used when you want to add constants to the scripting language interface that are not defined in the original header file. @@ -868,7 +868,7 @@ from a scripting language to a C char *, the pointer usually points to string data stored inside the interpreter. It is almost always a really bad idea to modify this data. Furthermore, some languages may explicitly disallow it. For instance, in Python, -strings are supposed be immutable. If you violate this, you will probably +strings are supposed to be immutable. If you violate this, you will probably receive a vast amount of wrath when you unleash your module on the world.

    @@ -1483,7 +1483,7 @@ void transpose(double (*a)[20]);

    Like C, SWIG does not perform array bounds checking. It is up to the -user to make sure the pointer points a suitably allocated region of memory. +user to make sure the pointer points to a suitably allocated region of memory.

    @@ -2265,7 +2265,7 @@ disabled using %nocallback. When you do this, the interface now works

    Notice that when the function is used as a callback, special names -such as add_cb is used instead. To call the function +such as add_cb are used instead. To call the function normally, just use the original function name such as add().

    @@ -2311,7 +2311,7 @@ handle C++ are described in the next section. If SWIG encounters the definition of a structure or union, it creates a set of accessor functions. Although SWIG does not need structure definitions to build an interface, providing definitions -make it possible to access structure members. The accessor functions +makes it possible to access structure members. The accessor functions generated by SWIG simply take a pointer to an object and allow access to an individual member. For example, the declaration :

    @@ -2434,7 +2434,7 @@ vector_struct
    , SWIG knows that this is the same as Structures involving character strings require some care. SWIG assumes that all members of type char * have been dynamically allocated using malloc() and that they are NULL-terminated -ASCII strings. When such a member is modified, the previously contents +ASCII strings. When such a member is modified, the previous contents will be released, and the new contents allocated. For example :

    @@ -2519,7 +2519,7 @@ typedef struct Bar {
     

    When a structure member is wrapped, it is handled as a pointer, unless the %naturalvar directive is used where it is handled more like a C++ reference (see C++ Member data). -The accessors to the member variable as a pointer is effectively wrapped as follows: +The accessors to the member variable as a pointer are effectively wrapped as follows:

    @@ -2656,8 +2656,8 @@ struct Bar { // Default constructor generated.

    -Since ignoring the implicit or default destructors most of the times -produce memory leaks, SWIG will always try to generate them. If +Since ignoring the implicit or default destructors most of the time +produces memory leaks, SWIG will always try to generate them. If needed, however, you can selectively disable the generation of the default/implicit destructor by using %nodefaultdtor

    @@ -2687,7 +2687,7 @@ has now been enabled as the default behavior. Note: There are also the -nodefault option and %nodefault directive, which disable both the default or implicit destructor generation. This could lead to memory leaks across -the target languages, and is highly recommended you don't use them. +the target languages, and it is highly recommended you don't use them.

    @@ -3280,7 +3280,7 @@ initialization on module loading, you could write this:

    -This section describes the general approach for building interface +This section describes the general approach for building interfaces with SWIG. The specifics related to a particular scripting language are found in later chapters.

    @@ -3295,9 +3295,9 @@ of steps you can follow to make an interface for a C program :

    • Identify the functions that you want to wrap. It's probably not -necessary to access every single function in a C program--thus, a +necessary to access every single function of a C program--thus, a little forethought can dramatically simplify the resulting scripting -language interface. C header files are particularly good source for +language interface. C header files are a particularly good source for finding things to wrap.
    • Create a new interface file to describe the scripting language @@ -3342,7 +3342,7 @@ to the swig-devel mailing list or to

      -The preferred method of using SWIG is to generate separate interface +The preferred method of using SWIG is to generate a separate interface file. Suppose you have the following C header file :

      @@ -3436,7 +3436,7 @@ include certain header files by using a %{,%} block like this:
       #include <GL/glu.h>
       %}
       
      -// Put rest of declarations here
      +// Put the rest of the declarations here
       ...
       
      @@ -3478,7 +3478,7 @@ program that is more interactive. In many cases, the old or Tcl script.

      -Note: If some cases, you might be inclined to create a +Note: In some cases, you might be inclined to create a scripting language wrapper for main(). If you do this, the compilation will probably work and your module might even load correctly. The only trouble is that when you call your diff --git a/Doc/Manual/Scripting.html b/Doc/Manual/Scripting.html index e6a2eee24..26a8dd017 100644 --- a/Doc/Manual/Scripting.html +++ b/Doc/Manual/Scripting.html @@ -293,7 +293,7 @@ A proxy class is a special kind of object that gets created in a scripting language to access a C/C++ class (or struct) in a way that looks like the original structure (that is, it proxies the real C++ class). For example, if you -have the following C definition :

      +have the following C++ definition :

       class Vector {
      @@ -334,12 +334,12 @@ Finally, in Tcl :
       
       
       Vector v
      -v configure -x 3 -y 4 -z 13
      +v configure -x 3 -y 4 -z -13
       
       

      -When proxy classes are used, two objects are at really work--one in +When proxy classes are used, two objects are really at work--one in the scripting language, and an underlying C/C++ object. Operations affect both objects equally and for all practical purposes, it appears as if you are simply manipulating a C/C++ object. @@ -353,7 +353,7 @@ The final step in using a scripting language with your C/C++ application is adding your extensions to the scripting language itself. There are two primary approaches for doing this. The preferred technique is to build a dynamically loadable -extension in the form a shared library. Alternatively, you can +extension in the form of a shared library. Alternatively, you can recompile the scripting language interpreter with your extensions added to it.

      @@ -364,7 +364,7 @@ added to it.

      To create a shared library or DLL, you often need to look at the manual pages for your compiler and linker. However, the procedure -for a few common machines is shown below:

      +for a few common platforms is shown below:

       # Build a shared library for Solaris
      
      From 8be8b62d8381813618ad259d16ebd87d11118eb9 Mon Sep 17 00:00:00 2001
      From: jleveque 
      Date: Tue, 19 Nov 2013 23:55:37 -0600
      Subject: [PATCH 230/481] Fix compile warning on Linux
      
      ---
       Lib/lua/wchar.i | 2 +-
       1 file changed, 1 insertion(+), 1 deletion(-)
      
      diff --git a/Lib/lua/wchar.i b/Lib/lua/wchar.i
      index 141ecc41f..aff21b46c 100644
      --- a/Lib/lua/wchar.i
      +++ b/Lib/lua/wchar.i
      @@ -18,7 +18,7 @@ wchar_t* str2wstr(const char *str, int len)
         if (str==0 || len<1)  return 0;
         p=(wchar *)malloc((len+1)*sizeof(wchar_t));
         if (p==0)	return 0;
      -  if (mbstowcs(p, str, len)==-1)
      +  if (mbstowcs(p, str, len)==(size_t)-1)
         {
           free(p);
           return 0;
      
      From 227192f80a79db7edfb25342cd13626be49e567f Mon Sep 17 00:00:00 2001
      From: Miklos Vajna 
      Date: Mon, 18 Nov 2013 21:50:33 +0100
      Subject: [PATCH 231/481] Fix Examples/php/pointer to work with PHP 5.5
      
      With this, all examples work with PHP 5.5 for me.
      ---
       Examples/php/pointer/runme.php |  2 +-
       Lib/php/phppointers.i          |  2 +-
       Source/Modules/php.cxx         | 34 ++++++++++++++++++++++++++--------
       3 files changed, 28 insertions(+), 10 deletions(-)
      
      diff --git a/Examples/php/pointer/runme.php b/Examples/php/pointer/runme.php
      index 5e86de6a2..e79b23810 100644
      --- a/Examples/php/pointer/runme.php
      +++ b/Examples/php/pointer/runme.php
      @@ -15,7 +15,7 @@
       	print "	c = $c\n";
       
       	# Call the add() function wuth some pointers
      -	add(&$a,&$b,&$c);
      +	add($a,$b,$c);
       
       	print "	$a + $b = $c\n";
       
      diff --git a/Lib/php/phppointers.i b/Lib/php/phppointers.i
      index 91b2c6d96..e50ada7ac 100644
      --- a/Lib/php/phppointers.i
      +++ b/Lib/php/phppointers.i
      @@ -1,5 +1,5 @@
       %define %pass_by_ref( TYPE, CONVERT_IN, CONVERT_OUT )
      -%typemap(in) TYPE *REF ($*1_ltype tmp),
      +%typemap(in, byref=1) TYPE *REF ($*1_ltype tmp),
                    TYPE &REF ($*1_ltype tmp)
       %{
         /* First Check for SWIG wrapped type */
      diff --git a/Source/Modules/php.cxx b/Source/Modules/php.cxx
      index a8659b9f1..a4b01a624 100644
      --- a/Source/Modules/php.cxx
      +++ b/Source/Modules/php.cxx
      @@ -90,6 +90,7 @@ static String *s_vinit;		// varinit initialization code.
       static String *s_vdecl;
       static String *s_cinit;		// consttab initialization code.
       static String *s_oinit;
      +static String *s_arginfo;
       static String *s_entry;
       static String *cs_entry;
       static String *all_cs_entry;
      @@ -517,6 +518,9 @@ public:
           Printf(f_h, "PHP_RSHUTDOWN_FUNCTION(%s);\n", module);
           Printf(f_h, "PHP_MINFO_FUNCTION(%s);\n\n", module);
       
      +    /* start the arginfo section */
      +    s_arginfo = NewString("/* arginfo subsection */\n");
      +
           /* start the function entry section */
           s_entry = NewString("/* entry subsection */\n");
       
      @@ -643,7 +647,7 @@ public:
             Dump(f_directors, f_begin);
           }
           Printv(f_begin, s_vdecl, s_wrappers, NIL);
      -    Printv(f_begin, all_cs_entry, "\n\n", s_entry,
      +    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"
       	"{NULL, NULL, NULL}\n};\n\n", NIL);
      @@ -654,6 +658,7 @@ public:
           Delete(s_vdecl);
           Delete(all_cs_entry);
           Delete(s_entry);
      +    Delete(s_arginfo);
           Delete(f_runtime);
           Delete(f_begin);
       
      @@ -672,12 +677,25 @@ public:
         }
       
         /* Just need to append function names to function table to register with PHP. */
      -  void create_command(String *cname, String *iname) {
      +  void create_command(String *cname, String *iname, Node *n) {
           // This is for the single main zend_function_entry record
           Printf(f_h, "ZEND_NAMED_FUNCTION(%s);\n", iname);
           String * s = cs_entry;
           if (!s) s = s_entry;
      -    Printf(s, " SWIG_ZEND_NAMED_FE(%(lower)s,%s,NULL)\n", cname, iname);
      +    Printf(s, " SWIG_ZEND_NAMED_FE(%(lower)s,%s,swig_arginfo_%(lower)s)\n", cname, iname, cname);
      +
      +    // This is the above referenced arginfo structure.
      +    ParmList *l = Getattr(n, "parms");
      +    Printf(s_arginfo, "ZEND_BEGIN_ARG_INFO_EX(swig_arginfo_%(lower)s, 0, 0, 0)\n", cname);
      +    for (Parm *p = l; p; p = Getattr(p, "tmap:in:next")) {
      +      /* Ignored parameters */
      +      if (checkAttribute(p, "tmap:in:numinputs", "0")) {
      +	continue;
      +      }
      +      int byref = GetFlag(p, "tmap:in:byref");
      +      Printf(s_arginfo, " ZEND_ARG_PASS_INFO(%d)\n", byref);
      +    }
      +    Printf(s_arginfo, "ZEND_END_ARG_INFO()\n");
         }
       
         /* ------------------------------------------------------------
      @@ -700,7 +718,7 @@ public:
           String *symname = Getattr(n, "sym:name");
           String *wname = Swig_name_wrapper(symname);
       
      -    create_command(symname, wname);
      +    create_command(symname, wname, n);
           Printv(f->def, "ZEND_NAMED_FUNCTION(", wname, ") {\n", NIL);
       
           Wrapper_add_local(f, "argc", "int argc");
      @@ -790,16 +808,16 @@ public:
           String *outarg = NewStringEmpty();
           String *cleanup = NewStringEmpty();
       
      -    // Not issued for overloaded functions.
      -    if (!overloaded) {
      -      create_command(iname, wname);
      -    }
           Printv(f->def, "ZEND_NAMED_FUNCTION(", wname, ") {\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);
      +    }
       
           // wrap:parms is used by overload resolution.
           Setattr(n, "wrap:parms", l);
      
      From bef3cfe594d292576d53b39b385fa4e32b6bb14d Mon Sep 17 00:00:00 2001
      From: Olly Betts 
      Date: Thu, 12 Dec 2013 16:06:00 +1300
      Subject: [PATCH 232/481] Add CHANGES.current entry and minimal doc update for
       previous change
      
      ---
       CHANGES.current     |  7 +++++++
       Doc/Manual/Php.html | 11 ++++++-----
       2 files changed, 13 insertions(+), 5 deletions(-)
      
      diff --git a/CHANGES.current b/CHANGES.current
      index 597a0e853..719fbe879 100644
      --- a/CHANGES.current
      +++ b/CHANGES.current
      @@ -5,6 +5,13 @@ See the RELEASENOTES file for a summary of changes in each release.
       Version 3.0.0 (in progress)
       ============================
       
      +2013-12-12: vmiklos
      +	    [PHP] PHP's peculiar call-time pass-by-reference feature was
      +	    deprecated in PHP 5.3 and removed in PHP 5.4, so update the REF
      +	    typemaps in phppointers.i to specify pass-by-reference in the
      +	    function definition.  Examples/php/pointer has been updated
      +	    accordingly.
      +
       2013-12-12: olly
       	    [PHP] The usage of $input in PHP directorout typemaps has been
       	    changed to be consistent with other languages.  The typemaps
      diff --git a/Doc/Manual/Php.html b/Doc/Manual/Php.html
      index 78ee6ea7f..185883235 100644
      --- a/Doc/Manual/Php.html
      +++ b/Doc/Manual/Php.html
      @@ -503,13 +503,14 @@ echo "The sum $in1 + $in2 = $result\n";
       Because PHP has a native concept of reference, it may seem more natural
       to the PHP developer to use references to pass pointers.  To enable
       this, one needs to include phppointers.i which defines the
      -named typemap REFERENCE.
      +named typemap REF.
       

      -However, this relies on call-time pass-by-reference, which has been -deprecated in PHP for some time, and was finally removed in PHP 5.4. -So you should avoid creating new wrappers which rely on this approach. +Prior to SWIG 3.0, the REF typemaps relied on PHP's call-time +pass-by-reference, which was deprecated in PHP 5.3 and removed in PHP 5.4. +So if you use these REF typemaps, you should ensure that SWIG≥3.0 is +used to generate wrappers from your interface file.

      @@ -532,7 +533,7 @@ include("example.php");
       $in1 = 3;
       $in2 = 5;
       $result = 0;
      -add(&$in1,&$in2,&$result);
      +add($in1,$in2,$result);
       
       echo "The sum $in1 + $in2 = $result\n";
       ?>
      
      From c7ef5935496a04f3a83c70af6f841abf3ad7606e Mon Sep 17 00:00:00 2001
      From: jleveque 
      Date: Sat, 16 Nov 2013 14:19:18 -0600
      Subject: [PATCH 233/481] Bug fix (typo - "wchar" instead of "wchar_t")
      
      ---
       Lib/lua/wchar.i | 2 +-
       1 file changed, 1 insertion(+), 1 deletion(-)
      
      diff --git a/Lib/lua/wchar.i b/Lib/lua/wchar.i
      index aff21b46c..9f3be6fca 100644
      --- a/Lib/lua/wchar.i
      +++ b/Lib/lua/wchar.i
      @@ -16,7 +16,7 @@ wchar_t* str2wstr(const char *str, int len)
       {
         wchar_t* p;
         if (str==0 || len<1)  return 0;
      -  p=(wchar *)malloc((len+1)*sizeof(wchar_t));
      +  p=(wchar_t *)malloc((len+1)*sizeof(wchar_t));
         if (p==0)	return 0;
         if (mbstowcs(p, str, len)==(size_t)-1)
         {
      
      From dcc4096f8c7388cd7f9153458f1c56518bf7d7dd Mon Sep 17 00:00:00 2001
      From: Olly Betts 
      Date: Thu, 12 Dec 2013 17:00:26 +1300
      Subject: [PATCH 234/481] Add CHANGES.current entry for previous commit
      
      ---
       CHANGES.current | 4 ++++
       1 file changed, 4 insertions(+)
      
      diff --git a/CHANGES.current b/CHANGES.current
      index 719fbe879..3df92ef33 100644
      --- a/CHANGES.current
      +++ b/CHANGES.current
      @@ -5,6 +5,10 @@ See the RELEASENOTES file for a summary of changes in each release.
       Version 3.0.0 (in progress)
       ============================
       
      +2013-12-12: jleveque
      +	    [Lua] Fix typo (wchar instead of wchar_t) which made wchar.i
      +	    for Lua useless.
      +
       2013-12-12: vmiklos
       	    [PHP] PHP's peculiar call-time pass-by-reference feature was
       	    deprecated in PHP 5.3 and removed in PHP 5.4, so update the REF
      
      From e95ac8265154e1f3f9f05406c7f800182f1350b9 Mon Sep 17 00:00:00 2001
      From: William S Fulton 
      Date: Thu, 12 Dec 2013 07:59:47 +0000
      Subject: [PATCH 235/481] Nested C class setters restored in c++out mode for
       Octave
      
      Suitable casts are required so that assignment of instances of nested classes
      work as the nested class is duplicated in the global namespace, eg:
      
      struct Outer {
        struct Nested {
          int bar;
        } bar_instance;
      };
      
      Outer.bar_instance can now be assigned to.
      ---
       Examples/test-suite/nested_structs.i          |  2 ++
       .../test-suite/octave/nested_structs_runme.m  | 14 +++++++++++++
       Lib/typemaps/swigtype.swg                     |  6 +++---
       Source/CParse/parser.y                        |  4 ++--
       Source/Swig/cwrap.c                           | 21 ++++++++++++++++++-
       5 files changed, 41 insertions(+), 6 deletions(-)
       create mode 100644 Examples/test-suite/octave/nested_structs_runme.m
      
      diff --git a/Examples/test-suite/nested_structs.i b/Examples/test-suite/nested_structs.i
      index add24ec17..459f25f00 100644
      --- a/Examples/test-suite/nested_structs.i
      +++ b/Examples/test-suite/nested_structs.i
      @@ -23,6 +23,8 @@ void setValues(struct Outer *outer, int val) {
         outer->inside3 = &outer->inside2;
         outer->inside4[0].val = val * 4;
       }
      +
      +int getInside1Val(struct Outer *n) { return n->inside1.val; }
       %}
       
       /* 
      diff --git a/Examples/test-suite/octave/nested_structs_runme.m b/Examples/test-suite/octave/nested_structs_runme.m
      new file mode 100644
      index 000000000..a04aaa672
      --- /dev/null
      +++ b/Examples/test-suite/octave/nested_structs_runme.m
      @@ -0,0 +1,14 @@
      +nested_structs
      +
      +named = nested_structs.Named();
      +named.val = 999;
      +assert(nested_structs.nestedByVal(named), 999);
      +assert(nested_structs.nestedByPtr(named), 999);
      +
      +outer = nested_structs.Outer();
      +outer.inside1.val = 456;
      +assert(nested_structs.getInside1Val(outer), 456);
      +
      +outer.inside1 = named;
      +assert(nested_structs.getInside1Val(outer), 999);
      +
      diff --git a/Lib/typemaps/swigtype.swg b/Lib/typemaps/swigtype.swg
      index 5e92790d8..6c0affbe2 100644
      --- a/Lib/typemaps/swigtype.swg
      +++ b/Lib/typemaps/swigtype.swg
      @@ -159,7 +159,7 @@
       %typemap(memberin) SWIGTYPE [ANY] {
         if ($input) {
           size_t ii = 0;
      -    for (; ii < (size_t)$1_dim0; ++ii) $1[ii] = $input[ii];
      +    for (; ii < (size_t)$1_dim0; ++ii) *($1_ltype)&$1[ii] = ($*1_ltype)$input[ii];
         } else {
           %variable_nullref("$type","$name");
         }
      @@ -168,7 +168,7 @@
       %typemap(globalin) SWIGTYPE [ANY] {
         if ($input) {
           size_t ii = 0;
      -    for (; ii < (size_t)$1_dim0; ++ii) $1[ii] = $input[ii];
      +    for (; ii < (size_t)$1_dim0; ++ii) *($1_ltype)&$1[ii] = ($*1_ltype)$input[ii];
         } else {
           %variable_nullref("$type","$name");
         }
      @@ -181,7 +181,7 @@
           %variable_fail(res, "$type", "$name");
         } else if (inp) {
           size_t ii = 0;
      -    for (; ii < (size_t)$1_dim0; ++ii) $1[ii] = inp[ii];
      +    for (; ii < (size_t)$1_dim0; ++ii) *($1_ltype)&$1[ii] = ($*1_ltype)inp[ii];
         } else {
           %variable_nullref("$type", "$name");
         }
      diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y
      index 0124ad25a..8e34833e2 100644
      --- a/Source/CParse/parser.y
      +++ b/Source/CParse/parser.y
      @@ -3513,7 +3513,7 @@ cpp_class_decl  : storage_class cpptype idcolon inherit LBRACE {
       		   while (p) {
       		     Setattr(p, "storage", $1);
       		     Setattr(p, "type" ,ty);
      -		     if (!cparse_cplusplus && currentOuterClass && (!Getattr(currentOuterClass, "name") || CPlusPlusOut)) {
      +		     if (!cparse_cplusplus && currentOuterClass && (!Getattr(currentOuterClass, "name"))) {
       		       SetFlag(p, "hasconsttype");
       		       SetFlag(p, "feature:immutable");
       		     }
      @@ -3674,7 +3674,7 @@ cpp_class_decl  : storage_class cpptype idcolon inherit LBRACE {
       		   while (n) {
       		     Setattr(n,"storage",$1);
       		     Setattr(n, "type", ty);
      -		     if (!cparse_cplusplus && currentOuterClass && (!Getattr(currentOuterClass, "name") || CPlusPlusOut)) {
      +		     if (!cparse_cplusplus && currentOuterClass && (!Getattr(currentOuterClass, "name"))) {
       		       SetFlag(n,"hasconsttype");
       		       SetFlag(n,"feature:immutable");
       		     }
      diff --git a/Source/Swig/cwrap.c b/Source/Swig/cwrap.c
      index 6f8fa39e9..03020bb72 100644
      --- a/Source/Swig/cwrap.c
      +++ b/Source/Swig/cwrap.c
      @@ -15,6 +15,7 @@
       #include "swig.h"
       
       extern int cparse_cplusplus;
      +extern int CPlusPlusOut;
       static const char *cresult_variable_name = "result";
       
       static Parm *nonvoid_parms(Parm *p) {
      @@ -775,7 +776,25 @@ String *Swig_cmemberset_call(const_String_or_char_ptr name, SwigType *type, Stri
         if (SwigType_type(type) != T_ARRAY) {
           if (!Strstr(type, "enum $unnamed")) {
             String *dref = Swig_wrapped_var_deref(type, pname1, varcref);
      -      Printf(func, "if (%s) %s%s = %s", pname0, self, name, dref);
      +      int extra_cast = 0;
      +      if (CPlusPlusOut) {
      +	/* Required for C nested structs compiled as C++ as a duplicate of the nested struct is put into the global namespace.
      +	 * We could improve this by adding the extra casts just for nested structs rather than all structs. */
      +	String *base = SwigType_base(type);
      +	extra_cast = SwigType_isclass(base);
      +	Delete(base);
      +      }
      +      if (extra_cast) {
      +	String *lstr;
      +	SwigType *ptype = Copy(type);
      +	SwigType_add_pointer(ptype);
      +	lstr = SwigType_lstr(ptype, 0);
      +	Printf(func, "if (%s) *(%s)&%s%s = %s", pname0, lstr, self, name, dref);
      +	Delete(lstr);
      +	Delete(ptype);
      +      } else {
      +        Printf(func, "if (%s) %s%s = %s", pname0, self, name, dref);
      +      }
             Delete(dref);
           } else {
             Printf(func, "if (%s && sizeof(int) == sizeof(%s%s)) *(int*)(void*)&(%s%s) = %s", pname0, self, name, self, name, pname1);
      
      From 3b4d33131096949e5dc3800a96760e096555db6b Mon Sep 17 00:00:00 2001
      From: William S Fulton 
      Date: Thu, 12 Dec 2013 08:23:56 +0000
      Subject: [PATCH 236/481] Add missing header to new source file
      
      ---
       Source/Modules/nested.cxx | 13 +++++++++++++
       1 file changed, 13 insertions(+)
      
      diff --git a/Source/Modules/nested.cxx b/Source/Modules/nested.cxx
      index 4be27ebc4..ff563b3ba 100644
      --- a/Source/Modules/nested.cxx
      +++ b/Source/Modules/nested.cxx
      @@ -1,3 +1,16 @@
      +/* -----------------------------------------------------------------------------
      + * 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.
      + *
      + * nested.cxx
      + *
      + * Nested structs support
      + * ----------------------------------------------------------------------------- */
      +
       #include "swigmod.h"
       #include "cparse.h"
       
      
      From 2121e1217eae19a0a3e852fc52c89f55faf7e20a Mon Sep 17 00:00:00 2001
      From: William S Fulton 
      Date: Thu, 12 Dec 2013 20:44:08 +0000
      Subject: [PATCH 237/481] Ensure -c++out is not used with -c++
      
      Error checking for this combination implemented as well as correcting
      Octave
      
      Also refactor, replacing CPlusPlusOut variable with cparse_cplusplusout
      for an implementation which more closely resembles cparse_cplusplus which
      is also required in both .c and .cxx files.
      ---
       Source/CParse/cparse.h    |  2 ++
       Source/CParse/cscanner.c  | 11 +++++++++++
       Source/CParse/parser.y    |  5 ++---
       Source/Modules/main.cxx   | 12 +++++++-----
       Source/Modules/nested.cxx |  2 +-
       Source/Modules/octave.cxx |  6 +++++-
       Source/Modules/swigmod.h  |  1 -
       Source/Swig/cwrap.c       |  5 ++---
       8 files changed, 30 insertions(+), 14 deletions(-)
      
      diff --git a/Source/CParse/cparse.h b/Source/CParse/cparse.h
      index 19bf3f3f0..6d7342a45 100644
      --- a/Source/CParse/cparse.h
      +++ b/Source/CParse/cparse.h
      @@ -25,9 +25,11 @@ extern "C" {
         extern String *cparse_file;
         extern int cparse_line;
         extern int cparse_cplusplus;
      +  extern int cparse_cplusplusout;
         extern int cparse_start_line;
       
         extern void Swig_cparse_cplusplus(int);
      +  extern void Swig_cparse_cplusplusout(int);
         extern void scanner_file(File *);
         extern void scanner_next_token(int);
         extern void skip_balanced(int startchar, int endchar);
      diff --git a/Source/CParse/cscanner.c b/Source/CParse/cscanner.c
      index ee2c49cd4..2dfc2c479 100644
      --- a/Source/CParse/cscanner.c
      +++ b/Source/CParse/cscanner.c
      @@ -37,6 +37,9 @@ int     cparse_start_line = 0;
       /* C++ mode */
       int cparse_cplusplus = 0;
       
      +/* Generate C++ compatible code when wrapping C code */
      +int cparse_cplusplusout = 0;
      +
       /* Private vars */
       static int scan_init = 0;
       static int num_brace = 0;
      @@ -52,6 +55,14 @@ void Swig_cparse_cplusplus(int v) {
         cparse_cplusplus = v;
       }
       
      +/* -----------------------------------------------------------------------------
      + * Swig_cparse_cplusplusout()
      + * ----------------------------------------------------------------------------- */
      +
      +void Swig_cparse_cplusplusout(int v) {
      +  cparse_cplusplusout = v;
      +}
      +
       /* ----------------------------------------------------------------------------
        * scanner_init()
        *
      diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y
      index 8e34833e2..9b1cec387 100644
      --- a/Source/CParse/parser.y
      +++ b/Source/CParse/parser.y
      @@ -59,7 +59,6 @@ static int      extendmode   = 0;
       static int      compact_default_args = 0;
       static int      template_reduce = 0;
       static int      cparse_externc = 0;
      -extern int CPlusPlusOut;
       
       /* -----------------------------------------------------------------------------
        *                            Assist Functions
      @@ -3446,7 +3445,7 @@ cpp_class_decl  : storage_class cpptype idcolon inherit LBRACE {
       		   Delete(prefix);
       		   inclass = 1;
       		   currentOuterClass = $$;
      -		   if (CPlusPlusOut) {
      +		   if (cparse_cplusplusout) {
       		     /* save the structure declaration to declare it in global scope for C++ to see */
       		     code = get_raw_text_balanced('{', '}');
       		     Setattr($$, "code", code);
      @@ -3577,7 +3576,7 @@ cpp_class_decl  : storage_class cpptype idcolon inherit LBRACE {
       		       Namespaceprefix = Swig_symbol_qualifiedscopename(0);
       		       yyrename = Copy(Getattr($$, "class_rename"));
       		       add_symbols($$);
      -		       if (!CPlusPlusOut)
      +		       if (!cparse_cplusplusout)
       			 Delattr($$, "nested:outer");
       		       Delattr($$, "class_rename");
       		       $$ = 0;
      diff --git a/Source/Modules/main.cxx b/Source/Modules/main.cxx
      index aa7e83ef8..f3aff2349 100644
      --- a/Source/Modules/main.cxx
      +++ b/Source/Modules/main.cxx
      @@ -29,10 +29,6 @@
       
       static Language *lang = 0;	// Language method
       int CPlusPlus = 0;
      -extern "C"
      -{
      -  int CPlusPlusOut = 0;		// Generate C++ compatible code when wrapping C code
      -}
       int Extend = 0;			// Extend flag
       int ForceExtern = 0;		// Force extern mode
       int GenerateDefault = 1;	// Generate default constructors
      @@ -488,7 +484,8 @@ void SWIG_getoptions(int argc, char *argv[]) {
       	Swig_cparse_cplusplus(1);
       	Swig_mark_arg(i);
             } else if (strcmp(argv[i], "-c++out") == 0) {
      -	CPlusPlusOut = 1;
      +	// Undocumented
      +	Swig_cparse_cplusplusout(1);
       	Swig_mark_arg(i);
             } else if (strcmp(argv[i], "-fcompact") == 0) {
       	Wrapper_compact_print_mode_set(1);
      @@ -955,6 +952,11 @@ int SWIG_main(int argc, char *argv[], Language *l) {
         // Don't check for an input file if -external-runtime is passed
         Swig_check_options(external_runtime ? 0 : 1);
       
      +  if (CPlusPlus && cparse_cplusplusout) {
      +    Printf(stderr, "The -c++out option is for C input but C++ input has been requested via -c++\n");
      +    SWIG_exit(EXIT_FAILURE);
      +  }
      +
         install_opts(argc, argv);
       
         // Add language dependent directory to the search path
      diff --git a/Source/Modules/nested.cxx b/Source/Modules/nested.cxx
      index ff563b3ba..a62a9e9da 100644
      --- a/Source/Modules/nested.cxx
      +++ b/Source/Modules/nested.cxx
      @@ -400,7 +400,7 @@ void Swig_nested_name_unnamed_c_structs(Node *n) {
       	c = next;
       	continue;
             }
      -    } else if (CPlusPlusOut) {
      +    } else if (cparse_cplusplusout) {
             if (Getattr(c, "nested:outer")) {
       	Node *ins = create_insert(c, true);
       	insertNodeAfter(c, ins);
      diff --git a/Source/Modules/octave.cxx b/Source/Modules/octave.cxx
      index 1c0192d07..14118972d 100644
      --- a/Source/Modules/octave.cxx
      +++ b/Source/Modules/octave.cxx
      @@ -12,6 +12,7 @@
        * ----------------------------------------------------------------------------- */
       
       #include "swigmod.h"
      +#include "cparse.h"
       
       static String *global_name = 0;
       static String *op_prefix   = 0;
      @@ -86,7 +87,6 @@ public:
            director_multiple_inheritance = 1;
            director_language = 1;
            docs = NewHash();
      -     CPlusPlusOut = 1;
          }
       
         virtual void main(int argc, char *argv[]) {
      @@ -133,6 +133,10 @@ public:
           SWIG_config_file("octave.swg");
           SWIG_typemap_lang("octave");
           allow_overloading();
      +
      +    // Octave API is C++, so output must be C++ compatibile even when wrapping C code
      +    if (!cparse_cplusplus)
      +      Swig_cparse_cplusplusout(1);
         }
       
         virtual int top(Node *n) {
      diff --git a/Source/Modules/swigmod.h b/Source/Modules/swigmod.h
      index 41ef44e41..9e76b4d10 100644
      --- a/Source/Modules/swigmod.h
      +++ b/Source/Modules/swigmod.h
      @@ -32,7 +32,6 @@ extern String *input_file;
       extern int line_number;
       extern int start_line;
       extern int CPlusPlus;		// C++ mode
      -extern "C" int CPlusPlusOut;	// generate C++ declarations for C code (currently used for Octave)
       extern int Extend;		// Extend mode
       extern int Verbose;
       extern int IsVirtual;
      diff --git a/Source/Swig/cwrap.c b/Source/Swig/cwrap.c
      index 03020bb72..04845f3cf 100644
      --- a/Source/Swig/cwrap.c
      +++ b/Source/Swig/cwrap.c
      @@ -13,9 +13,8 @@
        * ----------------------------------------------------------------------------- */
       
       #include "swig.h"
      +#include "cparse.h"
       
      -extern int cparse_cplusplus;
      -extern int CPlusPlusOut;
       static const char *cresult_variable_name = "result";
       
       static Parm *nonvoid_parms(Parm *p) {
      @@ -777,7 +776,7 @@ String *Swig_cmemberset_call(const_String_or_char_ptr name, SwigType *type, Stri
           if (!Strstr(type, "enum $unnamed")) {
             String *dref = Swig_wrapped_var_deref(type, pname1, varcref);
             int extra_cast = 0;
      -      if (CPlusPlusOut) {
      +      if (cparse_cplusplusout) {
       	/* Required for C nested structs compiled as C++ as a duplicate of the nested struct is put into the global namespace.
       	 * We could improve this by adding the extra casts just for nested structs rather than all structs. */
       	String *base = SwigType_base(type);
      
      From c256dd140b8a1de1262a57981639d1c56fa93b6f Mon Sep 17 00:00:00 2001
      From: William S Fulton 
      Date: Thu, 12 Dec 2013 20:58:10 +0000
      Subject: [PATCH 238/481] Add check-c and check-cpp targets for running just C
       and C++ test cases
      
      ---
       Examples/test-suite/common.mk | 4 ++++
       1 file changed, 4 insertions(+)
      
      diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk
      index e9caaedab..c65fd7901 100644
      --- a/Examples/test-suite/common.mk
      +++ b/Examples/test-suite/common.mk
      @@ -638,6 +638,10 @@ all:	$(NOT_BROKEN_TEST_CASES) $(BROKEN_TEST_CASES)
       
       check: 	$(NOT_BROKEN_TEST_CASES)
       
      +check-c: $(C_TEST_CASES:=.ctest)
      +
      +check-cpp: $(CPP_TEST_CASES:=.cpptest)
      +
       check-cpp11: $(CPP11_TEST_CASES:=.cpptest)
       
       # partialcheck target runs SWIG only, ie no compilation or running of tests (for a subset of languages)
      
      From fb103f8db46477e6d0285f83449b73c2a2c75810 Mon Sep 17 00:00:00 2001
      From: William S Fulton 
      Date: Thu, 12 Dec 2013 21:23:49 +0000
      Subject: [PATCH 239/481] Minor expansion of nested C structs testing
      
      ---
       Examples/test-suite/nested_structs.i | 6 ++++--
       1 file changed, 4 insertions(+), 2 deletions(-)
      
      diff --git a/Examples/test-suite/nested_structs.i b/Examples/test-suite/nested_structs.i
      index 60e34a638..c15623085 100644
      --- a/Examples/test-suite/nested_structs.i
      +++ b/Examples/test-suite/nested_structs.i
      @@ -5,10 +5,10 @@
       struct Outer {
         struct {
           int val;
      -  } inner1, inner2, *inner3, inner4[1];
      +  } inner1, inner2, *inner3, inner4[1], **inner5;
         struct Named {
           int val;
      -  } inside1, inside2, *inside3, inside4[1];
      +  } inside1, inside2, *inside3, inside4[1], **inside5;
       } outer;
       
       void setValues(struct Outer *outer, int val) {
      @@ -16,12 +16,14 @@ void setValues(struct Outer *outer, int val) {
         outer->inner2.val = val * 2;
         outer->inner3 = &outer->inner2;
         outer->inner4[0].val = val * 4;
      +  outer->inner5 = &outer->inner3;
       
         val = val * 10;
         outer->inside1.val = val;
         outer->inside2.val = val * 2;
         outer->inside3 = &outer->inside2;
         outer->inside4[0].val = val * 4;
      +  outer->inside5 = &outer->inside3;
       }
       %}
       
      
      From 0f4ceaf5923fd9a30eb9201048cd285a9bba8084 Mon Sep 17 00:00:00 2001
      From: William S Fulton 
      Date: Fri, 13 Dec 2013 08:11:17 +0000
      Subject: [PATCH 240/481] Deprecation of the 'nestedworkaround' feature
      
      Also add in macros for the flatnested feature which can be used in place
      of the nestedworkaround feature
      ---
       Doc/Manual/SWIGPlus.html  | 26 +++++++++++++++++++++-----
       Doc/Manual/Warnings.html  |  1 +
       Lib/swig.swg              |  9 +++++++--
       Source/CParse/parser.y    |  4 ++++
       Source/Include/swigwarn.h |  1 +
       5 files changed, 34 insertions(+), 7 deletions(-)
      
      diff --git a/Doc/Manual/SWIGPlus.html b/Doc/Manual/SWIGPlus.html
      index 2ec98f33a..20c03cc71 100644
      --- a/Doc/Manual/SWIGPlus.html
      +++ b/Doc/Manual/SWIGPlus.html
      @@ -4992,11 +4992,27 @@ class Bar {
       
       

      Compatibility Note: -In SWIG 2.0 and earlier, nested classes were treated as opaque pointers. -Also there was a workaround, implementing approximately the same behaviour as the -%feature ("flatnested") with an additional help from the user: -nested class had to be manually redeclared in the global scope, typedef name and %feature nestedworkaround -added for the inner class. +Prior to SWIG-3.0.0, there was limited nested class support. Nested classes were treated as opaque pointers. +However, there was a workaround for nested class support in these older versions requiring the user to replicate +the nested class in the global scope, adding in a typedef for the nested class in the global scope and +using the "nestedworkaround" feature on the nested class. This resulted in approximately the +same behaviour as the "flatnested" feature. With proper nested class support now available in SWIG-3.0.0, this +feature has been deprecated and no longer works requiring code changes. If you see the following warning: +

      + +
      +
      +example.i:8: Warning 126: The nestedworkaround feature is deprecated
      +
      +
      + +

      +consider using the "flatnested" feature discussed above which generates a non-nested proxy class, like the +"nestedworkaround" feature did. Alternatively, use the default nested class code generation, which may generate an +equivalent to a nested proxy class in the target language, depending on the target language support. +

      + +

      SWIG-1.3.40 and earlier versions did not have the nestedworkaround feature and the generated code resulting from parsing nested classes did not always compile. Nested class warnings could also not be suppressed using %warnfilter. diff --git a/Doc/Manual/Warnings.html b/Doc/Manual/Warnings.html index e0debe41c..b4d27872c 100644 --- a/Doc/Manual/Warnings.html +++ b/Doc/Manual/Warnings.html @@ -382,6 +382,7 @@ example.i(4) : Syntax error in input.

    • 119. Deprecated %typemap(ignore).
    • 120. Deprecated command line option (-runtime, -noruntime).
    • 121. Deprecated %name directive. +
    • 126. The 'nestedworkaround' feature is deprecated.

    14.9.2 Preprocessor (200-299)

    diff --git a/Lib/swig.swg b/Lib/swig.swg index a63169b3e..33e920c82 100644 --- a/Lib/swig.swg +++ b/Lib/swig.swg @@ -9,7 +9,7 @@ * User Directives * ----------------------------------------------------------------------------- */ -/* Deprecated SWIG directives */ +/* Deprecated SWIG-1.1 directives */ #define %disabledoc %warn "104:%disabledoc is deprecated" #define %enabledoc %warn "105:%enabledoc is deprecated" @@ -136,11 +136,16 @@ #define %nocallback %feature("callback","0") #define %clearcallback %feature("callback","") -/* the %nestedworkaround directive */ +/* the %nestedworkaround directive (deprecated) */ #define %nestedworkaround %feature("nestedworkaround") #define %nonestedworkaround %feature("nestedworkaround","0") #define %clearnestedworkaround %feature("nestedworkaround","") +/* the %flatnested directive */ +#define %flatnested %feature("flatnested") +#define %noflatnested %feature("flatnested","0") +#define %clearflatnested %feature("flatnested","") + /* the %fastdispatch directive */ #define %fastdispatch %feature("fastdispatch") #define %nofastdispatch %feature("fastdispatch","0") diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 9b1cec387..93ee9e3e1 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1080,6 +1080,10 @@ static void single_new_feature(const char *featurename, String *val, Hash *featu /* Printf(stdout, "single_new_feature: [%s] [%s] [%s] [%s] [%s] [%s]\n", featurename, val, declaratorid, t, ParmList_str_defaultargs(declaratorparms), qualifier); */ + /* Warn about deprecated features */ + if (strcmp(featurename, "nestedworkaround") == 0) + Swig_warning(WARN_DEPRECATED_NESTED_WORKAROUND, cparse_file, cparse_line, "The 'nestedworkaround' feature is deprecated.\n"); + fname = NewStringf("feature:%s",featurename); if (declaratorid) { fixname = feature_identifier_fix(declaratorid); diff --git a/Source/Include/swigwarn.h b/Source/Include/swigwarn.h index 7b535f748..ea1cf7fe4 100644 --- a/Source/Include/swigwarn.h +++ b/Source/Include/swigwarn.h @@ -52,6 +52,7 @@ #define WARN_DEPRECATED_NODEFAULT 123 #define WARN_DEPRECATED_TYPEMAP_LANG 124 #define WARN_DEPRECATED_INPUT_FILE 125 +#define WARN_DEPRECATED_NESTED_WORKAROUND 126 /* -- Preprocessor -- */ From 4cf5de797f15fa0c2a500cea12db7c9223f07fdc Mon Sep 17 00:00:00 2001 From: Ian Lance Taylor Date: Fri, 13 Dec 2013 11:56:31 -0800 Subject: [PATCH 241/481] Add comment with SWIG file name in files generated for Go. --- CHANGES.current | 4 ++++ Source/Modules/go.cxx | 10 ++++++++++ 2 files changed, 14 insertions(+) diff --git a/CHANGES.current b/CHANGES.current index 3df92ef33..f64d8f55a 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,10 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2013-12-13: iant + [Go] Add SWIG source file name as comments in generated + files. This can be used by Go documentation tools. + 2013-12-12: jleveque [Lua] Fix typo (wchar instead of wchar_t) which made wchar.i for Lua useless. diff --git a/Source/Modules/go.cxx b/Source/Modules/go.cxx index 52e2459b7..e5398ba7a 100644 --- a/Source/Modules/go.cxx +++ b/Source/Modules/go.cxx @@ -281,6 +281,7 @@ private: // Get filenames. + String *swig_filename = Getattr(n, "infile"); String *c_filename = Getattr(n, "outfile"); String *c_filename_h = Getattr(n, "outfile_h"); @@ -360,6 +361,11 @@ private: } Swig_banner(f_c_begin); + if (CPlusPlus) { + Printf(f_c_begin, "\n// source: %s\n\n", swig_filename); + } else { + Printf(f_c_begin, "\n/* source: %s */\n\n", swig_filename); + } Printf(f_c_runtime, "#define SWIGMODULE %s\n", module); @@ -367,6 +373,8 @@ private: Printf(f_c_runtime, "#define SWIG_DIRECTORS\n"); Swig_banner(f_c_directors_h); + Printf(f_c_directors_h, "\n// source: %s\n\n", swig_filename); + Printf(f_c_directors_h, "#ifndef SWIG_%s_WRAP_H_\n", module); Printf(f_c_directors_h, "#define SWIG_%s_WRAP_H_\n\n", module); @@ -377,9 +385,11 @@ private: } Swig_banner(f_go_begin); + Printf(f_go_begin, "\n// source: %s\n", swig_filename); if (!gccgo_flag) { 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); } From 66ebb2a7cb0b9f001a399ff7a4066dac0659f472 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 14 Dec 2013 15:13:59 +0000 Subject: [PATCH 242/481] Remove nested branch from Travis builds --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 7f868ae91..70cbb2f27 100644 --- a/.travis.yml +++ b/.travis.yml @@ -57,4 +57,3 @@ script: branches: only: - master - - nested From a1c17d585dfa831141b2c23e75f61cf232bf0d03 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 14 Dec 2013 22:35:02 +0000 Subject: [PATCH 243/481] Fix R unions seg fault Started seg faulting since nested branch merge --- Source/Modules/r.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/Modules/r.cxx b/Source/Modules/r.cxx index 8b3bc20bb..c3860a161 100644 --- a/Source/Modules/r.cxx +++ b/Source/Modules/r.cxx @@ -2299,7 +2299,7 @@ int R::classDeclaration(Node *n) { /* If we have a typedef union { ... } U, then we never get to see the typedef via a regular call to typedefHandler. Instead, */ - if(Getattr(n, "unnamed") && Strcmp(Getattr(n, "storage"), "typedef") == 0 + if(Getattr(n, "unnamed") && Getattr(n, "storage") && Strcmp(Getattr(n, "storage"), "typedef") == 0 && Getattr(n, "tdname") && Strcmp(Getattr(n, "tdname"), name) == 0) { if (debugMode) Printf(stdout, "Typedef in the class declaration for %s\n", name); From 0cf116128bd784bf9307c857b50405b4e5ee2efb Mon Sep 17 00:00:00 2001 From: Geert Janssens Date: Fri, 13 Dec 2013 16:32:13 +0100 Subject: [PATCH 244/481] Skip unsigned (long) long integer tests on OS X with guile 1.8 --- Examples/test-suite/schemerunme/integers.scm | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/Examples/test-suite/schemerunme/integers.scm b/Examples/test-suite/schemerunme/integers.scm index 903e6a9f1..7c03c3dd8 100644 --- a/Examples/test-suite/schemerunme/integers.scm +++ b/Examples/test-suite/schemerunme/integers.scm @@ -34,10 +34,16 @@ (check-range signed-int-identity signed-int-min signed-int-max) (check-range unsigned-int-identity 0 unsigned-int-max) (check-range signed-long-identity signed-long-min signed-long-max) - (check-range unsigned-long-identity 0 unsigned-long-max) - ;;; long long not implemented in Guile and MzScheme. (check-range signed-long-long-identity signed-long-long-min signed-long-long-max) - (check-range unsigned-long-long-identity 0 unsigned-long-long-max) + + ;;; unsigned (long) long is broken in guile 1.8 on Mac OS X, skip test + (if (or (>= (string->number (major-version)) 2) + (not (equal? (utsname:sysname (uname)) "Darwin"))) + (begin + (check-range unsigned-long-identity 0 unsigned-long-max) + (check-range unsigned-long-long-identity 0 unsigned-long-long-max)) + ) + ) (exit 0) From 865408874f3b6a392fe5fda7d5102deeb53ade06 Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Mon, 16 Dec 2013 11:43:28 +0400 Subject: [PATCH 245/481] fixed %template declared within class, next to template declaration added a few tests for C# nested classes support --- .../test-suite/csharp/nested_class_runme.cs | 66 +++++++++++++++++++ .../test-suite/csharp/nested_structs_runme.cs | 28 ++++++++ .../csharp/nested_workaround_runme.cs | 23 +++++++ .../csharp/template_nested_runme.cs | 25 +++++++ .../test-suite/java/derived_nested_runme.java | 22 +++++++ Source/CParse/parser.y | 9 ++- 6 files changed, 172 insertions(+), 1 deletion(-) create mode 100644 Examples/test-suite/csharp/nested_class_runme.cs create mode 100644 Examples/test-suite/csharp/nested_structs_runme.cs create mode 100644 Examples/test-suite/csharp/nested_workaround_runme.cs create mode 100644 Examples/test-suite/csharp/template_nested_runme.cs create mode 100644 Examples/test-suite/java/derived_nested_runme.java diff --git a/Examples/test-suite/csharp/nested_class_runme.cs b/Examples/test-suite/csharp/nested_class_runme.cs new file mode 100644 index 000000000..c94537bbf --- /dev/null +++ b/Examples/test-suite/csharp/nested_class_runme.cs @@ -0,0 +1,66 @@ +using System; +using nested_classNamespace; +#pragma warning disable 219 + +public class runme { + static void Main() { + + Outer outer = new Outer(); + outer.a = 1; + outer.b = 2; + Outer.InnerStruct1 is1 = outer.makeInnerStruct1(); + Outer.InnerClass1 ic1 = outer.makeInnerClass1(); + Outer.InnerUnion1 iu1 = outer.makeInnerUnion1(); + + Outer.InnerStruct2 is2 = outer.makeInnerStruct2(); + Outer.InnerClass2 ic2 = outer.makeInnerClass2(); + Outer.InnerUnion2 iu2 = outer.makeInnerUnion2(); + + Outer.InnerClass4Typedef ic4 = outer.makeInnerClass4Typedef(); + Outer.InnerStruct4Typedef is4 = outer.makeInnerStruct4Typedef(); + Outer.InnerUnion4Typedef iu4 = outer.makeInnerUnion4Typedef(); + + Outer.InnerClass5Typedef ic5 = outer.makeInnerClass5(); + Outer.InnerStruct5Typedef is5 = outer.makeInnerStruct5(); + Outer.InnerUnion5Typedef iu5 = outer.makeInnerUnion5(); + + ic5 = outer.makeInnerClass5Typedef(); + is5 = outer.makeInnerStruct5Typedef(); + iu5 = outer.makeInnerUnion5Typedef(); + + { + Outer.InnerMultiple im1 = outer.MultipleInstance1; + Outer.InnerMultiple im2 = outer.MultipleInstance2; + Outer.InnerMultiple im3 = outer.MultipleInstance3; + Outer.InnerMultiple im4 = outer.MultipleInstance4; + } + + { + Outer.InnerMultipleDerived im1 = outer.MultipleDerivedInstance1; + Outer.InnerMultipleDerived im2 = outer.MultipleDerivedInstance2; + Outer.InnerMultipleDerived im3 = outer.MultipleDerivedInstance3; + Outer.InnerMultipleDerived im4 = outer.MultipleDerivedInstance4; + } + + { + Outer.InnerMultipleDerived im1 = outer.MultipleDerivedInstance1; + Outer.InnerMultipleDerived im2 = outer.MultipleDerivedInstance2; + Outer.InnerMultipleDerived im3 = outer.MultipleDerivedInstance3; + Outer.InnerMultipleDerived im4 = outer.MultipleDerivedInstance4; + } + + { + Outer.InnerMultipleAnonTypedef1 mat1 = outer.makeInnerMultipleAnonTypedef1(); + Outer.InnerMultipleAnonTypedef1 mat2 = outer.makeInnerMultipleAnonTypedef2(); + SWIGTYPE_p_p_Outer__InnerMultipleAnonTypedef1 mat3 = outer.makeInnerMultipleAnonTypedef3(); + + Outer.InnerMultipleNamedTypedef1 mnt = outer.makeInnerMultipleNamedTypedef(); + Outer.InnerMultipleNamedTypedef1 mnt1 = outer.makeInnerMultipleNamedTypedef1(); + Outer.InnerMultipleNamedTypedef1 mnt2 = outer.makeInnerMultipleNamedTypedef2(); + SWIGTYPE_p_p_Outer__InnerMultipleNamedTypedef mnt3 = outer.makeInnerMultipleNamedTypedef3(); + } + { + Outer.InnerSameName isn = outer.makeInnerSameName(); + } + } +} diff --git a/Examples/test-suite/csharp/nested_structs_runme.cs b/Examples/test-suite/csharp/nested_structs_runme.cs new file mode 100644 index 000000000..ffe2cb71b --- /dev/null +++ b/Examples/test-suite/csharp/nested_structs_runme.cs @@ -0,0 +1,28 @@ +using System; +using nested_structsNamespace; +#pragma warning disable 219 + +public class runme { + static void Main() { + Outer outer = new Outer(); + nested_structs.setValues(outer, 10); + + Outer_inner1 inner1 = outer.inner1; + Outer_inner1 inner2 = outer.inner2; + Outer_inner1 inner3 = outer.inner3; + Outer_inner1 inner4 = outer.inner4; + if (inner1.val != 10) throw new Exception("failed inner1"); + if (inner2.val != 20) throw new Exception("failed inner2"); + if (inner3.val != 20) throw new Exception("failed inner3"); + if (inner4.val != 40) throw new Exception("failed inner4"); + + Named inside1 = outer.inside1; + Named inside2 = outer.inside2; + Named inside3 = outer.inside3; + Named inside4 = outer.inside4; + if (inside1.val != 100) throw new Exception("failed inside1"); + if (inside2.val != 200) throw new Exception("failed inside2"); + if (inside3.val != 200) throw new Exception("failed inside3"); + if (inside4.val != 400) throw new Exception("failed inside4"); + } +} diff --git a/Examples/test-suite/csharp/nested_workaround_runme.cs b/Examples/test-suite/csharp/nested_workaround_runme.cs new file mode 100644 index 000000000..12d474bd7 --- /dev/null +++ b/Examples/test-suite/csharp/nested_workaround_runme.cs @@ -0,0 +1,23 @@ +using System; +using nested_workaroundNamespace; +#pragma warning disable 219 + +public class runme { + static void Main() { + { + Inner inner = new Inner(5); + Outer outer = new Outer(); + Inner newInner = outer.doubleInnerValue(inner); + if (newInner.getValue() != 10) + throw new Exception("inner failed"); + } + + { + Outer outer = new Outer(); + Inner inner = outer.createInner(3); + Inner newInner = outer.doubleInnerValue(inner); + if (outer.getInnerValue(newInner) != 6) + throw new Exception("inner failed"); + } + } +} diff --git a/Examples/test-suite/csharp/template_nested_runme.cs b/Examples/test-suite/csharp/template_nested_runme.cs new file mode 100644 index 000000000..edf4b76cf --- /dev/null +++ b/Examples/test-suite/csharp/template_nested_runme.cs @@ -0,0 +1,25 @@ +using System; +using template_nestedNamespace; +#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"); + OuterClass.T_OuterClassInner1Int inner1 = new OuterClass().useInner1(new OuterClass.T_OuterClassInner1Int()); + OuterClass.T_OuterClassInner2NormalClass inner2 = new OuterClass.T_OuterClassInner2NormalClass(); + inner2.embeddedVar = 2; + OuterClass.T_OuterClassInner2NormalClass inner22 = new OuterClass().useInner2Again(inner2); + } +} + diff --git a/Examples/test-suite/java/derived_nested_runme.java b/Examples/test-suite/java/derived_nested_runme.java new file mode 100644 index 000000000..1a9c62416 --- /dev/null +++ b/Examples/test-suite/java/derived_nested_runme.java @@ -0,0 +1,22 @@ + +import derived_nested.*; + +public class derived_nested_runme { + + static { + try { + System.loadLibrary("derived_nested"); + } 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[]) { + BB outer = new BB(); + BB.DD d = new BB.DD(); + BB.EE e = new BB.EE(); + outer.getFf_instance().setZ(outer.getFf_instance().getX()); + outer.useEE(e); + } +} \ No newline at end of file diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 203284402..d2fa06f72 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -146,6 +146,10 @@ static Node *copy_node(Node *n) { Delete(pl); continue; } + if (strcmp(ckey,"nested:outer") == 0) { /* don't copy outer classes links, they will be updated later */ + Setattr(nn, key, k.item); + continue; + } /* Looks okay. Just copy the data using Copy */ ci = Copy(k.item); Setattr(nn, key, ci); @@ -2662,7 +2666,7 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va } templnode = copy_node(nn); - update_nested_classes(templnode); + update_nested_classes(templnode); /* update classes nested withing template */ /* We need to set the node name based on name used to instantiate */ Setattr(templnode,"name",tname); Delete(tname); @@ -2698,7 +2702,10 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va Delete(temparms); if (currentOuterClass) { SetFlag(templnode, "nested"); + Setattr(templnode, "nested:outer", currentOuterClass); } + else + Delattr(templnode, "nested:outer"); add_symbols_copy(templnode); From 5487345ce7ff484f9313e1ae6e65d754c47f1efa Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Mon, 16 Dec 2013 13:08:34 +0400 Subject: [PATCH 246/481] properly disabled nested %template declared in other scopes --- Source/CParse/parser.y | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index d2fa06f72..ef5aa6ef4 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -2675,7 +2675,8 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va } else { Setattr(templnode,"sym:typename","1"); } - if ($3) { + /* for now, nested %template is allowed only in the same scope as the template declaration */ + if ($3 && !(currentOuterClass && (currentOuterClass != Getattr(nn, "nested:outer")))) { /* Comment this out for 1.3.28. We need to re-enable it later but first we need to @@ -2694,6 +2695,9 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va Setattr(templnode,"sym:name",nname); Delete(nname); Setattr(templnode,"feature:onlychildren", "typemap,typemapitem,typemapcopy,typedef,types,fragment"); + if ($3) { + Swig_warning(WARN_PARSE_NESTED_TEMPLATE, cparse_file, cparse_line, "Named nested template instantiations not supported. Processing as if no name was given to %%template().\n"); + } } Delattr(templnode,"templatetype"); Setattr(templnode,"template",nn); @@ -2704,9 +2708,6 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va SetFlag(templnode, "nested"); Setattr(templnode, "nested:outer", currentOuterClass); } - else - Delattr(templnode, "nested:outer"); - add_symbols_copy(templnode); if (Strcmp(nodeType(templnode),"class") == 0) { From 39bf2efdc980f800219cb488c24eef3ef6be5c5c Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 16 Dec 2013 19:28:11 +0000 Subject: [PATCH 247/481] Revert template_nested_typemaps to what it was before nested merge The breaks were fixed in the last couple of commits --- Examples/test-suite/template_nested_typemaps.i | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Examples/test-suite/template_nested_typemaps.i b/Examples/test-suite/template_nested_typemaps.i index b40e7e291..54f5bc503 100644 --- a/Examples/test-suite/template_nested_typemaps.i +++ b/Examples/test-suite/template_nested_typemaps.i @@ -4,22 +4,18 @@ // Testing that the typemaps invoked within a class via %template are picked up by appropriate methods -%inline %{ template struct Typemap { -#ifdef SWIG %typemap(in) T { $1 = -99; } -#endif }; template <> struct Typemap { // Note explicit specialization -#ifdef SWIG %typemap(in) short { $1 = -77; } -#endif }; +%inline %{ int globalInt1(int s) { return s; } short globalShort1(short s) { return s; } From 1dca0af0241475c11a842e4dd4c16ff7b367a962 Mon Sep 17 00:00:00 2001 From: Ian Lance Taylor Date: Mon, 16 Dec 2013 19:50:17 -0800 Subject: [PATCH 248/481] Update for Go 1.2 release. Add support for linking SWIG code directly into executable, rather than using a shared library. --- CHANGES.current | 5 + Doc/Manual/Go.html | 67 ++- Examples/Makefile.in | 60 ++- Examples/go/callback/Makefile | 4 +- .../go/callback/{example.cxx => callback.cxx} | 0 Examples/go/class/Makefile | 4 +- Examples/go/class/{example.cxx => class.cxx} | 0 Examples/go/constants/Makefile | 2 +- Examples/go/enum/Makefile | 4 +- Examples/go/enum/{example.cxx => enum.cxx} | 0 Examples/go/extend/Makefile | 4 +- .../go/extend/{example.cxx => extend.cxx} | 0 Examples/go/funcptr/Makefile | 4 +- Examples/go/funcptr/{example.c => funcptr.c} | 0 Examples/go/multimap/Makefile | 4 +- .../go/multimap/{example.c => multimap.c} | 0 Examples/go/pointer/Makefile | 4 +- Examples/go/pointer/{example.c => pointer.c} | 0 Examples/go/reference/Makefile | 4 +- .../reference/{example.cxx => reference.cxx} | 0 Examples/go/simple/Makefile | 4 +- Examples/go/simple/{example.c => simple.c} | 0 Examples/go/template/Makefile | 2 +- Examples/go/variables/Makefile | 4 +- .../go/variables/{example.c => variables.c} | 0 Examples/test-suite/go/Makefile.in | 24 +- .../test-suite/go/director_abstract_runme.go | 62 --- .../test-suite/go/director_thread_runme.go | 28 -- .../go/template_typedef_import_runme.go | 29 -- Lib/go/cdata.i | 6 +- Source/Modules/go.cxx | 418 +++++++++--------- configure.ac | 13 + 32 files changed, 385 insertions(+), 371 deletions(-) rename Examples/go/callback/{example.cxx => callback.cxx} (100%) rename Examples/go/class/{example.cxx => class.cxx} (100%) rename Examples/go/enum/{example.cxx => enum.cxx} (100%) rename Examples/go/extend/{example.cxx => extend.cxx} (100%) rename Examples/go/funcptr/{example.c => funcptr.c} (100%) rename Examples/go/multimap/{example.c => multimap.c} (100%) rename Examples/go/pointer/{example.c => pointer.c} (100%) rename Examples/go/reference/{example.cxx => reference.cxx} (100%) rename Examples/go/simple/{example.c => simple.c} (100%) rename Examples/go/variables/{example.c => variables.c} (100%) delete mode 100644 Examples/test-suite/go/director_abstract_runme.go delete mode 100644 Examples/test-suite/go/director_thread_runme.go delete mode 100644 Examples/test-suite/go/template_typedef_import_runme.go diff --git a/CHANGES.current b/CHANGES.current index f64d8f55a..21c97407d 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,11 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2013-12-16: iant + [Go] Update for Go 1.2 release. Add support for linking + SWIG code directly into executable, rather than using a + shared library. + 2013-12-13: iant [Go] Add SWIG source file name as comments in generated files. This can be used by Go documentation tools. diff --git a/Doc/Manual/Go.html b/Doc/Manual/Go.html index 7a55a4364..3482d34dc 100644 --- a/Doc/Manual/Go.html +++ b/Doc/Manual/Go.html @@ -55,7 +55,7 @@ there is no convenient way to call C++ code. SWIG fills this gap.

    There are (at least) two different Go compilers. One is the gc -compiler, normally invoked under the names 6g, 8g, or 5g. The other +compiler, normally invoked under via the go tool. The other 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. SWIG supports both, selected by a command line option. @@ -80,7 +80,7 @@ code for gccgo, you should also use the -gccgo option.

    -These are the command line options for SWIG's GO module. They can +These are the command line options for SWIG's Go module. They can also be seen by using:

    @@ -108,7 +108,7 @@ swig -go -help -gccgo Generate code for gccgo. The default is to generate code for - 6g/8g/5g. + the gc compiler. @@ -117,13 +117,21 @@ swig -go -help package name is the SWIG module name. + +-use-shlib +Tell SWIG to emit code that uses a shared library. This is only + meaningful for the gc compiler, which needs to know at compile time + whether a shared library will be used. + + -soname %lt;name%gt; Set the runtime name of the shared library that the dynamic linker should include at runtime. The default is the package name with ".so" appended. This is only used when generating code for - 6g/8g/5g; when using gccgo, the equivalent name will be taken from - the -soname option passed to the linker. + the gc compiler; when using gccgo, the equivalent name will be taken from + the -soname option passed to the linker. Using this + option implies the -use-shlib option. @@ -165,25 +173,56 @@ may be helpful to include it in your code, compiled with the usual C or C++ compiler.
  • If using the gc compiler, MODULE_gc.c will contain C code which should -be compiled with the C compiler distributed as part of the gc compiler: 6c, 8c, -or 5c. It should then be combined with the compiled MODULE.go using -gopack. This file will not be generated when using gccgo. +be compiled with the C compiler distributed as part of the gc +compiler. It should then be combined with the compiled MODULE.go +using gopack. This file will not be generated when using gccgo.

    -A typical command sequence would look like this: +Most Go programs are built using the go tool. The go tool has limited +support for SWIG. To use it, put your SWIG interface into a file with +the extension .swig, or, if you are wrapping C++ code, .swigcxx. Put +that file in a GOPATH/src directory as usual for Go sources. Put +other interface code in the same directory with extensions of .c and +.cxx. The go build command and go install commands will automatically +run SWIG for you and will build the interface code. +

    + +

    +You can also use SWIG directly yourself. When using the gc compiler +version 1.2 or later, or when using gccgo, the code generated by SWIG +can be linked directly into the Go program. A typical command +sequence when using the gc compiler would look like this:

     % swig -go 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 gc compiler before version 1.2 this is the only supported +option. A typical command sequence for this approach would look like +this: +

    + +
    +% swig -go -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
    -% 6g example.go
    -% 6c example_gc.c
    -% gopack grc example.a example.6 example_gc.6
    -% 6g main.go  # your code, not generated by SWIG
    -% 6l main.6
    +% 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
     

    22.3 A tour of basic C/C++ wrapping

    diff --git a/Examples/Makefile.in b/Examples/Makefile.in index b986774b6..0169f26a7 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -1555,6 +1555,7 @@ r_clean: GO = @GO@ GOGCC = @GOGCC@ GO1 = @GO1@ +GO12 = @GO12@ GOC = @GOC@ GOOPT = @GOOPT@ GOVERSIONOPTION = @GOVERSIONOPTION@ @@ -1576,41 +1577,76 @@ GOGCOBJS = $(GOSRCS:.go=.$(GOOBJEXT)) GOGCCOBJS = $(GOSRCS:.go=.@OBJEXT@) # ---------------------------------------------------------------- -# Build a Go dynamically loadable module (C) +# Build a Go module (C) # ---------------------------------------------------------------- go: $(SRCS) $(SWIG) -go $(GOOPT) $(GOSWIGARG) $(SWIGOPT) $(INTERFACEPATH) - $(CC) -g -c $(CCSHARED) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + if $(GO12) || $(GOGCC); then \ + $(CC) -g -c $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES); \ + else \ + $(CC) -g -c $(CCSHARED) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES); \ + $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO); \ + fi $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(GOSRCS) if ! $(GOGCC) ; then \ - $(COMPILETOOL) $(GOTOOL) $(GOC) -I $${GOROOT}/pkg/$${GOOS}_$${GOARCH} $(GOCSRCS) && \ - $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)); \ + $(COMPILETOOL) $(GOTOOL) $(GOC) -I $${GOROOT}/pkg/$${GOOS}_$${GOARCH} $(GOCSRCS); \ + rm -f $(GOPACKAGE); \ + if $(GO12); then \ + $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)) $(OBJS) $(IOBJS); \ + else \ + $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)); \ + fi; \ fi # ---------------------------------------------------------------- -# Build a Go dynamically loadable module (C++) +# Build a Go module (C++) # ---------------------------------------------------------------- go_cpp: $(SRCS) $(SWIG) -go -c++ $(GOOPT) $(GOSWIGARG) $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -g -c $(CCSHARED) $(CXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) - $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + if $(GO12) || $(GOGCC); then \ + $(CXX) -g -c $(CXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES); \ + else \ + $(CXX) -g -c $(CCSHARED) $(CXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES); \ + $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO); \ + fi $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(GOSRCS) if ! $(GOGCC) ; then \ - $(COMPILETOOL) $(GOTOOL) $(GOC) -I $${GOROOT}/pkg/$${GOOS}_$${GOARCH} $(GOCSRCS) && \ - $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)); \ + $(COMPILETOOL) $(GOTOOL) $(GOC) -I $${GOROOT}/pkg/$${GOOS}_$${GOARCH} $(GOCSRCS); \ + rm -f $(GOPACKAGE); \ + if $(GO12); then \ + $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)) $(OBJS) $(IOBJS); \ + else \ + $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)); \ + fi; \ fi # ----------------------------------------------------------------- -# Running a Go example +# Running a Go example (C) # ----------------------------------------------------------------- go_run: runme.go $(GO) $(GOCOMPILEARG) runme.go if $(GOGCC) ; then \ - $(COMPILETOOL) $(GO) -o runme runme.@OBJEXT@ $(GOGCCOBJS) $(LIBPREFIX)$(TARGET)$(SO); \ + $(COMPILETOOL) $(GO) -o runme runme.@OBJEXT@ $(GOGCCOBJS) $(OBJS) $(IOBJS); \ + elif $(GO12); then \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CC) -extldflags "$(CFLAGS)" -o runme runme.$(GOOBJEXT); \ + else \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT}/pkg/$${GOOS}_$${GOARCH}:. -o runme runme.$(GOOBJEXT); \ + fi + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) ./runme $(RUNPIPE) + +# ----------------------------------------------------------------- +# Running a Go example (C++) +# ----------------------------------------------------------------- + +go_run_cpp: runme.go + $(GO) $(GOCOMPILEARG) runme.go + if $(GOGCC) ; then \ + $(COMPILETOOL) $(GO) -o runme runme.@OBJEXT@ $(GOGCCOBJS) $(OBJS) $(IOBJS) -lstdc++; \ + elif $(GO12); then \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CXX) -extldflags "$(CXXFLAGS)" -o runme runme.$(GOOBJEXT); \ else \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT}/pkg/$${GOOS}_$${GOARCH}:. -o runme runme.$(GOOBJEXT); \ fi diff --git a/Examples/go/callback/Makefile b/Examples/go/callback/Makefile index 7489f87dc..4516d2674 100644 --- a/Examples/go/callback/Makefile +++ b/Examples/go/callback/Makefile @@ -1,12 +1,12 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cxx +CXXSRCS = callback.cxx TARGET = example INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run_cpp build: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ diff --git a/Examples/go/callback/example.cxx b/Examples/go/callback/callback.cxx similarity index 100% rename from Examples/go/callback/example.cxx rename to Examples/go/callback/callback.cxx diff --git a/Examples/go/class/Makefile b/Examples/go/class/Makefile index a099654f1..66b2df325 100644 --- a/Examples/go/class/Makefile +++ b/Examples/go/class/Makefile @@ -1,12 +1,12 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cxx +CXXSRCS = class.cxx TARGET = example INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run_cpp build: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ diff --git a/Examples/go/class/example.cxx b/Examples/go/class/class.cxx similarity index 100% rename from Examples/go/class/example.cxx rename to Examples/go/class/class.cxx diff --git a/Examples/go/constants/Makefile b/Examples/go/constants/Makefile index b45feb963..c232e9ed1 100644 --- a/Examples/go/constants/Makefile +++ b/Examples/go/constants/Makefile @@ -6,7 +6,7 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ diff --git a/Examples/go/enum/Makefile b/Examples/go/enum/Makefile index 7489f87dc..6f9347ca8 100644 --- a/Examples/go/enum/Makefile +++ b/Examples/go/enum/Makefile @@ -1,12 +1,12 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cxx +CXXSRCS = enum.cxx TARGET = example INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run_cpp build: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ diff --git a/Examples/go/enum/example.cxx b/Examples/go/enum/enum.cxx similarity index 100% rename from Examples/go/enum/example.cxx rename to Examples/go/enum/enum.cxx diff --git a/Examples/go/extend/Makefile b/Examples/go/extend/Makefile index 7489f87dc..386d4d0bb 100644 --- a/Examples/go/extend/Makefile +++ b/Examples/go/extend/Makefile @@ -1,12 +1,12 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cxx +CXXSRCS = extend.cxx TARGET = example INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run_cpp build: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ diff --git a/Examples/go/extend/example.cxx b/Examples/go/extend/extend.cxx similarity index 100% rename from Examples/go/extend/example.cxx rename to Examples/go/extend/extend.cxx diff --git a/Examples/go/funcptr/Makefile b/Examples/go/funcptr/Makefile index 452ea2118..2c32c45fc 100644 --- a/Examples/go/funcptr/Makefile +++ b/Examples/go/funcptr/Makefile @@ -1,12 +1,12 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -SRCS = example.c +SRCS = funcptr.c TARGET = example INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ diff --git a/Examples/go/funcptr/example.c b/Examples/go/funcptr/funcptr.c similarity index 100% rename from Examples/go/funcptr/example.c rename to Examples/go/funcptr/funcptr.c diff --git a/Examples/go/multimap/Makefile b/Examples/go/multimap/Makefile index 452ea2118..0c5ec395f 100644 --- a/Examples/go/multimap/Makefile +++ b/Examples/go/multimap/Makefile @@ -1,12 +1,12 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -SRCS = example.c +SRCS = multimap.c TARGET = example INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ diff --git a/Examples/go/multimap/example.c b/Examples/go/multimap/multimap.c similarity index 100% rename from Examples/go/multimap/example.c rename to Examples/go/multimap/multimap.c diff --git a/Examples/go/pointer/Makefile b/Examples/go/pointer/Makefile index 452ea2118..12e94f939 100644 --- a/Examples/go/pointer/Makefile +++ b/Examples/go/pointer/Makefile @@ -1,12 +1,12 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -SRCS = example.c +SRCS = pointer.c TARGET = example INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ diff --git a/Examples/go/pointer/example.c b/Examples/go/pointer/pointer.c similarity index 100% rename from Examples/go/pointer/example.c rename to Examples/go/pointer/pointer.c diff --git a/Examples/go/reference/Makefile b/Examples/go/reference/Makefile index 7489f87dc..5c5e6808b 100644 --- a/Examples/go/reference/Makefile +++ b/Examples/go/reference/Makefile @@ -1,12 +1,12 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cxx +CXXSRCS = reference.cxx TARGET = example INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run_cpp build: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ diff --git a/Examples/go/reference/example.cxx b/Examples/go/reference/reference.cxx similarity index 100% rename from Examples/go/reference/example.cxx rename to Examples/go/reference/reference.cxx diff --git a/Examples/go/simple/Makefile b/Examples/go/simple/Makefile index 75f81bffe..907da8821 100644 --- a/Examples/go/simple/Makefile +++ b/Examples/go/simple/Makefile @@ -1,11 +1,11 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -SRCS = example.c +SRCS = simple.c TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ diff --git a/Examples/go/simple/example.c b/Examples/go/simple/simple.c similarity index 100% rename from Examples/go/simple/example.c rename to Examples/go/simple/simple.c diff --git a/Examples/go/template/Makefile b/Examples/go/template/Makefile index 9ee030479..20ffb7136 100644 --- a/Examples/go/template/Makefile +++ b/Examples/go/template/Makefile @@ -6,7 +6,7 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run_cpp build: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ diff --git a/Examples/go/variables/Makefile b/Examples/go/variables/Makefile index 452ea2118..1f144929c 100644 --- a/Examples/go/variables/Makefile +++ b/Examples/go/variables/Makefile @@ -1,12 +1,12 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -SRCS = example.c +SRCS = variables.c TARGET = example INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ diff --git a/Examples/go/variables/example.c b/Examples/go/variables/variables.c similarity index 100% rename from Examples/go/variables/example.c rename to Examples/go/variables/variables.c diff --git a/Examples/test-suite/go/Makefile.in b/Examples/test-suite/go/Makefile.in index 1eb6cb377..1b4887e23 100644 --- a/Examples/test-suite/go/Makefile.in +++ b/Examples/test-suite/go/Makefile.in @@ -6,6 +6,7 @@ LANGUAGE = go GO = @GO@ GOGCC = @GOGCC@ GO1 = @GO1@ +GO12 = @GO12@ GOC = @GOC@ SCRIPTSUFFIX = _runme.go @@ -30,7 +31,7 @@ include $(srcdir)/../common.mk %.cpptest: $(setup) +$(swig_and_compile_cpp) - $(run_testcase) + $(run_testcase_cpp) %.ctest: $(setup) @@ -58,7 +59,22 @@ run_testcase = \ if test -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); then \ $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ if $(GOGCC) ; then \ - $(COMPILETOOL) $(GO) -o $*_runme $(SCRIPTPREFIX)$*_runme.@OBJEXT@ $*.@OBJEXT@ $*$(SO); \ + $(COMPILETOOL) $(GO) -o $*_runme $(SCRIPTPREFIX)$*_runme.@OBJEXT@ $*.@OBJEXT@ $*_wrap.@OBJEXT@; \ + elif $(GO12); then \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CC) -extldflags "$(CFLAGS)" -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ + else \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -r $${GOROOT}/pkg/$${GOOS}_$${GOARCH}:. -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ + fi && \ + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) ./$*_runme; \ + fi + +run_testcase_cpp = \ + if test -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); then \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ + if $(GOGCC) ; then \ + $(COMPILETOOL) $(GO) -o $*_runme $(SCRIPTPREFIX)$*_runme.@OBJEXT@ $*.@OBJEXT@ $*_wrap.@OBJEXT@ -lstdc++; \ + elif $(GO12); then \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CXX) -extldflags "$(CXXFLAGS)" -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ else \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -r $${GOROOT}/pkg/$${GOOS}_$${GOARCH}:. -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ fi && \ @@ -70,7 +86,9 @@ run_multi_testcase = \ $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ if $(GOGCC) ; then \ files=`cat $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$*.list`; \ - $(COMPILETOOL) $(GO) -o $*_runme $(SCRIPTPREFIX)$*_runme.@OBJEXT@ `for f in $$files; do echo $$f.@OBJEXT@ $$f$(SO); done`; \ + $(COMPILETOOL) $(GO) -o $*_runme $(SCRIPTPREFIX)$*_runme.@OBJEXT@ `for f in $$files; do echo $$f.@OBJEXT@ $${f}_wrap.@OBJEXT@; done` -lstdc++; \ + elif $(GO12); then \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -linkmode external -extld $(CXX) -extldflags "$(CXXFLAGS)" -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ else \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -r $${GOROOT}/pkg/$${GOOS}_$${GOARCH}:. -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ fi && \ diff --git a/Examples/test-suite/go/director_abstract_runme.go b/Examples/test-suite/go/director_abstract_runme.go deleted file mode 100644 index 37279383a..000000000 --- a/Examples/test-suite/go/director_abstract_runme.go +++ /dev/null @@ -1,62 +0,0 @@ -package main - -import "./director_abstract" - -type MyFoo struct{} - -func (p *MyFoo) Ping() string { - return "MyFoo::ping()" -} - -func f1() { - a := director_abstract.NewDirectorFoo(&MyFoo{}) - - if a.Ping() != "MyFoo::ping()" { - panic(a.Ping()) - } - - if a.Pong() != "Foo::pong();MyFoo::ping()" { - panic(a.Pong()) - } -} - -type MyExample1 struct{} - -func (p *MyExample1) Color(r, g, b byte) int { - return int(r) -} - -type MyExample2 struct{} - -func (p *MyExample2) Color(r, g, b byte) int { - return int(g) -} - -type MyExample3 struct{} - -func (p *MyExample3) Color(r, g, b byte) int { - return int(b) -} - -func f2() { - me1 := director_abstract.NewDirectorExample1(&MyExample1{}) - if director_abstract.Example1Get_color(me1, 1, 2, 3) != 1 { - println(director_abstract.Example1Get_color(me1, 1, 2, 3)) - panic(0) - } - - me2 := director_abstract.NewDirectorExample2(&MyExample2{}, 1, 2) - if director_abstract.Example2Get_color(me2, 1, 2, 3) != 2 { - panic(0) - } - - me3 := director_abstract.NewDirectorExample3_i(&MyExample3{}) - if director_abstract.Example3_iGet_color(me3, 1, 2, 3) != 3 { - panic(0) - } -} - -func main() { - f1() - f2() -} diff --git a/Examples/test-suite/go/director_thread_runme.go b/Examples/test-suite/go/director_thread_runme.go deleted file mode 100644 index ddfacedbe..000000000 --- a/Examples/test-suite/go/director_thread_runme.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import . "./director_thread" - -type Derived struct { - abi Foo -} // From Foo -func (p *Derived) Do_foo() { - p.abi.SetVal(p.abi.GetVal() - 1) -} - -func main() { - - // FIXME: This test fails until we fix callbacks from a - // different thread. - return - - p := &Derived{nil} - d := NewDirectorFoo(p) - p.abi = d - d.Run() - - if d.GetVal() >= 0 { - panic(d.GetVal()) - } - - d.Stop() -} diff --git a/Examples/test-suite/go/template_typedef_import_runme.go b/Examples/test-suite/go/template_typedef_import_runme.go deleted file mode 100644 index f1c00ff13..000000000 --- a/Examples/test-suite/go/template_typedef_import_runme.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import "template_typedef_cplx2" -import "template_typedef_import" - -func main() { - // this is OK - - s := template_typedef_import.NewSin() - s.Get_base_value() - s.Get_value() - s.Get_arith_value() - template_typedef_import.My_func_r(s) - template_typedef_cplx2.Make_Multiplies_double_double_double_double(s, s) - - z := template_typedef_import.NewCSin() - z.Get_base_value() - z.Get_value() - z.Get_arith_value() - template_typedef_import.My_func_c(z) - template_typedef_cplx2.Make_Multiplies_complex_complex_complex_complex(z, z) - - // Here we fail - d := template_typedef_cplx2.Make_Identity_double() - template_typedef_import.My_func_r(d) - - c := template_typedef_cplx2.Make_Identity_complex() - template_typedef_import.My_func_c(c) -} diff --git a/Lib/go/cdata.i b/Lib/go/cdata.i index 0dac6420c..9e6dc2161 100644 --- a/Lib/go/cdata.i +++ b/Lib/go/cdata.i @@ -7,7 +7,8 @@ %{ typedef struct SWIGCDATA { char *data; - int len; + intgo len; + intgo cap; } SWIGCDATA; %} @@ -15,7 +16,8 @@ typedef struct SWIGCDATA { %typemap(out) SWIGCDATA %{ $result.data = (char*)_swig_goallocate($1.len); memcpy($result.data, $1.data, $1.len); - $result.len = (int)$1.len; + $result.len = (intgo)$1.len; + $result.cap = $result.len; %} /* ----------------------------------------------------------------------------- diff --git a/Source/Modules/go.cxx b/Source/Modules/go.cxx index e5398ba7a..adb81345e 100644 --- a/Source/Modules/go.cxx +++ b/Source/Modules/go.cxx @@ -22,6 +22,8 @@ class GO:public Language { bool gccgo_flag; // Prefix to use with gccgo. String *go_prefix; + // Whether to use a shared library. + bool use_shlib; // Name of shared library to import. String *soname; // Size in bits of the C type "long". @@ -86,6 +88,7 @@ public: module(NULL), gccgo_flag(false), go_prefix(NULL), + use_shlib(false), soname(NULL), long_type_size(32), intgo_type_size(0), @@ -153,6 +156,9 @@ private: } else { Swig_arg_error(); } + } else if (strcmp(argv[i], "-use-shlib") == 0) { + Swig_mark_arg(i); + use_shlib = true; } else if (strcmp(argv[i], "-soname") == 0) { if (argv[i + 1]) { soname = NewString(argv[i + 1]); @@ -274,7 +280,7 @@ private: if (!package) { package = Copy(module); } - if (!soname) { + if (!soname && use_shlib) { soname = Copy(package); Append(soname, ".so"); } @@ -387,7 +393,7 @@ private: Swig_banner(f_go_begin); Printf(f_go_begin, "\n// source: %s\n", swig_filename); - if (!gccgo_flag) { + if (!gccgo_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"); @@ -1084,6 +1090,7 @@ private: 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); Printv(f->def, "static void (*x", wname, ")(void*) = ", wname, ";\n", NULL); Printv(f->def, "\n", NULL); @@ -2825,6 +2832,7 @@ private: 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, "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); @@ -2918,17 +2926,20 @@ private: return r; } - String *go_upcall = NewString("Director"); - Append(go_upcall, cn); - Append(go_upcall, go_name); - r = makeDispatchFunction(on, go_upcall, director_struct_name, is_static, director_struct_name, true); - if (r != SWIG_OK) { - return r; + if (!GetFlag(n, "abstract")) { + String *go_upcall = NewString("Director"); + Append(go_upcall, cn); + Append(go_upcall, go_name); + r = makeDispatchFunction(on, go_upcall, director_struct_name, is_static, director_struct_name, true); + if (r != SWIG_OK) { + return r; + } + Delete(go_upcall); } - Delete(cn); - Delete(go_name); + Delete(director_struct_name); - Delete(go_upcall); + Delete(go_name); + Delete(cn); } } Setattr(class_methods, name, NewString("")); @@ -3010,6 +3021,11 @@ private: Append(upcall_name, go_name); String *upcall_wname = Swig_name_wrapper(upcall_name); + if (overname) { + Append(upcall_wname, overname); + } + + String *upcall_gc_name = buildGoWrapperName(upcall_name, overname); String *go_with_over_name = Copy(go_name); if (overname) { @@ -3052,40 +3068,36 @@ private: Printv(f_go_wrappers, "\n", NULL); Printv(f_go_wrappers, "}\n\n", NULL); - // Declare the upcall function, which calls the method on the - // parent class. + if (!GetFlag(n, "abstract")) { + // Declare the upcall function, which calls the method on the + // parent class. - if (overname) { - Append(upcall_wname, overname); + if (gccgo_flag) { + Printv(f_go_wrappers, "//extern ", go_prefix, "_", upcall_wname, "\n", NULL); + } + + Printv(f_go_wrappers, "func ", upcall_gc_name, "(", 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, " ", tm, NULL); + Delete(tm); + } + + Printv(f_go_wrappers, "\n", NULL); } - String *upcall_gc_name = buildGoWrapperName(upcall_name, overname); - - if (gccgo_flag) { - Printv(f_go_wrappers, "//extern ", go_prefix, "_", upcall_wname, "\n", NULL); - } - - Printv(f_go_wrappers, "func ", upcall_gc_name, "(", 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, " ", tm, NULL); - Delete(tm); - } - - Printv(f_go_wrappers, "\n", NULL); - // Define the method on the director class in Go. Printv(f_go_wrappers, "func (swig_p *", director_struct_name, ") ", go_with_over_name, "(", NULL); @@ -3136,181 +3148,189 @@ private: } Printv(f_go_wrappers, "\t}\n", NULL); - if (gccgo_flag) { - Printv(f_go_wrappers, "\tdefer SwigCgocallDone()\n", NULL); - Printv(f_go_wrappers, "\tSwigCgocall()\n", NULL); - } - - Printv(f_go_wrappers, "\t", NULL); - if (SwigType_type(result) != T_VOID) { - Printv(f_go_wrappers, "return ", NULL); - } - Printv(f_go_wrappers, upcall_gc_name, "(swig_p.", go_type_name, NULL); - - p = parms; - for (int i = 0; i < parm_count; ++i) { - p = getParm(p); - SwigType *pt = Getattr(p, "type"); - Printv(f_go_wrappers, ", ", Getattr(p, "lname"), NULL); - if (goTypeIsInterface(p, pt)) { - Printv(f_go_wrappers, ".Swigcptr()", NULL); + if (GetFlag(n, "abstract")) { + Printv(f_go_wrappers, "\tpanic(\"call to pure virtual method\")\n", NULL); + } else { + if (gccgo_flag) { + Printv(f_go_wrappers, "\tdefer SwigCgocallDone()\n", NULL); + Printv(f_go_wrappers, "\tSwigCgocall()\n", NULL); } - p = nextParm(p); + + Printv(f_go_wrappers, "\t", NULL); + if (SwigType_type(result) != T_VOID) { + Printv(f_go_wrappers, "return ", NULL); + } + Printv(f_go_wrappers, upcall_gc_name, "(swig_p.", go_type_name, NULL); + + p = parms; + for (int i = 0; i < parm_count; ++i) { + p = getParm(p); + SwigType *pt = Getattr(p, "type"); + Printv(f_go_wrappers, ", ", Getattr(p, "lname"), NULL); + if (goTypeIsInterface(p, pt)) { + Printv(f_go_wrappers, ".Swigcptr()", NULL); + } + p = nextParm(p); + } + + Printv(f_go_wrappers, ")\n", NULL); } - Printv(f_go_wrappers, ")\n", NULL); Printv(f_go_wrappers, "}\n\n", NULL); // Define a method in the C++ director class that the C++ upcall // function can call. This permits an upcall to a protected // method. - String *upcall_method_name = NewString("_swig_upcall_"); - Append(upcall_method_name, name); - if (overname) { - Append(upcall_method_name, overname); - } - SwigType *rtype = Getattr(n, "classDirectorMethods:type"); - String *upcall_decl = Swig_method_decl(rtype, Getattr(n, "decl"), upcall_method_name, parms, 0, 0); - Printv(f_c_directors_h, " ", upcall_decl, " {\n", NULL); - Delete(upcall_decl); - - Printv(f_c_directors_h, " ", NULL); - if (SwigType_type(result) != T_VOID) { - Printv(f_c_directors_h, "return ", NULL); - } - - String *super_call = Swig_method_call(super, parms); - Printv(f_c_directors_h, super_call, ";\n", NULL); - Delete(super_call); - - Printv(f_c_directors_h, " }\n", NULL); - - // Define the C++ function that the Go function calls. - - SwigType *first_type = NULL; - Parm *first_parm = parms; - if (!is_static) { - first_type = NewString("SwigDirector_"); - Append(first_type, class_name); - SwigType_add_pointer(first_type); - first_parm = NewParm(first_type, "p", n); - set_nextSibling(first_parm, parms); - } - - Swig_save("classDirectorMethod", n, "wrap:name", "wrap:action", NULL); - - Setattr(n, "wrap:name", upcall_wname); - - String *action = NewString(""); - if (SwigType_type(result) != T_VOID) { - Printv(action, Swig_cresult_name(), " = (", SwigType_lstr(result, 0), ")", NULL); - if (SwigType_isreference(result)) { - Printv(action, "&", NULL); + if (!GetFlag(n, "abstract")) { + String *upcall_method_name = NewString("_swig_upcall_"); + Append(upcall_method_name, name); + if (overname) { + Append(upcall_method_name, overname); } - } - Printv(action, Swig_cparm_name(NULL, 0), "->", upcall_method_name, "(", NULL); + SwigType *rtype = Getattr(n, "classDirectorMethods:type"); + String *upcall_decl = Swig_method_decl(rtype, Getattr(n, "decl"), upcall_method_name, parms, 0, 0); + Printv(f_c_directors_h, " ", upcall_decl, " {\n", NULL); + Delete(upcall_decl); - p = parms; - int i = 0; - while (p != NULL) { - if (SwigType_type(Getattr(p, "type")) != T_VOID) { - String *pname = Swig_cparm_name(NULL, i + 1); - if (i > 0) { - Printv(action, ", ", NULL); + Printv(f_c_directors_h, " ", NULL); + if (SwigType_type(result) != T_VOID) { + Printv(f_c_directors_h, "return ", NULL); + } + + String *super_call = Swig_method_call(super, parms); + Printv(f_c_directors_h, super_call, ";\n", NULL); + Delete(super_call); + + Printv(f_c_directors_h, " }\n", NULL); + + // Define the C++ function that the Go function calls. + + SwigType *first_type = NULL; + Parm *first_parm = parms; + if (!is_static) { + first_type = NewString("SwigDirector_"); + Append(first_type, class_name); + SwigType_add_pointer(first_type); + first_parm = NewParm(first_type, "p", n); + set_nextSibling(first_parm, parms); + } + + Swig_save("classDirectorMethod", n, "wrap:name", "wrap:action", NULL); + + Setattr(n, "wrap:name", upcall_wname); + + String *action = NewString(""); + if (SwigType_type(result) != T_VOID) { + Printv(action, Swig_cresult_name(), " = (", SwigType_lstr(result, 0), ")", NULL); + if (SwigType_isreference(result)) { + Printv(action, "&", NULL); } + } + Printv(action, Swig_cparm_name(NULL, 0), "->", upcall_method_name, "(", NULL); - // A parameter whose type is a reference is converted into a - // pointer type by gcCTypeForGoValue. We are calling a - // function which expects a reference so we need to convert - // back. - if (SwigType_isreference(Getattr(p, "type"))) { - Printv(action, "*", NULL); + p = parms; + int i = 0; + while (p != NULL) { + if (SwigType_type(Getattr(p, "type")) != T_VOID) { + String *pname = Swig_cparm_name(NULL, i + 1); + if (i > 0) { + Printv(action, ", ", NULL); + } + + // A parameter whose type is a reference is converted into a + // pointer type by gcCTypeForGoValue. We are calling a + // function which expects a reference so we need to convert + // back. + if (SwigType_isreference(Getattr(p, "type"))) { + Printv(action, "*", NULL); + } + + Printv(action, pname, NULL); + Delete(pname); + i++; } - - Printv(action, pname, NULL); - Delete(pname); - i++; + p = nextSibling(p); } - p = nextSibling(p); - } - Printv(action, ");", NULL); - Setattr(n, "wrap:action", action); + Printv(action, ");", NULL); + Setattr(n, "wrap:action", action); - if (!gccgo_flag) { - // Write the upcall wrapper function. This is compiled by gc - // and calls the C++ function. - int r = gcFunctionWrapper(n, upcall_name, upcall_name, overname, upcall_wname, first_parm, result, is_static, true); - if (r != SWIG_OK) { - return r; + if (!gccgo_flag) { + // Write the upcall wrapper function. This is compiled by gc + // and calls the C++ function. + int r = gcFunctionWrapper(n, upcall_name, upcall_name, overname, upcall_wname, first_parm, result, is_static, true); + 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; + } } - r = gccFunctionWrapper(n, NULL, upcall_wname, first_parm, result); - if (r != SWIG_OK) { - return r; + + Delete(first_type); + if (first_parm != parms) { + Delete(first_parm); } - } else { - int r = gccgoFunctionWrapper(n, NULL, upcall_wname, first_parm, result); - if (r != SWIG_OK) { - return r; + + Swig_restore(n); + Delete(upcall_method_name); + + // Define a function that uses the Go director type that other + // methods in the Go type can call to get parent methods. + + Printv(f_go_wrappers, "func Director", cn, go_with_over_name, "(p ", cn, NULL); + + p = parms; + for (int i = 0; i < parm_count; ++i) { + p = getParm(p); + Printv(f_go_wrappers, ", ", Getattr(p, "lname"), " ", NULL); + String *tm = goType(p, Getattr(p, "type")); + Printv(f_go_wrappers, tm, NULL); + Delete(tm); + p = nextParm(p); } - } - Delete(first_type); - if (first_parm != parms) { - Delete(first_parm); - } + Printv(f_go_wrappers, ")", NULL); - Swig_restore(n); - - // Define a function which uses the Go director type that other - // methods in the Go type can call to get parent methods. - - Printv(f_go_wrappers, "func Director", cn, go_with_over_name, "(p ", cn, NULL); - - p = parms; - for (int i = 0; i < parm_count; ++i) { - p = getParm(p); - Printv(f_go_wrappers, ", ", Getattr(p, "lname"), " ", NULL); - String *tm = goType(p, Getattr(p, "type")); - Printv(f_go_wrappers, tm, NULL); - Delete(tm); - p = nextParm(p); - } - - Printv(f_go_wrappers, ")", NULL); - - if (SwigType_type(result) != T_VOID) { - String *tm = goType(n, result); - Printv(f_go_wrappers, " ", tm, NULL); - Delete(tm); - } - - Printv(f_go_wrappers, " {\n", NULL); - - if (gccgo_flag) { - Printv(f_go_wrappers, "\tdefer SwigCgocallDone()\n", NULL); - Printv(f_go_wrappers, "\tSwigCgocall()\n", NULL); - } - - Printv(f_go_wrappers, "\t", NULL); - if (SwigType_type(result) != T_VOID) { - Printv(f_go_wrappers, "return ", NULL); - } - Printv(f_go_wrappers, upcall_gc_name, "(p.(*", director_struct_name, ").", go_type_name, NULL); - - p = parms; - for (int i = 0; i < parm_count; ++i) { - p = getParm(p); - SwigType *pt = Getattr(p, "type"); - Printv(f_go_wrappers, ", ", Getattr(p, "lname"), NULL); - if (goTypeIsInterface(p, pt)) { - Printv(f_go_wrappers, ".Swigcptr()", NULL); + if (SwigType_type(result) != T_VOID) { + String *tm = goType(n, result); + Printv(f_go_wrappers, " ", tm, NULL); + Delete(tm); } - p = nextParm(p); - } - Printv(f_go_wrappers, ")\n", NULL); - Printv(f_go_wrappers, "}\n\n", NULL); + Printv(f_go_wrappers, " {\n", NULL); + + if (gccgo_flag) { + Printv(f_go_wrappers, "\tdefer SwigCgocallDone()\n", NULL); + Printv(f_go_wrappers, "\tSwigCgocall()\n", NULL); + } + + Printv(f_go_wrappers, "\t", NULL); + if (SwigType_type(result) != T_VOID) { + Printv(f_go_wrappers, "return ", NULL); + } + Printv(f_go_wrappers, upcall_gc_name, "(p.(*", director_struct_name, ").", go_type_name, NULL); + + p = parms; + for (int i = 0; i < parm_count; ++i) { + p = getParm(p); + SwigType *pt = Getattr(p, "type"); + Printv(f_go_wrappers, ", ", Getattr(p, "lname"), NULL); + if (goTypeIsInterface(p, pt)) { + Printv(f_go_wrappers, ".Swigcptr()", NULL); + } + p = nextParm(p); + } + + Printv(f_go_wrappers, ")\n", NULL); + Printv(f_go_wrappers, "}\n\n", NULL); + } // The Go function which invokes the method. This is called // from by the C++ method on the director class. @@ -3390,17 +3410,16 @@ private: } Printv(f_go_wrappers, "\n", NULL); - - Delete(upcall_gc_name); } Printv(f_go_wrappers, "}\n\n", NULL); Delete(result_wrapper); - // Build the C++ functions. - Delete(upcall_wname); + Delete(upcall_gc_name); + + // Build the C++ functions. if (!gccgo_flag) { Printv(f_c_directors, "extern \"C\" void ", callback_wname, "(void*, int);\n", NULL); @@ -3437,7 +3456,6 @@ private: Printv(f_c_directors, " __asm__(\"", go_prefix, ".", package, ".", callback_name, "\");\n", NULL); } - Delete(upcall_method_name); Delete(go_with_over_name); } @@ -3544,6 +3562,7 @@ private: // 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, "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); @@ -4909,5 +4928,6 @@ Go Options (available with -go)\n\ -longsize - Set size of C/C++ long type--32 or 64 bits\n\ -intgosize - Set size of Go int type--32 or 64 bits\n\ -package - Set name of the Go package to \n\ + -use-shlib - Force use of a shared library\n\ -soname - Set shared library holding C/C++ code to \n\ \n"; diff --git a/configure.ac b/configure.ac index 557138dbc..3acc2aa9e 100644 --- a/configure.ac +++ b/configure.ac @@ -1996,6 +1996,7 @@ if test x"${GOBIN}" = xno -o x"${with_alllang}" = xno ; then GO= GOC= GO1=false + GO12=false GOGCC=false GOOPT= GOVERSIONOPTION= @@ -2009,6 +2010,7 @@ else GOGCC=false GO1=false + GO12=false GOOPT= GOVERSIONOPTION= if test -n "$GO" ; then @@ -2046,6 +2048,15 @@ else fi ;; esac + case $go_version in + go1.0* | go1.1*) + GO12=false + GOOPT="$GOOPT -use-shlib" + ;; + *) + GO12=true + ;; + esac else GOC=`echo $GO | sed -e 's/g/c/'` GOVERSIONOPTION=-V @@ -2059,6 +2070,7 @@ else AC_MSG_RESULT([no]) fi GOOPT="-intgosize 32" + GO12=false fi fi fi @@ -2067,6 +2079,7 @@ AC_SUBST(GOGCC) AC_SUBST(GO) AC_SUBST(GOC) AC_SUBST(GO1) +AC_SUBST(GO12) AC_SUBST(GOOPT) AC_SUBST(GOVERSIONOPTION) From 25689857eb7ae8d1027dc8550686005807ed0641 Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Tue, 17 Dec 2013 12:14:33 +0400 Subject: [PATCH 249/481] Language::addSymbol fix, to handle classes correctly --- Source/Modules/lang.cxx | 6 ------ 1 file changed, 6 deletions(-) diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 78c37dbb9..be83b5069 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -3049,12 +3049,6 @@ int Language::addSymbol(const String *s, const Node *n, const_String_or_char_ptr // New scope which has not been added by the target language - lazily created. symbols = NewHash(); Setattr(symtabs, scope, symbols); - - // Add the new scope as a symbol in the top level scope. - // Alternatively the target language must add it in before attempting to add symbols into the scope. - const_String_or_char_ptr top_scope = ""; - Hash *topscope_symbols = Getattr(symtabs, top_scope); - Setattr(topscope_symbols, scope, NewHash()); } else { Node *c = Getattr(symbols, s); if (c && (c != n)) { From 532da6989c9f9723a5ea1f278653f816f6a2d4a5 Mon Sep 17 00:00:00 2001 From: Ian Lance Taylor Date: Tue, 17 Dec 2013 13:50:39 -0800 Subject: [PATCH 250/481] [Go] Add -go-pkgpath option. --- CHANGES.current | 3 ++ Doc/Manual/Go.html | 10 +++++- Lib/go/goruntime.swg | 21 ++++++++---- Source/Modules/go.cxx | 76 +++++++++++++++++++++++++++++++++---------- 4 files changed, 85 insertions(+), 25 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index 21c97407d..4691d65d7 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,9 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2013-12-17: iant + [Go] Add -go-pkgpath option. + 2013-12-16: iant [Go] Update for Go 1.2 release. Add support for linking SWIG code directly into executable, rather than using a diff --git a/Doc/Manual/Go.html b/Doc/Manual/Go.html index 3482d34dc..87e224aee 100644 --- a/Doc/Manual/Go.html +++ b/Doc/Manual/Go.html @@ -134,10 +134,18 @@ swig -go -help option implies the -use-shlib option. + +-go-pkgpath <pkgpath> +When generating code for gccgo, set the pkgpath to use. This + corresponds to the -fgo-pkgpath option to gccgo. + + -go-prefix <prefix> When generating code for gccgo, set the prefix to use. This - corresponds to the -fgo-prefix option to gccgo. + corresponds to the -fgo-prefix option to gccgo. + If -go-pkgpath is used, -go-prefix will be + ignored. diff --git a/Lib/go/goruntime.swg b/Lib/go/goruntime.swg index 4b7daf41f..3e639cdc2 100644 --- a/Lib/go/goruntime.swg +++ b/Lib/go/goruntime.swg @@ -115,13 +115,6 @@ extern void _cgo_panic(const char *); version. We assume that the version of gcc used to compile this file is the same as the version of gccgo. */ -#define SWIGCONCAT2(s1, s2) s1 ## s2 -#define SWIGCONCAT1(s1, s2) SWIGCONCAT2(s1, s2) -#define SwigCgocall SWIGCONCAT1(SWIGMODULE, SwigCgocall) -#define SwigCgocallDone SWIGCONCAT1(SWIGMODULE, SwigCgocallDone) -#define SwigCgocallBack SWIGCONCAT1(SWIGMODULE, SwigCgocallBack) -#define SwigCgocallBackDone SWIGCONCAT1(SWIGMODULE, SwigCgocallBackDone) - #define SWIG_GCC_VERSION \ (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC__PATH_LEVEL__) @@ -142,22 +135,36 @@ 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 diff --git a/Source/Modules/go.cxx b/Source/Modules/go.cxx index adb81345e..6db099662 100644 --- a/Source/Modules/go.cxx +++ b/Source/Modules/go.cxx @@ -22,6 +22,10 @@ class GO:public Language { bool gccgo_flag; // Prefix to use with gccgo. String *go_prefix; + // -fgo-prefix option. + String *prefix_option; + // -fgo-pkgpath option. + String *pkgpath_option; // Whether to use a shared library. bool use_shlib; // Name of shared library to import. @@ -88,6 +92,8 @@ public: module(NULL), gccgo_flag(false), go_prefix(NULL), + prefix_option(NULL), + pkgpath_option(NULL), use_shlib(false), soname(NULL), long_type_size(32), @@ -149,7 +155,16 @@ private: gccgo_flag = true; } else if (strcmp(argv[i], "-go-prefix") == 0) { if (argv[i + 1]) { - go_prefix = NewString(argv[i + 1]); + prefix_option = NewString(argv[i + 1]); + Swig_mark_arg(i); + Swig_mark_arg(i + 1); + i++; + } else { + Swig_arg_error(); + } + } else if (strcmp(argv[i], "-go-pkgpath") == 0) { + if (argv[i + 1]) { + pkgpath_option = NewString(argv[i + 1]); Swig_mark_arg(i); Swig_mark_arg(i + 1); i++; @@ -201,8 +216,8 @@ private: } } - if (gccgo_flag && !go_prefix) { - go_prefix = NewString("go"); + if (gccgo_flag && !pkgpath_option && !prefix_option) { + prefix_option = NewString("go"); } // Add preprocessor symbol to parser. @@ -285,6 +300,27 @@ private: Append(soname, ".so"); } + if (gccgo_flag) { + String *pref; + if (pkgpath_option) { + pref = pkgpath_option; + } else { + pref = prefix_option; + } + go_prefix = NewString(""); + for (char *p = Char(pref); *p != '\0'; p++) { + if ((*p >= 'A' && *p <= 'Z') || (*p >= 'a' && *p <= 'z') || (*p >= '0' && *p <= '9') || *p == '.' || *p == '$') { + Putc(*p, go_prefix); + } else { + Putc('_', go_prefix); + } + } + if (!pkgpath_option) { + Append(go_prefix, "."); + Append(go_prefix, package); + } + } + // Get filenames. String *swig_filename = Getattr(n, "infile"); @@ -374,6 +410,9 @@ private: } Printf(f_c_runtime, "#define SWIGMODULE %s\n", module); + if (gccgo_flag) { + Printf(f_c_runtime, "#define SWIGGO_PREFIX %s\n", go_prefix); + } if (directorsEnabled()) { Printf(f_c_runtime, "#define SWIG_DIRECTORS\n"); @@ -404,14 +443,12 @@ private: Printf(f_go_begin, "\npackage %s\n\n", package); - Printf(f_go_runtime, "//extern %sSwigCgocall\n", module); - Printf(f_go_runtime, "func SwigCgocall()\n"); - Printf(f_go_runtime, "//extern %sSwigCgocallDone\n", module); - Printf(f_go_runtime, "func SwigCgocallDone()\n"); - Printf(f_go_runtime, "//extern %sSwigCgocallBack\n", module); - Printf(f_go_runtime, "func SwigCgocallBack()\n"); - Printf(f_go_runtime, "//extern %sSwigCgocallBackDone\n", module); - Printf(f_go_runtime, "func SwigCgocallBackDone()\n\n"); + if (gccgo_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". @@ -1340,7 +1377,7 @@ private: // Start the function definition. String *fnname = NewString(""); - Printv(fnname, go_prefix, "_", wname, "(", NULL); + Printv(fnname, "go_", wname, "(", NULL); if (parm_count > required_count) { Printv(fnname, "intgo _swig_optargc", NULL); @@ -1369,17 +1406,21 @@ private: Printv(fnname, ")", NULL); + String *fndef = NewString(""); if (SwigType_type(result) == T_VOID) { - Printv(f->def, "void ", fnname, NULL); + Printv(fndef, "void ", fnname, NULL); } else { String *ct = gccgoCTypeForGoValue(n, result, fnname); - Printv(f->def, ct, NULL); + Printv(fndef, ct, NULL); Delete(ct); } - Printv(f->def, " {\n", NULL); + 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("go_result"); @@ -2811,7 +2852,7 @@ private: if (!gccgo_flag) { Printv(f_c_directors, "extern \"C\" void ", wname, "(void*, int);\n", NULL); } else { - Printv(f_c_directors, "extern \"C\" void ", wname, "(void*) __asm__(\"", go_prefix, ".", package, ".", go_name, "\");\n", NULL); + Printv(f_c_directors, "extern \"C\" void ", wname, "(void*) __asm__(\"", go_prefix, ".", go_name, "\");\n", NULL); } } @@ -3453,7 +3494,7 @@ private: Delete(fnname); - Printv(f_c_directors, " __asm__(\"", go_prefix, ".", package, ".", callback_name, "\");\n", NULL); + Printv(f_c_directors, " __asm__(\"", go_prefix, ".", callback_name, "\");\n", NULL); } Delete(go_with_over_name); @@ -4924,6 +4965,7 @@ extern "C" Language *swig_go(void) { const char * const GO::usage = (char *) "\ Go Options (available with -go)\n\ -gccgo - Generate code for gccgo rather than 6g/8g\n\ + -go-pkgpath

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

    - Like gccgo -fgo-prefix option\n\ -longsize - Set size of C/C++ long type--32 or 64 bits\n\ -intgosize - Set size of Go int type--32 or 64 bits\n\ From ba049db40b5a4400fc19a72d9178df92ffcbc203 Mon Sep 17 00:00:00 2001 From: Ian Lance Taylor Date: Tue, 17 Dec 2013 17:37:55 -0800 Subject: [PATCH 251/481] Remove Go -longsize option. --- CHANGES.current | 10 ++++--- Doc/Manual/Go.html | 11 ++------ .../test-suite/go/template_opaque_runme.go | 2 +- Examples/test-suite/go/wrapmacro_runme.go | 4 +-- Lib/go/go.swg | 27 ------------------- Source/Modules/go.cxx | 16 +---------- 6 files changed, 13 insertions(+), 57 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index 4691d65d7..f7a882aa1 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,15 +5,19 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ -2013-12-17: iant +2013-12-17: ianlancetaylor + [Go] Remove -longsize option (for backward compatibility, + ignore it if seen). + +2013-12-17: ianlancetaylor [Go] Add -go-pkgpath option. -2013-12-16: iant +2013-12-16: ianlancetaylor [Go] Update for Go 1.2 release. Add support for linking SWIG code directly into executable, rather than using a shared library. -2013-12-13: iant +2013-12-13: ianlancetaylor [Go] Add SWIG source file name as comments in generated files. This can be used by Go documentation tools. diff --git a/Doc/Manual/Go.html b/Doc/Manual/Go.html index 87e224aee..43bfc6971 100644 --- a/Doc/Manual/Go.html +++ b/Doc/Manual/Go.html @@ -148,13 +148,6 @@ swig -go -help ignored. - --long-type-size <s> -Set the size for the C/C++ type long. This controls - whether long is converted to the Go type int32 - or int64. The <s> argument should be 32 or 64. - -

    22.2.2 Go Output Files

    @@ -501,12 +494,12 @@ uses a given C/C++ type. long -int32 or int64, depending on -long-type-size +int64 unsigned long -uint32 or uint64, depending on -long-type-size +uint64 diff --git a/Examples/test-suite/go/template_opaque_runme.go b/Examples/test-suite/go/template_opaque_runme.go index c22b71946..201f7ba16 100644 --- a/Examples/test-suite/go/template_opaque_runme.go +++ b/Examples/test-suite/go/template_opaque_runme.go @@ -3,7 +3,7 @@ package main import "./template_opaque" func main() { - v := template_opaque.NewOpaqueVectorType(10) + v := template_opaque.NewOpaqueVectorType(int64(10)) template_opaque.FillVector(v) } diff --git a/Examples/test-suite/go/wrapmacro_runme.go b/Examples/test-suite/go/wrapmacro_runme.go index 4d3791be8..dc7e7bf5b 100644 --- a/Examples/test-suite/go/wrapmacro_runme.go +++ b/Examples/test-suite/go/wrapmacro_runme.go @@ -5,7 +5,7 @@ import "./wrapmacro" func main() { a := 2 b := -1 - wrapmacro.Maximum(a, b) - wrapmacro.Maximum(a/7.0, -b*256) + wrapmacro.Maximum(int64(a), int64(b)) + wrapmacro.Maximum(float64(a/7.0), float64(-b*256)) wrapmacro.GUINT16_SWAP_LE_BE_CONSTANT(1) } diff --git a/Lib/go/go.swg b/Lib/go/go.swg index 3408f422e..b9086caac 100644 --- a/Lib/go/go.swg +++ b/Lib/go/go.swg @@ -14,15 +14,8 @@ %typemap(gotype) unsigned short, const unsigned short & "uint16" %typemap(gotype) int, const int & "int" %typemap(gotype) unsigned int, const unsigned int & "uint" -#if SWIGGO_LONG_TYPE_SIZE == 32 -%typemap(gotype) long, const long & "int32" -%typemap(gotype) unsigned long, const unsigned long & "uint32" -#elif SWIGGO_LONG_TYPE_SIZE == 64 %typemap(gotype) long, const long & "int64" %typemap(gotype) unsigned long, const unsigned long & "uint64" -#else -#error "SWIGGO_LONG_TYPE_SIZE not 32 or 64" -#endif %typemap(gotype) long long, const long long & "int64" %typemap(gotype) unsigned long long, const unsigned long long & "uint64" %typemap(gotype) float, const float & "float32" @@ -163,11 +156,7 @@ /* The size_t type. */ -#if SWIGGO_LONG_TYPE_SIZE == 32 -%typemap(gotype) size_t, const size_t & %{int%} -#else %typemap(gotype) size_t, const size_t & %{int64%} -#endif %typemap(in) size_t %{ $1 = (size_t)$input; %} @@ -486,32 +475,16 @@ const unsigned int & "" -#if SWIGGO_LONG_TYPE_SIZE == 32 -%typecheck(SWIG_TYPECHECK_INT32) /* Go int32 */ - long, - const long & - "" - -%typecheck(SWIG_TYPECHECK_INT32) /* Go uint32 */ - unsigned long, - const unsigned long & - "" -#endif - %typecheck(SWIG_TYPECHECK_INT64) /* Go int64 */ -#if SWIGGO_LONG_TYPE_SIZE == 64 long, const long &, -#endif long long, const long long & "" %typecheck(SWIG_TYPECHECK_INT64) /* Go uint64 */ -#if SWIGGO_LONG_TYPE_SIZE == 64 unsigned long, const unsigned long &, -#endif unsigned long long, const unsigned long long & "" diff --git a/Source/Modules/go.cxx b/Source/Modules/go.cxx index 6db099662..3dec6503b 100644 --- a/Source/Modules/go.cxx +++ b/Source/Modules/go.cxx @@ -30,8 +30,6 @@ class GO:public Language { bool use_shlib; // Name of shared library to import. String *soname; - // Size in bits of the C type "long". - int long_type_size; // Size in bits of the Go type "int". 0 if not specified. int intgo_type_size; @@ -96,7 +94,6 @@ public: pkgpath_option(NULL), use_shlib(false), soname(NULL), - long_type_size(32), intgo_type_size(0), f_c_begin(NULL), f_go_begin(NULL), @@ -184,12 +181,8 @@ private: Swig_arg_error(); } } else if (strcmp(argv[i], "-longsize") == 0) { + // Ignore for backward compatibility. if (argv[i + 1]) { - long_type_size = atoi(argv[i + 1]); - if (long_type_size != 32 && long_type_size != 64) { - Printf(stderr, "-longsize not 32 or 64\n"); - Swig_arg_error(); - } Swig_mark_arg(i); Swig_mark_arg(i + 1); ++i; @@ -227,12 +220,6 @@ private: Preprocessor_define("SWIGGO_GCCGO 1", 0); } - if (long_type_size == 32) { - Preprocessor_define("SWIGGO_LONG_TYPE_SIZE 32", 0); - } else { - Preprocessor_define("SWIGGO_LONG_TYPE_SIZE 64", 0); - } - // This test may be removed in the future, when we can assume that // everybody has upgraded to Go 1.1. The code below is prepared // for this test to simply be taken out. @@ -4967,7 +4954,6 @@ Go Options (available with -go)\n\ -gccgo - Generate code for gccgo rather than 6g/8g\n\ -go-pkgpath

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

    - Like gccgo -fgo-prefix option\n\ - -longsize - Set size of C/C++ long type--32 or 64 bits\n\ -intgosize - Set size of Go int type--32 or 64 bits\n\ -package - Set name of the Go package to \n\ -use-shlib - Force use of a shared library\n\ From 8dba8b1fde7f3234c816840b5a376d74ebd5a181 Mon Sep 17 00:00:00 2001 From: Ian Lance Taylor Date: Wed, 18 Dec 2013 11:03:39 -0800 Subject: [PATCH 252/481] Go: Don't require that Go environment variables be set when running examples or testsuite. --- CHANGES.current | 5 +++++ Examples/Makefile.in | 8 ++++---- Examples/test-suite/go/Makefile.in | 6 +++--- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index f7a882aa1..f9934b49d 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,11 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2013-12-18: ianlancetaylor + [Go] Don't require that Go environment variables be set + when running examples or testsuite when using Go 1 or + later. + 2013-12-17: ianlancetaylor [Go] Remove -longsize option (for backward compatibility, ignore it if seen). diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 0169f26a7..d8ebb80e3 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -1590,7 +1590,7 @@ go: $(SRCS) fi $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(GOSRCS) if ! $(GOGCC) ; then \ - $(COMPILETOOL) $(GOTOOL) $(GOC) -I $${GOROOT}/pkg/$${GOOS}_$${GOARCH} $(GOCSRCS); \ + $(COMPILETOOL) $(GOTOOL) $(GOC) -I $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`} $(GOCSRCS); \ rm -f $(GOPACKAGE); \ if $(GO12); then \ $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)) $(OBJS) $(IOBJS); \ @@ -1613,7 +1613,7 @@ go_cpp: $(SRCS) fi $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(GOSRCS) if ! $(GOGCC) ; then \ - $(COMPILETOOL) $(GOTOOL) $(GOC) -I $${GOROOT}/pkg/$${GOOS}_$${GOARCH} $(GOCSRCS); \ + $(COMPILETOOL) $(GOTOOL) $(GOC) -I $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`} $(GOCSRCS); \ rm -f $(GOPACKAGE); \ if $(GO12); then \ $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)) $(OBJS) $(IOBJS); \ @@ -1633,7 +1633,7 @@ go_run: runme.go elif $(GO12); then \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CC) -extldflags "$(CFLAGS)" -o runme runme.$(GOOBJEXT); \ else \ - $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT}/pkg/$${GOOS}_$${GOARCH}:. -o runme runme.$(GOOBJEXT); \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o runme runme.$(GOOBJEXT); \ fi env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) ./runme $(RUNPIPE) @@ -1648,7 +1648,7 @@ go_run_cpp: runme.go elif $(GO12); then \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CXX) -extldflags "$(CXXFLAGS)" -o runme runme.$(GOOBJEXT); \ else \ - $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT}/pkg/$${GOOS}_$${GOARCH}:. -o runme runme.$(GOOBJEXT); \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o runme runme.$(GOOBJEXT); \ fi env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) ./runme $(RUNPIPE) diff --git a/Examples/test-suite/go/Makefile.in b/Examples/test-suite/go/Makefile.in index 1b4887e23..35937bcdb 100644 --- a/Examples/test-suite/go/Makefile.in +++ b/Examples/test-suite/go/Makefile.in @@ -63,7 +63,7 @@ run_testcase = \ elif $(GO12); then \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CC) -extldflags "$(CFLAGS)" -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ else \ - $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -r $${GOROOT}/pkg/$${GOOS}_$${GOARCH}:. -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ fi && \ env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) ./$*_runme; \ fi @@ -76,7 +76,7 @@ run_testcase_cpp = \ elif $(GO12); then \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CXX) -extldflags "$(CXXFLAGS)" -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ else \ - $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -r $${GOROOT}/pkg/$${GOOS}_$${GOARCH}:. -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ fi && \ env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) ./$*_runme; \ fi @@ -90,7 +90,7 @@ run_multi_testcase = \ elif $(GO12); then \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -linkmode external -extld $(CXX) -extldflags "$(CXXFLAGS)" -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ else \ - $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -r $${GOROOT}/pkg/$${GOOS}_$${GOARCH}:. -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ fi && \ env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) ./$*_runme; \ fi From b4fef06c42044441c49888f0a96eb94315f98380 Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Thu, 19 Dec 2013 02:11:22 +0400 Subject: [PATCH 253/481] fixed %template within %extend, test added fixed language symbol table nested classes name separator, test added fixed %feature "flatnested" working with %extend fixed Swig_offset_string for empty string added simple template to save/restore values in current scope (readability reasons) --- .../java/template_nested_runme.java | 1 + Examples/test-suite/nested_class.i | 6 +++++ Examples/test-suite/template_nested.i | 8 ++++++- Source/CParse/parser.y | 22 +++++++++---------- Source/Modules/allocate.cxx | 10 ++++----- Source/Modules/csharp.cxx | 4 ++-- Source/Modules/java.cxx | 3 +-- Source/Modules/lang.cxx | 17 +++++--------- Source/Modules/nested.cxx | 2 ++ Source/Modules/swigmod.h | 9 ++++++++ Source/Modules/typepass.cxx | 4 +--- Source/Swig/misc.c | 8 +++---- 12 files changed, 55 insertions(+), 39 deletions(-) diff --git a/Examples/test-suite/java/template_nested_runme.java b/Examples/test-suite/java/template_nested_runme.java index 422e7ea9e..4cca9f34a 100644 --- a/Examples/test-suite/java/template_nested_runme.java +++ b/Examples/test-suite/java/template_nested_runme.java @@ -29,6 +29,7 @@ public class template_nested_runme { OuterClass.T_OuterClassInner2NormalClass inner2 = new OuterClass.T_OuterClassInner2NormalClass(); inner2.setEmbeddedVar(2); OuterClass.T_OuterClassInner2NormalClass inner22 = new OuterClass().useInner2Again(inner2); + OuterClass.T_OuterClassInner1Double inner3 = new OuterClass.T_OuterClassInner1Double(); } } diff --git a/Examples/test-suite/nested_class.i b/Examples/test-suite/nested_class.i index 0d418192d..282875531 100644 --- a/Examples/test-suite/nested_class.i +++ b/Examples/test-suite/nested_class.i @@ -167,10 +167,16 @@ struct Outer { /////////////////////////////////////////// typedef struct InnerSameName { Integer x; + struct InnerSameName2 {}; } InnerSameName; InnerSameName* makeInnerSameName() { return 0; } }; +#if defined(SWIGCSHARP) || defined (SWIGJAVA) +// place a class with the same name as in Outer in global scope, to test language symbol table +class InnerSameName {}; +class InnerSameName2 {}; +#endif %} // Ignore nested struct instance diff --git a/Examples/test-suite/template_nested.i b/Examples/test-suite/template_nested.i index bbca9502c..c33018e0f 100644 --- a/Examples/test-suite/template_nested.i +++ b/Examples/test-suite/template_nested.i @@ -30,6 +30,7 @@ namespace ns { %} %template(T_NormalTemplateNormalClass) ns::NormalTemplate; %template(T_NormalTemplateInt) ns::NormalTemplate; +%template(T_NormalTemplateDouble) ns::NormalTemplate; %inline %{ namespace ns { @@ -70,6 +71,9 @@ namespace ns { }; Inner2 useInner2(const Inner2& inner) { return inner; } Inner2 useInner2Again(const Inner2& inner) { return inner; } +#ifdef SWIG + %template(T_OuterClassInner1Double) Inner1; +#endif int iii; }; struct ABC { @@ -105,8 +109,10 @@ namespace ns { NestedStruct useNestedStruct(const NestedStruct& inner) { return inner; } }; } - %} +%extend ns::OuterClass { + %template(T_OuterClassInner2Double) Inner2; +} %template(T_OuterTMethodNormalClass) ns::OuterClass::InnerTMethod; %template(T_TemplateFuncs1Int) ns::TemplateFuncs::templateMethod1; diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index ef5aa6ef4..40d853387 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1311,16 +1311,18 @@ static void default_arguments(Node *n) { } /* ----------------------------------------------------------------------------- - * tag_nodes() + * mark_nodes_as_extend() * - * Used by the parser to mark subtypes with extra information. + * Used by the %extend to mark subtypes with "feature:extend". + * template instances declared within %extend are skipped * ----------------------------------------------------------------------------- */ -static void tag_nodes(Node *n, const_String_or_char_ptr attrname, DOH *value) { - while (n) { - Setattr(n, attrname, value); - tag_nodes(firstChild(n), attrname, value); - n = nextSibling(n); +static void mark_nodes_as_extend(Node *n) { + for (; n; n = nextSibling(n)) { + if (Getattr(n, "template") && Strcmp(nodeType(n), "class") == 0) + continue; + Setattr(n, "feature:extend", "1"); + mark_nodes_as_extend(firstChild(n)); } } @@ -1648,9 +1650,7 @@ extend_directive : EXTEND options idcolon LBRACE { clsname = make_class_name($3); Setattr($$,"name",clsname); - /* Mark members as extend */ - - tag_nodes($6,"feature:extend",(char*) "1"); + mark_nodes_as_extend($6); if (current_class) { /* We add the extension to the previously defined class */ appendChild($$,$6); @@ -4267,7 +4267,7 @@ cpp_members : cpp_member cpp_members { } } cpp_members RBRACE cpp_members { $$ = new_node("extend"); - tag_nodes($4,"feature:extend",(char*) "1"); + mark_nodes_as_extend($4); appendChild($$,$4); set_nextSibling($$,$6); } diff --git a/Source/Modules/allocate.cxx b/Source/Modules/allocate.cxx index 7f1d13678..d3384e1ba 100644 --- a/Source/Modules/allocate.cxx +++ b/Source/Modules/allocate.cxx @@ -559,9 +559,11 @@ Allocate(): virtual int classDeclaration(Node *n) { Symtab *symtab = Swig_symbol_current(); Swig_symbol_setscope(Getattr(n, "symtab")); - Node *oldInclass = inclass; - AccessMode oldAcessMode = cplus_mode; - + save_value oldInclass(inclass); + save_value oldAcessMode(cplus_mode); + save_value oldExtendMode(extendmode); + if (Getattr(n, "template")) + extendmode = 0; if (!CPlusPlus) { /* Always have default constructors/destructors in C */ Setattr(n, "allocate:default_constructor", "1"); @@ -729,8 +731,6 @@ Allocate(): /* Only care about default behavior. Remove temporary values */ Setattr(n, "allocate:visit", "1"); - inclass = oldInclass; - cplus_mode = oldAcessMode; Swig_symbol_setscope(symtab); return SWIG_OK; } diff --git a/Source/Modules/csharp.cxx b/Source/Modules/csharp.cxx index 9197b4b17..3c765835e 100644 --- a/Source/Modules/csharp.cxx +++ b/Source/Modules/csharp.cxx @@ -1888,10 +1888,10 @@ public: if (Node *outer = Getattr(n, "nested:outer")) { String *outerClassesPrefix = Copy(Getattr(outer, "sym:name")); for (outer = Getattr(outer, "nested:outer"); outer != 0; outer = Getattr(outer, "nested:outer")) { - Push(outerClassesPrefix, "::"); + Push(outerClassesPrefix, "."); Push(outerClassesPrefix, Getattr(outer, "sym:name")); } - String *fnspace = nspace ? NewStringf("%s::%s", nspace, outerClassesPrefix) : outerClassesPrefix; + String *fnspace = nspace ? NewStringf("%s.%s", nspace, outerClassesPrefix) : outerClassesPrefix; if (!addSymbol(proxy_class_name, n, fnspace)) return SWIG_ERROR; if (nspace) diff --git a/Source/Modules/java.cxx b/Source/Modules/java.cxx index fdc678dbf..d378a02f3 100644 --- a/Source/Modules/java.cxx +++ b/Source/Modules/java.cxx @@ -1969,8 +1969,7 @@ public: } if (outerClassesPrefix) { - Replaceall(outerClassesPrefix, ".", "::"); - String *fnspace = nspace ? NewStringf("%s::%s", nspace, outerClassesPrefix) : outerClassesPrefix; + String *fnspace = nspace ? NewStringf("%s.%s", nspace, outerClassesPrefix) : outerClassesPrefix; if (!addSymbol(proxy_class_name, n, fnspace)) return SWIG_ERROR; if (nspace) diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index be83b5069..795b9edb8 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -525,15 +525,9 @@ int Language::top(Node *n) { * ---------------------------------------------------------------------- */ int Language::extendDirective(Node *n) { - int oldam = Extend; - AccessMode oldmode = cplus_mode; - Extend = CWRAP_EXTEND; - cplus_mode = PUBLIC; - + save_value oldam(Extend, CWRAP_EXTEND); + save_value oldmode(cplus_mode, PUBLIC); emit_children(n); - - Extend = oldam; - cplus_mode = oldmode; return SWIG_OK; } @@ -2486,7 +2480,9 @@ int Language::classDeclaration(Node *n) { * ---------------------------------------------------------------------- */ int Language::classHandler(Node *n) { - + save_value oldExtend(Extend); + if (Getattr(n, "template")) + Extend = 0; bool hasDirector = Swig_directorclass(n) ? true : false; /* Emit all of the class members */ @@ -2519,7 +2515,7 @@ int Language::classHandler(Node *n) { if (dirprot_mode() && extraDirectorProtectedCPPMethodsRequired()) { Node *vtable = Getattr(n, "vtable"); String *symname = Getattr(n, "sym:name"); - AccessMode old_mode = cplus_mode; + save_value old_mode(cplus_mode); cplus_mode = PROTECTED; int len = Len(vtable); for (int i = 0; i < len; i++) { @@ -2548,7 +2544,6 @@ int Language::classHandler(Node *n) { } Delete(wrapname); } - cplus_mode = old_mode; } } diff --git a/Source/Modules/nested.cxx b/Source/Modules/nested.cxx index a62a9e9da..37248608c 100644 --- a/Source/Modules/nested.cxx +++ b/Source/Modules/nested.cxx @@ -432,6 +432,8 @@ void Swig_nested_process_classes(Node *n) { removeNode(c); if (!checkAttribute(c, "access", "public")) SetFlag(c, "feature:ignore"); + else if (Strcmp(nodeType(n),"extend") == 0 && Strcmp(nodeType(parentNode(n)),"class") == 0) + insertNodeAfter(parentNode(n), c); else insertNodeAfter(n, c); } diff --git a/Source/Modules/swigmod.h b/Source/Modules/swigmod.h index 9e76b4d10..6d3cd35de 100644 --- a/Source/Modules/swigmod.h +++ b/Source/Modules/swigmod.h @@ -423,4 +423,13 @@ void Swig_process_types(Node *n); void Swig_nested_process_classes(Node *n); void Swig_nested_name_unnamed_c_structs(Node *n); +template class save_value { + T _value; + T& _value_ptr; +public: + save_value(T& value) : _value(value), _value_ptr(value){} + save_value(T& value, T new_val) : _value(value), _value_ptr(value){ value = new_val; } + ~save_value(){ _value_ptr = _value; } +}; + #endif diff --git a/Source/Modules/typepass.cxx b/Source/Modules/typepass.cxx index 3f8e33dae..e918c0770 100644 --- a/Source/Modules/typepass.cxx +++ b/Source/Modules/typepass.cxx @@ -417,7 +417,7 @@ class TypePass:private Dispatcher { String *unnamed = Getattr(n, "unnamed"); String *storage = Getattr(n, "storage"); String *kind = Getattr(n, "kind"); - Node *oldinclass = inclass; + save_value oldinclass(inclass); List *olist = normalize; Symtab *symtab; String *nname = 0; @@ -537,8 +537,6 @@ class TypePass:private Dispatcher { normalize = olist; - inclass = oldinclass; - /* If in a namespace, patch the class name */ if (nname) { Setattr(n, "name", nname); diff --git a/Source/Swig/misc.c b/Source/Swig/misc.c index 7d8180d1c..161c71e43 100644 --- a/Source/Swig/misc.c +++ b/Source/Swig/misc.c @@ -1154,13 +1154,13 @@ String *Swig_string_strip(String *s) { * ----------------------------------------------------------------------------- */ void Swig_offset_string(String *s, int number) { - char *res; - char *p; - char *end; + char *res, *p, *end, *start; /* count a number of lines in s */ int lines = 1; int len = Len(s); - char *start = strchr(Char(s), '\n'); + if (len == 0) + return; + start = strchr(Char(s), '\n'); while (start) { ++lines; start = strchr(start + 1, '\n'); From 257a9865e94a22dba5b212785541f9f8d5fe2a30 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 19 Dec 2013 18:12:19 +0000 Subject: [PATCH 254/481] Make save_value non-copyable --- Source/Modules/swigmod.h | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Source/Modules/swigmod.h b/Source/Modules/swigmod.h index 6d3cd35de..7ebcfeee1 100644 --- a/Source/Modules/swigmod.h +++ b/Source/Modules/swigmod.h @@ -426,10 +426,13 @@ void Swig_nested_name_unnamed_c_structs(Node *n); template class save_value { T _value; T& _value_ptr; + save_value(const save_value&); + save_value& operator=(const save_value&); + public: - save_value(T& value) : _value(value), _value_ptr(value){} - save_value(T& value, T new_val) : _value(value), _value_ptr(value){ value = new_val; } - ~save_value(){ _value_ptr = _value; } + save_value(T& value) : _value(value), _value_ptr(value) {} + save_value(T& value, T new_val) : _value(value), _value_ptr(value) { value = new_val; } + ~save_value() { _value_ptr = _value; } }; #endif From 82990df5739acaef168ca66a32e3c2253e04f3d9 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 19 Dec 2013 18:23:28 +0000 Subject: [PATCH 255/481] Error test-suite updated for nested changes WARN_DEPRECATED_NESTED_WORKAROUND test added WARN_PARSE_NAMED_NESTED_CLASS test removed --- Examples/test-suite/errors/cpp_nested.i | 13 ------------ .../test-suite/errors/cpp_nested_template.i | 20 +++++++++++++++++++ Examples/test-suite/errors/expected.log | 6 ++---- Examples/test-suite/errors/make.sh | 2 +- 4 files changed, 23 insertions(+), 18 deletions(-) delete mode 100644 Examples/test-suite/errors/cpp_nested.i create mode 100644 Examples/test-suite/errors/cpp_nested_template.i diff --git a/Examples/test-suite/errors/cpp_nested.i b/Examples/test-suite/errors/cpp_nested.i deleted file mode 100644 index 625812e7d..000000000 --- a/Examples/test-suite/errors/cpp_nested.i +++ /dev/null @@ -1,13 +0,0 @@ -%module xxx - -class Foo { -public: - class Bar { - }; -}; - -class Spam { -public: - class Grok { - } x; -}; diff --git a/Examples/test-suite/errors/cpp_nested_template.i b/Examples/test-suite/errors/cpp_nested_template.i new file mode 100644 index 000000000..ec8cab6b6 --- /dev/null +++ b/Examples/test-suite/errors/cpp_nested_template.i @@ -0,0 +1,20 @@ +%module xxx + +template struct Temply { + T thing; +}; + +struct A { + int var; +%template(TemplyInt) Temply; +}; + + +struct B { + int var; +}; + +%extend B { +%template(TemplyDouble) Temply; +} + diff --git a/Examples/test-suite/errors/expected.log b/Examples/test-suite/errors/expected.log index 2db3d8cbc..5fb0e715f 100644 --- a/Examples/test-suite/errors/expected.log +++ b/Examples/test-suite/errors/expected.log @@ -286,7 +286,6 @@ cpp_inherit.i:54: Warning 401: 'Base< double >' must be defined before it is use :::::::::::::::::::::::::::::::: cpp_macro_locator.i ::::::::::::::::::::::::::::::::::: cpp_macro_locator.i:66: Warning 204: CPP #warning, "inline warning message one". cpp_macro_locator.i:96: Warning 204: CPP #warning, "an inline warning message 2". -cpp_macro_locator.i:50: Warning 325: Nested struct not currently supported (Inner ignored) cpp_macro_locator.i:53: Warning 509: Overloaded method overload1(int const *) effectively ignored, cpp_macro_locator.i:52: Warning 509: as it is shadowed by overload1(int *). cpp_macro_locator.i:61: Warning 509: Overloaded method overload2(int const *) effectively ignored, @@ -322,9 +321,8 @@ cpp_namespace_aliasnot.i:4: Error: 'blah' is not a namespace :::::::::::::::::::::::::::::::: cpp_namespace_aliasundef.i ::::::::::::::::::::::::::::::::::: cpp_namespace_aliasundef.i:3: Error: Unknown namespace 'blah' -:::::::::::::::::::::::::::::::: cpp_nested.i ::::::::::::::::::::::::::::::::::: -cpp_nested.i:6: Warning 325: Nested class not currently supported (Bar ignored) -cpp_nested.i:12: Warning 325: Nested class not currently supported (Grok ignored) +:::::::::::::::::::::::::::::::: cpp_nested_template.i ::::::::::::::::::::::::::::::::::: +cpp_nested_template.i:9: Warning 324: Named nested template instantiations not supported. Processing as if no name was given to %template(). :::::::::::::::::::::::::::::::: cpp_no_access.i ::::::::::::::::::::::::::::::::::: cpp_no_access.i:3: Warning 319: No access specifier given for base class 'foo' (ignored). diff --git a/Examples/test-suite/errors/make.sh b/Examples/test-suite/errors/make.sh index b194299c9..5f96897d9 100755 --- a/Examples/test-suite/errors/make.sh +++ b/Examples/test-suite/errors/make.sh @@ -76,7 +76,7 @@ cpp_missing_rtemplate cpp_namespace_alias cpp_namespace_aliasnot cpp_namespace_aliasundef -cpp_nested +cpp_nested_template cpp_no_access cpp_no_return_type cpp_nobase From 715e254e0577af2c6964b58882e08d278dc64e0c Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Fri, 20 Dec 2013 07:37:49 +0400 Subject: [PATCH 256/481] fixed enums & enum values language symbol table namespace fixed skipping of %templates in %extend if they are in the wrong scope --- Source/CParse/parser.y | 3 ++- Source/Modules/csharp.cxx | 44 ++++++++++++++++++++++++++------------- Source/Modules/java.cxx | 44 ++++++++++++++++++++++++++------------- Source/Modules/lang.cxx | 1 - 4 files changed, 62 insertions(+), 30 deletions(-) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 40d853387..c6fe56b70 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -2676,7 +2676,8 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va Setattr(templnode,"sym:typename","1"); } /* for now, nested %template is allowed only in the same scope as the template declaration */ - if ($3 && !(currentOuterClass && (currentOuterClass != Getattr(nn, "nested:outer")))) { + if ($3 && !((currentOuterClass && (currentOuterClass != Getattr(nn, "nested:outer"))) + ||(extendmode && current_class && (current_class != Getattr(nn, "nested:outer"))))) { /* Comment this out for 1.3.28. We need to re-enable it later but first we need to diff --git a/Source/Modules/csharp.cxx b/Source/Modules/csharp.cxx index 3c765835e..1713e6f3f 100644 --- a/Source/Modules/csharp.cxx +++ b/Source/Modules/csharp.cxx @@ -1107,6 +1107,30 @@ public: return ret; } + + String *getCurrentScopeName(String *nspace) + { + String *scope = 0; + if (nspace || getCurrentClass()) { + scope = NewString(""); + if (nspace) + Printf(scope, "%s", nspace); + if (Node* cls = getCurrentClass()) + { + if (Node *outer = Getattr(cls, "nested:outer")) { + String *outerClassesPrefix = Copy(Getattr(outer, "sym:name")); + for (outer = Getattr(outer, "nested:outer"); outer != 0; outer = Getattr(outer, "nested:outer")) { + Push(outerClassesPrefix, "."); + Push(outerClassesPrefix, Getattr(outer, "sym:name")); + } + Printv(scope, nspace ? "." : "", outerClassesPrefix, ".", proxy_class_name, NIL); + Delete(outerClassesPrefix); + } else + Printv(scope, nspace ? "." : "", proxy_class_name, NIL); + } + } + return scope; + } /* ---------------------------------------------------------------------- * enumDeclaration() @@ -1150,14 +1174,7 @@ public: if ((enum_feature != SimpleEnum) && symname && typemap_lookup_type) { // Wrap (non-anonymous) C/C++ enum within a typesafe, typeunsafe or proper C# enum - String *scope = 0; - if (nspace || proxy_class_name) { - scope = NewString(""); - if (nspace) - Printf(scope, "%s", nspace); - if (proxy_class_name) - Printv(scope, nspace ? "." : "", proxy_class_name, NIL); - } + String *scope = getCurrentScopeName(nspace); if (!addSymbol(symname, n, scope)) return SWIG_ERROR; @@ -1305,12 +1322,11 @@ public: scope = Copy(module_class_name); } } else { - scope = NewString(""); - if (nspace) - Printf(scope, "%s.", nspace); - if (proxy_class_name) - Printf(scope, "%s.", proxy_class_name); - Printf(scope, "%s",Getattr(parent, "sym:name")); + scope = getCurrentScopeName(nspace); + if (!scope) + scope = Copy(Getattr(parent, "sym:name")); + else + Printf(scope, ".%s", Getattr(parent, "sym:name")); } if (!addSymbol(name, n, scope)) return SWIG_ERROR; diff --git a/Source/Modules/java.cxx b/Source/Modules/java.cxx index d378a02f3..c47dd3e48 100644 --- a/Source/Modules/java.cxx +++ b/Source/Modules/java.cxx @@ -1194,6 +1194,30 @@ public: return ret; } + String *getCurrentScopeName(String *nspace) + { + String *scope = 0; + if (nspace || getCurrentClass()) { + scope = NewString(""); + if (nspace) + Printf(scope, "%s", nspace); + if (Node* cls = getCurrentClass()) + { + if (Node *outer = Getattr(cls, "nested:outer")) { + String *outerClassesPrefix = Copy(Getattr(outer, "sym:name")); + for (outer = Getattr(outer, "nested:outer"); outer != 0; outer = Getattr(outer, "nested:outer")) { + Push(outerClassesPrefix, "."); + Push(outerClassesPrefix, Getattr(outer, "sym:name")); + } + Printv(scope, nspace ? "." : "", outerClassesPrefix, ".", proxy_class_name, NIL); + Delete(outerClassesPrefix); + } else + Printv(scope, nspace ? "." : "", proxy_class_name, NIL); + } + } + return scope; + } + /* ---------------------------------------------------------------------- * enumDeclaration() * @@ -1227,14 +1251,7 @@ public: if ((enum_feature != SimpleEnum) && symname && typemap_lookup_type) { // Wrap (non-anonymous) C/C++ enum within a typesafe, typeunsafe or proper Java enum - String *scope = 0; - if (nspace || proxy_class_name) { - scope = NewString(""); - if (nspace) - Printf(scope, "%s", nspace); - if (proxy_class_name) - Printv(scope, nspace ? "." : "", proxy_class_name, NIL); - } + String *scope = getCurrentScopeName(nspace); if (!addSymbol(symname, n, scope)) return SWIG_ERROR; @@ -1389,12 +1406,11 @@ public: scope = Copy(constants_interface_name); } } else { - scope = NewString(""); - if (nspace) - Printf(scope, "%s.", nspace); - if (proxy_class_name) - Printf(scope, "%s.", proxy_class_name); - Printf(scope, "%s",Getattr(parent, "sym:name")); + scope = getCurrentScopeName(nspace); + if (!scope) + scope = Copy(Getattr(parent, "sym:name")); + else + Printf(scope, ".%s", Getattr(parent, "sym:name")); } if (!addSymbol(name, n, scope)) return SWIG_ERROR; diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 795b9edb8..c3c148fa5 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -3620,4 +3620,3 @@ Language *Language::instance() { Hash *Language::getClassHash() const { return classhash; } - From 01ebdc0995e2c7b482cd44fa00412a9ed8e06d8a Mon Sep 17 00:00:00 2001 From: Ian Lance Taylor Date: Fri, 20 Dec 2013 08:14:45 -0800 Subject: [PATCH 257/481] In Examples/Makefile.in, compile and link the program in go and go_cpp, rather than in go_run. This permits eliminating go_run_cpp. --- Examples/Makefile.in | 45 ++++++++++++++++------------------ Examples/go/callback/Makefile | 2 +- Examples/go/class/Makefile | 2 +- Examples/go/enum/Makefile | 2 +- Examples/go/extend/Makefile | 2 +- Examples/go/reference/Makefile | 2 +- Examples/go/template/Makefile | 2 +- 7 files changed, 27 insertions(+), 30 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index d8ebb80e3..cee91db30 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -1598,6 +1598,16 @@ go: $(SRCS) $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)); \ fi; \ fi + if test -f $(RUNME).go; then \ + $(GO) $(GOCOMPILEARG) $(RUNME).go; \ + if $(GOGCC) ; then \ + $(COMPILETOOL) $(GO) -o $(RUNME) $(RUNME).@OBJEXT@ $(GOGCCOBJS) $(OBJS) $(IOBJS); \ + elif $(GO12); then \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CC) -extldflags "$(CFLAGS)" -o $(RUNME) $(RUNME).$(GOOBJEXT); \ + else \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $(RUNME) $(RUNME).$(GOOBJEXT); \ + fi; \ + fi # ---------------------------------------------------------------- # Build a Go module (C++) @@ -1621,35 +1631,22 @@ go_cpp: $(SRCS) $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)); \ fi; \ fi + if test -f $(RUNME).go; then \ + $(GO) $(GOCOMPILEARG) $(RUNME).go; \ + if $(GOGCC) ; then \ + $(COMPILETOOL) $(GO) -o $(RUNME) $(RUNME).@OBJEXT@ $(GOGCCOBJS) $(OBJS) $(IOBJS) -lstdc++; \ + elif $(GO12); then \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CXX) -extldflags "$(CXXFLAGS)" -o $(RUNME) $(RUNME).$(GOOBJEXT); \ + else \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $(RUNME) $(RUNME).$(GOOBJEXT); \ + fi; \ + fi # ----------------------------------------------------------------- # Running a Go example (C) # ----------------------------------------------------------------- -go_run: runme.go - $(GO) $(GOCOMPILEARG) runme.go - if $(GOGCC) ; then \ - $(COMPILETOOL) $(GO) -o runme runme.@OBJEXT@ $(GOGCCOBJS) $(OBJS) $(IOBJS); \ - elif $(GO12); then \ - $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CC) -extldflags "$(CFLAGS)" -o runme runme.$(GOOBJEXT); \ - else \ - $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o runme runme.$(GOOBJEXT); \ - fi - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) ./runme $(RUNPIPE) - -# ----------------------------------------------------------------- -# Running a Go example (C++) -# ----------------------------------------------------------------- - -go_run_cpp: runme.go - $(GO) $(GOCOMPILEARG) runme.go - if $(GOGCC) ; then \ - $(COMPILETOOL) $(GO) -o runme runme.@OBJEXT@ $(GOGCCOBJS) $(OBJS) $(IOBJS) -lstdc++; \ - elif $(GO12); then \ - $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CXX) -extldflags "$(CXXFLAGS)" -o runme runme.$(GOOBJEXT); \ - else \ - $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o runme runme.$(GOOBJEXT); \ - fi +go_run: env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) ./runme $(RUNPIPE) # ----------------------------------------------------------------- diff --git a/Examples/go/callback/Makefile b/Examples/go/callback/Makefile index 4516d2674..46a14b417 100644 --- a/Examples/go/callback/Makefile +++ b/Examples/go/callback/Makefile @@ -6,7 +6,7 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run_cpp + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ diff --git a/Examples/go/class/Makefile b/Examples/go/class/Makefile index 66b2df325..72605caa5 100644 --- a/Examples/go/class/Makefile +++ b/Examples/go/class/Makefile @@ -6,7 +6,7 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run_cpp + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ diff --git a/Examples/go/enum/Makefile b/Examples/go/enum/Makefile index 6f9347ca8..1ceecc15c 100644 --- a/Examples/go/enum/Makefile +++ b/Examples/go/enum/Makefile @@ -6,7 +6,7 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run_cpp + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ diff --git a/Examples/go/extend/Makefile b/Examples/go/extend/Makefile index 386d4d0bb..67da89286 100644 --- a/Examples/go/extend/Makefile +++ b/Examples/go/extend/Makefile @@ -6,7 +6,7 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run_cpp + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ diff --git a/Examples/go/reference/Makefile b/Examples/go/reference/Makefile index 5c5e6808b..41a944239 100644 --- a/Examples/go/reference/Makefile +++ b/Examples/go/reference/Makefile @@ -6,7 +6,7 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run_cpp + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ diff --git a/Examples/go/template/Makefile b/Examples/go/template/Makefile index 20ffb7136..6796348a9 100644 --- a/Examples/go/template/Makefile +++ b/Examples/go/template/Makefile @@ -6,7 +6,7 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run_cpp + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ From 32ad89668a69bbddd5a2672822d3fa291d537c5f Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 20 Dec 2013 18:43:33 +0000 Subject: [PATCH 258/481] Use RUNME consistently in examples makefile --- Examples/Makefile.in | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index cee91db30..4c1a11ca4 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -1252,7 +1252,7 @@ csharp_version: # ----------------------------------------------------------------- csharp_clean: - rm -f *_wrap* *~ .~* runme runme.exe *.exe.mdb gc.log `find . -name \*.cs | grep -v runme.cs` + rm -f *_wrap* *~ .~* $(RUNME) $(RUNME).exe *.exe.mdb gc.log `find . -name \*.cs | grep -v $(RUNME).cs` rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *@CSHARPSO@ @@ -1643,11 +1643,11 @@ go_cpp: $(SRCS) fi # ----------------------------------------------------------------- -# Running a Go example (C) +# Running Go example # ----------------------------------------------------------------- go_run: - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) ./runme $(RUNPIPE) + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) ./$(RUNME) $(RUNPIPE) # ----------------------------------------------------------------- # Version display @@ -1661,7 +1661,7 @@ go_version: # ----------------------------------------------------------------- go_clean: - rm -f *_wrap* *_gc* .~* runme $(GOSRCS) + rm -f *_wrap* *_gc* .~* $(RUNME) $(GOSRCS) rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *.[568] *.a *@SO@ @@ -1732,6 +1732,6 @@ d_version: # ----------------------------------------------------------------- d_clean: - rm -f *_wrap* *~ .~* runme runme.exe `find . -name \*.d | grep -v runme.d` + rm -f *_wrap* *~ .~* $(RUNME) $(RUNME).exe `find . -name \*.d | grep -v $(RUNME).d` rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *@SO@ From 6250c288b5b83b95807e063427fc8c00d739b00b Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 22 Dec 2013 17:49:16 +0000 Subject: [PATCH 259/481] Suppress gcc-4.9 auto_ptr deprecation in test --- Examples/test-suite/li_std_auto_ptr.i | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Examples/test-suite/li_std_auto_ptr.i b/Examples/test-suite/li_std_auto_ptr.i index b58a1d79d..1dcb3e02e 100644 --- a/Examples/test-suite/li_std_auto_ptr.i +++ b/Examples/test-suite/li_std_auto_ptr.i @@ -1,5 +1,11 @@ %module li_std_auto_ptr +%{ +#if (__GNUC__ == 4 && __GNUC_MINOR__ >= 9) +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" // auto_ptr deprecation +#endif +%} + #if defined(SWIGCSHARP) || defined(SWIGJAVA) || defined(SWIGPYTHON) %include "std_auto_ptr.i" From cf92954bc06a9f245d14de2440896b3866b29ed3 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 22 Dec 2013 19:38:46 +0000 Subject: [PATCH 260/481] C++11 tests re-organise - gcc-4.8 minimum expected for all to pass --- Examples/test-suite/common.mk | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 7972b28d8..642e7fd8c 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -491,6 +491,7 @@ CPP11_TEST_CASES = \ cpp11_delegating_constructors \ cpp11_explicit_conversion_operators \ cpp11_function_objects \ + cpp11_inheriting_constructors \ cpp11_initializer_list \ cpp11_initializer_list_extend \ cpp11_lambda_functions \ @@ -502,7 +503,7 @@ CPP11_TEST_CASES = \ cpp11_rvalue_reference3 \ cpp11_sizeof_object \ cpp11_static_assert \ - cpp11_strongly_typed_enumerations \ + cpp11_thread_local \ cpp11_template_double_brackets \ cpp11_template_explicit \ cpp11_template_typedefs \ @@ -511,10 +512,9 @@ CPP11_TEST_CASES = \ cpp11_userdefined_literals \ cpp11_variadic_templates -# cpp11_inheriting_constructors \ # not supported by gcc-4.7 # cpp11_hash_tables \ # not fully implemented yet # cpp11_result_of \ # SWIG does not support -# cpp11_thread_local \ # needs gcc-4.8 +# cpp11_strongly_typed_enumerations \ # SWIG not quite getting this right yet in all langs # Broken C++11 test cases. CPP11_TEST_BROKEN = From 92128eef445f75f674894e3f5d4e1fc2a1818957 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 22 Dec 2013 19:39:21 +0000 Subject: [PATCH 261/481] C++11 support for new versions of erase and insert in the STL containers. The erase and insert methods in the containers use const_iterator instead of iterator in C++11. There are times when the methods wrapped must match the parameters exactly. Specifically when full type information for template types is missing or SWIG fails to look up the type correctly, for example: %include typedef float Real; %template(RealVector) std::vector; SWIG does not find std::vector::iterator because %template using typedefs does not always work and so SWIG doesn't know if the type is copyable and so uses SwigValueWrapper which does not support conversion to another type (const_iterator). This resulted in compilation errors when using the C++11 version of the containers. Closes #73 --- CHANGES.current | 21 +++++++++++++++++++++ Lib/std/std_container.i | 21 +++++++++++++++------ Lib/std/std_map.i | 8 +++++--- Lib/std/std_set.i | 7 +++++-- Lib/std/std_unordered_map.i | 8 +++++--- Lib/std/std_unordered_set.i | 7 +++++-- 6 files changed, 56 insertions(+), 16 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index f9934b49d..c9043df14 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,27 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2013-12-22: wsfulton + C++11 support for new versions of erase and insert in the STL containers. + + The erase and insert methods in the containers use const_iterator instead + of iterator in C++11. There are times when the methods wrapped must match + the parameters exactly. Specifically when full type information for + template types is missing or SWIG fails to look up the type correctly, + for example: + + %include + typedef float Real; + %template(RealVector) std::vector; + + SWIG does not find std::vector::iterator because %template using + typedefs does not always work and so SWIG doesn't know if the type is + copyable and so uses SwigValueWrapper which does + not support conversion to another type (const_iterator). This resulted + in compilation errors when using the C++11 version of the containers. + + Closes #73 + 2013-12-18: ianlancetaylor [Go] Don't require that Go environment variables be set when running examples or testsuite when using Go 1 or diff --git a/Lib/std/std_container.i b/Lib/std/std_container.i index 73d0c6ad9..8ed327bbe 100644 --- a/Lib/std/std_container.i +++ b/Lib/std/std_container.i @@ -46,8 +46,11 @@ void resize(size_type new_size); #ifdef SWIG_EXPORT_ITERATOR_METHODS - iterator erase(iterator pos); - iterator erase(iterator first, iterator last); +%extend { + // %extend wrapper used for differing definitions of these methods introduced in C++11 + iterator erase(iterator pos) { return $self->erase(pos); } + iterator erase(iterator first, iterator last) { return $self->erase(first, last); } +} #endif %enddef @@ -68,8 +71,11 @@ void resize(size_type new_size, const value_type& x); #ifdef SWIG_EXPORT_ITERATOR_METHODS - iterator insert(iterator pos, const value_type& x); - void insert(iterator pos, size_type n, const value_type& x); +%extend { + // %extend wrapper used for differing definitions of these methods introduced in C++11 + iterator insert(iterator pos, const value_type& x) { return $self->insert(pos, x); } + void insert(iterator pos, size_type n, const value_type& x) { $self->insert(pos, n, x); } +} #endif %enddef @@ -89,8 +95,11 @@ void resize(size_type new_size, value_type x); #ifdef SWIG_EXPORT_ITERATOR_METHODS - iterator insert(iterator pos, value_type x); - void insert(iterator pos, size_type n, value_type x); +%extend { + // %extend wrapper used for differing definitions of these methods introduced in C++11 + iterator insert(iterator pos, value_type x) { return $self->insert(pos, x); } + void insert(iterator pos, size_type n, value_type x) { $self->insert(pos, n, x); } +} #endif %enddef diff --git a/Lib/std/std_map.i b/Lib/std/std_map.i index 05208418f..e523c3deb 100644 --- a/Lib/std/std_map.i +++ b/Lib/std/std_map.i @@ -12,9 +12,11 @@ size_type count(const key_type& x) const; #ifdef SWIG_EXPORT_ITERATOR_METHODS -// iterator insert(iterator position, const value_type& x); - void erase(iterator position); - void erase(iterator first, iterator last); +%extend { + // %extend wrapper used for differing definitions of these methods introduced in C++11 + void erase(iterator position) { $self->erase(position); } + void erase(iterator first, iterator last) { $self->erase(first, last); } +} iterator find(const key_type& x); iterator lower_bound(const key_type& x); diff --git a/Lib/std/std_set.i b/Lib/std/std_set.i index 16f0f1482..f96ddd9f1 100644 --- a/Lib/std/std_set.i +++ b/Lib/std/std_set.i @@ -29,8 +29,11 @@ reverse_iterator rbegin(); reverse_iterator rend(); - void erase(iterator pos); - void erase(iterator first, iterator last); +%extend { + // %extend wrapper used for differing definitions of these methods introduced in C++11 + void erase(iterator pos) { $self->erase(pos); } + void erase(iterator first, iterator last) { $self->erase(first, last); } +} iterator find(const key_type& x); iterator lower_bound(const key_type& x); diff --git a/Lib/std/std_unordered_map.i b/Lib/std/std_unordered_map.i index 3c36d78e3..3d80788e2 100644 --- a/Lib/std/std_unordered_map.i +++ b/Lib/std/std_unordered_map.i @@ -15,9 +15,11 @@ size_type count(const key_type& x) const; #ifdef SWIG_EXPORT_ITERATOR_METHODS -// iterator insert(iterator position, const value_type& x); - void erase(iterator position); - void erase(iterator first, iterator last); +%extend { + // %extend wrapper used for differing definitions of these methods introduced in C++11 + void erase(iterator position) { $self->erase(position); } + void erase(iterator first, iterator last) { $self->erase(first, last); } +} iterator find(const key_type& x); iterator lower_bound(const key_type& x); diff --git a/Lib/std/std_unordered_set.i b/Lib/std/std_unordered_set.i index 4cdfd65a5..ed8888eb4 100644 --- a/Lib/std/std_unordered_set.i +++ b/Lib/std/std_unordered_set.i @@ -29,8 +29,11 @@ iterator begin(); iterator end(); - void erase(iterator pos); - void erase(iterator first, iterator last); +%extend { + // %extend wrapper used for differing definitions of these methods introduced in C++11 + void erase(iterator pos) { $self->erase(pos); } + void erase(iterator first, iterator last) { $self->erase(first, last); } +} iterator find(const key_type& x); std::pair equal_range(const key_type& x); From e7834c8daa9414a631e90c1b03372ab5668302d8 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 23 Dec 2013 18:04:14 +0000 Subject: [PATCH 262/481] Perl directors changes entry added and minor tidy up --- .travis.yml | 1 - CHANGES.current | 3 +++ Examples/perl5/callback/runme.pl | 2 +- Examples/perl5/check.list | 4 ++-- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 2b860cc9e..70cbb2f27 100644 --- a/.travis.yml +++ b/.travis.yml @@ -57,4 +57,3 @@ script: branches: only: - master - - perl5-directors-minimal diff --git a/CHANGES.current b/CHANGES.current index c9043df14..59ebeebcd 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,9 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2013-12-23: talby + [Perl] Add support for directors. + 2013-12-22: wsfulton C++11 support for new versions of erase and insert in the STL containers. diff --git a/Examples/perl5/callback/runme.pl b/Examples/perl5/callback/runme.pl index a6b80d988..54d86783a 100644 --- a/Examples/perl5/callback/runme.pl +++ b/Examples/perl5/callback/runme.pl @@ -29,7 +29,7 @@ $caller->setCallback($callback); $caller->call(); $caller->delCallback(); -print +print "\n"; print "Adding and calling a Perl callback\n"; print "----------------------------------\n"; diff --git a/Examples/perl5/check.list b/Examples/perl5/check.list index 925bd263f..78d45fc0b 100644 --- a/Examples/perl5/check.list +++ b/Examples/perl5/check.list @@ -1,7 +1,9 @@ # see top-level Makefile.in +callback class constants constants2 +extend funcptr import multimap @@ -11,5 +13,3 @@ reference simple value variables -callback -extend From 279ebdc0cf655feca4c80c23f115e90ce0470102 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 23 Dec 2013 18:21:52 +0000 Subject: [PATCH 263/481] Beautify director output --- Lib/perl5/director.swg | 16 ++++++++-------- Lib/python/director.swg | 32 ++++++++++++++++---------------- Source/Modules/perl5.cxx | 13 +++++++------ Source/Modules/python.cxx | 15 ++++++++------- 4 files changed, 39 insertions(+), 37 deletions(-) diff --git a/Lib/perl5/director.swg b/Lib/perl5/director.swg index 5acc4fd15..34514972a 100644 --- a/Lib/perl5/director.swg +++ b/Lib/perl5/director.swg @@ -33,8 +33,8 @@ namespace Swig { class Director; - SWIGINTERN std::map& get_rtdir_map() { - static std::map rtdir_map; + SWIGINTERN std::map& get_rtdir_map() { + static std::map rtdir_map; return rtdir_map; } @@ -43,15 +43,15 @@ namespace Swig { } SWIGINTERNINLINE Director *get_rtdir(void *vptr) { - std::map::const_iterator pos = get_rtdir_map().find(vptr); + std::map::const_iterator pos = get_rtdir_map().find(vptr); Director *rtdir = (pos != get_rtdir_map().end()) ? pos->second : 0; return rtdir; } } # endif /* SWIG_DIRECTOR_RTDIR */ -# define SWIG_DIRECTOR_CAST(ARG) Swig::get_rtdir(static_cast(ARG)) -# define SWIG_DIRECTOR_RGTR(ARG1, ARG2) Swig::set_rtdir(static_cast(ARG1), ARG2) +# define SWIG_DIRECTOR_CAST(ARG) Swig::get_rtdir(static_cast(ARG)) +# define SWIG_DIRECTOR_RGTR(ARG1, ARG2) Swig::set_rtdir(static_cast(ARG1), ARG2) #else @@ -293,16 +293,16 @@ namespace Swig { } /* methods to implement pseudo protected director members */ - virtual bool swig_get_inner(const char* /* swig_protected_method_name */) const { + virtual bool swig_get_inner(const char * /* swig_protected_method_name */) const { return true; } - virtual void swig_set_inner(const char* /* swig_protected_method_name */, bool /* swig_val */) const { + virtual void swig_set_inner(const char * /* swig_protected_method_name */, bool /* swig_val */) const { } /* ownership management */ private: - typedef std::map swig_ownership_map; + typedef std::map swig_ownership_map; mutable swig_ownership_map swig_owner; public: diff --git a/Lib/python/director.swg b/Lib/python/director.swg index 97edc7ef0..d6bfe51f0 100644 --- a/Lib/python/director.swg +++ b/Lib/python/director.swg @@ -68,8 +68,8 @@ namespace Swig { class Director; - SWIGINTERN std::map& get_rtdir_map() { - static std::map rtdir_map; + SWIGINTERN std::map& get_rtdir_map() { + static std::map rtdir_map; return rtdir_map; } @@ -78,15 +78,15 @@ namespace Swig { } SWIGINTERNINLINE Director *get_rtdir(void *vptr) { - std::map::const_iterator pos = get_rtdir_map().find(vptr); + std::map::const_iterator pos = get_rtdir_map().find(vptr); Director *rtdir = (pos != get_rtdir_map().end()) ? pos->second : 0; return rtdir; } } # endif /* SWIG_DIRECTOR_RTDIR */ -# define SWIG_DIRECTOR_CAST(ARG) Swig::get_rtdir(static_cast(ARG)) -# define SWIG_DIRECTOR_RGTR(ARG1, ARG2) Swig::set_rtdir(static_cast(ARG1), ARG2) +# define SWIG_DIRECTOR_CAST(ARG) Swig::get_rtdir(static_cast(ARG)) +# define SWIG_DIRECTOR_RGTR(ARG1, ARG2) Swig::set_rtdir(static_cast(ARG1), ARG2) #else @@ -196,7 +196,7 @@ namespace Swig { protected: std::string swig_msg; public: - DirectorException(PyObject *error, const char* hdr ="", const char* msg ="") + DirectorException(PyObject *error, const char *hdr ="", const char *msg ="") : swig_msg(hdr) { SWIG_PYTHON_THREAD_BEGIN_BLOCK; @@ -272,12 +272,12 @@ namespace Swig { /* type mismatch in the return value from a python method call */ class DirectorTypeMismatchException : public Swig::DirectorException { public: - DirectorTypeMismatchException(PyObject *error, const char* msg="") + DirectorTypeMismatchException(PyObject *error, const char *msg="") : Swig::DirectorException(error, "SWIG director type mismatch", msg) { } - DirectorTypeMismatchException(const char* msg="") + DirectorTypeMismatchException(const char *msg="") : Swig::DirectorException(PyExc_TypeError, "SWIG director type mismatch", msg) { } @@ -296,7 +296,7 @@ namespace Swig { /* any python exception that occurs during a director method call */ class DirectorMethodException : public Swig::DirectorException { public: - DirectorMethodException(const char* msg = "") + DirectorMethodException(const char *msg = "") : DirectorException(PyExc_RuntimeError, "SWIG director method error.", msg) { } @@ -311,7 +311,7 @@ namespace Swig { class DirectorPureVirtualException : public Swig::DirectorException { public: - DirectorPureVirtualException(const char* msg = "") + DirectorPureVirtualException(const char *msg = "") : DirectorException(PyExc_RuntimeError, "SWIG director pure virtual method called", msg) { } @@ -356,7 +356,7 @@ namespace Swig { class Director { private: /* pointer to the wrapped python object */ - PyObject* swig_self; + PyObject *swig_self; /* flag indicating whether the object is owned by python or c++ */ mutable bool swig_disown_flag; @@ -371,7 +371,7 @@ namespace Swig { public: /* wrap a python object, optionally taking ownership */ - Director(PyObject* self) : swig_self(self), swig_disown_flag(false) { + Director(PyObject *self) : swig_self(self), swig_disown_flag(false) { swig_incref(); } @@ -404,16 +404,16 @@ namespace Swig { } /* methods to implement pseudo protected director members */ - virtual bool swig_get_inner(const char* /* swig_protected_method_name */) const { + virtual bool swig_get_inner(const char * /* swig_protected_method_name */) const { return true; } - virtual void swig_set_inner(const char* /* swig_protected_method_name */, bool /* swig_val */) const { + virtual void swig_set_inner(const char * /* swig_protected_method_name */, bool /* swig_val */) const { } /* ownership management */ private: - typedef std::map swig_ownership_map; + typedef std::map swig_ownership_map; mutable swig_ownership_map swig_owner; #ifdef __THREAD__ static PyThread_type_lock swig_mutex_own; @@ -461,7 +461,7 @@ namespace Swig { } template - static PyObject* swig_pyobj_disown(PyObject *pyobj, PyObject *SWIGUNUSEDPARM(args)) + static PyObject *swig_pyobj_disown(PyObject *pyobj, PyObject *SWIGUNUSEDPARM(args)) { SwigPyObject *sobj = (SwigPyObject *)pyobj; sobj->own = 0; diff --git a/Source/Modules/perl5.cxx b/Source/Modules/perl5.cxx index d7a131aa2..28f4a3f3d 100644 --- a/Source/Modules/perl5.cxx +++ b/Source/Modules/perl5.cxx @@ -1988,16 +1988,17 @@ public: But for now, this seems to be the least intrusive way. */ - Printf(f_directors_h, "\n\n"); - Printf(f_directors_h, "/* Internal Director utilities */\n"); + Printf(f_directors_h, "\n"); + Printf(f_directors_h, "/* Internal director utilities */\n"); Printf(f_directors_h, "public:\n"); - Printf(f_directors_h, " bool swig_get_inner(const char* swig_protected_method_name) const {\n"); + Printf(f_directors_h, " bool swig_get_inner(const char *swig_protected_method_name) const {\n"); Printf(f_directors_h, " std::map::const_iterator iv = swig_inner.find(swig_protected_method_name);\n"); Printf(f_directors_h, " return (iv != swig_inner.end() ? iv->second : false);\n"); - Printf(f_directors_h, " }\n\n"); + Printf(f_directors_h, " }\n"); - Printf(f_directors_h, " void swig_set_inner(const char* swig_protected_method_name, bool val) const\n"); - Printf(f_directors_h, " { swig_inner[swig_protected_method_name] = val;}\n\n"); + Printf(f_directors_h, " void swig_set_inner(const char *swig_protected_method_name, bool val) const {\n"); + Printf(f_directors_h, " swig_inner[swig_protected_method_name] = val;\n"); + Printf(f_directors_h, " }\n"); Printf(f_directors_h, "private:\n"); Printf(f_directors_h, " mutable std::map swig_inner;\n"); } diff --git a/Source/Modules/python.cxx b/Source/Modules/python.cxx index 1022f9fa0..e281bbbec 100644 --- a/Source/Modules/python.cxx +++ b/Source/Modules/python.cxx @@ -3074,22 +3074,23 @@ public: But for now, this seems to be the least intrusive way. */ - Printf(f_directors_h, "\n\n"); - Printf(f_directors_h, "/* Internal Director utilities */\n"); + Printf(f_directors_h, "\n"); + Printf(f_directors_h, "/* Internal director utilities */\n"); Printf(f_directors_h, "public:\n"); - Printf(f_directors_h, " bool swig_get_inner(const char* swig_protected_method_name) const {\n"); + Printf(f_directors_h, " bool swig_get_inner(const char *swig_protected_method_name) const {\n"); Printf(f_directors_h, " std::map::const_iterator iv = swig_inner.find(swig_protected_method_name);\n"); Printf(f_directors_h, " return (iv != swig_inner.end() ? iv->second : false);\n"); - Printf(f_directors_h, " }\n\n"); + Printf(f_directors_h, " }\n"); - Printf(f_directors_h, " void swig_set_inner(const char* swig_protected_method_name, bool val) const\n"); - Printf(f_directors_h, " { swig_inner[swig_protected_method_name] = val;}\n\n"); + Printf(f_directors_h, " void swig_set_inner(const char *swig_protected_method_name, bool val) const {\n"); + Printf(f_directors_h, " swig_inner[swig_protected_method_name] = val;\n"); + Printf(f_directors_h, " }\n"); Printf(f_directors_h, "private:\n"); Printf(f_directors_h, " mutable std::map swig_inner;\n"); } if (director_method_index) { - Printf(f_directors_h, "\n\n"); + Printf(f_directors_h, "\n"); Printf(f_directors_h, "#if defined(SWIG_PYTHON_DIRECTOR_VTABLE)\n"); Printf(f_directors_h, "/* VTable implementation */\n"); Printf(f_directors_h, " PyObject *swig_get_method(size_t method_index, const char *method_name) const {\n"); From 135a7cc558442062ce8d65de834870a71eb30aca Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 23 Dec 2013 19:50:41 +0000 Subject: [PATCH 264/481] Beautify director.swg files Also some comment corrections for Perl --- Lib/csharp/director.swg | 9 +- Lib/d/director.swg | 8 +- Lib/java/director.swg | 4 +- Lib/ocaml/director.swg | 33 +++--- Lib/octave/director.swg | 15 ++- Lib/perl5/director.swg | 122 +++++++++------------- Lib/php/director.swg | 87 ++++++---------- Lib/python/director.swg | 218 ++++++++++++++++------------------------ Lib/ruby/director.swg | 199 +++++++++++++++--------------------- 9 files changed, 289 insertions(+), 406 deletions(-) diff --git a/Lib/csharp/director.swg b/Lib/csharp/director.swg index 7768d8c02..c68c2d98f 100644 --- a/Lib/csharp/director.swg +++ b/Lib/csharp/director.swg @@ -1,7 +1,7 @@ /* ----------------------------------------------------------------------------- * director.swg * - * This file contains support for director classes so that C# proxy + * This file contains support for director classes so that C# proxy * methods can be called from C++. * ----------------------------------------------------------------------------- */ @@ -23,13 +23,16 @@ namespace Swig { std::string swig_msg; public: - DirectorException(const char* msg) : swig_msg(msg) { + DirectorException(const char *msg) : swig_msg(msg) { } + DirectorException(const std::string &msg) : swig_msg(msg) { } + const std::string& what() const { return swig_msg; } + virtual ~DirectorException() { } }; @@ -37,7 +40,7 @@ namespace Swig { /* Pure virtual method exception */ class DirectorPureVirtualException : public Swig::DirectorException { public: - DirectorPureVirtualException(const char* msg) : DirectorException(std::string("Attempt to invoke pure virtual method ") + msg) { + DirectorPureVirtualException(const char *msg) : DirectorException(std::string("Attempt to invoke pure virtual method ") + msg) { } }; } diff --git a/Lib/d/director.swg b/Lib/d/director.swg index 9692e03c1..d0ef2372b 100644 --- a/Lib/d/director.swg +++ b/Lib/d/director.swg @@ -13,6 +13,7 @@ #include namespace Swig { + // Director base class – not used in D directors. class Director { }; @@ -23,13 +24,16 @@ namespace Swig { std::string swig_msg; public: - DirectorException(const char* msg) : swig_msg(msg) { + DirectorException(const char *msg) : swig_msg(msg) { } + DirectorException(const std::string &msg) : swig_msg(msg) { } + const std::string& what() const { return swig_msg; } + virtual ~DirectorException() { } }; @@ -38,7 +42,7 @@ namespace Swig { // from D code thorugh the director layer. class DirectorPureVirtualException : public Swig::DirectorException { public: - DirectorPureVirtualException(const char* msg) : DirectorException(std::string("Attempted to invoke pure virtual method ") + msg) { + DirectorPureVirtualException(const char *msg) : DirectorException(std::string("Attempted to invoke pure virtual method ") + msg) { } }; } diff --git a/Lib/java/director.swg b/Lib/java/director.swg index f9ddbeffe..86880a55e 100644 --- a/Lib/java/director.swg +++ b/Lib/java/director.swg @@ -126,7 +126,7 @@ namespace Swig { #endif env_status = director_->swig_jvm_->GetEnv((void **)&jenv_, JNI_VERSION_1_2); #if defined(SWIG_JAVA_ATTACH_CURRENT_THREAD_AS_DAEMON) - // Attach a daemon thread to the JVM. Useful when the JVM should not wait for + // Attach a daemon thread to the JVM. Useful when the JVM should not wait for // the thread to exit upon shutdown. Only for jdk-1.4 and later. director_->swig_jvm_->AttachCurrentThreadAsDaemon(jenv, NULL); #else @@ -358,7 +358,7 @@ namespace Swig { if (throwable && jenv && classname) { // Exceptions need to be cleared for correct behavior. - // The caller of ExceptionMatches should restore pending exceptions if desired - + // The caller of ExceptionMatches should restore pending exceptions if desired - // the caller already has the throwable. jenv->ExceptionClear(); diff --git a/Lib/ocaml/director.swg b/Lib/ocaml/director.swg index 77b2fd3c0..dc4c69b7d 100644 --- a/Lib/ocaml/director.swg +++ b/Lib/ocaml/director.swg @@ -18,18 +18,21 @@ namespace Swig { protected: std::string swig_msg; public: - DirectorException(const char* msg="") { + DirectorException(const char *msg="") { } - const char *getMessage() const { - return swig_msg.c_str(); + + const char *getMessage() const { + return swig_msg.c_str(); + } + + virtual ~DirectorException() { } - virtual ~DirectorException() {} }; /* type mismatch in the return value from a python method call */ class DirectorTypeMismatchException : public Swig::DirectorException { public: - DirectorTypeMismatchException(const char* msg="") { + DirectorTypeMismatchException(const char *msg="") { } }; @@ -39,7 +42,7 @@ namespace Swig { /* attempt to call a pure virtual method via a director method */ class DirectorPureVirtualException : public Swig::DirectorException { public: - DirectorPureVirtualException(const char* msg="") { + DirectorPureVirtualException(const char *msg="") { } static void raise(const char *msg) { @@ -57,7 +60,7 @@ namespace Swig { #define MUTEX_INIT(var) CRITICAL_SECTION var #else #include -#define MUTEX_INIT(var) pthread_mutex_t var = PTHREAD_MUTEX_INITIALIZER +#define MUTEX_INIT(var) pthread_mutex_t var = PTHREAD_MUTEX_INITIALIZER #endif #endif @@ -78,23 +81,21 @@ namespace Swig { /* discard our reference at destruction */ virtual ~Director() { remove_global_root(&swig_self); - swig_disown(); - // Disown is safe here because we're just divorcing a reference that - // points to us. + swig_disown(); + // Disown is safe here because we're just divorcing a reference that points to us. } /* return a pointer to the wrapped ocaml object */ - CAML_VALUE swig_get_self() const { + CAML_VALUE swig_get_self() const { return swig_self; } - /* acquire ownership of the wrapped ocaml object (the sense of "disown" - * is from ocaml) */ - void swig_disown() const { - if (!swig_disown_flag) { + /* acquire ownership of the wrapped ocaml object (the sense of "disown" is from ocaml) */ + void swig_disown() const { + if (!swig_disown_flag) { swig_disown_flag=true; callback(*caml_named_value("caml_obj_disown"),swig_self); - } + } } }; } diff --git a/Lib/octave/director.swg b/Lib/octave/director.swg index 5e5d6f1f4..ce4377ef1 100644 --- a/Lib/octave/director.swg +++ b/Lib/octave/director.swg @@ -1,3 +1,10 @@ +/* ----------------------------------------------------------------------------- + * director.swg + * + * This file contains support for director classes so that D proxy + * methods can be called from C++. + * ----------------------------------------------------------------------------- */ + # define SWIG_DIRECTOR_CAST(ARG) dynamic_cast(ARG) @@ -62,7 +69,7 @@ namespace Swig { } }; - SWIGINTERN rtdir_map* get_rtdir_map() { + SWIGINTERN rtdir_map *get_rtdir_map() { static swig_module_info *module = 0; if (!module) module = SWIG_GetModule(0); @@ -74,19 +81,19 @@ namespace Swig { } SWIGINTERNINLINE void set_rtdir(void *vptr, Director *d) { - rtdir_map* rm = get_rtdir_map(); + rtdir_map *rm = get_rtdir_map(); if (rm) (*rm)[vptr] = d; } SWIGINTERNINLINE void erase_rtdir(void *vptr) { - rtdir_map* rm = get_rtdir_map(); + rtdir_map *rm = get_rtdir_map(); if (rm) (*rm).erase(vptr); } SWIGINTERNINLINE Director *get_rtdir(void *vptr) { - rtdir_map* rm = get_rtdir_map(); + rtdir_map *rm = get_rtdir_map(); if (!rm) return 0; rtdir_map::const_iterator pos = rm->find(vptr); diff --git a/Lib/perl5/director.swg b/Lib/perl5/director.swg index 34514972a..0e7faee6c 100644 --- a/Lib/perl5/director.swg +++ b/Lib/perl5/director.swg @@ -2,7 +2,7 @@ * director.swg * * This file contains support for director classes that proxy - * method calls from C++ to Python extensions. + * method calls from C++ to Perl extensions. * ----------------------------------------------------------------------------- */ #ifndef SWIG_DIRECTOR_PERL_HEADER_ @@ -67,37 +67,30 @@ extern "C" { namespace Swig { /* memory handler */ - struct GCItem - { + struct GCItem { virtual ~GCItem() {} - virtual int get_own() const - { + virtual int get_own() const { return 0; } }; - struct GCItem_var - { - GCItem_var(GCItem *item = 0) : _item(item) - { + struct GCItem_var { + GCItem_var(GCItem *item = 0) : _item(item) { } - GCItem_var& operator=(GCItem *item) - { + GCItem_var& operator=(GCItem *item) { GCItem *tmp = _item; _item = item; delete tmp; return *this; } - ~GCItem_var() - { + ~GCItem_var() { delete _item; } - GCItem * operator->() const - { + GCItem *operator->() const { return _item; } @@ -105,18 +98,14 @@ namespace Swig { GCItem *_item; }; - struct GCItem_Object : GCItem - { - GCItem_Object(int own) : _own(own) - { + struct GCItem_Object : GCItem { + GCItem_Object(int own) : _own(own) { } - virtual ~GCItem_Object() - { + virtual ~GCItem_Object() { } - int get_own() const - { + int get_own() const { return _own; } @@ -125,14 +114,11 @@ namespace Swig { }; template - struct GCItem_T : GCItem - { - GCItem_T(Type *ptr) : _ptr(ptr) - { + struct GCItem_T : GCItem { + GCItem_T(Type *ptr) : _ptr(ptr) { } - virtual ~GCItem_T() - { + virtual ~GCItem_T() { delete _ptr; } @@ -141,14 +127,11 @@ namespace Swig { }; template - struct GCArray_T : GCItem - { - GCArray_T(Type *ptr) : _ptr(ptr) - { + struct GCArray_T : GCItem { + GCArray_T(Type *ptr) : _ptr(ptr) { } - virtual ~GCArray_T() - { + virtual ~GCArray_T() { delete[] _ptr; } @@ -162,30 +145,29 @@ namespace Swig { virtual const char *getMessage() const = 0; virtual SV *getNative() const = 0; }; + /* exceptions emitted by Perl */ class DirectorMethodException : public Swig::DirectorException { protected: SV *err; public: - DirectorMethodException(SV *sv = sv_mortalcopy(ERRSV)) - : err(sv) - { + DirectorMethodException(SV *sv = sv_mortalcopy(ERRSV)) : err(sv) { SvREFCNT_inc(err); } - ~DirectorMethodException() - { + + ~DirectorMethodException() { SvREFCNT_dec(err); } - const char *getMessage() const - { + + const char *getMessage() const { return SvPV_nolen(err); } - SV *getNative() const - { + + SV *getNative() const { return sv_2mortal(newSVsv(err)); } - static void raise(SV *sv) - { + + static void raise(SV *sv) { throw DirectorMethodException(sv); } }; @@ -193,42 +175,38 @@ namespace Swig { class DirectorWrapException : public Swig::DirectorException { protected: std::string msg; - DirectorWrapException(const char *str) - : msg(str) - { + DirectorWrapException(const char *str) : msg(str) { } + public: - virtual const char *getMessage() const - { + virtual const char *getMessage() const { return msg.c_str(); } + virtual SV *getNative() const { return sv_2mortal(newSVpvn(msg.data(), msg.size())); } }; + class DirectorTypeMismatchException : public Swig::DirectorWrapException { public: - DirectorTypeMismatchException(const char *str) - : DirectorWrapException(str) - { + DirectorTypeMismatchException(const char *str) : DirectorWrapException(str) { } - static void raise(const char *type, const char *msg) - { + static void raise(const char *type, const char *msg) { std::string err = std::string(type); err += ": "; err += msg; throw DirectorTypeMismatchException(err.c_str()); } }; + class DirectorPureVirtualException : public Swig::DirectorWrapException { public: DirectorPureVirtualException(const char *name) - : DirectorWrapException("SWIG director pure virtual method called: ") - { + : DirectorWrapException("SWIG director pure virtual method called: ") { msg += name; } - static void raise(const char *name) - { + static void raise(const char *name) { throw DirectorPureVirtualException(name); } }; @@ -251,7 +229,7 @@ namespace Swig { } public: - /* wrap a python object, optionally taking ownership */ + /* wrap a Perl object, optionally taking ownership */ Director(SV *pkg) : swig_disown_flag(false) { STRLEN len; char *str = SvPV(pkg, len); @@ -260,14 +238,12 @@ namespace Swig { swig_incref(); } - /* discard our reference at destruction */ virtual ~Director() { swig_decref(); } - - /* return a pointer to the wrapped python object */ + /* return a pointer to the wrapped Perl object */ SV *swig_get_self() const { return swig_self; } @@ -276,8 +252,7 @@ namespace Swig { return swig_class.c_str(); } - /* acquire ownership of the wrapped python object (the sense of "disown" - * is from python) */ + /* acquire ownership of the wrapped Perl object (the sense of "disown" is from perl) */ void swig_disown() const { if (!swig_disown_flag) { swig_disown_flag=true; @@ -285,7 +260,7 @@ namespace Swig { } } - /* increase the reference count of the wrapped python object */ + /* increase the reference count of the wrapped Perl object */ void swig_incref() const { if (swig_disown_flag) { SvREFCNT_inc(swig_self); @@ -307,30 +282,26 @@ namespace Swig { public: template - void swig_acquire_ownership_array(Type *vptr) const - { + void swig_acquire_ownership_array(Type *vptr) const { if (vptr) { swig_owner[vptr] = new GCArray_T(vptr); } } template - void swig_acquire_ownership(Type *vptr) const - { + void swig_acquire_ownership(Type *vptr) const { if (vptr) { swig_owner[vptr] = new GCItem_T(vptr); } } - void swig_acquire_ownership_obj(void *vptr, int own) const - { + void swig_acquire_ownership_obj(void *vptr, int own) const { if (vptr && own) { swig_owner[vptr] = new GCItem_Object(own); } } - int swig_release_ownership(void *vptr) const - { + int swig_release_ownership(void *vptr) const { int own = 0; if (vptr) { swig_ownership_map::iterator iter = swig_owner.find(vptr); @@ -341,7 +312,6 @@ namespace Swig { } return own; } - }; } diff --git a/Lib/php/director.swg b/Lib/php/director.swg index 90f6a74a2..b864cff84 100644 --- a/Lib/php/director.swg +++ b/Lib/php/director.swg @@ -23,38 +23,33 @@ #endif namespace Swig { - /* memory handler */ - struct GCItem - { - virtual ~GCItem() {} - virtual int get_own() const - { + /* memory handler */ + struct GCItem { + virtual ~GCItem() { + } + + virtual int get_own() const { return 0; } }; - struct GCItem_var - { - GCItem_var(GCItem *item = 0) : _item(item) - { + struct GCItem_var { + GCItem_var(GCItem *item = 0) : _item(item) { } - GCItem_var& operator=(GCItem *item) - { + GCItem_var& operator=(GCItem *item) { GCItem *tmp = _item; _item = item; delete tmp; return *this; } - ~GCItem_var() - { + ~GCItem_var() { delete _item; } - GCItem * operator->() const - { + GCItem * operator->() const { return _item; } @@ -62,18 +57,14 @@ namespace Swig { GCItem *_item; }; - struct GCItem_Object : GCItem - { - GCItem_Object(int own) : _own(own) - { + struct GCItem_Object : GCItem { + GCItem_Object(int own) : _own(own) { } - virtual ~GCItem_Object() - { + virtual ~GCItem_Object() { } - int get_own() const - { + int get_own() const { return _own; } @@ -82,14 +73,11 @@ namespace Swig { }; template - struct GCItem_T : GCItem - { - GCItem_T(Type *ptr) : _ptr(ptr) - { + struct GCItem_T : GCItem { + GCItem_T(Type *ptr) : _ptr(ptr) { } - virtual ~GCItem_T() - { + virtual ~GCItem_T() { delete _ptr; } @@ -100,14 +88,14 @@ namespace Swig { class Director { protected: zval *swig_self; - typedef std::map swig_ownership_map; + typedef std::map swig_ownership_map; mutable swig_ownership_map swig_owner; #ifdef ZTS // Store the ZTS context so it's available when C++ calls back to PHP. void *** swig_zts_ctx; -#endif +#endif public: - Director(zval* self TSRMLS_DC) : swig_self(self) { + Director(zval *self TSRMLS_DC) : swig_self(self) { TSRMLS_SET_CTX(swig_zts_ctx); } @@ -116,11 +104,11 @@ namespace Swig { zend_class_entry **ce; zend_function *mptr; int name_len = strlen(lc_fname); - + if (zend_lookup_class(cname, strlen(cname), &ce TSRMLS_CC) != SUCCESS) { return false; } - if (zend_hash_find(&(*ce)->function_table, lc_fname, name_len + 1, (void**) &mptr) != SUCCESS) { + if (zend_hash_find(&(*ce)->function_table, lc_fname, name_len + 1, (void **) &mptr) != SUCCESS) { return false; } // common.scope points to the declaring class @@ -128,8 +116,7 @@ namespace Swig { } template - void swig_acquire_ownership(Type *vptr) const - { + void swig_acquire_ownership(Type *vptr) const { if (vptr) { swig_owner[vptr] = new GCItem_T(vptr); } @@ -141,9 +128,7 @@ namespace Swig { protected: std::string swig_msg; public: - DirectorException(int code, const char *hdr, const char* msg TSRMLS_DC) - : swig_msg(hdr) - { + DirectorException(int code, const char *hdr, const char *msg TSRMLS_DC) : swig_msg(hdr) { if (strlen(msg)) { swig_msg += " "; swig_msg += msg; @@ -152,23 +137,19 @@ namespace Swig { SWIG_ErrorMsg() = swig_msg.c_str(); } - static void raise(int code, const char *hdr, const char* msg TSRMLS_DC) - { + static void raise(int code, const char *hdr, const char *msg TSRMLS_DC) { throw DirectorException(code, hdr, msg TSRMLS_CC); } }; /* attempt to call a pure virtual method via a director method */ - class DirectorPureVirtualException : public Swig::DirectorException - { + class DirectorPureVirtualException : public Swig::DirectorException { public: - DirectorPureVirtualException(const char* msg TSRMLS_DC) - : DirectorException(E_ERROR, "SWIG director pure virtual method called", msg TSRMLS_CC) - { + DirectorPureVirtualException(const char *msg TSRMLS_DC) + : DirectorException(E_ERROR, "SWIG director pure virtual method called", msg TSRMLS_CC) { } - static void raise(const char *msg TSRMLS_DC) - { + static void raise(const char *msg TSRMLS_DC) { throw DirectorPureVirtualException(msg TSRMLS_CC); } }; @@ -176,13 +157,11 @@ namespace Swig { class DirectorMethodException : public Swig::DirectorException { public: - DirectorMethodException(const char* msg TSRMLS_DC) - : DirectorException(E_ERROR, "SWIG director method error", msg TSRMLS_CC) - { + DirectorMethodException(const char *msg TSRMLS_DC) + : DirectorException(E_ERROR, "SWIG director method error", msg TSRMLS_CC) { } - static void raise(const char *msg TSRMLS_DC) - { + static void raise(const char *msg TSRMLS_DC) { throw DirectorMethodException(msg TSRMLS_CC); } }; diff --git a/Lib/python/director.swg b/Lib/python/director.swg index d6bfe51f0..baa72c664 100644 --- a/Lib/python/director.swg +++ b/Lib/python/director.swg @@ -58,7 +58,7 @@ could stop working when using this option. */ #ifdef SWIG_DIRECTOR_NORTTI -/* +/* When we don't use the native C++ RTTI, we implement a minimal one only for Directors. */ @@ -99,94 +99,77 @@ extern "C" { struct swig_type_info; } -namespace Swig { +namespace Swig { /* memory handler */ - struct GCItem - { + struct GCItem { virtual ~GCItem() {} - virtual int get_own() const - { + virtual int get_own() const { return 0; } }; - struct GCItem_var - { - GCItem_var(GCItem *item = 0) : _item(item) - { + struct GCItem_var { + GCItem_var(GCItem *item = 0) : _item(item) { } - GCItem_var& operator=(GCItem *item) - { + GCItem_var& operator=(GCItem *item) { GCItem *tmp = _item; _item = item; delete tmp; return *this; } - ~GCItem_var() - { + ~GCItem_var() { delete _item; } - - GCItem * operator->() const - { + + GCItem * operator->() const { return _item; } - + private: GCItem *_item; }; - - struct GCItem_Object : GCItem - { - GCItem_Object(int own) : _own(own) - { - } - - virtual ~GCItem_Object() - { + + struct GCItem_Object : GCItem { + GCItem_Object(int own) : _own(own) { } - int get_own() const - { + virtual ~GCItem_Object() { + } + + int get_own() const { return _own; } - + private: int _own; }; template - struct GCItem_T : GCItem - { - GCItem_T(Type *ptr) : _ptr(ptr) - { + struct GCItem_T : GCItem { + GCItem_T(Type *ptr) : _ptr(ptr) { } - - virtual ~GCItem_T() - { + + virtual ~GCItem_T() { delete _ptr; } - + private: Type *_ptr; }; template - struct GCArray_T : GCItem - { - GCArray_T(Type *ptr) : _ptr(ptr) - { + struct GCArray_T : GCItem { + GCArray_T(Type *ptr) : _ptr(ptr) { } - - virtual ~GCArray_T() - { + + virtual ~GCArray_T() { delete[] _ptr; } - + private: Type *_ptr; }; @@ -196,10 +179,8 @@ namespace Swig { protected: std::string swig_msg; public: - DirectorException(PyObject *error, const char *hdr ="", const char *msg ="") - : swig_msg(hdr) - { - SWIG_PYTHON_THREAD_BEGIN_BLOCK; + DirectorException(PyObject *error, const char *hdr ="", const char *msg ="") : swig_msg(hdr) { + SWIG_PYTHON_THREAD_BEGIN_BLOCK; if (strlen(msg)) { swig_msg += " "; swig_msg += msg; @@ -207,30 +188,26 @@ namespace Swig { if (!PyErr_Occurred()) { PyErr_SetString(error, getMessage()); } - SWIG_PYTHON_THREAD_END_BLOCK; + SWIG_PYTHON_THREAD_END_BLOCK; } - const char *getMessage() const - { - return swig_msg.c_str(); + const char *getMessage() const { + return swig_msg.c_str(); } - static void raise(PyObject *error, const char *msg) - { + static void raise(PyObject *error, const char *msg) { throw DirectorException(error, msg); } - static void raise(const char *msg) - { + static void raise(const char *msg) { raise(PyExc_RuntimeError, msg); } }; /* unknown exception handler */ - class UnknownExceptionHandler - { + class UnknownExceptionHandler { #ifdef SWIG_DIRECTOR_UEH - static void handler() { + static void handler() { try { throw; } catch (DirectorException& e) { @@ -241,12 +218,12 @@ namespace Swig { } catch (...) { std::cerr << "Unknown exception caught." << std::endl; } - + std::cerr << std::endl << "Python interpreter traceback:" << std::endl; PyErr_Print(); std::cerr << std::endl; - + std::cerr << "This exception was caught by the SWIG unexpected exception handler." << std::endl << "Try using %feature(\"director:except\") to avoid reaching this point." << std::endl << std::endl @@ -255,15 +232,13 @@ namespace Swig { } public: - + std::unexpected_handler old; - UnknownExceptionHandler(std::unexpected_handler nh = handler) - { + UnknownExceptionHandler(std::unexpected_handler nh = handler) { old = std::set_unexpected(nh); } - ~UnknownExceptionHandler() - { + ~UnknownExceptionHandler() { std::set_unexpected(old); } #endif @@ -272,23 +247,19 @@ namespace Swig { /* type mismatch in the return value from a python method call */ class DirectorTypeMismatchException : public Swig::DirectorException { public: - DirectorTypeMismatchException(PyObject *error, const char *msg="") - : Swig::DirectorException(error, "SWIG director type mismatch", msg) - { + DirectorTypeMismatchException(PyObject *error, const char *msg="") + : Swig::DirectorException(error, "SWIG director type mismatch", msg) { } - DirectorTypeMismatchException(const char *msg="") - : Swig::DirectorException(PyExc_TypeError, "SWIG director type mismatch", msg) - { + DirectorTypeMismatchException(const char *msg="") + : Swig::DirectorException(PyExc_TypeError, "SWIG director type mismatch", msg) { } - static void raise(PyObject *error, const char *msg) - { + static void raise(PyObject *error, const char *msg) { throw DirectorTypeMismatchException(error, msg); } - static void raise(const char *msg) - { + static void raise(const char *msg) { throw DirectorTypeMismatchException(msg); } }; @@ -296,28 +267,23 @@ namespace Swig { /* any python exception that occurs during a director method call */ class DirectorMethodException : public Swig::DirectorException { public: - DirectorMethodException(const char *msg = "") - : DirectorException(PyExc_RuntimeError, "SWIG director method error.", msg) - { - } + DirectorMethodException(const char *msg = "") + : DirectorException(PyExc_RuntimeError, "SWIG director method error.", msg) { + } - static void raise(const char *msg) - { + static void raise(const char *msg) { throw DirectorMethodException(msg); } }; /* attempt to call a pure virtual method via a director method */ - class DirectorPureVirtualException : public Swig::DirectorException - { + class DirectorPureVirtualException : public Swig::DirectorException { public: - DirectorPureVirtualException(const char *msg = "") - : DirectorException(PyExc_RuntimeError, "SWIG director pure virtual method called", msg) - { + DirectorPureVirtualException(const char *msg = "") + : DirectorException(PyExc_RuntimeError, "SWIG director pure virtual method called", msg) { } - static void raise(const char *msg) - { + static void raise(const char *msg) { throw DirectorPureVirtualException(msg); } }; @@ -332,24 +298,21 @@ namespace Swig { #ifdef __THREAD__ # include "pythread.h" - class Guard - { - PyThread_type_lock & mutex_; - + class Guard { + PyThread_type_lock &mutex_; + public: - Guard(PyThread_type_lock & mutex) : mutex_(mutex) - { + Guard(PyThread_type_lock & mutex) : mutex_(mutex) { PyThread_acquire_lock(mutex_, WAIT_LOCK); } - - ~Guard() - { + + ~Guard() { PyThread_release_lock(mutex_); } }; # define SWIG_GUARD(mutex) Guard _guard(mutex) #else -# define SWIG_GUARD(mutex) +# define SWIG_GUARD(mutex) #endif /* director base class */ @@ -361,11 +324,11 @@ namespace Swig { mutable bool swig_disown_flag; /* decrement the reference count of the wrapped python object */ - void swig_decref() const { + void swig_decref() const { if (swig_disown_flag) { - SWIG_PYTHON_THREAD_BEGIN_BLOCK; - Py_DECREF(swig_self); - SWIG_PYTHON_THREAD_END_BLOCK; + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + Py_DECREF(swig_self); + SWIG_PYTHON_THREAD_END_BLOCK; } } @@ -375,31 +338,28 @@ namespace Swig { swig_incref(); } - /* discard our reference at destruction */ virtual ~Director() { - swig_decref(); + swig_decref(); } - /* return a pointer to the wrapped python object */ - PyObject *swig_get_self() const { - return swig_self; + PyObject *swig_get_self() const { + return swig_self; } - /* acquire ownership of the wrapped python object (the sense of "disown" - * is from python) */ - void swig_disown() const { - if (!swig_disown_flag) { + /* acquire ownership of the wrapped python object (the sense of "disown" is from python) */ + void swig_disown() const { + if (!swig_disown_flag) { swig_disown_flag=true; - swig_incref(); - } + swig_incref(); + } } /* increase the reference count of the wrapped python object */ - void swig_incref() const { + void swig_incref() const { if (swig_disown_flag) { - Py_INCREF(swig_self); + Py_INCREF(swig_self); } } @@ -407,7 +367,7 @@ namespace Swig { virtual bool swig_get_inner(const char * /* swig_protected_method_name */) const { return true; } - + virtual void swig_set_inner(const char * /* swig_protected_method_name */, bool /* swig_val */) const { } @@ -421,33 +381,29 @@ namespace Swig { public: template - void swig_acquire_ownership_array(Type *vptr) const - { + void swig_acquire_ownership_array(Type *vptr) const { if (vptr) { SWIG_GUARD(swig_mutex_own); swig_owner[vptr] = new GCArray_T(vptr); } } - + template - void swig_acquire_ownership(Type *vptr) const - { + void swig_acquire_ownership(Type *vptr) const { if (vptr) { SWIG_GUARD(swig_mutex_own); swig_owner[vptr] = new GCItem_T(vptr); } } - void swig_acquire_ownership_obj(void *vptr, int own) const - { + void swig_acquire_ownership_obj(void *vptr, int own) const { if (vptr && own) { SWIG_GUARD(swig_mutex_own); swig_owner[vptr] = new GCItem_Object(own); } } - - int swig_release_ownership(void *vptr) const - { + + int swig_release_ownership(void *vptr) const { int own = 0; if (vptr) { SWIG_GUARD(swig_mutex_own); @@ -461,8 +417,7 @@ namespace Swig { } template - static PyObject *swig_pyobj_disown(PyObject *pyobj, PyObject *SWIGUNUSEDPARM(args)) - { + static PyObject *swig_pyobj_disown(PyObject *pyobj, PyObject *SWIGUNUSEDPARM(args)) { SwigPyObject *sobj = (SwigPyObject *)pyobj; sobj->own = 0; Director *d = SWIG_DIRECTOR_CAST(reinterpret_cast(sobj->ptr)); @@ -470,7 +425,6 @@ namespace Swig { d->swig_disown(); return PyWeakref_NewProxy(pyobj, NULL); } - }; #ifdef __THREAD__ diff --git a/Lib/ruby/director.swg b/Lib/ruby/director.swg index a5daf2176..360344f6c 100644 --- a/Lib/ruby/director.swg +++ b/Lib/ruby/director.swg @@ -24,96 +24,78 @@ # define SWIG_DIRECTOR_CAST(ARG) dynamic_cast(ARG) namespace Swig { + /* memory handler */ - struct GCItem - { - virtual ~GCItem() - { + struct GCItem { + virtual ~GCItem() { } - virtual ruby_owntype get_own() const - { + virtual ruby_owntype get_own() const { return 0; } }; - - struct GCItem_var - { - GCItem_var(GCItem *item = 0) : _item(item) - { + + struct GCItem_var { + GCItem_var(GCItem *item = 0) : _item(item) { } - GCItem_var& operator=(GCItem *item) - { + GCItem_var& operator=(GCItem *item) { GCItem *tmp = _item; _item = item; delete tmp; return *this; } - - ~GCItem_var() - { + + ~GCItem_var() { delete _item; } - - GCItem * operator->() const - { + + GCItem *operator->() const { return _item; } - + private: GCItem *_item; }; template - struct GCItem_T : GCItem - { - GCItem_T(Type *ptr) : _ptr(ptr) - { + struct GCItem_T : GCItem { + GCItem_T(Type *ptr) : _ptr(ptr) { } - - virtual ~GCItem_T() - { + + virtual ~GCItem_T() { delete _ptr; } - + private: Type *_ptr; }; - struct GCItem_Object : GCItem - { - GCItem_Object(ruby_owntype own) : _own(own) - { - } - - virtual ~GCItem_Object() - { + struct GCItem_Object : GCItem { + GCItem_Object(ruby_owntype own) : _own(own) { } - ruby_owntype get_own() const - { + virtual ~GCItem_Object() { + } + + ruby_owntype get_own() const { return _own; } - + private: ruby_owntype _own; }; - template - struct GCArray_T : GCItem - { - GCArray_T(Type *ptr) : _ptr(ptr) - { + struct GCArray_T : GCItem { + GCArray_T(Type *ptr) : _ptr(ptr) { } - - virtual ~GCArray_T() - { + + virtual ~GCArray_T() { delete[] _ptr; } - + private: Type *_ptr; }; @@ -126,20 +108,17 @@ namespace Swig { int argc; VALUE *argv; }; - + /* Base class for director exceptions */ class DirectorException { protected: VALUE swig_error; std::string swig_msg; protected: - DirectorException(VALUE error) - : swig_error(error) - { + DirectorException(VALUE error) : swig_error(error) { } - - DirectorException(VALUE error, const char* hdr, const char* msg ="") - : swig_error(error), swig_msg(hdr) { + + DirectorException(VALUE error, const char *hdr, const char *msg ="") : swig_error(error), swig_msg(hdr) { if (strlen(msg)) { swig_msg += " "; swig_msg += msg; @@ -151,25 +130,26 @@ namespace Swig { swig_error = error; } } + public: - VALUE getType() const { - return CLASS_OF(swig_error); + VALUE getType() const { + return CLASS_OF(swig_error); } + VALUE getError() const { return swig_error; } - const std::string& getMessage() const - { + + const std::string& getMessage() const { return swig_msg; } - - virtual ~DirectorException() {} - }; - - /* unknown exception handler */ - class UnknownExceptionHandler - { + virtual ~DirectorException() { + } + }; + + /* unknown exception handler */ + class UnknownExceptionHandler { #ifdef SWIG_DIRECTOR_UEH static void handler() { try { @@ -181,26 +161,24 @@ namespace Swig { std::cerr << "std::exception caught: "<< e.what() << std::endl; } catch (...) { std::cerr << "Unknown exception caught." << std::endl; - } + } std::cerr << std::endl << "Ruby interpreter traceback:" << std::endl; - std::cerr << std::endl; + std::cerr << std::endl; std::cerr << "This exception was caught by the SWIG unexpected exception handler." << std::endl << "Try using %feature(\"director:except\") to avoid reaching this point." << std::endl << std::endl << "Exception is being re-thrown, program will like abort/terminate." << std::endl; throw; } - - public: + + public: std::unexpected_handler old; - UnknownExceptionHandler(std::unexpected_handler nh = handler) - { + UnknownExceptionHandler(std::unexpected_handler nh = handler) { old = std::set_unexpected(nh); } - ~UnknownExceptionHandler() - { + ~UnknownExceptionHandler() { std::set_unexpected(old); } #endif @@ -211,13 +189,11 @@ namespace Swig { class DirectorTypeMismatchException : public Swig::DirectorException { public: DirectorTypeMismatchException(VALUE error, const char *msg="") - : Swig::DirectorException(error, "SWIG director type mismatch", msg) - { + : Swig::DirectorException(error, "SWIG director type mismatch", msg) { } DirectorTypeMismatchException(const char *msg="") - : Swig::DirectorException(rb_eTypeError, "SWIG director type mismatch", msg) - { + : Swig::DirectorException(rb_eTypeError, "SWIG director type mismatch", msg) { } static void raise(VALUE error, const char *msg) { @@ -232,31 +208,28 @@ namespace Swig { /* Any Ruby exception that occurs during a director method call */ class DirectorMethodException : public Swig::DirectorException { public: - DirectorMethodException(VALUE error) + DirectorMethodException(VALUE error) : Swig::DirectorException(error) { } - DirectorMethodException(const char* msg = "") + DirectorMethodException(const char *msg = "") : Swig::DirectorException(rb_eRuntimeError, "SWIG director method error.", msg) { } - - static void raise(VALUE error) - { + + static void raise(VALUE error) { throw DirectorMethodException(error); - } + } }; /* Attempted to call a pure virtual method via a director method */ class DirectorPureVirtualException : public Swig::DirectorException { public: - DirectorPureVirtualException(const char* msg = "") - : DirectorException(rb_eRuntimeError, "SWIG director pure virtual method called", msg) - { + DirectorPureVirtualException(const char *msg = "") + : DirectorException(rb_eRuntimeError, "SWIG director pure virtual method called", msg) { } - static void raise(const char *msg) - { + static void raise(const char *msg) { throw DirectorPureVirtualException(msg); } }; @@ -271,28 +244,25 @@ namespace Swig { # define SWIG_MUTEX_INIT(var) var # else # include -# define SWIG_MUTEX_INIT(var) var = PTHREAD_MUTEX_INITIALIZER +# define SWIG_MUTEX_INIT(var) var = PTHREAD_MUTEX_INITIALIZER # endif #endif #ifdef __PTHREAD__ - struct Guard - { + struct Guard { pthread_mutex_t *_mutex; - - Guard(pthread_mutex_t &mutex) : _mutex(&mutex) - { + + Guard(pthread_mutex_t &mutex) : _mutex(&mutex) { pthread_mutex_lock(_mutex); } - - ~Guard() - { + + ~Guard() { pthread_mutex_unlock(_mutex); } }; # define SWIG_GUARD(mutex) Guard _guard(mutex) #else -# define SWIG_GUARD(mutex) +# define SWIG_GUARD(mutex) #endif /* director base class */ @@ -313,21 +283,20 @@ namespace Swig { } /* return a pointer to the wrapped Ruby object */ - VALUE swig_get_self() const { - return swig_self; + VALUE swig_get_self() const { + return swig_self; } - /* acquire ownership of the wrapped Ruby object (the sense of "disown" - * is from Ruby) */ - void swig_disown() const { - if (!swig_disown_flag) { + /* acquire ownership of the wrapped Ruby object (the sense of "disown" is from Ruby) */ + void swig_disown() const { + if (!swig_disown_flag) { swig_disown_flag = true; - } + } } /* ownership management */ private: - typedef std::map swig_ownership_map; + typedef std::map swig_ownership_map; mutable swig_ownership_map swig_owner; #ifdef __PTHREAD__ static pthread_mutex_t swig_mutex_own; @@ -335,33 +304,29 @@ namespace Swig { public: template - void swig_acquire_ownership_array(Type *vptr) const - { + void swig_acquire_ownership_array(Type *vptr) const { if (vptr) { SWIG_GUARD(swig_mutex_own); swig_owner[vptr] = new GCArray_T(vptr); } } - + template - void swig_acquire_ownership(Type *vptr) const - { + void swig_acquire_ownership(Type *vptr) const { if (vptr) { SWIG_GUARD(swig_mutex_own); swig_owner[vptr] = new GCItem_T(vptr); } } - void swig_acquire_ownership_obj(void *vptr, ruby_owntype own) const - { + void swig_acquire_ownership_obj(void *vptr, ruby_owntype own) const { if (vptr && own) { SWIG_GUARD(swig_mutex_own); swig_owner[vptr] = new GCItem_Object(own); } } - - ruby_owntype swig_release_ownership(void *vptr) const - { + + ruby_owntype swig_release_ownership(void *vptr) const { ruby_owntype own = 0; if (vptr) { SWIG_GUARD(swig_mutex_own); From 1a19451c1ba189319a0ced355c7e6b93eeb6957a Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 23 Dec 2013 20:23:54 +0000 Subject: [PATCH 265/481] Error out attempting to use directors without -c++ Remove redundant #ifdef __cplusplus markers in director.swg --- Lib/csharp/director.swg | 5 ----- Lib/d/director.swg | 3 --- Lib/java/director.swg | 3 --- Lib/ocaml/director.swg | 3 --- Lib/octave/director.swg | 1 - Lib/perl5/director.swg | 6 +----- Lib/php/director.swg | 4 ---- Lib/python/director.swg | 5 ----- Lib/ruby/director.swg | 5 ----- Source/CParse/parser.y | 3 +++ 10 files changed, 4 insertions(+), 34 deletions(-) diff --git a/Lib/csharp/director.swg b/Lib/csharp/director.swg index c68c2d98f..403a0ac34 100644 --- a/Lib/csharp/director.swg +++ b/Lib/csharp/director.swg @@ -5,8 +5,6 @@ * methods can be called from C++. * ----------------------------------------------------------------------------- */ -#ifdef __cplusplus - #if defined(DEBUG_DIRECTOR_OWNED) #include #endif @@ -45,6 +43,3 @@ namespace Swig { }; } -#endif /* __cplusplus */ - - diff --git a/Lib/d/director.swg b/Lib/d/director.swg index d0ef2372b..6b6537103 100644 --- a/Lib/d/director.swg +++ b/Lib/d/director.swg @@ -5,8 +5,6 @@ * methods can be called from C++. * ----------------------------------------------------------------------------- */ -#ifdef __cplusplus - #if defined(DEBUG_DIRECTOR_OWNED) #include #endif @@ -47,4 +45,3 @@ namespace Swig { }; } -#endif /* __cplusplus */ diff --git a/Lib/java/director.swg b/Lib/java/director.swg index 86880a55e..72f166406 100644 --- a/Lib/java/director.swg +++ b/Lib/java/director.swg @@ -5,8 +5,6 @@ * method calls from C++ to Java extensions. * ----------------------------------------------------------------------------- */ -#ifdef __cplusplus - #if defined(DEBUG_DIRECTOR_OWNED) || defined(DEBUG_DIRECTOR_EXCEPTION) #include #endif @@ -384,4 +382,3 @@ namespace Swig { } -#endif /* __cplusplus */ diff --git a/Lib/ocaml/director.swg b/Lib/ocaml/director.swg index dc4c69b7d..0f997acd0 100644 --- a/Lib/ocaml/director.swg +++ b/Lib/ocaml/director.swg @@ -6,8 +6,6 @@ * * ----------------------------------------------------------------------------- */ -#ifdef __cplusplus - #include # define SWIG_DIRECTOR_CAST(ARG) dynamic_cast(ARG) @@ -100,4 +98,3 @@ namespace Swig { }; } -#endif /* __cplusplus */ diff --git a/Lib/octave/director.swg b/Lib/octave/director.swg index ce4377ef1..96bbf03cc 100644 --- a/Lib/octave/director.swg +++ b/Lib/octave/director.swg @@ -5,7 +5,6 @@ * methods can be called from C++. * ----------------------------------------------------------------------------- */ - # define SWIG_DIRECTOR_CAST(ARG) dynamic_cast(ARG) namespace Swig { diff --git a/Lib/perl5/director.swg b/Lib/perl5/director.swg index 0e7faee6c..9fa64e147 100644 --- a/Lib/perl5/director.swg +++ b/Lib/perl5/director.swg @@ -8,8 +8,6 @@ #ifndef SWIG_DIRECTOR_PERL_HEADER_ #define SWIG_DIRECTOR_PERL_HEADER_ -#ifdef __cplusplus - #include #include #include @@ -316,7 +314,5 @@ namespace Swig { } -#endif /* __cplusplus */ - - #endif + diff --git a/Lib/php/director.swg b/Lib/php/director.swg index b864cff84..2b176ed09 100644 --- a/Lib/php/director.swg +++ b/Lib/php/director.swg @@ -8,8 +8,6 @@ #ifndef SWIG_DIRECTOR_PHP_HEADER_ #define SWIG_DIRECTOR_PHP_HEADER_ -#ifdef __cplusplus - #include #include @@ -171,6 +169,4 @@ namespace Swig { // so use a macro to insert TSRMLS_CC so any ZTS context gets passed. #define DirectorMethodException() DirectorMethodException("" TSRMLS_CC) -#endif /* __cplusplus */ - #endif diff --git a/Lib/python/director.swg b/Lib/python/director.swg index baa72c664..3eac683f9 100644 --- a/Lib/python/director.swg +++ b/Lib/python/director.swg @@ -8,8 +8,6 @@ #ifndef SWIG_DIRECTOR_PYTHON_HEADER_ #define SWIG_DIRECTOR_PYTHON_HEADER_ -#ifdef __cplusplus - #include #include #include @@ -432,7 +430,4 @@ namespace Swig { #endif } -#endif /* __cplusplus */ - - #endif diff --git a/Lib/ruby/director.swg b/Lib/ruby/director.swg index 360344f6c..23aa6da48 100644 --- a/Lib/ruby/director.swg +++ b/Lib/ruby/director.swg @@ -15,8 +15,6 @@ #endif #endif -#ifdef __cplusplus - #include #include #include @@ -341,6 +339,3 @@ namespace Swig { }; } -#endif /* __cplusplus */ - - diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 40d853387..d01c2fcd1 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -2024,6 +2024,9 @@ module_directive: MODULE options idstring { Setattr($$,"options",$2); if (Getattr($2,"directors")) { Wrapper_director_mode_set(1); + if (!cparse_cplusplus) { + Swig_error(cparse_file, cparse_line, "Directors are not supported for C code and require the -c++ option\n"); + } } if (Getattr($2,"dirprot")) { Wrapper_director_protected_mode_set(1); From ad02cb98e6847147b4a6e5d4c327403bc71f9d2c Mon Sep 17 00:00:00 2001 From: Vadim Zeitlin Date: Wed, 27 Nov 2013 14:32:55 +0100 Subject: [PATCH 266/481] Relax Java preproc_line_file unit test to pass in a separate build directory. Exact paths comparison doesn't work when SWIG is built in a directory different from the source one, so check whether the path just ends with the expected path components instead. This allows all Java tests to pass in this build configuration. closes #115 --- .../java/preproc_line_file_runme.java | 26 ++++++++++--------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/Examples/test-suite/java/preproc_line_file_runme.java b/Examples/test-suite/java/preproc_line_file_runme.java index c29cef680..123753fd9 100644 --- a/Examples/test-suite/java/preproc_line_file_runme.java +++ b/Examples/test-suite/java/preproc_line_file_runme.java @@ -11,8 +11,17 @@ public class preproc_line_file_runme { } } - public static String FILENAME_WINDOWS = "..\\..\\..\\..\\Examples\\test-suite\\preproc_line_file.i"; - public static String FILENAME_UNIX = "../../../../Examples/test-suite/preproc_line_file.i"; + private static void test_file(String file, String suffix) throws Throwable + { + String FILENAME_WINDOWS = "Examples\\test-suite\\preproc_line_file.i"; + String FILENAME_UNIX = "Examples/test-suite/preproc_line_file.i"; + + // We don't test for exact equality here because the file names are relative to the build directory, which can be different from the source directory, + // under Unix. But they do need to end with the same path components. + if (!file.endsWith(FILENAME_UNIX + suffix) && !file.endsWith(FILENAME_WINDOWS + suffix)) + throw new RuntimeException("file \"" + file + "\" doesn't end with " + FILENAME_UNIX + suffix); + } + public static void main(String argv[]) throws Throwable { int myline = preproc_line_file.MYLINE; @@ -22,13 +31,8 @@ public class preproc_line_file_runme { if (myline + 100 + 1 != myline_adjusted) throw new RuntimeException("preproc failure"); - String myfile = preproc_line_file.MYFILE; - String myfile_adjusted = preproc_line_file.MYFILE_ADJUSTED; - if (!(myfile.equals(FILENAME_UNIX) || myfile.equals(FILENAME_WINDOWS))) - throw new RuntimeException("preproc failure"); - - if (!(myfile_adjusted.equals(FILENAME_UNIX + ".bak") || myfile_adjusted.equals(FILENAME_WINDOWS + ".bak"))) - throw new RuntimeException("preproc failure"); + test_file(preproc_line_file.MYFILE, ""); + test_file(preproc_line_file.MYFILE_ADJUSTED, ".bak"); if (!preproc_line_file.MY_STRINGNUM_A.equals("my15")) throw new RuntimeException("preproc failed MY_STRINGNUM_A"); @@ -57,9 +61,7 @@ public class preproc_line_file_runme { if (preproc_line_file.INLINE_LINE != 87) throw new RuntimeException("preproc failure"); - String inlineFile = preproc_line_file.INLINE_FILE; - if (!(inlineFile.equals(FILENAME_UNIX) || inlineFile.equals(FILENAME_WINDOWS))) - throw new RuntimeException("preproc failure"); + test_file(preproc_line_file.INLINE_FILE, ""); if (Slash.LINE_NUM != 93) throw new RuntimeException("preproc failure"); From 88a0e228a9c80bedc414164f17b26be0147da333 Mon Sep 17 00:00:00 2001 From: Vadim Zeitlin Date: Wed, 18 Dec 2013 01:28:32 +0100 Subject: [PATCH 267/481] Change the length of strings created from fixed-size buffers. Use the usual C rule for NUL-terminated strings instead of discarding all the trailing NUL characters. This was unexpected (as buffers in C code are not necessarily always padded with NULs to their full length) and also inconsistent among languages as this was only done for those of them using typemaps/strings.swg but not for C# or Java, for example, which terminated the string at the first NUL even before this change. Notice that this patch couldn't use strlen() or wcslen() with possibly not NUL-terminated strings, so we had to add [our own equivalents of] strnlen() and wcsnlen() and use them instead. This required adding yet another parameter to string typemap macros, so update the example using them accordingly too. --- CHANGES.current | 8 ++++ Examples/perl5/xmlstring/xmlstring.i | 12 ++++++ .../test-suite/perl5/primitive_types_runme.pl | 2 +- Examples/test-suite/primitive_types.i | 2 +- .../python/primitive_types_runme.py | 2 +- Lib/typemaps/string.swg | 13 +++++- Lib/typemaps/strings.swg | 42 ++++++++++++------- Lib/typemaps/wstring.swg | 14 ++++++- 8 files changed, 75 insertions(+), 20 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index 59ebeebcd..680765d40 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,14 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2013-12-23: vadz + [Octave, Perl, Python, R, Ruby, Tcl] Change the length of strings created from fixed-size char + buffers in C code. + + This is a potential backwards compatibility break: a "char buf[5]" containing "ho\0la" was + returned as a string of length 5 before, but is returned as a string of length 2 now. Apply + "char FIXSIZE[ANY]" typemaps to explicitly choose the old behaviour. + 2013-12-23: talby [Perl] Add support for directors. diff --git a/Examples/perl5/xmlstring/xmlstring.i b/Examples/perl5/xmlstring/xmlstring.i index 3ef53169d..861e1b84d 100644 --- a/Examples/perl5/xmlstring/xmlstring.i +++ b/Examples/perl5/xmlstring/xmlstring.i @@ -93,6 +93,17 @@ SWIG_FromXMLChPtrAndSize(const XMLCh* input, size_t size) } } +%fragment("SWIG_XMLStringNLen","header") { +size_t +SWIG_XMLStringNLen(const XMLCh* s, size_t maxlen) +{ + const XMLCh *p; + for (p = s; maxlen-- && *p; p++) + ; + return p - s; +} +} + %init { if (!SWIG_UTF8Transcoder()) { croak("ERROR: XML::Xerces: INIT: Could not create UTF-8 transcoder"); @@ -106,6 +117,7 @@ SWIG_FromXMLChPtrAndSize(const XMLCh* input, size_t size) SWIG_AsXMLChPtrAndSize, SWIG_FromXMLChPtrAndSize, XERCES_CPP_NAMESPACE::XMLString::stringLen, + SWIG_XMLStringNLen, "", INT_MIN, INT_MAX); diff --git a/Examples/test-suite/perl5/primitive_types_runme.pl b/Examples/test-suite/perl5/primitive_types_runme.pl index 31604ad06..688b241c2 100755 --- a/Examples/test-suite/perl5/primitive_types_runme.pl +++ b/Examples/test-suite/perl5/primitive_types_runme.pl @@ -166,7 +166,7 @@ $t->{var_paramd} = $primitive_types::sct_paramd; $t->{var_paramc} = $primitive_types::sct_paramc; ok($t->v_check(), 'v_check'); -is($primitive_types::def_namet, "ho\0la", "namet"); +is($primitive_types::def_namet, "hola", "namet"); $t->{var_namet} = $primitive_types::def_namet; is($t->{var_namet}, $primitive_types::def_namet, "namet"); diff --git a/Examples/test-suite/primitive_types.i b/Examples/test-suite/primitive_types.i index 9425cc1a0..5e3ce3eed 100644 --- a/Examples/test-suite/primitive_types.i +++ b/Examples/test-suite/primitive_types.i @@ -185,7 +185,7 @@ char* const def_pchar = (char *const)"hello"; const char* const def_pcharc = "hija"; - const namet def_namet = {'h','o',0, 'l','a'}; + const namet def_namet = {'h','o','l','a', 0}; extern namet gbl_namet; diff --git a/Examples/test-suite/python/primitive_types_runme.py b/Examples/test-suite/python/primitive_types_runme.py index be8d38bad..0986da5ad 100644 --- a/Examples/test-suite/python/primitive_types_runme.py +++ b/Examples/test-suite/python/primitive_types_runme.py @@ -165,7 +165,7 @@ t.var_paramc = sct_paramc t.v_check() # this value contains a '0' char! -if def_namet != 'ho\0la': +if def_namet != 'hola': print "bad namet", def_namet raise RuntimeError diff --git a/Lib/typemaps/string.swg b/Lib/typemaps/string.swg index 279ee2a41..1bf0bd15a 100644 --- a/Lib/typemaps/string.swg +++ b/Lib/typemaps/string.swg @@ -17,8 +17,19 @@ SWIG_pchar_descriptor(void) } } +%fragment("SWIG_strnlen","header",fragment="SWIG_FromCharPtrAndSize") { +size_t +SWIG_strnlen(const char* s, size_t maxlen) +{ + const char *p; + for (p = s; maxlen-- && *p; p++) + ; + return p - s; +} +} %include %typemaps_string(%checkcode(STRING), %checkcode(CHAR), - char, Char, SWIG_AsCharPtrAndSize, SWIG_FromCharPtrAndSize, strlen, + char, Char, SWIG_AsCharPtrAndSize, SWIG_FromCharPtrAndSize, + strlen, SWIG_strnlen, "", CHAR_MIN, CHAR_MAX) diff --git a/Lib/typemaps/strings.swg b/Lib/typemaps/strings.swg index 55e9d2bb5..79ad85cd6 100644 --- a/Lib/typemaps/strings.swg +++ b/Lib/typemaps/strings.swg @@ -22,6 +22,7 @@ SWIG_AsCharPtrAndSize, SWIG_FromCharPtrAndSize, SWIG_CharPtrLen, + SWIG_CharBufLen, SWIG_AsCharPtr, SWIG_FromCharPtr, SWIG_AsCharArray, @@ -276,12 +277,13 @@ } %typemap(freearg) const Char (&)[ANY] ""; -%typemap(out,fragment=#SWIG_FromCharPtrAndSize) +%typemap(out,fragment=#SWIG_FromCharPtrAndSize,fragment=#SWIG_CharBufLen) Char [ANY], const Char[ANY] { - size_t size = $1_dim0; %#ifndef SWIG_PRESERVE_CARRAY_SIZE - while (size && ($1[size - 1] == '\0')) --size; + size_t size = SWIG_CharBufLen($1, $1_dim0); +%#else + size_t size = $1_dim0; %#endif %set_output(SWIG_FromCharPtrAndSize($1, size)); } @@ -298,23 +300,25 @@ /* varout */ -%typemap(varout,noblock=1,fragment=#SWIG_FromCharPtrAndSize) +%typemap(varout,noblock=1,fragment=#SWIG_CharBufLen) Char [ANY], const Char [ANY] { - size_t size = $1_dim0; %#ifndef SWIG_PRESERVE_CARRAY_SIZE - while (size && ($1[size - 1] == '\0')) --size; + size_t size = SWIG_CharBufLen($1, $1_dim0); +%#else + size_t size = $1_dim0; %#endif %set_varoutput(SWIG_FromCharPtrAndSize($1, size)); } /* constant */ -%typemap(constcode,fragment=#SWIG_FromCharPtrAndSize) +%typemap(constcode,fragment=#SWIG_CharBufLen) Char [ANY], const Char [ANY] { - size_t size = $value_dim0; %#ifndef SWIG_PRESERVE_CARRAY_SIZE - while (size && ($value[size - 1] == '\0')) --size; + size_t size = SWIG_CharBufLen($1, $1_dim0); +%#else + size_t size = $value_dim0; %#endif %set_constant("$symname", SWIG_FromCharPtrAndSize($value,size)); } @@ -323,12 +327,13 @@ #if defined(SWIG_DIRECTOR_TYPEMAPS) /* directorin */ -%typemap(directorin,fragment=#SWIG_FromCharPtrAndSize) +%typemap(directorin,fragment=#SWIG_CharBufLen) Char [ANY], const Char [ANY] { - size_t size = $1_dim0; %#ifndef SWIG_PRESERVE_CARRAY_SIZE - while (size && ($1[size - 1] == '\0')) --size; + size_t size = SWIG_CharBufLen($1, $1_dim0); +%#else + size_t size = $1_dim0; %#endif $input = SWIG_FromCharPtrAndSize($1, size); } @@ -360,12 +365,13 @@ /* throws */ -%typemap(throws,fragment=#SWIG_FromCharPtrAndSize) +%typemap(throws,fragment=#SWIG_CharBufLen) Char [ANY], const Char[ANY] { - size_t size = $1_dim0; %#ifndef SWIG_PRESERVE_CARRAY_SIZE - while (size && ($1[size - 1] == '\0')) --size; + size_t size = SWIG_CharBufLen($1, $1_dim0); +%#else + size_t size = $1_dim0; %#endif %raise(SWIG_FromCharPtrAndSize($1, size), "$type", 0); } @@ -499,6 +505,7 @@ SWIG_AsCharPtrAndSize, SWIG_FromCharPtrAndSize, SWIG_CharPtrLen, + SWIG_CharBufLen, SWIG_NewCopyCharArray, SWIG_DeleteCharArray, FragLimits, CHAR_MIN, CHAR_MAX) @@ -586,6 +593,7 @@ SWIG_AsVal_dec(Char)(SWIG_Object obj, Char *val) SWIG_AsCharPtrAndSize, SWIG_FromCharPtrAndSize, SWIG_CharPtrLen, + SWIG_CharBufLen, SWIG_As##CharName##Ptr, SWIG_From##CharName##Ptr, SWIG_As##CharName##Array, @@ -604,12 +612,14 @@ SWIG_AsVal_dec(Char)(SWIG_Object obj, Char *val) SWIG_AsCharPtrAndSize, SWIG_FromCharPtrAndSize, SWIG_CharPtrLen, + SWIG_CharBufLen, FragLimits, CHAR_MIN, CHAR_MAX) %_typemap2_string(StringCode, CharCode, Char, CharName, SWIG_AsCharPtrAndSize, SWIG_FromCharPtrAndSize, SWIG_CharPtrLen, + SWIG_CharBufLen, %new_copy_array, %delete_array, FragLimits, CHAR_MIN, CHAR_MAX) @@ -624,6 +634,7 @@ SWIG_AsVal_dec(Char)(SWIG_Object obj, Char *val) SWIG_AsCharPtrAndSize, SWIG_FromCharPtrAndSize, SWIG_CharPtrLen, + SWIG_CharBufLen, SWIG_NewCopyCharArray, SWIG_DeleteCharArray, FragLimits, CHAR_MIN, CHAR_MAX) @@ -632,6 +643,7 @@ SWIG_AsVal_dec(Char)(SWIG_Object obj, Char *val) SWIG_AsCharPtrAndSize, SWIG_FromCharPtrAndSize, SWIG_CharPtrLen, + SWIG_CharBufLen, SWIG_NewCopyCharArray, SWIG_DeleteCharArray, FragLimits, CHAR_MIN, CHAR_MAX) diff --git a/Lib/typemaps/wstring.swg b/Lib/typemaps/wstring.swg index 2567dc782..1f2de8221 100644 --- a/Lib/typemaps/wstring.swg +++ b/Lib/typemaps/wstring.swg @@ -18,8 +18,20 @@ SWIG_pwchar_descriptor() } } +%fragment("SWIG_wcsnlen","header",fragment="SWIG_FromWCharPtrAndSize") { +size_t +SWIG_wcsnlen(const wchar_t* s, size_t maxlen) +{ + const wchar_t *p; + for (p = s; maxlen-- && *p; p++) + ; + return p - s; +} +} + %include %typemaps_string(%checkcode(UNISTRING), %checkcode(UNICHAR), - wchar_t, WChar, SWIG_AsWCharPtrAndSize, SWIG_FromWCharPtrAndSize, wcslen, + wchar_t, WChar, SWIG_AsWCharPtrAndSize, SWIG_FromWCharPtrAndSize, + wcslen, SWIG_wcsnlen, "", WCHAR_MIN, WCHAR_MAX) From cdf1ba912067f306284ab37536862eeeeef8fedb Mon Sep 17 00:00:00 2001 From: Vadim Zeitlin Date: Mon, 23 Dec 2013 20:47:43 +0100 Subject: [PATCH 268/481] Don't accept strings too long to fit in char[N] with trailing NUL. It was previously possible to assign "hello" to a variable backed by char[5] storage in C, and the array contained the correct character data but without the trailing NUL, which was unexpected in C. This is not allowed any more, only "helo" can fit into a char[5] now and anything else fails the type check, just as it already happened for the longer strings before. Closes #122 --- CHANGES.current | 9 +++++++-- Examples/test-suite/perl5/primitive_types_runme.pl | 4 ++-- Examples/test-suite/python/primitive_types_runme.py | 4 ++-- Lib/typemaps/strings.swg | 3 ++- 4 files changed, 13 insertions(+), 7 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index 680765d40..5629532b7 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -10,8 +10,13 @@ Version 3.0.0 (in progress) buffers in C code. This is a potential backwards compatibility break: a "char buf[5]" containing "ho\0la" was - returned as a string of length 5 before, but is returned as a string of length 2 now. Apply - "char FIXSIZE[ANY]" typemaps to explicitly choose the old behaviour. + returned as a string of length 5 before, but is returned as a string of length 2 now. Also, + it was possible to assign a (non-NUL-terminated) string "hello" to such a buffer before but + now this fails and only "helo" can fit. + + Apply "char FIXSIZE[ANY]" typemaps to explicitly choose the old behaviour. + + *** POTENTIAL INCOMPATIBILITY *** 2013-12-23: talby [Perl] Add support for directors. diff --git a/Examples/test-suite/perl5/primitive_types_runme.pl b/Examples/test-suite/perl5/primitive_types_runme.pl index 688b241c2..311c138e0 100755 --- a/Examples/test-suite/perl5/primitive_types_runme.pl +++ b/Examples/test-suite/perl5/primitive_types_runme.pl @@ -170,9 +170,9 @@ is($primitive_types::def_namet, "hola", "namet"); $t->{var_namet} = $primitive_types::def_namet; is($t->{var_namet}, $primitive_types::def_namet, "namet"); -$t->{var_namet} = 'holac'; +$t->{var_namet} = 'hola'; -is($t->{var_namet}, 'holac', "namet"); +is($t->{var_namet}, 'hola', "namet"); $t->{var_namet} = 'hol'; diff --git a/Examples/test-suite/python/primitive_types_runme.py b/Examples/test-suite/python/primitive_types_runme.py index 0986da5ad..d4173b7d3 100644 --- a/Examples/test-suite/python/primitive_types_runme.py +++ b/Examples/test-suite/python/primitive_types_runme.py @@ -174,9 +174,9 @@ if t.var_namet != def_namet: print "bad namet", t.var_namet, def_namet raise RuntimeError -t.var_namet = 'holac' +t.var_namet = 'hola' -if t.var_namet != 'holac': +if t.var_namet != 'hola': print "bad namet", t.var_namet raise RuntimeError diff --git a/Lib/typemaps/strings.swg b/Lib/typemaps/strings.swg index 79ad85cd6..e31e5037f 100644 --- a/Lib/typemaps/strings.swg +++ b/Lib/typemaps/strings.swg @@ -537,7 +537,8 @@ SWIG_As##CharName##Array(SWIG_Object obj, Char *val, size_t size) Char* cptr = 0; size_t csize = 0; int alloc = SWIG_OLDOBJ; int res = SWIG_AsCharPtrAndSize(obj, &cptr, &csize, &alloc); if (SWIG_IsOK(res)) { - if ((csize == size + 1) && cptr && !(cptr[csize-1])) --csize; + /* special case of single char conversion when we don't need space for NUL */ + if (size == 1 && csize == 2 && cptr && !cptr[1]) --csize; if (csize <= size) { if (val) { if (csize) memcpy(val, cptr, csize*sizeof(Char)); From 6b7185989a9c2ff145b011f55a4999018d6cbc63 Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Tue, 24 Dec 2013 06:47:54 +0400 Subject: [PATCH 269/481] additional check for template type, to handle constructors correctly --- Source/CParse/parser.y | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index c6fe56b70..0fc1d758a 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -2676,8 +2676,8 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va Setattr(templnode,"sym:typename","1"); } /* for now, nested %template is allowed only in the same scope as the template declaration */ - if ($3 && !((currentOuterClass && (currentOuterClass != Getattr(nn, "nested:outer"))) - ||(extendmode && current_class && (current_class != Getattr(nn, "nested:outer"))))) { + if ($3 && !(nnisclass && ((currentOuterClass && (currentOuterClass != Getattr(nn, "nested:outer"))) + ||(extendmode && current_class && (current_class != Getattr(nn, "nested:outer")))))) { /* Comment this out for 1.3.28. We need to re-enable it later but first we need to From 5562deec62e0b4b4dca9bad05a5971dc08d3c982 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Tomulik?= Date: Tue, 28 May 2013 05:33:56 +0200 Subject: [PATCH 270/481] Fixed SF bug #1297 (Python imports) This changeset resolves several issues related to python imports. For example, it's possible now to import modules having same module names, but belonging to different packages. From the user's viewpoint, this patch gives a little bit more control on import directives generated by swig. The user may choose to use relative or absolute imports (docs are provided in separate PR). Some details: - we (still) generate import directives in form 'import a.b.c' which corresponds to absolute imports in python3 and (the only available) ambiguous one in python2. - added -relativeimport option to use explicit relative import syntax (python3), Tests are under Examples/python, these are in fact regression tests but with the current swig testing framework it seems to be impossible to put appropriate tests under test-suite. Closes #7 --- Examples/python/check.list | 1 + Examples/python/import_packages/Makefile | 35 ++ Examples/python/import_packages/README | 2 + .../import_packages/from_init1/Makefile | 25 ++ .../python/import_packages/from_init1/README | 63 ++++ .../import_packages/from_init1/py2/Makefile | 14 + .../from_init1/py2/__init__.py | 0 .../from_init1/py2/pkg2/Makefile | 20 ++ .../from_init1/py2/pkg2/__init__.py | 1 + .../from_init1/py2/pkg2/bar.hpp | 5 + .../import_packages/from_init1/py2/pkg2/bar.i | 6 + .../from_init1/py2/pkg2/foo.hpp | 4 + .../import_packages/from_init1/py2/pkg2/foo.i | 5 + .../import_packages/from_init1/py3/Makefile | 14 + .../from_init1/py3/__init__.py | 0 .../from_init1/py3/pkg2/Makefile | 20 ++ .../from_init1/py3/pkg2/__init__.py | 1 + .../from_init1/py3/pkg2/bar.hpp | 5 + .../import_packages/from_init1/py3/pkg2/bar.i | 6 + .../from_init1/py3/pkg2/foo.hpp | 4 + .../import_packages/from_init1/py3/pkg2/foo.i | 5 + .../import_packages/from_init1/runme.py | 9 + .../import_packages/from_init2/Makefile | 25 ++ .../python/import_packages/from_init2/README | 81 +++++ .../import_packages/from_init2/py2/Makefile | 14 + .../from_init2/py2/__init__.py | 0 .../from_init2/py2/pkg2/Makefile | 18 + .../from_init2/py2/pkg2/__init__.py | 1 + .../from_init2/py2/pkg2/bar.hpp | 5 + .../import_packages/from_init2/py2/pkg2/bar.i | 6 + .../from_init2/py2/pkg2/pkg3/Makefile | 15 + .../from_init2/py2/pkg2/pkg3/__init__.py | 0 .../from_init2/py2/pkg2/pkg3/foo.hpp | 4 + .../from_init2/py2/pkg2/pkg3/foo.i | 5 + .../import_packages/from_init2/py3/Makefile | 14 + .../from_init2/py3/__init__.py | 0 .../from_init2/py3/pkg2/Makefile | 18 + .../from_init2/py3/pkg2/__init__.py | 1 + .../from_init2/py3/pkg2/bar.hpp | 5 + .../import_packages/from_init2/py3/pkg2/bar.i | 6 + .../from_init2/py3/pkg2/pkg3/Makefile | 15 + .../from_init2/py3/pkg2/pkg3/__init__.py | 0 .../from_init2/py3/pkg2/pkg3/foo.hpp | 4 + .../from_init2/py3/pkg2/pkg3/foo.i | 5 + .../import_packages/from_init2/runme.py | 9 + .../import_packages/from_init3/Makefile | 25 ++ .../python/import_packages/from_init3/README | 67 ++++ .../import_packages/from_init3/py2/Makefile | 14 + .../from_init3/py2/__init__.py | 0 .../from_init3/py2/pkg2/Makefile | 18 + .../from_init3/py2/pkg2/__init__.py | 1 + .../from_init3/py2/pkg2/bar.hpp | 5 + .../import_packages/from_init3/py2/pkg2/bar.i | 6 + .../from_init3/py2/pkg2/pkg3/Makefile | 14 + .../from_init3/py2/pkg2/pkg3/__init__.py | 0 .../from_init3/py2/pkg2/pkg3/pkg4/Makefile | 15 + .../from_init3/py2/pkg2/pkg3/pkg4/__init__.py | 0 .../from_init3/py2/pkg2/pkg3/pkg4/foo.hpp | 4 + .../from_init3/py2/pkg2/pkg3/pkg4/foo.i | 5 + .../import_packages/from_init3/py3/Makefile | 14 + .../from_init3/py3/__init__.py | 0 .../from_init3/py3/pkg2/Makefile | 18 + .../from_init3/py3/pkg2/__init__.py | 1 + .../from_init3/py3/pkg2/bar.hpp | 5 + .../import_packages/from_init3/py3/pkg2/bar.i | 6 + .../from_init3/py3/pkg2/pkg3/Makefile | 14 + .../from_init3/py3/pkg2/pkg3/__init__.py | 0 .../from_init3/py3/pkg2/pkg3/pkg4/Makefile | 15 + .../from_init3/py3/pkg2/pkg3/pkg4/__init__.py | 0 .../from_init3/py3/pkg2/pkg3/pkg4/foo.hpp | 4 + .../from_init3/py3/pkg2/pkg3/pkg4/foo.i | 5 + .../import_packages/from_init3/runme.py | 9 + .../import_packages/relativeimport1/Makefile | 25 ++ .../import_packages/relativeimport1/README | 22 ++ .../relativeimport1/py2/Makefile | 14 + .../relativeimport1/py2/__init__.py | 0 .../relativeimport1/py2/pkg2/Makefile | 18 + .../relativeimport1/py2/pkg2/__init__.py | 0 .../relativeimport1/py2/pkg2/bar.hpp | 5 + .../relativeimport1/py2/pkg2/bar.i | 6 + .../relativeimport1/py2/pkg2/pkg3/Makefile | 15 + .../relativeimport1/py2/pkg2/pkg3/__init__.py | 0 .../relativeimport1/py2/pkg2/pkg3/foo.hpp | 4 + .../relativeimport1/py2/pkg2/pkg3/foo.i | 5 + .../relativeimport1/py3/Makefile | 14 + .../relativeimport1/py3/__init__.py | 0 .../relativeimport1/py3/pkg2/Makefile | 18 + .../relativeimport1/py3/pkg2/__init__.py | 0 .../relativeimport1/py3/pkg2/bar.hpp | 5 + .../relativeimport1/py3/pkg2/bar.i | 6 + .../relativeimport1/py3/pkg2/pkg3/Makefile | 15 + .../relativeimport1/py3/pkg2/pkg3/__init__.py | 0 .../relativeimport1/py3/pkg2/pkg3/foo.hpp | 4 + .../relativeimport1/py3/pkg2/pkg3/foo.i | 5 + .../import_packages/relativeimport1/runme.py | 9 + .../import_packages/relativeimport2/Makefile | 25 ++ .../import_packages/relativeimport2/README | 22 ++ .../relativeimport2/py2/Makefile | 14 + .../relativeimport2/py2/__init__.py | 0 .../relativeimport2/py2/pkg2/Makefile | 18 + .../relativeimport2/py2/pkg2/__init__.py | 0 .../relativeimport2/py2/pkg2/bar.hpp | 5 + .../relativeimport2/py2/pkg2/bar.i | 6 + .../relativeimport2/py2/pkg2/pkg3/Makefile | 14 + .../relativeimport2/py2/pkg2/pkg3/__init__.py | 0 .../py2/pkg2/pkg3/pkg4/Makefile | 15 + .../py2/pkg2/pkg3/pkg4/__init__.py | 0 .../py2/pkg2/pkg3/pkg4/foo.hpp | 4 + .../relativeimport2/py2/pkg2/pkg3/pkg4/foo.i | 5 + .../relativeimport2/py3/Makefile | 14 + .../relativeimport2/py3/__init__.py | 0 .../relativeimport2/py3/pkg2/Makefile | 18 + .../relativeimport2/py3/pkg2/__init__.py | 0 .../relativeimport2/py3/pkg2/bar.hpp | 5 + .../relativeimport2/py3/pkg2/bar.i | 6 + .../relativeimport2/py3/pkg2/pkg3/Makefile | 14 + .../relativeimport2/py3/pkg2/pkg3/__init__.py | 0 .../py3/pkg2/pkg3/pkg4/Makefile | 15 + .../py3/pkg2/pkg3/pkg4/__init__.py | 0 .../py3/pkg2/pkg3/pkg4/foo.hpp | 4 + .../relativeimport2/py3/pkg2/pkg3/pkg4/foo.i | 5 + .../import_packages/relativeimport2/runme.py | 9 + .../import_packages/relativeimport2/runme3.py | 9 + .../import_packages/same_modnames1/Makefile | 20 ++ .../import_packages/same_modnames1/README | 26 ++ .../same_modnames1/pkg1/Makefile | 15 + .../same_modnames1/pkg1/__init__.py | 0 .../same_modnames1/pkg1/foo.hpp | 4 + .../import_packages/same_modnames1/pkg1/foo.i | 5 + .../same_modnames1/pkg2/Makefile | 15 + .../same_modnames1/pkg2/__init__.py | 0 .../same_modnames1/pkg2/foo.hpp | 5 + .../import_packages/same_modnames1/pkg2/foo.i | 6 + .../import_packages/same_modnames1/runme.py | 7 + .../import_packages/same_modnames2/Makefile | 20 ++ .../import_packages/same_modnames2/README | 26 ++ .../same_modnames2/pkg1/Makefile | 15 + .../same_modnames2/pkg1/__init__.py | 0 .../same_modnames2/pkg1/foo.hpp | 4 + .../import_packages/same_modnames2/pkg1/foo.i | 5 + .../same_modnames2/pkg1/pkg2/Makefile | 15 + .../same_modnames2/pkg1/pkg2/__init__.py | 0 .../same_modnames2/pkg1/pkg2/foo.hpp | 5 + .../same_modnames2/pkg1/pkg2/foo.i | 6 + .../import_packages/same_modnames2/runme.py | 4 + Source/Modules/python.cxx | 325 ++++++++++++++++-- 146 files changed, 1676 insertions(+), 30 deletions(-) create mode 100644 Examples/python/import_packages/Makefile create mode 100644 Examples/python/import_packages/README create mode 100644 Examples/python/import_packages/from_init1/Makefile create mode 100644 Examples/python/import_packages/from_init1/README create mode 100644 Examples/python/import_packages/from_init1/py2/Makefile create mode 100644 Examples/python/import_packages/from_init1/py2/__init__.py create mode 100644 Examples/python/import_packages/from_init1/py2/pkg2/Makefile create mode 100644 Examples/python/import_packages/from_init1/py2/pkg2/__init__.py create mode 100644 Examples/python/import_packages/from_init1/py2/pkg2/bar.hpp create mode 100644 Examples/python/import_packages/from_init1/py2/pkg2/bar.i create mode 100644 Examples/python/import_packages/from_init1/py2/pkg2/foo.hpp create mode 100644 Examples/python/import_packages/from_init1/py2/pkg2/foo.i create mode 100644 Examples/python/import_packages/from_init1/py3/Makefile create mode 100644 Examples/python/import_packages/from_init1/py3/__init__.py create mode 100644 Examples/python/import_packages/from_init1/py3/pkg2/Makefile create mode 100644 Examples/python/import_packages/from_init1/py3/pkg2/__init__.py create mode 100644 Examples/python/import_packages/from_init1/py3/pkg2/bar.hpp create mode 100644 Examples/python/import_packages/from_init1/py3/pkg2/bar.i create mode 100644 Examples/python/import_packages/from_init1/py3/pkg2/foo.hpp create mode 100644 Examples/python/import_packages/from_init1/py3/pkg2/foo.i create mode 100644 Examples/python/import_packages/from_init1/runme.py create mode 100644 Examples/python/import_packages/from_init2/Makefile create mode 100644 Examples/python/import_packages/from_init2/README create mode 100644 Examples/python/import_packages/from_init2/py2/Makefile create mode 100644 Examples/python/import_packages/from_init2/py2/__init__.py create mode 100644 Examples/python/import_packages/from_init2/py2/pkg2/Makefile create mode 100644 Examples/python/import_packages/from_init2/py2/pkg2/__init__.py create mode 100644 Examples/python/import_packages/from_init2/py2/pkg2/bar.hpp create mode 100644 Examples/python/import_packages/from_init2/py2/pkg2/bar.i create mode 100644 Examples/python/import_packages/from_init2/py2/pkg2/pkg3/Makefile create mode 100644 Examples/python/import_packages/from_init2/py2/pkg2/pkg3/__init__.py create mode 100644 Examples/python/import_packages/from_init2/py2/pkg2/pkg3/foo.hpp create mode 100644 Examples/python/import_packages/from_init2/py2/pkg2/pkg3/foo.i create mode 100644 Examples/python/import_packages/from_init2/py3/Makefile create mode 100644 Examples/python/import_packages/from_init2/py3/__init__.py create mode 100644 Examples/python/import_packages/from_init2/py3/pkg2/Makefile create mode 100644 Examples/python/import_packages/from_init2/py3/pkg2/__init__.py create mode 100644 Examples/python/import_packages/from_init2/py3/pkg2/bar.hpp create mode 100644 Examples/python/import_packages/from_init2/py3/pkg2/bar.i create mode 100644 Examples/python/import_packages/from_init2/py3/pkg2/pkg3/Makefile create mode 100644 Examples/python/import_packages/from_init2/py3/pkg2/pkg3/__init__.py create mode 100644 Examples/python/import_packages/from_init2/py3/pkg2/pkg3/foo.hpp create mode 100644 Examples/python/import_packages/from_init2/py3/pkg2/pkg3/foo.i create mode 100644 Examples/python/import_packages/from_init2/runme.py create mode 100644 Examples/python/import_packages/from_init3/Makefile create mode 100644 Examples/python/import_packages/from_init3/README create mode 100644 Examples/python/import_packages/from_init3/py2/Makefile create mode 100644 Examples/python/import_packages/from_init3/py2/__init__.py create mode 100644 Examples/python/import_packages/from_init3/py2/pkg2/Makefile create mode 100644 Examples/python/import_packages/from_init3/py2/pkg2/__init__.py create mode 100644 Examples/python/import_packages/from_init3/py2/pkg2/bar.hpp create mode 100644 Examples/python/import_packages/from_init3/py2/pkg2/bar.i create mode 100644 Examples/python/import_packages/from_init3/py2/pkg2/pkg3/Makefile create mode 100644 Examples/python/import_packages/from_init3/py2/pkg2/pkg3/__init__.py create mode 100644 Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/Makefile create mode 100644 Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/__init__.py create mode 100644 Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/foo.hpp create mode 100644 Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/foo.i create mode 100644 Examples/python/import_packages/from_init3/py3/Makefile create mode 100644 Examples/python/import_packages/from_init3/py3/__init__.py create mode 100644 Examples/python/import_packages/from_init3/py3/pkg2/Makefile create mode 100644 Examples/python/import_packages/from_init3/py3/pkg2/__init__.py create mode 100644 Examples/python/import_packages/from_init3/py3/pkg2/bar.hpp create mode 100644 Examples/python/import_packages/from_init3/py3/pkg2/bar.i create mode 100644 Examples/python/import_packages/from_init3/py3/pkg2/pkg3/Makefile create mode 100644 Examples/python/import_packages/from_init3/py3/pkg2/pkg3/__init__.py create mode 100644 Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/Makefile create mode 100644 Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/__init__.py create mode 100644 Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/foo.hpp create mode 100644 Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/foo.i create mode 100644 Examples/python/import_packages/from_init3/runme.py create mode 100644 Examples/python/import_packages/relativeimport1/Makefile create mode 100644 Examples/python/import_packages/relativeimport1/README create mode 100644 Examples/python/import_packages/relativeimport1/py2/Makefile create mode 100644 Examples/python/import_packages/relativeimport1/py2/__init__.py create mode 100644 Examples/python/import_packages/relativeimport1/py2/pkg2/Makefile create mode 100644 Examples/python/import_packages/relativeimport1/py2/pkg2/__init__.py create mode 100644 Examples/python/import_packages/relativeimport1/py2/pkg2/bar.hpp create mode 100644 Examples/python/import_packages/relativeimport1/py2/pkg2/bar.i create mode 100644 Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/Makefile create mode 100644 Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/__init__.py create mode 100644 Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/foo.hpp create mode 100644 Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/foo.i create mode 100644 Examples/python/import_packages/relativeimport1/py3/Makefile create mode 100644 Examples/python/import_packages/relativeimport1/py3/__init__.py create mode 100644 Examples/python/import_packages/relativeimport1/py3/pkg2/Makefile create mode 100644 Examples/python/import_packages/relativeimport1/py3/pkg2/__init__.py create mode 100644 Examples/python/import_packages/relativeimport1/py3/pkg2/bar.hpp create mode 100644 Examples/python/import_packages/relativeimport1/py3/pkg2/bar.i create mode 100644 Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/Makefile create mode 100644 Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/__init__.py create mode 100644 Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/foo.hpp create mode 100644 Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/foo.i create mode 100644 Examples/python/import_packages/relativeimport1/runme.py create mode 100644 Examples/python/import_packages/relativeimport2/Makefile create mode 100644 Examples/python/import_packages/relativeimport2/README create mode 100644 Examples/python/import_packages/relativeimport2/py2/Makefile create mode 100644 Examples/python/import_packages/relativeimport2/py2/__init__.py create mode 100644 Examples/python/import_packages/relativeimport2/py2/pkg2/Makefile create mode 100644 Examples/python/import_packages/relativeimport2/py2/pkg2/__init__.py create mode 100644 Examples/python/import_packages/relativeimport2/py2/pkg2/bar.hpp create mode 100644 Examples/python/import_packages/relativeimport2/py2/pkg2/bar.i create mode 100644 Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/Makefile create mode 100644 Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/__init__.py create mode 100644 Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/Makefile create mode 100644 Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/__init__.py create mode 100644 Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/foo.hpp create mode 100644 Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/foo.i create mode 100644 Examples/python/import_packages/relativeimport2/py3/Makefile create mode 100644 Examples/python/import_packages/relativeimport2/py3/__init__.py create mode 100644 Examples/python/import_packages/relativeimport2/py3/pkg2/Makefile create mode 100644 Examples/python/import_packages/relativeimport2/py3/pkg2/__init__.py create mode 100644 Examples/python/import_packages/relativeimport2/py3/pkg2/bar.hpp create mode 100644 Examples/python/import_packages/relativeimport2/py3/pkg2/bar.i create mode 100644 Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/Makefile create mode 100644 Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/__init__.py create mode 100644 Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/Makefile create mode 100644 Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/__init__.py create mode 100644 Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/foo.hpp create mode 100644 Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/foo.i create mode 100644 Examples/python/import_packages/relativeimport2/runme.py create mode 100644 Examples/python/import_packages/relativeimport2/runme3.py create mode 100644 Examples/python/import_packages/same_modnames1/Makefile create mode 100644 Examples/python/import_packages/same_modnames1/README create mode 100644 Examples/python/import_packages/same_modnames1/pkg1/Makefile create mode 100644 Examples/python/import_packages/same_modnames1/pkg1/__init__.py create mode 100644 Examples/python/import_packages/same_modnames1/pkg1/foo.hpp create mode 100644 Examples/python/import_packages/same_modnames1/pkg1/foo.i create mode 100644 Examples/python/import_packages/same_modnames1/pkg2/Makefile create mode 100644 Examples/python/import_packages/same_modnames1/pkg2/__init__.py create mode 100644 Examples/python/import_packages/same_modnames1/pkg2/foo.hpp create mode 100644 Examples/python/import_packages/same_modnames1/pkg2/foo.i create mode 100644 Examples/python/import_packages/same_modnames1/runme.py create mode 100644 Examples/python/import_packages/same_modnames2/Makefile create mode 100644 Examples/python/import_packages/same_modnames2/README create mode 100644 Examples/python/import_packages/same_modnames2/pkg1/Makefile create mode 100644 Examples/python/import_packages/same_modnames2/pkg1/__init__.py create mode 100644 Examples/python/import_packages/same_modnames2/pkg1/foo.hpp create mode 100644 Examples/python/import_packages/same_modnames2/pkg1/foo.i create mode 100644 Examples/python/import_packages/same_modnames2/pkg1/pkg2/Makefile create mode 100644 Examples/python/import_packages/same_modnames2/pkg1/pkg2/__init__.py create mode 100644 Examples/python/import_packages/same_modnames2/pkg1/pkg2/foo.hpp create mode 100644 Examples/python/import_packages/same_modnames2/pkg1/pkg2/foo.i create mode 100644 Examples/python/import_packages/same_modnames2/runme.py diff --git a/Examples/python/check.list b/Examples/python/check.list index 7cfe437f0..e9e7c8357 100644 --- a/Examples/python/check.list +++ b/Examples/python/check.list @@ -13,6 +13,7 @@ funcptr2 functor import import_template +import_packages java #libffi multimap diff --git a/Examples/python/import_packages/Makefile b/Examples/python/import_packages/Makefile new file mode 100644 index 000000000..fda2380b3 --- /dev/null +++ b/Examples/python/import_packages/Makefile @@ -0,0 +1,35 @@ +TOP = ../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = +PY3 = + +import_packages_subdirs = \ + same_modnames1 \ + same_modnames2 \ + from_init1 \ + from_init2 \ + from_init3 \ + relativeimport1 \ + relativeimport1 + +check: build + for s in $(import_packages_subdirs); do \ + (cd $$s && $(MAKE) check); \ + done + +build: + for s in $(import_packages_subdirs); do \ + (cd $$s && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build); \ + done + +static: + for s in $(import_packages_subdirs); do \ + (cd $$s && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static); \ + done + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + for s in $(import_packages_subdirs); do \ + (cd $$s && $(MAKE) clean); \ + done diff --git a/Examples/python/import_packages/README b/Examples/python/import_packages/README new file mode 100644 index 000000000..69fe3516e --- /dev/null +++ b/Examples/python/import_packages/README @@ -0,0 +1,2 @@ +These are actually regression tests for SF bug #1297 (GH issue #7). +See individual READMEs in subdirectories. diff --git a/Examples/python/import_packages/from_init1/Makefile b/Examples/python/import_packages/from_init1/Makefile new file mode 100644 index 000000000..8e35c6c61 --- /dev/null +++ b/Examples/python/import_packages/from_init1/Makefile @@ -0,0 +1,25 @@ +TOP = ../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = +PY3 = + +ifeq (,$(PY3)) + PKG1DIR = "py2" +else + PKG1DIR = "py3" +endif + +check: build + $(MAKE) -f $(TOP)/Makefile python_run + +build: + cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build + +static: + cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + cd py2 && $(MAKE) clean + cd py3 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init1/README b/Examples/python/import_packages/from_init1/README new file mode 100644 index 000000000..e7d7eca9e --- /dev/null +++ b/Examples/python/import_packages/from_init1/README @@ -0,0 +1,63 @@ +This example tests the %import directive and python import from __init__.py. + +This case is not correctly handled by swig 2. + +The issue was reported as Source Forge bug #1297 and later as GitHub issue #7. + +Use 'python runme.py' to run a test. + + +Overview: +--------- + +The example defines 2 different extension modules--each wrapping a separate C++ +class. + + pyX/pkg2/foo.i - Pkg2_Foo class + pyX/pkg2/bar.i - Pkg2_Bar class derived from Pkg2_Foo + +and the package pyX.pkg2 has: + + pyX/pkg2/__init__.py - which imports something from "bar" module (we + import Pkg2_Bar class, but it is not the clue, + the clue is the 'from' keyword) + +For example with python2.x the py2/pkg2/__init__.py imports Pkg2_Bar class +as follows + + from bar import Pkg2_Bar # [1] + +Such cases doesn't work when fully qualified python module names are used by +swig (swig 2.0.10, e.g.) to generate python import directives (SF bug #1297). +The generated file "py2/pkg2/bar.py" has following lines: + + import py2.pkg2.foo # [2] + class Pkg2_Bar(py2.pkg2.foo.Pkg2_Foo): # [3] + +but it's not possible to import anything from py2.pkg2 subpackage, e.g. + + import py2.pkg2 + +fails with the following exception: + +Traceback (most recent call last): + File "runme.py", line 3, in + import py2.pkg2 + File "py2/pkg2/__init__.py", line 7, in + from .bar import Pkg2_Bar + File "py2/pkg2/bar.py", line 71, in + class Pkg2_Bar(py2.pkg2.foo.Pkg2_Foo): + AttributeError: 'module' object has no attribute 'pkg2' + + +It seems like during the import [1], the sub-package pkg2 is not yet fully +initialized, so py2.pkg2 is not known. The above exception is raised at +line [3]. The problem disappears, for example, if we force swig to use relative +package names. + +If everything works well, the package py2.pkg2 shall load properly. + +Unix: +----- +- Run make +- Run the test as described above diff --git a/Examples/python/import_packages/from_init1/py2/Makefile b/Examples/python/import_packages/from_init1/py2/Makefile new file mode 100644 index 000000000..4c0dfab07 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py2/Makefile @@ -0,0 +1,14 @@ +TOP = ../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init1/py2/__init__.py b/Examples/python/import_packages/from_init1/py2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init1/py2/pkg2/Makefile b/Examples/python/import_packages/from_init1/py2/pkg2/Makefile new file mode 100644 index 000000000..0dd174659 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py2/pkg2/Makefile @@ -0,0 +1,20 @@ +TOP = ../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp_static + +clean:: + $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean + $(MAKE) -f $(TOP)/Makefile TARGET='bar' python_clean diff --git a/Examples/python/import_packages/from_init1/py2/pkg2/__init__.py b/Examples/python/import_packages/from_init1/py2/pkg2/__init__.py new file mode 100644 index 000000000..0f9c90203 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py2/pkg2/__init__.py @@ -0,0 +1 @@ +from bar import Pkg2_Bar diff --git a/Examples/python/import_packages/from_init1/py2/pkg2/bar.hpp b/Examples/python/import_packages/from_init1/py2/pkg2/bar.hpp new file mode 100644 index 000000000..b369161d3 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py2/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY2_PKG2_BAR_HPP +#define PY2_PKG2_BAR_HPP +#include "../../py2/pkg2/foo.hpp" +struct Pkg2_Bar : Pkg2_Foo {}; +#endif /* PY2_PKG2_BAR_HPP */ diff --git a/Examples/python/import_packages/from_init1/py2/pkg2/bar.i b/Examples/python/import_packages/from_init1/py2/pkg2/bar.i new file mode 100644 index 000000000..0795a7751 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py2/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py2.pkg2") bar +%{ +#include "../../py2/pkg2/bar.hpp" +%} +%import "../../py2/pkg2/foo.i" +%include "../../py2/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/from_init1/py2/pkg2/foo.hpp b/Examples/python/import_packages/from_init1/py2/pkg2/foo.hpp new file mode 100644 index 000000000..fed8239f6 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py2/pkg2/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY2_PKG2_FOO_HPP +#define PY2_PKG2_FOO_HPP +struct Pkg2_Foo {}; +#endif /* PY2_PKG2_FOO_HPP */ diff --git a/Examples/python/import_packages/from_init1/py2/pkg2/foo.i b/Examples/python/import_packages/from_init1/py2/pkg2/foo.i new file mode 100644 index 000000000..37b2e1f82 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py2/pkg2/foo.i @@ -0,0 +1,5 @@ +%module(package="py2.pkg2") foo +%{ +#include "../../py2/pkg2/foo.hpp" +%} +%include "../../py2/pkg2/foo.hpp" diff --git a/Examples/python/import_packages/from_init1/py3/Makefile b/Examples/python/import_packages/from_init1/py3/Makefile new file mode 100644 index 000000000..4c0dfab07 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py3/Makefile @@ -0,0 +1,14 @@ +TOP = ../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init1/py3/__init__.py b/Examples/python/import_packages/from_init1/py3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init1/py3/pkg2/Makefile b/Examples/python/import_packages/from_init1/py3/pkg2/Makefile new file mode 100644 index 000000000..0dd174659 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py3/pkg2/Makefile @@ -0,0 +1,20 @@ +TOP = ../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp_static + +clean:: + $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean + $(MAKE) -f $(TOP)/Makefile TARGET='bar' python_clean diff --git a/Examples/python/import_packages/from_init1/py3/pkg2/__init__.py b/Examples/python/import_packages/from_init1/py3/pkg2/__init__.py new file mode 100644 index 000000000..2097aaf2e --- /dev/null +++ b/Examples/python/import_packages/from_init1/py3/pkg2/__init__.py @@ -0,0 +1 @@ +from .bar import Pkg2_Bar diff --git a/Examples/python/import_packages/from_init1/py3/pkg2/bar.hpp b/Examples/python/import_packages/from_init1/py3/pkg2/bar.hpp new file mode 100644 index 000000000..d16463dff --- /dev/null +++ b/Examples/python/import_packages/from_init1/py3/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY3_PKG2_BAR_HPP +#define PY3_PKG2_BAR_HPP +#include "../../py3/pkg2/foo.hpp" +struct Pkg2_Bar : Pkg2_Foo {}; +#endif /* PY3_PKG2_BAR_HPP */ diff --git a/Examples/python/import_packages/from_init1/py3/pkg2/bar.i b/Examples/python/import_packages/from_init1/py3/pkg2/bar.i new file mode 100644 index 000000000..8d8d627b9 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py3/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py3.pkg2") bar +%{ +#include "../../py3/pkg2/bar.hpp" +%} +%import "../../py3/pkg2/foo.i" +%include "../../py3/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/from_init1/py3/pkg2/foo.hpp b/Examples/python/import_packages/from_init1/py3/pkg2/foo.hpp new file mode 100644 index 000000000..c2469dc86 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py3/pkg2/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY3_PKG2_FOO_HPP +#define PY3_PKG2_FOO_HPP +struct Pkg2_Foo {}; +#endif /* PY3_PKG2_FOO_HPP */ diff --git a/Examples/python/import_packages/from_init1/py3/pkg2/foo.i b/Examples/python/import_packages/from_init1/py3/pkg2/foo.i new file mode 100644 index 000000000..76613b593 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py3/pkg2/foo.i @@ -0,0 +1,5 @@ +%module(package="py3.pkg2") foo +%{ +#include "../../py3/pkg2/foo.hpp" +%} +%include "../../py3/pkg2/foo.hpp" diff --git a/Examples/python/import_packages/from_init1/runme.py b/Examples/python/import_packages/from_init1/runme.py new file mode 100644 index 000000000..c23a085fa --- /dev/null +++ b/Examples/python/import_packages/from_init1/runme.py @@ -0,0 +1,9 @@ +# Test import of modules content from within __init__.py +print "Testing %module(package=...) + python 'import' in __init__.py" +import sys +if sys.version_info < (3,0): + import py2.pkg2 + print " Finished importing py2.pkg2" +else: + import py3.pkg2 + print " Finished importing py3.pkg2" diff --git a/Examples/python/import_packages/from_init2/Makefile b/Examples/python/import_packages/from_init2/Makefile new file mode 100644 index 000000000..8e35c6c61 --- /dev/null +++ b/Examples/python/import_packages/from_init2/Makefile @@ -0,0 +1,25 @@ +TOP = ../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = +PY3 = + +ifeq (,$(PY3)) + PKG1DIR = "py2" +else + PKG1DIR = "py3" +endif + +check: build + $(MAKE) -f $(TOP)/Makefile python_run + +build: + cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build + +static: + cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + cd py2 && $(MAKE) clean + cd py3 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init2/README b/Examples/python/import_packages/from_init2/README new file mode 100644 index 000000000..a0eb41839 --- /dev/null +++ b/Examples/python/import_packages/from_init2/README @@ -0,0 +1,81 @@ +This example tests the %import directive and python import from __init__.py. + +This case is not correctly handled by swig 2. + +The issue was reported as Source Forge bug #1297 and later as GitHub issue #7. + +Use 'python runme.py' to run a test. + +Overview: +--------- + +The example defines 2 different extension modules--each wrapping a separate C++ +class. + + pyX/pkg2/pkg3/foo.i - Pkg3_Foo class + pyX/pkg2/bar.i - Pkg2_Bar class derived from Pkg3_Foo + +and the package pyX.pkg2 has: + + pyX/pkg2/__init__.py - which imports something from "bar" module + +For example with python 2.x the py2/pkg2/__init__.py imports Pkg2_Bar class as +follows + + from bar import Pkg2_Bar # [1] + +Such cases doesn't work when fully qualified python module names are used by +swig to generate python import directives (SF bug #1297). The generated file +"py2/pkg2/bar.py" has following lines: + + import py2.pkg2.pkg3.foo # [2] + class Pkg2_Bar(py2.pkg2.pkg3.foo.Pkg3_Foo): # [3] + +and it's not possible to import anything from py2.pkg2 subpackage, e.g. + + import py2.pkg2 + +fails with the following exception: + +Traceback (most recent call last): + File "runme.py", line 3, in + import py2.pkg2 + File "py2/pkg2/__init__.py", line 4, in + from bar import Pkg2_Bar + File "py2/pkg2/bar.py", line 71, in + class Pkg2_Bar(py2.pkg2.pkg3.foo.Pkg3_Foo): +AttributeError: 'module' object has no attribute 'pkg2' + +It seems like during the import [1], the subpackage pkg2 is not yet fully +initialized, so pyX.pkg2 is not known. The above exception is raised at line [3]. +The problem disappears, for example, if we force swig to use relative package +names. + +The difference between this ('from_init2') case and the case +'from_init1' is that here it's not sufficient to import relative module +by just ignoring the package part of the fully qualified module name. IOW +it is not correct to force swig to put: + + import foo + class Pkg2_Bar(foo.Pkg3_Foo) + +into pyX/pkg2/bar.py (note, that this would work for 'from_init1' case). +The import directive shall be rather: + + import pkg3.foo + +for python 2.x and: + + from . import pkg3 + import pkg3.foo + +for python 3, and the class definition shall begin with: + + class Pkg2_Bar(pkg3.foo.Pkg3_Foo) + +If everything works well, the package pyX.pkg2 shall load properly. + +Unix: +----- +- Run make +- Run the test as described above diff --git a/Examples/python/import_packages/from_init2/py2/Makefile b/Examples/python/import_packages/from_init2/py2/Makefile new file mode 100644 index 000000000..4c0dfab07 --- /dev/null +++ b/Examples/python/import_packages/from_init2/py2/Makefile @@ -0,0 +1,14 @@ +TOP = ../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init2/py2/__init__.py b/Examples/python/import_packages/from_init2/py2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init2/py2/pkg2/Makefile b/Examples/python/import_packages/from_init2/py2/pkg2/Makefile new file mode 100644 index 000000000..3fe56139d --- /dev/null +++ b/Examples/python/import_packages/from_init2/py2/pkg2/Makefile @@ -0,0 +1,18 @@ +TOP = ../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile TARGET='bar' python_clean + cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init2/py2/pkg2/__init__.py b/Examples/python/import_packages/from_init2/py2/pkg2/__init__.py new file mode 100644 index 000000000..0f9c90203 --- /dev/null +++ b/Examples/python/import_packages/from_init2/py2/pkg2/__init__.py @@ -0,0 +1 @@ +from bar import Pkg2_Bar diff --git a/Examples/python/import_packages/from_init2/py2/pkg2/bar.hpp b/Examples/python/import_packages/from_init2/py2/pkg2/bar.hpp new file mode 100644 index 000000000..8f09cd5fa --- /dev/null +++ b/Examples/python/import_packages/from_init2/py2/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY2_PKG2_BAR_HPP +#define PY2_PKG2_BAR_HPP +#include "../../py2/pkg2/pkg3/foo.hpp" +struct Pkg2_Bar : Pkg3_Foo {}; +#endif /* PY2_PKG2_BAR_HPP */ diff --git a/Examples/python/import_packages/from_init2/py2/pkg2/bar.i b/Examples/python/import_packages/from_init2/py2/pkg2/bar.i new file mode 100644 index 000000000..28a4c906e --- /dev/null +++ b/Examples/python/import_packages/from_init2/py2/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py2.pkg2") bar +%{ +#include "../../py2/pkg2/bar.hpp" +%} +%import "../../py2/pkg2/pkg3/foo.i" +%include "../../py2/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/Makefile b/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/Makefile new file mode 100644 index 000000000..a417e2745 --- /dev/null +++ b/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/Makefile @@ -0,0 +1,15 @@ +TOP = ../../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + +clean: + $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean diff --git a/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/__init__.py b/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/foo.hpp b/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/foo.hpp new file mode 100644 index 000000000..b6c89a431 --- /dev/null +++ b/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY2_PKG2_PKG3_FOO_HPP +#define PY2_PKG2_PKG3_FOO_HPP +struct Pkg3_Foo {}; +#endif /* PY2_PKG2_PKG3_FOO_HPP */ diff --git a/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/foo.i b/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/foo.i new file mode 100644 index 000000000..ba32483d2 --- /dev/null +++ b/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/foo.i @@ -0,0 +1,5 @@ +%module(package="py2.pkg2.pkg3") foo +%{ +#include "../../../py2/pkg2/pkg3/foo.hpp" +%} +%include "../../../py2/pkg2/pkg3/foo.hpp" diff --git a/Examples/python/import_packages/from_init2/py3/Makefile b/Examples/python/import_packages/from_init2/py3/Makefile new file mode 100644 index 000000000..4c0dfab07 --- /dev/null +++ b/Examples/python/import_packages/from_init2/py3/Makefile @@ -0,0 +1,14 @@ +TOP = ../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init2/py3/__init__.py b/Examples/python/import_packages/from_init2/py3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init2/py3/pkg2/Makefile b/Examples/python/import_packages/from_init2/py3/pkg2/Makefile new file mode 100644 index 000000000..3fe56139d --- /dev/null +++ b/Examples/python/import_packages/from_init2/py3/pkg2/Makefile @@ -0,0 +1,18 @@ +TOP = ../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile TARGET='bar' python_clean + cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init2/py3/pkg2/__init__.py b/Examples/python/import_packages/from_init2/py3/pkg2/__init__.py new file mode 100644 index 000000000..2097aaf2e --- /dev/null +++ b/Examples/python/import_packages/from_init2/py3/pkg2/__init__.py @@ -0,0 +1 @@ +from .bar import Pkg2_Bar diff --git a/Examples/python/import_packages/from_init2/py3/pkg2/bar.hpp b/Examples/python/import_packages/from_init2/py3/pkg2/bar.hpp new file mode 100644 index 000000000..408d910d7 --- /dev/null +++ b/Examples/python/import_packages/from_init2/py3/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY3_PKG2_BAR_HPP +#define PY3_PKG2_BAR_HPP +#include "../../py3/pkg2/pkg3/foo.hpp" +struct Pkg2_Bar : Pkg3_Foo {}; +#endif /* PY3_PKG2_BAR_HPP */ diff --git a/Examples/python/import_packages/from_init2/py3/pkg2/bar.i b/Examples/python/import_packages/from_init2/py3/pkg2/bar.i new file mode 100644 index 000000000..1468932ff --- /dev/null +++ b/Examples/python/import_packages/from_init2/py3/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py3.pkg2") bar +%{ +#include "../../py3/pkg2/bar.hpp" +%} +%import "../../py3/pkg2/pkg3/foo.i" +%include "../../py3/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/Makefile b/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/Makefile new file mode 100644 index 000000000..a417e2745 --- /dev/null +++ b/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/Makefile @@ -0,0 +1,15 @@ +TOP = ../../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + +clean: + $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean diff --git a/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/__init__.py b/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/foo.hpp b/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/foo.hpp new file mode 100644 index 000000000..531721d36 --- /dev/null +++ b/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY3_PKG2_PKG3_FOO_HPP +#define PY3_PKG2_PKG3_FOO_HPP +struct Pkg3_Foo {}; +#endif /* PY3_PKG2_PKG3_FOO_HPP */ diff --git a/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/foo.i b/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/foo.i new file mode 100644 index 000000000..c6ba529b7 --- /dev/null +++ b/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/foo.i @@ -0,0 +1,5 @@ +%module(package="py3.pkg2.pkg3") foo +%{ +#include "../../../py3/pkg2/pkg3/foo.hpp" +%} +%include "../../../py3/pkg2/pkg3/foo.hpp" diff --git a/Examples/python/import_packages/from_init2/runme.py b/Examples/python/import_packages/from_init2/runme.py new file mode 100644 index 000000000..c23a085fa --- /dev/null +++ b/Examples/python/import_packages/from_init2/runme.py @@ -0,0 +1,9 @@ +# Test import of modules content from within __init__.py +print "Testing %module(package=...) + python 'import' in __init__.py" +import sys +if sys.version_info < (3,0): + import py2.pkg2 + print " Finished importing py2.pkg2" +else: + import py3.pkg2 + print " Finished importing py3.pkg2" diff --git a/Examples/python/import_packages/from_init3/Makefile b/Examples/python/import_packages/from_init3/Makefile new file mode 100644 index 000000000..8e35c6c61 --- /dev/null +++ b/Examples/python/import_packages/from_init3/Makefile @@ -0,0 +1,25 @@ +TOP = ../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = +PY3 = + +ifeq (,$(PY3)) + PKG1DIR = "py2" +else + PKG1DIR = "py3" +endif + +check: build + $(MAKE) -f $(TOP)/Makefile python_run + +build: + cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build + +static: + cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + cd py2 && $(MAKE) clean + cd py3 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init3/README b/Examples/python/import_packages/from_init3/README new file mode 100644 index 000000000..131d5894c --- /dev/null +++ b/Examples/python/import_packages/from_init3/README @@ -0,0 +1,67 @@ +This example tests the %import directive and python import from __init__.py. + +This case is not correctly handled by swig 2. + +The issue was reported as Source Forge bug #1297 and later as GitHub issue #7. + +Use 'python runme.py' to run a test. + +Overview: +--------- + +The example defines 2 different extension modules--each wrapping a separate C++ +class. + + pyX/pkg2/pkg3/pkg4/foo.i - Pkg4_Foo class + pyX/pkg2/bar.i - Pkg2_Bar class derived from Pkg4_Foo + +and the package pyX.pkg2 has: + + pyX/pkg2/__init__.py - which imports something from "bar" module + +For example with python 2.x the py2/pkg2/__init__.py imports Pkg2_Bar class as +follows + + from bar import Pkg2_Bar # [1] + +Such cases doesn't work when fully qualified python module names are used by +swig to generate python import directives (SF bug 1297). The generated file +"py2/pkg2/bar.py" has following lines: + + import py2.pkg2.pkg3.pkg4.foo # [2] + class Pkg2_Bar(py2.pkg2.pkg3.pkg4.foo.P1_S1_S2_Foo): # [3] + +and it's not possible to import anything from py2.pkg2 subpackage, e.g. + + import py2.pkg2 + +fails with the following exception: + + Traceback (most recent call last): + File "runme.py", line 3, in + import py2.pkg2 + File "py2/pkg2/__init__.py", line 4, in + from bar import Pkg2_Bar + File "py2/pkg2/bar.py", line 71, in + class Pkg2_Bar(py2.pkg2.pkg3.pkg4.foo.Pkg4_Foo): + AttributeError: 'module' object has no attribute 'pkg2' + +It seems like during the import [1], the subpackage pkg2 is not yet fully +initialized, so py2.pkg2 can't be used. The above exception is raised at +line [3]. The problem disappears, for example, if we force swig to use relative +package names. + +The difference between this ('from_init3') case and the case +'from_init2' is that here we import base class from module +pyX.pkg2.pkg3.pkg4.foo, which is nested deeper than it was in +'from_init2'. This is just to ensure, that two (and more) levels of +subpackages get imported correctly by generated python code, i.e, not only +'pkg3.foo' is handled properly (one-level subpackage) but the code works also +for 'pkg3.pkg4.foo', and so on. + +If everything works well, the package pyX.pkg2 shall load properly. + +Unix: +----- +- Run make +- Run the test as described above diff --git a/Examples/python/import_packages/from_init3/py2/Makefile b/Examples/python/import_packages/from_init3/py2/Makefile new file mode 100644 index 000000000..4c0dfab07 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py2/Makefile @@ -0,0 +1,14 @@ +TOP = ../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init3/py2/__init__.py b/Examples/python/import_packages/from_init3/py2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/Makefile b/Examples/python/import_packages/from_init3/py2/pkg2/Makefile new file mode 100644 index 000000000..3fe56139d --- /dev/null +++ b/Examples/python/import_packages/from_init3/py2/pkg2/Makefile @@ -0,0 +1,18 @@ +TOP = ../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile TARGET='bar' python_clean + cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/__init__.py b/Examples/python/import_packages/from_init3/py2/pkg2/__init__.py new file mode 100644 index 000000000..0f9c90203 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py2/pkg2/__init__.py @@ -0,0 +1 @@ +from bar import Pkg2_Bar diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/bar.hpp b/Examples/python/import_packages/from_init3/py2/pkg2/bar.hpp new file mode 100644 index 000000000..20a00190a --- /dev/null +++ b/Examples/python/import_packages/from_init3/py2/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY2_PKG2_HPP +#define PY2_PKG2_HPP +#include "../../py2/pkg2/pkg3/pkg4/foo.hpp" +struct Pkg2_Bar : Pkg4_Foo {}; +#endif /* PY2_PKG2_HPP */ diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/bar.i b/Examples/python/import_packages/from_init3/py2/pkg2/bar.i new file mode 100644 index 000000000..0a932a2b9 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py2/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py2.pkg2") bar +%{ +#include "../../py2/pkg2/bar.hpp" +%} +%import "../../py2/pkg2/pkg3/pkg4/foo.i" +%include "../../py2/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/Makefile b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/Makefile new file mode 100644 index 000000000..470f9d561 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/Makefile @@ -0,0 +1,14 @@ +TOP = ../../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + cd pkg4 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg4 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + cd pkg4 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/__init__.py b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/Makefile b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/Makefile new file mode 100644 index 000000000..a98d31122 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/Makefile @@ -0,0 +1,15 @@ +TOP = ../../../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + +clean: + $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/__init__.py b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/foo.hpp b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/foo.hpp new file mode 100644 index 000000000..2df933c59 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY2_PKG2_PKG3_PKG4 +#define PY2_PKG2_PKG3_PKG4 +struct Pkg4_Foo {}; +#endif /* PY2_PKG2_PKG3_PKG4 */ diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/foo.i b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/foo.i new file mode 100644 index 000000000..311d7161c --- /dev/null +++ b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/foo.i @@ -0,0 +1,5 @@ +%module(package="py2.pkg2.pkg3.pkg4") foo +%{ +#include "../../../../py2/pkg2/pkg3/pkg4/foo.hpp" +%} +%include "../../../../py2/pkg2/pkg3/pkg4/foo.hpp" diff --git a/Examples/python/import_packages/from_init3/py3/Makefile b/Examples/python/import_packages/from_init3/py3/Makefile new file mode 100644 index 000000000..4c0dfab07 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py3/Makefile @@ -0,0 +1,14 @@ +TOP = ../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init3/py3/__init__.py b/Examples/python/import_packages/from_init3/py3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/Makefile b/Examples/python/import_packages/from_init3/py3/pkg2/Makefile new file mode 100644 index 000000000..3fe56139d --- /dev/null +++ b/Examples/python/import_packages/from_init3/py3/pkg2/Makefile @@ -0,0 +1,18 @@ +TOP = ../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile TARGET='bar' python_clean + cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/__init__.py b/Examples/python/import_packages/from_init3/py3/pkg2/__init__.py new file mode 100644 index 000000000..2097aaf2e --- /dev/null +++ b/Examples/python/import_packages/from_init3/py3/pkg2/__init__.py @@ -0,0 +1 @@ +from .bar import Pkg2_Bar diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/bar.hpp b/Examples/python/import_packages/from_init3/py3/pkg2/bar.hpp new file mode 100644 index 000000000..16fdd362e --- /dev/null +++ b/Examples/python/import_packages/from_init3/py3/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY3_PKG2_HPP +#define PY3_PKG2_HPP +#include "../../py3/pkg2/pkg3/pkg4/foo.hpp" +struct Pkg2_Bar : Pkg4_Foo {}; +#endif /* PY3_PKG2_HPP */ diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/bar.i b/Examples/python/import_packages/from_init3/py3/pkg2/bar.i new file mode 100644 index 000000000..3abbb05d3 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py3/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py3.pkg2") bar +%{ +#include "../../py3/pkg2/bar.hpp" +%} +%import "../../py3/pkg2/pkg3/pkg4/foo.i" +%include "../../py3/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/Makefile b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/Makefile new file mode 100644 index 000000000..470f9d561 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/Makefile @@ -0,0 +1,14 @@ +TOP = ../../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + cd pkg4 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg4 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + cd pkg4 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/__init__.py b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/Makefile b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/Makefile new file mode 100644 index 000000000..a98d31122 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/Makefile @@ -0,0 +1,15 @@ +TOP = ../../../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + +clean: + $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/__init__.py b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/foo.hpp b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/foo.hpp new file mode 100644 index 000000000..e24654c28 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY3_PKG2_PKG3_PKG4 +#define PY3_PKG2_PKG3_PKG4 +struct Pkg4_Foo {}; +#endif /* PY3_PKG2_PKG3_PKG4 */ diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/foo.i b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/foo.i new file mode 100644 index 000000000..36c5f01ea --- /dev/null +++ b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/foo.i @@ -0,0 +1,5 @@ +%module(package="py3.pkg2.pkg3.pkg4") foo +%{ +#include "../../../../py3/pkg2/pkg3/pkg4/foo.hpp" +%} +%include "../../../../py3/pkg2/pkg3/pkg4/foo.hpp" diff --git a/Examples/python/import_packages/from_init3/runme.py b/Examples/python/import_packages/from_init3/runme.py new file mode 100644 index 000000000..c23a085fa --- /dev/null +++ b/Examples/python/import_packages/from_init3/runme.py @@ -0,0 +1,9 @@ +# Test import of modules content from within __init__.py +print "Testing %module(package=...) + python 'import' in __init__.py" +import sys +if sys.version_info < (3,0): + import py2.pkg2 + print " Finished importing py2.pkg2" +else: + import py3.pkg2 + print " Finished importing py3.pkg2" diff --git a/Examples/python/import_packages/relativeimport1/Makefile b/Examples/python/import_packages/relativeimport1/Makefile new file mode 100644 index 000000000..8e35c6c61 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/Makefile @@ -0,0 +1,25 @@ +TOP = ../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = +PY3 = + +ifeq (,$(PY3)) + PKG1DIR = "py2" +else + PKG1DIR = "py3" +endif + +check: build + $(MAKE) -f $(TOP)/Makefile python_run + +build: + cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build + +static: + cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + cd py2 && $(MAKE) clean + cd py3 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport1/README b/Examples/python/import_packages/relativeimport1/README new file mode 100644 index 000000000..a99ef2426 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/README @@ -0,0 +1,22 @@ +This example tests the %import directive and -relativeimport swig option. + +Use 'python runme.py' to run a test. + +Overview: +--------- + +The example defines 2 different extension modules--each wrapping a separate C++ +class. + + pyX/pkg2/pkg3/foo.i - Pkg3_Foo class + pyX/pkg2/bar.i - Pkg2_Bar class derived from Pkg3_Foo + +The code is processed by swig with -relativeimport flag. The runtime test +imports pyX.pkg2.bar module. + +If everything works well, the module pyX.pkg2.bar shall load properly. + +Unix: +----- +- Run make +- Run the test as described above diff --git a/Examples/python/import_packages/relativeimport1/py2/Makefile b/Examples/python/import_packages/relativeimport1/py2/Makefile new file mode 100644 index 000000000..4c0dfab07 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py2/Makefile @@ -0,0 +1,14 @@ +TOP = ../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport1/py2/__init__.py b/Examples/python/import_packages/relativeimport1/py2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport1/py2/pkg2/Makefile b/Examples/python/import_packages/relativeimport1/py2/pkg2/Makefile new file mode 100644 index 000000000..3fe56139d --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py2/pkg2/Makefile @@ -0,0 +1,18 @@ +TOP = ../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile TARGET='bar' python_clean + cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport1/py2/pkg2/__init__.py b/Examples/python/import_packages/relativeimport1/py2/pkg2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport1/py2/pkg2/bar.hpp b/Examples/python/import_packages/relativeimport1/py2/pkg2/bar.hpp new file mode 100644 index 000000000..8f09cd5fa --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py2/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY2_PKG2_BAR_HPP +#define PY2_PKG2_BAR_HPP +#include "../../py2/pkg2/pkg3/foo.hpp" +struct Pkg2_Bar : Pkg3_Foo {}; +#endif /* PY2_PKG2_BAR_HPP */ diff --git a/Examples/python/import_packages/relativeimport1/py2/pkg2/bar.i b/Examples/python/import_packages/relativeimport1/py2/pkg2/bar.i new file mode 100644 index 000000000..28a4c906e --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py2/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py2.pkg2") bar +%{ +#include "../../py2/pkg2/bar.hpp" +%} +%import "../../py2/pkg2/pkg3/foo.i" +%include "../../py2/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/Makefile b/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/Makefile new file mode 100644 index 000000000..a417e2745 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/Makefile @@ -0,0 +1,15 @@ +TOP = ../../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + +clean: + $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean diff --git a/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/__init__.py b/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/foo.hpp b/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/foo.hpp new file mode 100644 index 000000000..b6c89a431 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY2_PKG2_PKG3_FOO_HPP +#define PY2_PKG2_PKG3_FOO_HPP +struct Pkg3_Foo {}; +#endif /* PY2_PKG2_PKG3_FOO_HPP */ diff --git a/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/foo.i b/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/foo.i new file mode 100644 index 000000000..ba32483d2 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/foo.i @@ -0,0 +1,5 @@ +%module(package="py2.pkg2.pkg3") foo +%{ +#include "../../../py2/pkg2/pkg3/foo.hpp" +%} +%include "../../../py2/pkg2/pkg3/foo.hpp" diff --git a/Examples/python/import_packages/relativeimport1/py3/Makefile b/Examples/python/import_packages/relativeimport1/py3/Makefile new file mode 100644 index 000000000..4c0dfab07 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py3/Makefile @@ -0,0 +1,14 @@ +TOP = ../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport1/py3/__init__.py b/Examples/python/import_packages/relativeimport1/py3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport1/py3/pkg2/Makefile b/Examples/python/import_packages/relativeimport1/py3/pkg2/Makefile new file mode 100644 index 000000000..3fe56139d --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py3/pkg2/Makefile @@ -0,0 +1,18 @@ +TOP = ../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile TARGET='bar' python_clean + cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport1/py3/pkg2/__init__.py b/Examples/python/import_packages/relativeimport1/py3/pkg2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport1/py3/pkg2/bar.hpp b/Examples/python/import_packages/relativeimport1/py3/pkg2/bar.hpp new file mode 100644 index 000000000..408d910d7 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py3/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY3_PKG2_BAR_HPP +#define PY3_PKG2_BAR_HPP +#include "../../py3/pkg2/pkg3/foo.hpp" +struct Pkg2_Bar : Pkg3_Foo {}; +#endif /* PY3_PKG2_BAR_HPP */ diff --git a/Examples/python/import_packages/relativeimport1/py3/pkg2/bar.i b/Examples/python/import_packages/relativeimport1/py3/pkg2/bar.i new file mode 100644 index 000000000..1468932ff --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py3/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py3.pkg2") bar +%{ +#include "../../py3/pkg2/bar.hpp" +%} +%import "../../py3/pkg2/pkg3/foo.i" +%include "../../py3/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/Makefile b/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/Makefile new file mode 100644 index 000000000..a417e2745 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/Makefile @@ -0,0 +1,15 @@ +TOP = ../../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + +clean: + $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean diff --git a/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/__init__.py b/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/foo.hpp b/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/foo.hpp new file mode 100644 index 000000000..531721d36 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY3_PKG2_PKG3_FOO_HPP +#define PY3_PKG2_PKG3_FOO_HPP +struct Pkg3_Foo {}; +#endif /* PY3_PKG2_PKG3_FOO_HPP */ diff --git a/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/foo.i b/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/foo.i new file mode 100644 index 000000000..c6ba529b7 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/foo.i @@ -0,0 +1,5 @@ +%module(package="py3.pkg2.pkg3") foo +%{ +#include "../../../py3/pkg2/pkg3/foo.hpp" +%} +%include "../../../py3/pkg2/pkg3/foo.hpp" diff --git a/Examples/python/import_packages/relativeimport1/runme.py b/Examples/python/import_packages/relativeimport1/runme.py new file mode 100644 index 000000000..44ce8d1c4 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/runme.py @@ -0,0 +1,9 @@ +# Test import of modules content from within __init__.py +print "Testing %module(package=...) with -relativeimport" +import sys +if sys.version_info < (3,0): + import py2.pkg2.bar + print " Finished importing py2.pkg2.bar" +else: + import py3.pkg2.bar + print " Finished importing py3.pkg2.bar" diff --git a/Examples/python/import_packages/relativeimport2/Makefile b/Examples/python/import_packages/relativeimport2/Makefile new file mode 100644 index 000000000..8e35c6c61 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/Makefile @@ -0,0 +1,25 @@ +TOP = ../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = +PY3 = + +ifeq (,$(PY3)) + PKG1DIR = "py2" +else + PKG1DIR = "py3" +endif + +check: build + $(MAKE) -f $(TOP)/Makefile python_run + +build: + cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build + +static: + cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + cd py2 && $(MAKE) clean + cd py3 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport2/README b/Examples/python/import_packages/relativeimport2/README new file mode 100644 index 000000000..af2d2840b --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/README @@ -0,0 +1,22 @@ +This example tests the %import directive and -relativeimport option. + +Use 'python runme.py' to run a test. + +Overview: +--------- + +The example defines 2 different extension modules--each wrapping a separate C++ +class. + + pyX/pkg2/pkg3/pkg4/foo.i - Pkg4_Foo class + pyX/pkg2/bar.i - Pkg2_Bar class derived from Pkg4_Foo + +The difference between this ('relativeimport2') case and the case +'relativeimport1' is the "distance" between importer and importee. + +If everything works well, the package pyX.pkg2 shall load properly. + +Unix: +----- +- Run make +- Run the test as described above diff --git a/Examples/python/import_packages/relativeimport2/py2/Makefile b/Examples/python/import_packages/relativeimport2/py2/Makefile new file mode 100644 index 000000000..4c0dfab07 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py2/Makefile @@ -0,0 +1,14 @@ +TOP = ../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport2/py2/__init__.py b/Examples/python/import_packages/relativeimport2/py2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/Makefile b/Examples/python/import_packages/relativeimport2/py2/pkg2/Makefile new file mode 100644 index 000000000..3fe56139d --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py2/pkg2/Makefile @@ -0,0 +1,18 @@ +TOP = ../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile TARGET='bar' python_clean + cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/__init__.py b/Examples/python/import_packages/relativeimport2/py2/pkg2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/bar.hpp b/Examples/python/import_packages/relativeimport2/py2/pkg2/bar.hpp new file mode 100644 index 000000000..20a00190a --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py2/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY2_PKG2_HPP +#define PY2_PKG2_HPP +#include "../../py2/pkg2/pkg3/pkg4/foo.hpp" +struct Pkg2_Bar : Pkg4_Foo {}; +#endif /* PY2_PKG2_HPP */ diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/bar.i b/Examples/python/import_packages/relativeimport2/py2/pkg2/bar.i new file mode 100644 index 000000000..0a932a2b9 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py2/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py2.pkg2") bar +%{ +#include "../../py2/pkg2/bar.hpp" +%} +%import "../../py2/pkg2/pkg3/pkg4/foo.i" +%include "../../py2/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/Makefile b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/Makefile new file mode 100644 index 000000000..470f9d561 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/Makefile @@ -0,0 +1,14 @@ +TOP = ../../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + cd pkg4 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg4 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + cd pkg4 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/__init__.py b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/Makefile b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/Makefile new file mode 100644 index 000000000..a98d31122 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/Makefile @@ -0,0 +1,15 @@ +TOP = ../../../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + +clean: + $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/__init__.py b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/foo.hpp b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/foo.hpp new file mode 100644 index 000000000..2df933c59 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY2_PKG2_PKG3_PKG4 +#define PY2_PKG2_PKG3_PKG4 +struct Pkg4_Foo {}; +#endif /* PY2_PKG2_PKG3_PKG4 */ diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/foo.i b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/foo.i new file mode 100644 index 000000000..311d7161c --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/foo.i @@ -0,0 +1,5 @@ +%module(package="py2.pkg2.pkg3.pkg4") foo +%{ +#include "../../../../py2/pkg2/pkg3/pkg4/foo.hpp" +%} +%include "../../../../py2/pkg2/pkg3/pkg4/foo.hpp" diff --git a/Examples/python/import_packages/relativeimport2/py3/Makefile b/Examples/python/import_packages/relativeimport2/py3/Makefile new file mode 100644 index 000000000..4c0dfab07 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py3/Makefile @@ -0,0 +1,14 @@ +TOP = ../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport2/py3/__init__.py b/Examples/python/import_packages/relativeimport2/py3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/Makefile b/Examples/python/import_packages/relativeimport2/py3/pkg2/Makefile new file mode 100644 index 000000000..3fe56139d --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py3/pkg2/Makefile @@ -0,0 +1,18 @@ +TOP = ../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile TARGET='bar' python_clean + cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/__init__.py b/Examples/python/import_packages/relativeimport2/py3/pkg2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/bar.hpp b/Examples/python/import_packages/relativeimport2/py3/pkg2/bar.hpp new file mode 100644 index 000000000..16fdd362e --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py3/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY3_PKG2_HPP +#define PY3_PKG2_HPP +#include "../../py3/pkg2/pkg3/pkg4/foo.hpp" +struct Pkg2_Bar : Pkg4_Foo {}; +#endif /* PY3_PKG2_HPP */ diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/bar.i b/Examples/python/import_packages/relativeimport2/py3/pkg2/bar.i new file mode 100644 index 000000000..3abbb05d3 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py3/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py3.pkg2") bar +%{ +#include "../../py3/pkg2/bar.hpp" +%} +%import "../../py3/pkg2/pkg3/pkg4/foo.i" +%include "../../py3/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/Makefile b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/Makefile new file mode 100644 index 000000000..470f9d561 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/Makefile @@ -0,0 +1,14 @@ +TOP = ../../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + cd pkg4 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg4 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + cd pkg4 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/__init__.py b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/Makefile b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/Makefile new file mode 100644 index 000000000..a98d31122 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/Makefile @@ -0,0 +1,15 @@ +TOP = ../../../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + +clean: + $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/__init__.py b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/foo.hpp b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/foo.hpp new file mode 100644 index 000000000..e24654c28 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY3_PKG2_PKG3_PKG4 +#define PY3_PKG2_PKG3_PKG4 +struct Pkg4_Foo {}; +#endif /* PY3_PKG2_PKG3_PKG4 */ diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/foo.i b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/foo.i new file mode 100644 index 000000000..36c5f01ea --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/foo.i @@ -0,0 +1,5 @@ +%module(package="py3.pkg2.pkg3.pkg4") foo +%{ +#include "../../../../py3/pkg2/pkg3/pkg4/foo.hpp" +%} +%include "../../../../py3/pkg2/pkg3/pkg4/foo.hpp" diff --git a/Examples/python/import_packages/relativeimport2/runme.py b/Examples/python/import_packages/relativeimport2/runme.py new file mode 100644 index 000000000..ac60eb630 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/runme.py @@ -0,0 +1,9 @@ +# Test import of modules content from within __init__.py +print "Testing %module(package=...) + python 'import' in __init__.py" +import sys +if sys.version_info < (3,0): + import py2.pkg2.bar + print " Finished importing py2.pkg2.bar" +else: + import py3.pkg2.bar + print " Finished importing py3.pkg2.bar" diff --git a/Examples/python/import_packages/relativeimport2/runme3.py b/Examples/python/import_packages/relativeimport2/runme3.py new file mode 100644 index 000000000..4b0d112cf --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/runme3.py @@ -0,0 +1,9 @@ +# Test import of modules content from within __init__.py +print("Testing %module(package=...) + python 'import' in __init__.py") +import sys +if sys.version_info < (3, 0): + import py2.pkg2.bar + print(" Finished importing py2.pkg2.bar") +else: + import py3.pkg2.bar + print(" Finished importing py3.pkg2.bar") diff --git a/Examples/python/import_packages/same_modnames1/Makefile b/Examples/python/import_packages/same_modnames1/Makefile new file mode 100644 index 000000000..9dd5971dc --- /dev/null +++ b/Examples/python/import_packages/same_modnames1/Makefile @@ -0,0 +1,20 @@ +TOP = ../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +check: build + $(MAKE) -f $(TOP)/Makefile python_run + +build: + cd pkg1 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg1 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + cd pkg1 && $(MAKE) clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/same_modnames1/README b/Examples/python/import_packages/same_modnames1/README new file mode 100644 index 000000000..ee3f8d6f7 --- /dev/null +++ b/Examples/python/import_packages/same_modnames1/README @@ -0,0 +1,26 @@ +This example tests the %import directive and working with multiple modules. + +There are two modules having same name but belonging to different packages. +This case is not correctly handled by swig 2. + +The issue was reported as Source Forge bug #1297 and later as GitHub issue #7. + +Use 'python runme.py' to run a test. + +Overview: +--------- + +The example defines 2 different extension modules--each wrapping a separate C++ +class. + + pkg1/foo.i - Pkg1_Foo class. + pkg2/foo.i - Pkg2_Foo class (derived from Pkg1_Foo). + +The pkg2/foo.i module uses %import to refer to pkg1/foo.i. + +If everything works well, the module pkg2.foo shall load properly. + +Unix: +----- +- Run make +- Run the test as described above. diff --git a/Examples/python/import_packages/same_modnames1/pkg1/Makefile b/Examples/python/import_packages/same_modnames1/pkg1/Makefile new file mode 100644 index 000000000..9b51a76ed --- /dev/null +++ b/Examples/python/import_packages/same_modnames1/pkg1/Makefile @@ -0,0 +1,15 @@ +TOP = ../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + +clean: + $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean diff --git a/Examples/python/import_packages/same_modnames1/pkg1/__init__.py b/Examples/python/import_packages/same_modnames1/pkg1/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/same_modnames1/pkg1/foo.hpp b/Examples/python/import_packages/same_modnames1/pkg1/foo.hpp new file mode 100644 index 000000000..b07c983b3 --- /dev/null +++ b/Examples/python/import_packages/same_modnames1/pkg1/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PKG1_FOO_HPP +#define PKG1_FOO_HPP +struct Pkg1_Foo{}; +#endif /* PKG1_FOO_HPP */ diff --git a/Examples/python/import_packages/same_modnames1/pkg1/foo.i b/Examples/python/import_packages/same_modnames1/pkg1/foo.i new file mode 100644 index 000000000..9939f420a --- /dev/null +++ b/Examples/python/import_packages/same_modnames1/pkg1/foo.i @@ -0,0 +1,5 @@ +%module(package="pkg1") foo +%{ +#include "../pkg1/foo.hpp" +%} +%include "../pkg1/foo.hpp" diff --git a/Examples/python/import_packages/same_modnames1/pkg2/Makefile b/Examples/python/import_packages/same_modnames1/pkg2/Makefile new file mode 100644 index 000000000..9b51a76ed --- /dev/null +++ b/Examples/python/import_packages/same_modnames1/pkg2/Makefile @@ -0,0 +1,15 @@ +TOP = ../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + +clean: + $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean diff --git a/Examples/python/import_packages/same_modnames1/pkg2/__init__.py b/Examples/python/import_packages/same_modnames1/pkg2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/same_modnames1/pkg2/foo.hpp b/Examples/python/import_packages/same_modnames1/pkg2/foo.hpp new file mode 100644 index 000000000..72563a9d0 --- /dev/null +++ b/Examples/python/import_packages/same_modnames1/pkg2/foo.hpp @@ -0,0 +1,5 @@ +#ifndef PKG2_FOO_HPP +#define PKG2_FOO_HPP +#include "../pkg1/foo.hpp" +struct Pkg2_Foo : public Pkg1_Foo{}; +#endif /* PKG2_FOO_HPP */ diff --git a/Examples/python/import_packages/same_modnames1/pkg2/foo.i b/Examples/python/import_packages/same_modnames1/pkg2/foo.i new file mode 100644 index 000000000..3a1ce0198 --- /dev/null +++ b/Examples/python/import_packages/same_modnames1/pkg2/foo.i @@ -0,0 +1,6 @@ +%module(package="pkg2") foo +%{ +#include "../pkg2/foo.hpp" +%} +%import "../pkg1/foo.i" +%include "../pkg2/foo.hpp" diff --git a/Examples/python/import_packages/same_modnames1/runme.py b/Examples/python/import_packages/same_modnames1/runme.py new file mode 100644 index 000000000..9cdb95caf --- /dev/null +++ b/Examples/python/import_packages/same_modnames1/runme.py @@ -0,0 +1,7 @@ +# Test import of same modules from different packages +print "Testing %module(package=...) + %import + same modules in different packages" +import pkg2.foo +print " Finished importing pkg2.foo" + +var2 = pkg2.foo.Pkg2_Foo() +print " Successfully created object pkg2.foo.Pkg2_Foo" diff --git a/Examples/python/import_packages/same_modnames2/Makefile b/Examples/python/import_packages/same_modnames2/Makefile new file mode 100644 index 000000000..cfc327883 --- /dev/null +++ b/Examples/python/import_packages/same_modnames2/Makefile @@ -0,0 +1,20 @@ +TOP = ../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +check: build + $(MAKE) -f $(TOP)/Makefile python_run + +build: + cd pkg1 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg1/pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg1 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg1/pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile python_clean + cd pkg1 && $(MAKE) clean + cd pkg1/pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/same_modnames2/README b/Examples/python/import_packages/same_modnames2/README new file mode 100644 index 000000000..9b0233f8b --- /dev/null +++ b/Examples/python/import_packages/same_modnames2/README @@ -0,0 +1,26 @@ +This example tests the %import directive and working with multiple modules. + +There are two modules having same name but belonging to different packages. +This case is not correctly handled by swig 2. + +The issue was reported as Source Forge bug #1297 and later as GitHub issue #7. + +Use 'python runme.py' to run a test. + +Overview: +--------- + +The example defines 2 different extension modules--each wrapping a separate C++ +class. + + pkg1/foo.i - Pkg1_Foo class + pkg1/pkg2/foo.i - Pkg2_Foo class derived from Pkg1_Foo + +The pkg1/pkg2/foo module uses %import to refer to pkg1/foo. + +If everything works well, the module pkg1.pkg2.foo shall load properly. + +Unix: +----- +- Run make +- Run the test as described above diff --git a/Examples/python/import_packages/same_modnames2/pkg1/Makefile b/Examples/python/import_packages/same_modnames2/pkg1/Makefile new file mode 100644 index 000000000..9b51a76ed --- /dev/null +++ b/Examples/python/import_packages/same_modnames2/pkg1/Makefile @@ -0,0 +1,15 @@ +TOP = ../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + +clean: + $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean diff --git a/Examples/python/import_packages/same_modnames2/pkg1/__init__.py b/Examples/python/import_packages/same_modnames2/pkg1/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/same_modnames2/pkg1/foo.hpp b/Examples/python/import_packages/same_modnames2/pkg1/foo.hpp new file mode 100644 index 000000000..b07c983b3 --- /dev/null +++ b/Examples/python/import_packages/same_modnames2/pkg1/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PKG1_FOO_HPP +#define PKG1_FOO_HPP +struct Pkg1_Foo{}; +#endif /* PKG1_FOO_HPP */ diff --git a/Examples/python/import_packages/same_modnames2/pkg1/foo.i b/Examples/python/import_packages/same_modnames2/pkg1/foo.i new file mode 100644 index 000000000..9939f420a --- /dev/null +++ b/Examples/python/import_packages/same_modnames2/pkg1/foo.i @@ -0,0 +1,5 @@ +%module(package="pkg1") foo +%{ +#include "../pkg1/foo.hpp" +%} +%include "../pkg1/foo.hpp" diff --git a/Examples/python/import_packages/same_modnames2/pkg1/pkg2/Makefile b/Examples/python/import_packages/same_modnames2/pkg1/pkg2/Makefile new file mode 100644 index 000000000..053b911f5 --- /dev/null +++ b/Examples/python/import_packages/same_modnames2/pkg1/pkg2/Makefile @@ -0,0 +1,15 @@ +TOP = ../../../../.. +SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + +static: + $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + +clean: + $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean diff --git a/Examples/python/import_packages/same_modnames2/pkg1/pkg2/__init__.py b/Examples/python/import_packages/same_modnames2/pkg1/pkg2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/same_modnames2/pkg1/pkg2/foo.hpp b/Examples/python/import_packages/same_modnames2/pkg1/pkg2/foo.hpp new file mode 100644 index 000000000..1b4a1d558 --- /dev/null +++ b/Examples/python/import_packages/same_modnames2/pkg1/pkg2/foo.hpp @@ -0,0 +1,5 @@ +#ifndef PKG1_PKG2_FOO_HPP +#define PKG1_PKG2_FOO_HPP +#include "../../pkg1/foo.hpp" +struct Pkg2_Foo : public Pkg1_Foo{}; +#endif /* PKG1_PKG2_FOO_HPP */ diff --git a/Examples/python/import_packages/same_modnames2/pkg1/pkg2/foo.i b/Examples/python/import_packages/same_modnames2/pkg1/pkg2/foo.i new file mode 100644 index 000000000..1741b3799 --- /dev/null +++ b/Examples/python/import_packages/same_modnames2/pkg1/pkg2/foo.i @@ -0,0 +1,6 @@ +%module(package="pkg1.pkg2") foo +%{ +#include "../../pkg1/pkg2/foo.hpp" +%} +%import "../../pkg1/foo.i" +%include "../../pkg1/pkg2/foo.hpp" diff --git a/Examples/python/import_packages/same_modnames2/runme.py b/Examples/python/import_packages/same_modnames2/runme.py new file mode 100644 index 000000000..bde4305c4 --- /dev/null +++ b/Examples/python/import_packages/same_modnames2/runme.py @@ -0,0 +1,4 @@ +import pkg1.pkg2.foo +print " Finished importing pkg1.pkg2.foo" +var2 = pkg1.pkg2.foo.Pkg2_Foo(); +print " Successfully created object pkg1.pkg2.foo.Pkg2_Foo" diff --git a/Source/Modules/python.cxx b/Source/Modules/python.cxx index e281bbbec..6f5446fa8 100644 --- a/Source/Modules/python.cxx +++ b/Source/Modules/python.cxx @@ -94,6 +94,7 @@ static int castmode = 0; static int extranative = 0; static int outputtuple = 0; static int nortti = 0; +static int relativeimport = 0; /* flags for the make_autodoc function */ enum autodoc_t { @@ -156,6 +157,7 @@ static const char *usage3 = (char *) "\ -oldrepr - Use shorter and old version of __repr__ in proxy classes\n\ -outputtuple - Use a PyTuple for outputs instead of a PyList (use carefully with legacy interfaces) \n\ -proxydel - Generate a __del__ method even though it is now redundant (default) \n\ + -relativeimport - Use relative python imports \n\ -safecstrings - Use safer (but slower) C string mapping, generating copies from Python -> C/C++\n\ -threads - Add thread support for all the interface\n\ -O - Enable the following optimization options: \n\ @@ -520,6 +522,9 @@ public: builtin = 1; Preprocessor_define("SWIGPYTHON_BUILTIN", 0); Swig_mark_arg(i); + } else if (strcmp(argv[i], "-relativeimport") == 0) { + relativeimport = 1; + Swig_mark_arg(i); } } @@ -1028,6 +1033,284 @@ public: return 0; } + /* ------------------------------------------------------------ + * tail = subpkg_tail(base, other) + * + * Return the name of 'other' package relative to 'base'. + * + * 1. If 'other' is a sub-package of 'base', returns the 'other' relative to + * 'base'. + * 2. If 'other' and 'base' are equal, returns empty string "". + * 3. In any other case, NULL pointer is returned. + * + * The 'base' and 'other' are expected to be fully qualified names. + * + * NOTE: none of 'base' nor 'other' can be null. + * + * Examples: + * + * # base other tail + * -- ---- ----- ---- + * 1 "Foo" "Foo.Bar" -> "Bar" + * 2 "Foo" "Foo." -> "" + * 3 "Foo" "FooB.ar" -> NULL + * 4 "Foo.Bar" "Foo.Bar" -> "" + * 5 "Foo.Bar" "Foo" -> NULL + * 6 "Foo.Bar" "Foo.Gez" -> NULL + * + * NOTE: the example #2 is actually a syntax error (at input). I believe + * swig parser prevents us from this case happening here. + * ------------------------------------------------------------ */ + static String* subpkg_tail(const String* base, const String* other) + { + int baselen = Len(base); + int otherlen = Len(other); + + if (Strncmp(other, base, baselen) == 0) { + if ((baselen < otherlen) && (Char(other))[baselen] == '.') { + return NewString((Char(other)) + baselen + 1); + } else if (baselen == otherlen) { + return NewString(""); + } else { + return 0; + } + } else { + return 0; + } + } + + /* ------------------------------------------------------------ + * out = abs_import_directive_string(pkg, mod, pfx) + * + * Return a String* containing python code to import module. + * + * pkg package name or the module being imported + * mod module name of the module being imported + * pfx optional prefix to module name + * + * NOTE: keep this function consistent with abs_import_name_string(). + * ------------------------------------------------------------ */ + static String* abs_import_directive_string(const String* pkg, + const String* mod, + const char* pfx = "") + { + String* out = NewString(""); + + if (pkg && *Char(pkg)) { + Printf(out, "import %s.%s%s\n", pkg, pfx, mod); + } else { + Printf(out, "import %s%s\n", pfx, mod); + } + return out; + } + + /* ------------------------------------------------------------ + * out = rel_import_directive_string(mainpkg, pkg, mod, pfx) + * + * Return a String* containing python code to import module that + * is potentially within a package. + * + * mainpkg package name of the module which imports the other module + * pkg package name or the module being imported + * mod module name of the module being imported + * pfx optional prefix to module name + * + * NOTE: keep this function consistent with rel_import_name_string(). + * ------------------------------------------------------------ */ + static String* rel_import_directive_string(const String* mainpkg, + const String* pkg, + const String* mod, + const char* pfx = "") + { + /* NOTE: things are not so trivial. This is what we do here (by examples): + * + * 0. To import module 'foo', which is not in any package, we do absolute + * import: + * + * import foo + * + * 1. To import 'pkg1.pkg2.foo', when mainpkg != "pkg1" and + * mainpkg != "pkg1.pkg2" or when mainpkg is not given we do absolute + * import: + * + * import pkg1.pkg2.foo + * + * 2. To import module pkg1.foo, when mainpkg == "pkg1", we do: + * + * - for py3 = 0: + * + * import foo + * + * - for py3 = 1: + * + * from . import foo + * + * 3. To import "pkg1.pkg2.pkg3.foo", when mainpkg = "pkg1", we do: + * + * - for py3 == 0: + * + * import pkg2.pkg3.foo + * + * - for py3 == 1: + * + * from . import pkg2 # [1] + * import pkg1.pkg2.pkg3.foo + * + * NOTE: [1] is necessary for pkg2.foo to be present in the importing module + */ + String* apkg = 0; // absolute (FQDN) package name of pkg + String* rpkg = 0; // relative package name + int py3_rlen1 = 0; // length of 1st level sub-package name, used by py3 + String* out = NewString(""); + + if (pkg && *Char(pkg)) { + if(mainpkg) { + String* tail = subpkg_tail(mainpkg, pkg); + if (tail) { + if(*Char(tail)) { + rpkg = NewString(tail); + const char* py3_end1 = Strchr(rpkg, '.'); + if(!py3_end1) py3_end1 = (Char(rpkg)) + Len(rpkg); + py3_rlen1 = py3_end1 - (Char(rpkg)); + } else { + rpkg = NewString(""); + } + Delete(tail); + } else { + apkg = NewString(pkg); + } + } else { + apkg = NewString(pkg); + } + } else { + apkg = NewString(""); + } + + if (apkg) { + Printf(out, "import %s%s%s%s\n", apkg, *Char(apkg) ? "." : "", pfx, mod); + Delete(apkg); + } else { + if (py3) { + if (py3_rlen1) + Printf(out, "from . import %.*s\n", py3_rlen1, rpkg); + Printf(out, "from .%s import %s%s\n", rpkg, pfx, mod); + } else { + Printf(out, "import %s%s%s%s\n", rpkg, *Char(rpkg) ? "." : "", pfx, mod); + } + Delete(rpkg); + } + return out; + } + + /* ------------------------------------------------------------ + * out = import_directive_string(mainpkg, pkg, mod, pfx) + * ------------------------------------------------------------ */ + static String* import_directive_string(const String* mainpkg, + const String* pkg, + const String* mod, + const char* pfx = "") + { + if (!relativeimport) { + return abs_import_directive_string(pkg, mod, pfx); + } else { + return rel_import_directive_string(mainpkg, pkg, mod, pfx); + } + } + + /* ------------------------------------------------------------ + * out = abs_import_name_string(mainpkg, mainmod, pkg, mod, sym) + * + * Return a String* with the name of a symbol (perhaps imported + * from external module by absolute import directive). + * + * mainpkg package name of current module + * mainmod module name of current module + * pkg package name of (perhaps other) module + * mod module name of (perhaps other) module + * sym symbol name + * + * NOTE: mainmod, mod, and sym can't be NULL. + * NOTE: keep this function consistent with abs_import_directive_string() + * ------------------------------------------------------------ */ + static String* abs_import_name_string(const String* mainpkg, + const String* mainmod, + const String* pkg, + const String* mod, + const String* sym) + { + String* out = NewString(""); + if (pkg && *Char(pkg)) { + if (mainpkg && *Char(mainpkg)) { + if (Strcmp(mainpkg,pkg) != 0 || Strcmp(mainmod, mod) != 0) { + Printf(out, "%s.%s.", pkg, mod); + } + } else { + Printf(out, "%s.%s.", pkg, mod); + } + } else if ((mainpkg && *Char(mainpkg)) || Strcmp(mainmod, mod) != 0) { + Printf(out, "%s.", mod); + } + Append(out, sym); + return out; + } + + /* ------------------------------------------------------------ + * out = rel_import_name_string(mainpkg, mainmod, pkg, mod, sym) + * + * Return a String* with the name of a symbol (perhaps imported + * from external module by relative import directive). + * + * mainpkg package name of current module + * mainmod module name of current module + * pkg package name of (perhaps other) module + * mod module name of (perhaps other) module + * sym symbol name + * + * NOTE: mainmod, mod, and sym can't be NULL. + * NOTE: keep this function consistent with rel_import_directive_string() + * ------------------------------------------------------------ */ + static String* rel_import_name_string(const String* mainpkg, + const String* mainmod, + const String* pkg, + const String* mod, + const String* sym) + { + String* out = NewString(""); + if (pkg && *Char(pkg)) { + String* tail = 0; + if (mainpkg) + tail = subpkg_tail(mainpkg, pkg); + if (!tail) + tail = NewString(pkg); + if(*Char(tail)) { + Printf(out, "%s.%s.", tail, mod); + } else if (Strcmp(mainmod, mod) != 0) { + Printf(out, "%s.", mod); + } + Delete(tail); + } else if ((mainpkg && *Char(mainpkg)) || Strcmp(mainmod, mod) != 0) { + Printf(out, "%s.", mod); + } + Append(out, sym); + return out; + } + + /* ------------------------------------------------------------ + * out = import_name_string(mainpkg, mainmod, pkg, mod, sym) + * ------------------------------------------------------------ */ + static String* import_name_string(const String* mainpkg, + const String* mainmod, + const String* pkg, + const String* mod, + const String* sym) + { + if (!relativeimport) { + return abs_import_name_string(mainpkg,mainmod,pkg,mod,sym); + } else { + return rel_import_name_string(mainpkg,mainmod,pkg,mod,sym); + } + } + /* ------------------------------------------------------------ * importDirective() * ------------------------------------------------------------ */ @@ -1037,38 +1320,26 @@ public: String *modname = Getattr(n, "module"); if (modname) { - String *import = NewString("import "); - // 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); - // Is the imported module in another package? (IOW, does it use the - // %module(package="name") option and it's different than the package - // of this module.) Node *options = Getattr(mod, "options"); String *pkg = options ? Getattr(options, "package") : 0; - if (pkg) { - Printf(import, "%s.", pkg); - } - // finally, output the name of the imported module if (shadowimport) { if (!options || (!Getattr(options, "noshadow") && !Getattr(options, "noproxy"))) { - Printf(import, "_%s\n", modname); - if (!GetFlagAttr(f_shadow_imports, import)) { - if (pkg) { - Printf(builtin ? f_shadow_builtin_imports : f_shadow, "import %s.%s\n", pkg, modname); - } else { - Printf(builtin ? f_shadow_builtin_imports : f_shadow, "import %s\n", modname); - } - SetFlag(f_shadow_imports, import); + String* _import = import_directive_string(package, pkg, modname, "_"); + if (!GetFlagAttr(f_shadow_imports, _import)) { + String* import = import_directive_string(package, pkg, modname); + Printf(builtin ? f_shadow_builtin_imports : f_shadow, "%s", import); + Delete(import); + SetFlag(f_shadow_imports, _import); } + Delete(_import); } } - - Delete(import); } } return Language::importDirective(n); @@ -3164,19 +3435,13 @@ public: if (shadow && !Getattr(n, "feature:onlychildren")) { Node *mod = Getattr(n, "module"); if (mod) { - String *importname = NewString(""); String *modname = Getattr(mod, "name"); - if (Strcmp(modname, mainmodule) != 0) { - // check if the module has a package option - Node *options = Getattr(mod, "options"); - String *pkg = options ? Getattr(options, "package") : 0; - if (pkg) { - Printf(importname, "%s.", pkg); - } - Printf(importname, "%s.", modname); - } - Append(importname, Getattr(n, "sym:name")); + Node *options = Getattr(mod, "options"); + String* pkg = options ? Getattr(options, "package") : 0; + String* sym = Getattr(n, "sym:name"); + String* importname = import_name_string(package, mainmodule, pkg, modname, sym); Setattr(n, "python:proxy", importname); + Delete(importname); } } int result = Language::classDeclaration(n); From 44dd28950ca5c45ee0cb950f05da60ac3879730d Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 24 Dec 2013 11:31:54 +0000 Subject: [PATCH 271/481] Python import code beautify --- Source/Modules/python.cxx | 137 +++++++++++++++++--------------------- 1 file changed, 60 insertions(+), 77 deletions(-) diff --git a/Source/Modules/python.cxx b/Source/Modules/python.cxx index 6f5446fa8..039623e62 100644 --- a/Source/Modules/python.cxx +++ b/Source/Modules/python.cxx @@ -1034,7 +1034,7 @@ public: } /* ------------------------------------------------------------ - * tail = subpkg_tail(base, other) + * subpkg_tail() * * Return the name of 'other' package relative to 'base'. * @@ -1049,8 +1049,8 @@ public: * * Examples: * - * # base other tail - * -- ---- ----- ---- + * # base other tail + * -- ---- ----- ---- * 1 "Foo" "Foo.Bar" -> "Bar" * 2 "Foo" "Foo." -> "" * 3 "Foo" "FooB.ar" -> NULL @@ -1061,8 +1061,8 @@ public: * NOTE: the example #2 is actually a syntax error (at input). I believe * swig parser prevents us from this case happening here. * ------------------------------------------------------------ */ - static String* subpkg_tail(const String* base, const String* other) - { + + static String *subpkg_tail(const String *base, const String *other) { int baselen = Len(base); int otherlen = Len(other); @@ -1080,9 +1080,9 @@ public: } /* ------------------------------------------------------------ - * out = abs_import_directive_string(pkg, mod, pfx) + * abs_import_directive_string() * - * Return a String* containing python code to import module. + * Return a string containing python code to import module. * * pkg package name or the module being imported * mod module name of the module being imported @@ -1090,11 +1090,9 @@ public: * * NOTE: keep this function consistent with abs_import_name_string(). * ------------------------------------------------------------ */ - static String* abs_import_directive_string(const String* pkg, - const String* mod, - const char* pfx = "") - { - String* out = NewString(""); + + static String *abs_import_directive_string(const String *pkg, const String *mod, const char *pfx = "") { + String *out = NewString(""); if (pkg && *Char(pkg)) { Printf(out, "import %s.%s%s\n", pkg, pfx, mod); @@ -1105,9 +1103,9 @@ public: } /* ------------------------------------------------------------ - * out = rel_import_directive_string(mainpkg, pkg, mod, pfx) + * rel_import_directive_string() * - * Return a String* containing python code to import module that + * Return a string containing python code to import module that * is potentially within a package. * * mainpkg package name of the module which imports the other module @@ -1117,11 +1115,9 @@ public: * * NOTE: keep this function consistent with rel_import_name_string(). * ------------------------------------------------------------ */ - static String* rel_import_directive_string(const String* mainpkg, - const String* pkg, - const String* mod, - const char* pfx = "") - { + + static String *rel_import_directive_string(const String *mainpkg, const String *pkg, const String *mod, const char *pfx = "") { + /* NOTE: things are not so trivial. This is what we do here (by examples): * * 0. To import module 'foo', which is not in any package, we do absolute @@ -1158,29 +1154,31 @@ public: * * NOTE: [1] is necessary for pkg2.foo to be present in the importing module */ - String* apkg = 0; // absolute (FQDN) package name of pkg - String* rpkg = 0; // relative package name + + String *apkg = 0; // absolute (FQDN) package name of pkg + String *rpkg = 0; // relative package name int py3_rlen1 = 0; // length of 1st level sub-package name, used by py3 - String* out = NewString(""); + String *out = NewString(""); if (pkg && *Char(pkg)) { - if(mainpkg) { - String* tail = subpkg_tail(mainpkg, pkg); - if (tail) { - if(*Char(tail)) { - rpkg = NewString(tail); - const char* py3_end1 = Strchr(rpkg, '.'); - if(!py3_end1) py3_end1 = (Char(rpkg)) + Len(rpkg); - py3_rlen1 = py3_end1 - (Char(rpkg)); - } else { - rpkg = NewString(""); - } - Delete(tail); - } else { - apkg = NewString(pkg); - } + if (mainpkg) { + String *tail = subpkg_tail(mainpkg, pkg); + if (tail) { + if (*Char(tail)) { + rpkg = NewString(tail); + const char *py3_end1 = Strchr(rpkg, '.'); + if (!py3_end1) + py3_end1 = (Char(rpkg)) + Len(rpkg); + py3_rlen1 = py3_end1 - (Char(rpkg)); + } else { + rpkg = NewString(""); + } + Delete(tail); + } else { + apkg = NewString(pkg); + } } else { - apkg = NewString(pkg); + apkg = NewString(pkg); } } else { apkg = NewString(""); @@ -1192,7 +1190,7 @@ public: } else { if (py3) { if (py3_rlen1) - Printf(out, "from . import %.*s\n", py3_rlen1, rpkg); + Printf(out, "from . import %.*s\n", py3_rlen1, rpkg); Printf(out, "from .%s import %s%s\n", rpkg, pfx, mod); } else { Printf(out, "import %s%s%s%s\n", rpkg, *Char(rpkg) ? "." : "", pfx, mod); @@ -1203,13 +1201,10 @@ public: } /* ------------------------------------------------------------ - * out = import_directive_string(mainpkg, pkg, mod, pfx) + * import_directive_string() * ------------------------------------------------------------ */ - static String* import_directive_string(const String* mainpkg, - const String* pkg, - const String* mod, - const char* pfx = "") - { + + static String *import_directive_string(const String *mainpkg, const String *pkg, const String *mod, const char *pfx = "") { if (!relativeimport) { return abs_import_directive_string(pkg, mod, pfx); } else { @@ -1218,9 +1213,9 @@ public: } /* ------------------------------------------------------------ - * out = abs_import_name_string(mainpkg, mainmod, pkg, mod, sym) + * abs_import_name_string() * - * Return a String* with the name of a symbol (perhaps imported + * Return a string with the name of a symbol (perhaps imported * from external module by absolute import directive). * * mainpkg package name of current module @@ -1232,13 +1227,9 @@ public: * NOTE: mainmod, mod, and sym can't be NULL. * NOTE: keep this function consistent with abs_import_directive_string() * ------------------------------------------------------------ */ - static String* abs_import_name_string(const String* mainpkg, - const String* mainmod, - const String* pkg, - const String* mod, - const String* sym) - { - String* out = NewString(""); + + static String *abs_import_name_string(const String *mainpkg, const String *mainmod, const String *pkg, const String *mod, const String *sym) { + String *out = NewString(""); if (pkg && *Char(pkg)) { if (mainpkg && *Char(mainpkg)) { if (Strcmp(mainpkg,pkg) != 0 || Strcmp(mainmod, mod) != 0) { @@ -1255,9 +1246,9 @@ public: } /* ------------------------------------------------------------ - * out = rel_import_name_string(mainpkg, mainmod, pkg, mod, sym) + * rel_import_name_string() * - * Return a String* with the name of a symbol (perhaps imported + * Return a string with the name of a symbol (perhaps imported * from external module by relative import directive). * * mainpkg package name of current module @@ -1269,20 +1260,16 @@ public: * NOTE: mainmod, mod, and sym can't be NULL. * NOTE: keep this function consistent with rel_import_directive_string() * ------------------------------------------------------------ */ - static String* rel_import_name_string(const String* mainpkg, - const String* mainmod, - const String* pkg, - const String* mod, - const String* sym) - { - String* out = NewString(""); + + static String *rel_import_name_string(const String *mainpkg, const String *mainmod, const String *pkg, const String *mod, const String *sym) { + String *out = NewString(""); if (pkg && *Char(pkg)) { - String* tail = 0; + String *tail = 0; if (mainpkg) tail = subpkg_tail(mainpkg, pkg); if (!tail) tail = NewString(pkg); - if(*Char(tail)) { + if (*Char(tail)) { Printf(out, "%s.%s.", tail, mod); } else if (Strcmp(mainmod, mod) != 0) { Printf(out, "%s.", mod); @@ -1296,14 +1283,10 @@ public: } /* ------------------------------------------------------------ - * out = import_name_string(mainpkg, mainmod, pkg, mod, sym) + * import_name_string() * ------------------------------------------------------------ */ - static String* import_name_string(const String* mainpkg, - const String* mainmod, - const String* pkg, - const String* mod, - const String* sym) - { + + static String *import_name_string(const String *mainpkg, const String *mainmod, const String *pkg, const String *mod, const String *sym) { if (!relativeimport) { return abs_import_name_string(mainpkg,mainmod,pkg,mod,sym); } else { @@ -1330,9 +1313,9 @@ public: String *pkg = options ? Getattr(options, "package") : 0; if (shadowimport) { if (!options || (!Getattr(options, "noshadow") && !Getattr(options, "noproxy"))) { - String* _import = import_directive_string(package, pkg, modname, "_"); + String *_import = import_directive_string(package, pkg, modname, "_"); if (!GetFlagAttr(f_shadow_imports, _import)) { - String* import = import_directive_string(package, pkg, modname); + String *import = import_directive_string(package, pkg, modname); Printf(builtin ? f_shadow_builtin_imports : f_shadow, "%s", import); Delete(import); SetFlag(f_shadow_imports, _import); @@ -3437,9 +3420,9 @@ public: if (mod) { String *modname = Getattr(mod, "name"); Node *options = Getattr(mod, "options"); - String* pkg = options ? Getattr(options, "package") : 0; - String* sym = Getattr(n, "sym:name"); - String* importname = import_name_string(package, mainmodule, pkg, modname, sym); + String *pkg = options ? Getattr(options, "package") : 0; + String *sym = Getattr(n, "sym:name"); + String *importname = import_name_string(package, mainmodule, pkg, modname, sym); Setattr(n, "python:proxy", importname); Delete(importname); } From f53bd5a1e18da855a4960eb019644cdcf3f0e393 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Tomulik?= Date: Sat, 23 Nov 2013 20:08:09 +0100 Subject: [PATCH 272/481] Documentation for improved python import option Docs for SFbug1297 patch (PR #7) closes #111 --- Doc/Manual/Python.html | 375 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 370 insertions(+), 5 deletions(-) diff --git a/Doc/Manual/Python.html b/Doc/Manual/Python.html index 6a22738bc..2a719ca7a 100644 --- a/Doc/Manual/Python.html +++ b/Doc/Manual/Python.html @@ -105,6 +105,12 @@

  • %feature("docstring")
  • Python Packages +
  • Python 3 Support
    • Function annotation @@ -5273,11 +5279,66 @@ with more than one line.

      34.11 Python Packages

      +

      Python has concepts of modules and packages. Modules are separate units of +code and may be grouped together to form a package. Packages may be nested, +that is they may contain subpackages. This leads to tree-like hierarchy, with +packages as intermediate nodes and modules as leaf nodes.

      + +

      The hierarchy of python packages/modules follows the hierarchy of +*.py files found in source tree (or, more generally, in python path). +Normally, the developer creates new module by placing a *.py file +somewhere under python path; the module is then named after that *.py +file. A package is created by placing __init__.py file within a +directory; the package is then named after that directory. For example, the +following source tree:

      + +
      +
      +mod1.py
      +pkg1/__init__.py
      +pkg1/mod2.py
      +pkg1/pkg2/__init__.py
      +pkg1/pkg2/mod3.py
      +
      +

      -Using the package option of the %module directive -allows you to specify what Python package that the module will be -living in when installed. +defines the following python packages and modules: +

      + +
      +
      +pkg1            # package
      +pkg1.pkg2       # package
      +mod1            # module
      +pkg1.mod2       # module
      +pkg1.pkg2.mod3  # module
      +
      +
      + +

      +The purpose of __init__.py file is two-fold. First, existence of +__init__.py in a directory informs python interpreter that this +directory contains python package. Second, the code of __init__.py is +loaded/executed automatically when the package is initialized (when it or its +submodule/subpackage gets import'ed). By default, swig generates +proxy python code – one *.py file for each *.i +interface. The __init__.py files, however, are not generated by swig. +They should be created by other means. Both files (module *.py and +__init__.py) should be installed in appropriate destination +directories in order to obtain desirable package/module hierarchy. +

      + +

      The way python defines its modules and packages impacts swig users. Some +users may need to use special features such as package option of +%module directive or import-related command-line options. These are +explained in the following sections.

      + +

      34.11.1 %module(package="...") syntax

      + +

      +Using the package option of the %module directive allows you +to specify a Python package that the module will be living in when installed.

      @@ -5294,10 +5355,314 @@ if they live in separate Python packages then that won't work. However if the importee specifies what its package is with the %module option then the Python code generated for the importer will use that package name when importing the other module -and also in base class declarations, etc. if the package name is -different than its own. +and also in base class declarations, etc..

      +

      Swig assumes, that the package option provided to %module +together with the module name (that is, wx.xrc in the above +example) forms a fully qualified (absolute) name of a module (in Python terms). +This is important especially for Python 3, where absolute imports are used by +default. It's up to you to place the generated module files (.py, +.so) in proper subdirectories. For example, if you have +interface foo.i with: +

      + +
      +
      +%module(package="pkg1.pkg2") foo
      +
      +
      + +

      +then the resultant directory layout should be +

      + +
      +
      +pkg1/
      +pkg1/__init__.py
      +pkg1/pkg2/__init__.py
      +pkg1/pkg2/foo.py        # (generated by swig)
      +pkg1/pkg2/_foo.so       # (shared library from C/C++ code generated by SWIG)
      +
      +
      + +

      34.11.2 Absolute and relative imports

      + +

      Suppose, we have the following hierarchy of files:

      + +
      +
      +pkg1/
      +pkg1/__init__.py
      +pkg1/mod2.py
      +pkg1/pkg2/__init__.py
      +pkg1/pkg2/mod3.py
      +
      +
      + +

      Let the contents of pkg1/pkg2/mod3.py be

      +
      +
      +class M3: pass
      +
      +
      + +

      +We edit pkg1/mod2.py and want to import module of +pkg1/pkg2/pkg3.py in order to derive from class M3. We can +write appropriate python code in several ways, for example: +

      + +
        +
      1. Using "import <>" syntax with absolute package name:

        +
        +
        +# pkg1/mod2.py
        +import pkg1.pkg2.mod3
        +class M2(pkg1.pkg2.mod3.M3): pass
        +
        +
        +
      2. + +
      3. Using "import <>" syntax with package name relative to + pkg1 (only in python 2.7 and earlier):

        +
        +
        +# pkg1/mod2.py
        +import pkg2.mod3
        +class M2(pkg2.mod3.M3): pass
        +
        +
        +
      4. + +
      5. Using "from <> import <>" syntax (relative import + syntax, only in python 2.5 and later):

        +
        +
        +# pkg1/mod2.py
        +from .pkg2 import mod3
        +class M2(mod3.M3): pass
        +
        +
        +
      6. + +
      7. Other variants, for example the following construction in order to + have the pkg2.mod3.M3 symbol available in mod2 as + in point 2 above (but now under python 3):

        +
        +
        +# pkg1/mod2.py
        +from . import pkg2
        +from .pkg2 import mod3
        +class M2(pkg2.mod3.M3): pass
        +
        +
        +
      8. + +
      + +

      Now suppose we have mod2.i with

      + +
      +
      +// mod2.i
      +%module (package="pkg1") mod2
      +%import "mod3.i"
      +// ...
      +
      +
      + +

      and mod3.i with

      + +
      +
      +// mod3.i
      +%module (package="pkg1.pkg2") mod3
      +// ...
      +
      +
      + +

      By default, swig would generate mod2.py proxy file with +import directive as in point 1. This may be changed with +-relativeimport CLI option. The -relativeimport instructs +swig to organize imports as in point 2 (for python 2.x) or as in point 4 (for +python 3, that is when -py3 CLI option is enabled). In short, if you have +mod2.i and mod3.i as above, then without +-relativeimport swig will write

      + +
      +
      +import pkg1.pkg2.mod3
      +
      +
      + +

      to mod2.py proxy file, and with -relativeimport it will +write

      + +
      +
      +import pkg2.mod3
      +
      +
      + +

      if -py3 is not used, or

      + +
      +
      +from . import pkg2
      +import pkg1.pkg2.mod3
      +
      +
      + +

      when -py3 option is used.

      + +

      You should avoid using relative imports and use absolute ones whenever +possible. There are some cases, however, when relative imports may be +necessary. The first example is, when some (legacy) python code refers entities +imported by proxy files generated by swig, and it assumes that the proxy file +uses relative imports. Second case is, when one puts import directives in +__init__.py to import symbols from submodules or subpackages and the +submodule depends on other submodules (discussed later).

      + +

      34.11.3 Enforcing absolute import semantics

      + +

      As you may know, there is incompatibility in import semantics (for the +import <> syntax) between python 2 and 3. In python 2.4 and +earlier it is not clear whether

      + +
      +
      +import foo
      +
      +
      +

      refers to a top-level module or to another module inside the current +package. In python 3 it always refers to a top-level module +(see PEP 328). +To instruct python 2.5 through 2.7 to use new semantics (that is import +foo is interpreted as absolute import), one have to put the following +line +

      + +
      +
      +from __future__ import absolute_import
      +
      +
      + +

      at the very beginning of his proxy *.py file. In swig, it may be +accomplished with %pythonbegin directive.

      + +

      34.11.4 Importing from __init__.py

      + +

      Imports in __init__.py are handy when you want to populate +package's namespace with names imported from other modules. In swig-based +projects this approach may also be used to split large piece of code into +smaller modules, compile them in parallel and then re-assemble all stuff at +python level by importing submodules' contents in __init__.py, for +example.

      + +

      Unfortunately import directives in __init__.py may cause troubles, +especially if they refer to package's submodules. This is caused by the way +python initializes packages. If you spot problems with imports from +__init__.py try using -relativeimport option. Below we +explain in detail one issue, for which the -relativeimport workaround +may be helpful.

      + +

      Consider the following example (python 3):

      + +
      +
      +pkg1/__init__.py        # (empty)
      +pkg1/pkg2/__init__.py   # (imports something from bar.py)
      +pkg1/pkg2/foo.py
      +pkg1/pkg2/bar.py        # (imports foo.py)
      +
      +
      + +

      Let's the files' contents be:

      + +
        +
      • for pkg1/pkg2/__init__.py:

        +
        +
        +# pkg1/pkg2/__init__.py
        +from .bar import Bar
        +
        +
        +
      • + +
      • for pkg1/pkg2/foo.py:

        +
        +
        +# pkg1/pkg2/foo.py
        +class Foo: pass
        +
        +
        +
      • + +
      • for pkg1/pkg2/foo.py:

        +
        +
        +# pkg1/pkg2/bar.py
        +import pkg1.pkg2.foo
        +class Bar(pkg1.pkg2.foo.Foo): pass
        +
        +
        +
      • +
      + +

      Now one would simply do import pkg1.pkg2, but this usually fails:

      + +
      +
      +>>> import pkg1.pkg2
      +Traceback (most recent call last):
      +  File "<stdin>", line 1, in <module>
      +  File "./pkg1/pkg2/__init__.py", line 2, in <module>
      +    from .bar import Bar
      +  File "./pkg1/pkg2/bar.py", line 3, in <module>
      +    class Bar(pkg1.pkg2.foo.Foo): pass
      +AttributeError: 'module' object has no attribute 'pkg2'
      +
      +
      + +

      Surprisingly, if we execute the import pkg1.pkg2 directive for the +second time, it succeeds. The reason seems to be following: when python spots +the from .bar import Bar directive in pkg1/pkg2/__init__.py +it starts loading pkg1/pkg2/bar.py. This module imports +pkg1.pkg2.foo in turn and tries to use pkg1.pkg2.foo.Foo, but +the package pkg1 is not fully initialized yet (the initialization +procedure is actually in progress) and it seems like the effect of already seen +directive import pkg1.pkg2.pkg3.foo is "delayed" or ignored. Exactly +same may happen to a proxy module generated by swig.

      + +

      It's observed, that a possible workaround for this case is to use relative +import in pkg1/pkg2/bar.py. If we change bar.py to be:

      + +
      +
      +from .pkg3 import foo
      +class Bar(foo.Foo): pass
      +
      +
      + +

      or

      + +
      +
      +from . import pkg3
      +from .pkg3 import foo
      +class Bar(pkg3.foo.Foo): pass
      +
      +
      + +

      then the example works again. With swig, you need to enable the +-relativeimport option in order to have the above workaround in +effect (note, that python 2 case also needs -relativeimport +workaround).

      + +

      34.12 Python 3 Support

      From 91120c84f2f3cc12f709d05d9dcc13e60018610c Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 24 Dec 2013 14:39:25 +0000 Subject: [PATCH 273/481] Python imports documentation edits --- Doc/Manual/Python.html | 136 ++++++++++++++++++++--------------------- 1 file changed, 68 insertions(+), 68 deletions(-) diff --git a/Doc/Manual/Python.html b/Doc/Manual/Python.html index 2a719ca7a..c6cc2f40f 100644 --- a/Doc/Manual/Python.html +++ b/Doc/Manual/Python.html @@ -108,7 +108,7 @@
    • Python 3 Support @@ -5284,11 +5284,11 @@ code and may be grouped together to form a package. Packages may be nested, that is they may contain subpackages. This leads to tree-like hierarchy, with packages as intermediate nodes and modules as leaf nodes.

      -

      The hierarchy of python packages/modules follows the hierarchy of -*.py files found in source tree (or, more generally, in python path). +

      The hierarchy of Python packages/modules follows the hierarchy of +*.py files found in a source tree (or, more generally, in the Python path). Normally, the developer creates new module by placing a *.py file -somewhere under python path; the module is then named after that *.py -file. A package is created by placing __init__.py file within a +somewhere under Python path; the module is then named after that *.py +file. A package is created by placing an __init__.py file within a directory; the package is then named after that directory. For example, the following source tree:

      @@ -5303,7 +5303,7 @@ pkg1/pkg2/mod3.py
  • -defines the following python packages and modules: +defines the following Python packages and modules:

    @@ -5317,28 +5317,28 @@ pkg1.pkg2.mod3 # module

    -The purpose of __init__.py file is two-fold. First, existence of -__init__.py in a directory informs python interpreter that this -directory contains python package. Second, the code of __init__.py is +The purpose of an __init__.py file is two-fold. First, the existence of +__init__.py in a directory informs the Python interpreter that this +directory contains a Python package. Second, the code in __init__.py is loaded/executed automatically when the package is initialized (when it or its -submodule/subpackage gets import'ed). By default, swig generates -proxy python code – one *.py file for each *.i -interface. The __init__.py files, however, are not generated by swig. +submodule/subpackage gets import'ed). By default, SWIG generates +proxy Python code – one *.py file for each *.i +interface. The __init__.py files, however, are not generated by SWIG. They should be created by other means. Both files (module *.py and __init__.py) should be installed in appropriate destination -directories in order to obtain desirable package/module hierarchy. +directories in order to obtain a desirable package/module hierarchy.

    -

    The way python defines its modules and packages impacts swig users. Some -users may need to use special features such as package option of -%module directive or import-related command-line options. These are +

    The way Python defines its modules and packages impacts SWIG users. Some +users may need to use special features such as the package option in the +%module directive or import related command line options. These are explained in the following sections.

    -

    34.11.1 %module(package="...") syntax

    +

    34.11.1 Setting the Python package

    -Using the package option of the %module directive allows you -to specify a Python package that the module will be living in when installed. +Using the package option in the %module directive allows you +to specify a Python package that the module will be in when installed.

    @@ -5351,20 +5351,20 @@ to specify a Python package that the module will be living in when installed. This is useful when the .i file is %imported by another .i file. By default SWIG will assume that the importer is able to find the importee with just the module name, but -if they live in separate Python packages then that won't work. +if they live in separate Python packages then this won't work. However if the importee specifies what its package is with the %module option then the Python code generated for the importer will use that package name when importing the other module -and also in base class declarations, etc.. +and in base class declarations, etc..

    -

    Swig assumes, that the package option provided to %module +

    SWIG assumes that the package option provided to %module together with the module name (that is, wx.xrc in the above example) forms a fully qualified (absolute) name of a module (in Python terms). This is important especially for Python 3, where absolute imports are used by default. It's up to you to place the generated module files (.py, -.so) in proper subdirectories. For example, if you have -interface foo.i with: +.so) in appropriate subdirectories. For example, if you have an +interface file foo.i with:

    @@ -5374,7 +5374,7 @@ interface foo.i with:

    -then the resultant directory layout should be +then the resulting directory layout should be

    @@ -5382,8 +5382,8 @@ then the resultant directory layout should be pkg1/ pkg1/__init__.py pkg1/pkg2/__init__.py -pkg1/pkg2/foo.py # (generated by swig) -pkg1/pkg2/_foo.so # (shared library from C/C++ code generated by SWIG) +pkg1/pkg2/foo.py # (generated by SWIG) +pkg1/pkg2/_foo.so # (shared library built from C/C++ code generated by SWIG)
    @@ -5409,9 +5409,9 @@ class M3: pass

    -We edit pkg1/mod2.py and want to import module of +We edit pkg1/mod2.py and want to import module pkg1/pkg2/pkg3.py in order to derive from class M3. We can -write appropriate python code in several ways, for example: +write appropriate Python code in several ways, for example:

      @@ -5426,7 +5426,7 @@ class M2(pkg1.pkg2.mod3.M3): pass
    1. Using "import <>" syntax with package name relative to - pkg1 (only in python 2.7 and earlier):

      + pkg1 (only in Python 2.7 and earlier):

       # pkg1/mod2.py
      @@ -5437,7 +5437,7 @@ class M2(pkg2.mod3.M3): pass
         
    2. Using "from <> import <>" syntax (relative import - syntax, only in python 2.5 and later):

      + syntax, only in Python 2.5 and later):

       # pkg1/mod2.py
      @@ -5449,7 +5449,7 @@ class M2(mod3.M3): pass
       
         
    3. Other variants, for example the following construction in order to have the pkg2.mod3.M3 symbol available in mod2 as - in point 2 above (but now under python 3):

      + in point 2 above (but now under Python 3):

       # pkg1/mod2.py
      @@ -5483,13 +5483,13 @@ class M2(pkg2.mod3.M3): pass
       
      -

      By default, swig would generate mod2.py proxy file with -import directive as in point 1. This may be changed with --relativeimport CLI option. The -relativeimport instructs -swig to organize imports as in point 2 (for python 2.x) or as in point 4 (for -python 3, that is when -py3 CLI option is enabled). In short, if you have +

      By default, SWIG would generate mod2.py proxy file with +import directive as in point 1. This can be changed with the +-relativeimport command line option. The -relativeimport instructs +SWIG to organize imports as in point 2 (for Python 2.x) or as in point 4 (for +Python 3, that is when the -py3 command line option is enabled). In short, if you have mod2.i and mod3.i as above, then without --relativeimport swig will write

      +-relativeimport SWIG will write

      @@ -5515,20 +5515,20 @@ import pkg1.pkg2.mod3
       
      -

      when -py3 option is used.

      +

      when -py3 is used.

      You should avoid using relative imports and use absolute ones whenever possible. There are some cases, however, when relative imports may be -necessary. The first example is, when some (legacy) python code refers entities -imported by proxy files generated by swig, and it assumes that the proxy file +necessary. The first example is, when some (legacy) Python code refers entities +imported by proxy files generated by SWIG, and it assumes that the proxy file uses relative imports. Second case is, when one puts import directives in __init__.py to import symbols from submodules or subpackages and the submodule depends on other submodules (discussed later).

      34.11.3 Enforcing absolute import semantics

      -

      As you may know, there is incompatibility in import semantics (for the -import <> syntax) between python 2 and 3. In python 2.4 and +

      As you may know, there is an incompatibility in import semantics (for the +import <> syntax) between Python 2 and 3. In Python 2.4 and earlier it is not clear whether

      @@ -5537,10 +5537,10 @@ import foo
    4. refers to a top-level module or to another module inside the current -package. In python 3 it always refers to a top-level module +package. In Python 3 it always refers to a top-level module (see PEP 328). -To instruct python 2.5 through 2.7 to use new semantics (that is import -foo is interpreted as absolute import), one have to put the following +To instruct Python 2.5 through 2.7 to use new semantics (that is import +foo is interpreted as absolute import), one has to put the following line

      @@ -5550,26 +5550,26 @@ from __future__ import absolute_import -

      at the very beginning of his proxy *.py file. In swig, it may be +

      at the very beginning of his proxy *.py file. In SWIG, it may be accomplished with %pythonbegin directive.

      34.11.4 Importing from __init__.py

      -

      Imports in __init__.py are handy when you want to populate -package's namespace with names imported from other modules. In swig-based -projects this approach may also be used to split large piece of code into -smaller modules, compile them in parallel and then re-assemble all stuff at -python level by importing submodules' contents in __init__.py, for +

      Imports in __init__.py are handy when you want to populate a +package's namespace with names imported from other modules. In SWIG based +projects this approach may also be used to split large pieces of code into +smaller modules, compile them in parallel and then re-assemble everything at another +level by importing submodules' contents in __init__.py, for example.

      -

      Unfortunately import directives in __init__.py may cause troubles, -especially if they refer to package's submodules. This is caused by the way -python initializes packages. If you spot problems with imports from +

      Unfortunately import directives in __init__.py may cause problems, +especially if they refer to a package's submodules. This is caused by the way +Python initializes packages. If you spot problems with imports from __init__.py try using -relativeimport option. Below we explain in detail one issue, for which the -relativeimport workaround may be helpful.

      -

      Consider the following example (python 3):

      +

      Consider the following example (Python 3):

      @@ -5580,10 +5580,10 @@ pkg1/pkg2/bar.py        # (imports foo.py)
       
      -

      Let's the files' contents be:

      +

      If the file contents are:

        -
      • for pkg1/pkg2/__init__.py:

        +
      • pkg1/pkg2/__init__.py:

         # pkg1/pkg2/__init__.py
        @@ -5592,7 +5592,7 @@ from .bar import Bar
             
      • -
      • for pkg1/pkg2/foo.py:

        +
      • pkg1/pkg2/foo.py:

         # pkg1/pkg2/foo.py
        @@ -5601,7 +5601,7 @@ class Foo: pass
             
      • -
      • for pkg1/pkg2/foo.py:

        +
      • pkg1/pkg2/bar.py:

         # pkg1/pkg2/bar.py
        @@ -5612,7 +5612,7 @@ class Bar(pkg1.pkg2.foo.Foo): pass
           
      -

      Now one would simply do import pkg1.pkg2, but this usually fails:

      +

      Now if one simply used import pkg1.pkg2, it will usually fail:

      @@ -5628,16 +5628,16 @@ AttributeError: 'module' object has no attribute 'pkg2'
       

      Surprisingly, if we execute the import pkg1.pkg2 directive for the -second time, it succeeds. The reason seems to be following: when python spots +second time, it succeeds. The reason seems to be following: when Python spots the from .bar import Bar directive in pkg1/pkg2/__init__.py it starts loading pkg1/pkg2/bar.py. This module imports pkg1.pkg2.foo in turn and tries to use pkg1.pkg2.foo.Foo, but the package pkg1 is not fully initialized yet (the initialization -procedure is actually in progress) and it seems like the effect of already seen -directive import pkg1.pkg2.pkg3.foo is "delayed" or ignored. Exactly -same may happen to a proxy module generated by swig.

      +procedure is actually in progress) and it seems like the effect of the already seen +import pkg1.pkg2.pkg3.foo is "delayed" or ignored. Exactly the +same may happen to a proxy module generated by SWIG.

      -

      It's observed, that a possible workaround for this case is to use relative +

      One workaround for this case is to use a relative import in pkg1/pkg2/bar.py. If we change bar.py to be:

      @@ -5657,9 +5657,9 @@ class Bar(pkg3.foo.Foo): pass
      -

      then the example works again. With swig, you need to enable the +

      then the example works again. With SWIG, you need to enable the -relativeimport option in order to have the above workaround in -effect (note, that python 2 case also needs -relativeimport +effect (note, that the Python 2 case also needs the -relativeimport workaround).

      From 2866c70f78cc8796323a9f7fb58d3222a162e349 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 24 Dec 2013 17:19:59 +0000 Subject: [PATCH 274/481] Add changes entry for python imports/packages changes --- CHANGES.current | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/CHANGES.current b/CHANGES.current index 5629532b7..7856c796e 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,27 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2013-12-24: ptomulik + [Python] SF Bug #1297 + + Resolve several issues related to python imports. + For example, it's now possible to import modules having the same module + names, but belonging in different packages. + + From the user's viewpoint, this patch gives a little bit more control on + import statements generated by SWIG. The user may choose to use relative + or absolute imports. + + Some details: + - we (still) generate import statements in the form 'import a.b.c' which + corresponds to absolute imports in python3 and (the only available) + ambiguous one in python2. + - added -relativeimport option to use explicit relative import syntax + (python3), + + The "Python Packages" section in the documentation discusses how to work + with importing packages including the new -relativeimport command line option. + 2013-12-23: vadz [Octave, Perl, Python, R, Ruby, Tcl] Change the length of strings created from fixed-size char buffers in C code. From fc3098ea55de41c5d6912286516fb1ae262a97b4 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 3 Jan 2014 08:27:41 +0000 Subject: [PATCH 275/481] auto_ptr deprecation warning suppression --- Examples/test-suite/li_std_auto_ptr.i | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Examples/test-suite/li_std_auto_ptr.i b/Examples/test-suite/li_std_auto_ptr.i index 1dcb3e02e..627572d5c 100644 --- a/Examples/test-suite/li_std_auto_ptr.i +++ b/Examples/test-suite/li_std_auto_ptr.i @@ -1,7 +1,7 @@ %module li_std_auto_ptr %{ -#if (__GNUC__ == 4 && __GNUC_MINOR__ >= 9) +#if (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) #pragma GCC diagnostic ignored "-Wdeprecated-declarations" // auto_ptr deprecation #endif %} From 6a72e16b371bf9b22324a157ec9e48f04dc802f0 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 3 Jan 2014 19:23:35 +0000 Subject: [PATCH 276/481] Add C++11 virtual specifier sequences (final and/or override on methods) Parsing support added. The final and override information is not used or added to the parse tree atm. --- Doc/Manual/CPlusPlus11.html | 23 ++++ Examples/test-suite/common.mk | 1 + Examples/test-suite/cpp11_final_override.i | 128 +++++++++++++++++++++ Source/CParse/cscanner.c | 16 +-- Source/CParse/parser.y | 85 +++++++++----- 5 files changed, 218 insertions(+), 35 deletions(-) create mode 100644 Examples/test-suite/cpp11_final_override.i diff --git a/Doc/Manual/CPlusPlus11.html b/Doc/Manual/CPlusPlus11.html index 0d2f22aff..9d315d8e3 100644 --- a/Doc/Manual/CPlusPlus11.html +++ b/Doc/Manual/CPlusPlus11.html @@ -414,6 +414,29 @@ class DerivedClass: public BaseClass { }; +

      Explicit overrides and final

      + +

      +The special identifiers final and override can be used on methods and destructors, +such as in the following example: +

      + +
      +struct BaseStruct {
      +  virtual void ab() const = 0;
      +  virtual void cd();
      +  virtual void ef();
      +  virtual ~BaseStruct();
      +};
      +struct DerivedStruct : BaseStruct {
      +  virtual void ab() const override;
      +  virtual void cd() final;
      +  virtual void ef() final override;
      +  virtual ~DerivedStruct() override;
      +};
      +
      + +

      7.2.11 Null pointer constant

      diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 642e7fd8c..fb53a0ec9 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -490,6 +490,7 @@ CPP11_TEST_CASES = \ cpp11_default_delete \ cpp11_delegating_constructors \ cpp11_explicit_conversion_operators \ + cpp11_final_override \ cpp11_function_objects \ cpp11_inheriting_constructors \ cpp11_initializer_list \ diff --git a/Examples/test-suite/cpp11_final_override.i b/Examples/test-suite/cpp11_final_override.i new file mode 100644 index 000000000..f691f8770 --- /dev/null +++ b/Examples/test-suite/cpp11_final_override.i @@ -0,0 +1,128 @@ +// Test C++11 virtual specifier sequences (final and/or override on methods) +// Also check final/override - the two 'identifiers with special meaning' work as normal identifiers + +%module cpp11_final_override + +%warnfilter(SWIGWARN_PARSE_KEYWORD) final; // 'final' is a java keyword, renaming to '_final' +%warnfilter(SWIGWARN_PARSE_KEYWORD) override; // 'override' is a C# keyword, renaming to '_override' + +%inline %{ + +struct Base { + virtual void stuff() const {} + virtual void override1() const {} + virtual void override2() const {} + virtual void finaloverride1() {} + virtual void finaloverride2() {} + virtual void finaloverride3() {} + virtual void finaloverride4() const {} + virtual ~Base() {} +}; + +struct Derived /*final*/ : Base { + virtual void stuff() const noexcept override final {} + virtual void override1() const noexcept override; + virtual void override2() const noexcept override; + virtual void final1() final {} + virtual void final2() noexcept final {} + virtual void final4() const final {} + virtual void final5() const noexcept final {} + virtual void finaloverride1() final override {} + virtual void finaloverride2() override final {} + virtual void finaloverride3() noexcept override final {} + virtual void finaloverride4() const noexcept override final {} + virtual ~Derived() override final {} +}; +void Derived::override2() const noexcept {} + +// Pure virtual methods +struct PureBase { + virtual void pure1(int) const = 0; + virtual void pure2(int) const = 0; + virtual void pure3(int) const = 0; + virtual void pure4(int) const = 0; + virtual void pure5(int) const = 0; + virtual ~PureBase() {} +}; + +struct PureDerived : PureBase { + virtual void pure1(int) const override = 0; + virtual void pure2(int) const final = 0; + virtual void pure3(int) const override final = 0; + virtual void pure4(int) const final override = 0; + virtual void pure5(int) const noexcept final override = 0; + virtual ~PureDerived() override final; +}; +void PureDerived::pure1(int) const {} +void PureDerived::pure2(int) const {} +void PureDerived::pure3(int) const {} +void PureDerived::pure4(int) const {} +void PureDerived::pure5(int) const noexcept {} +PureDerived::~PureDerived() {} + +// Destructors and virtual specifier sequences (final/override) +struct Destructors1 : Base { + virtual ~Destructors1() override {} +}; +struct Destructors2 : Base { + virtual ~Destructors2() final {} +}; +struct Destructors3 : Base { + virtual ~Destructors3() noexcept final override {} +}; +struct Destructors4 : Base { + virtual ~Destructors4() noexcept override final {} +}; + +// Check the two 'identifiers with special meaning' work as normal identifiers +struct FinalOverrideMethods { + virtual void final() {} + virtual void override(int) {} +}; +struct FinalOverrideVariables { + int final; + double override; +}; +void final(int) {} +void override() {} +%} + +%{ +void Derived::override1() const noexcept {} +%} + +// Example in documentation ... declarations only +%inline %{ +struct BaseStruct { + virtual void ab() const = 0; + virtual void cd(); + virtual void ef(); + virtual ~BaseStruct(); +}; +struct DerivedStruct : BaseStruct { + virtual void ab() const override; + virtual void cd() final; + virtual void ef() final override; + virtual ~DerivedStruct() override; +}; +struct DerivedNoVirtualStruct : BaseStruct { + void ab() const override; + void cd() final; + void ef() final override; + ~DerivedNoVirtualStruct() override; +}; +%} + +%{ +void BaseStruct::cd() {} +void BaseStruct::ef() {} +BaseStruct::~BaseStruct() {} +void DerivedStruct::ab() const {} +void DerivedStruct::cd() {} +void DerivedStruct::ef() {} +DerivedStruct::~DerivedStruct() {} +void DerivedNoVirtualStruct::ab() const {} +void DerivedNoVirtualStruct::cd() {} +void DerivedNoVirtualStruct::ef() {} +DerivedNoVirtualStruct::~DerivedNoVirtualStruct() {} +%} diff --git a/Source/CParse/cscanner.c b/Source/CParse/cscanner.c index 2dfc2c479..4e02b4b62 100644 --- a/Source/CParse/cscanner.c +++ b/Source/CParse/cscanner.c @@ -748,18 +748,18 @@ int yylex(void) { yylval.intvalue = cparse_line; return (TEMPLATE); } - if (strcmp(yytext, "delete") == 0) { + if (strcmp(yytext, "delete") == 0) return (DELETE_KW); - } - if (strcmp(yytext, "default") == 0) { + if (strcmp(yytext, "default") == 0) return (DEFAULT); - } - if (strcmp(yytext, "using") == 0) { + if (strcmp(yytext, "using") == 0) return (USING); - } - if (strcmp(yytext, "namespace") == 0) { + if (strcmp(yytext, "namespace") == 0) return (NAMESPACE); - } + if (strcmp(yytext, "override") == 0) + return (OVERRIDE); + if (strcmp(yytext, "final") == 0) + return (FINAL); } else { if (strcmp(yytext, "class") == 0) { Swig_warning(WARN_PARSE_CLASS_KEYWORD, cparse_file, cparse_line, "class keyword used, but not in C++ mode.\n"); diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index a7604ff56..fe8b7f97f 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1388,8 +1388,9 @@ static void mark_nodes_as_extend(Node *n) { %token ILLEGAL CONSTANT %token NAME RENAME NAMEWARN EXTEND PRAGMA FEATURE VARARGS %token ENUM -%token CLASS TYPENAME PRIVATE PUBLIC PROTECTED COLON STATIC VIRTUAL FRIEND THROW CATCH EXPLICIT AUTO NOEXCEPT -%token STATIC_ASSERT CONSTEXPR THREAD_LOCAL DECLTYPE /* C++11 keywords */ +%token CLASS TYPENAME PRIVATE PUBLIC PROTECTED COLON STATIC VIRTUAL FRIEND THROW CATCH EXPLICIT +%token STATIC_ASSERT CONSTEXPR THREAD_LOCAL DECLTYPE AUTO NOEXCEPT /* C++11 keywords */ +%token OVERRIDE FINAL /* C++11 identifiers with special meaning */ %token USING %token NAMESPACE %token NATIVE INLINE @@ -1443,6 +1444,7 @@ static void mark_nodes_as_extend(Node *n) { %type kwargs options; /* Misc */ +%type identifier; %type initializer cpp_const exception_specification; %type storage_class; %type parms ptail rawparms varargs_parms ; @@ -1480,6 +1482,7 @@ static void mark_nodes_as_extend(Node *n) { %type lambda_introducer lambda_body; %type lambda_tail; %type optional_constant_directive; +%type virt_specifier_seq; %% @@ -1701,7 +1704,7 @@ clear_directive : CLEAR tm_list SEMI { %constant type name = value; ------------------------------------------------------------ */ -constant_directive : CONSTANT ID EQUAL definetype SEMI { +constant_directive : CONSTANT identifier EQUAL definetype SEMI { if (($4.type != T_ERROR) && ($4.type != T_SYMBOL)) { SwigType *type = NewSwigType($4.type); $$ = new_node("constant"); @@ -1783,7 +1786,7 @@ echo_directive : ECHO HBLOCK { %except; ------------------------------------------------------------ */ -except_directive : EXCEPT LPAREN ID RPAREN LBRACE { +except_directive : EXCEPT LPAREN identifier RPAREN LBRACE { skip_balanced('{','}'); $$ = 0; Swig_warning(WARN_DEPRECATED_EXCEPT,cparse_file, cparse_line, "%%except is deprecated. Use %%exception instead.\n"); @@ -1795,7 +1798,7 @@ except_directive : EXCEPT LPAREN ID RPAREN LBRACE { Swig_warning(WARN_DEPRECATED_EXCEPT,cparse_file, cparse_line, "%%except is deprecated. Use %%exception instead.\n"); } - | EXCEPT LPAREN ID RPAREN SEMI { + | EXCEPT LPAREN identifier RPAREN SEMI { $$ = 0; Swig_warning(WARN_DEPRECATED_EXCEPT,cparse_file, cparse_line, "%%except is deprecated. Use %%exception instead.\n"); } @@ -2080,13 +2083,13 @@ name_directive : NAME LPAREN idstring RPAREN { %native(scriptname) type name (parms); ------------------------------------------------------------ */ -native_directive : NATIVE LPAREN ID RPAREN storage_class ID SEMI { +native_directive : NATIVE LPAREN identifier RPAREN storage_class identifier SEMI { $$ = new_node("native"); Setattr($$,"name",$3); Setattr($$,"wrap:name",$6); add_symbols($$); } - | NATIVE LPAREN ID RPAREN storage_class type declarator SEMI { + | NATIVE LPAREN identifier RPAREN storage_class type declarator SEMI { if (!SwigType_isfunction($7.type)) { Swig_error(cparse_file,cparse_line,"%%native declaration '%s' is not a function.\n", $7.id); $$ = 0; @@ -2112,13 +2115,13 @@ native_directive : NATIVE LPAREN ID RPAREN storage_class ID SEMI { %pragma name ------------------------------------------------------------ */ -pragma_directive : PRAGMA pragma_lang ID EQUAL pragma_arg { +pragma_directive : PRAGMA pragma_lang identifier EQUAL pragma_arg { $$ = new_node("pragma"); Setattr($$,"lang",$2); Setattr($$,"name",$3); Setattr($$,"value",$5); } - | PRAGMA pragma_lang ID { + | PRAGMA pragma_lang identifier { $$ = new_node("pragma"); Setattr($$,"lang",$2); Setattr($$,"name",$3); @@ -2129,13 +2132,12 @@ pragma_arg : string { $$ = NewString($1); } | HBLOCK { $$ = $1; } ; -pragma_lang : LPAREN ID RPAREN { $$ = $2; } +pragma_lang : LPAREN identifier RPAREN { $$ = $2; } | empty { $$ = (char *) "swig"; } ; /* ------------------------------------------------------------ - %rename identifier newname; - %rename identifier "newname"; + %rename(newname) identifier; ------------------------------------------------------------ */ rename_directive : rename_namewarn declarator idstring SEMI { @@ -2883,7 +2885,7 @@ c_declaration : c_decl { $$ = 0; /* TODO - ignored for now */ } - | TEMPLATE LESSTHAN template_parms GREATERTHAN USING idcolon EQUAL ID { + | TEMPLATE LESSTHAN template_parms GREATERTHAN USING idcolon EQUAL identifier { skip_decl(); $$ = new_node("using"); Setattr($$,"uname",$8); @@ -4221,7 +4223,7 @@ cpp_namespace_decl : NAMESPACE idcolon LBRACE { Namespaceprefix = Swig_symbol_qualifiedscopename(0); add_symbols($$); } - | NAMESPACE ID EQUAL idcolon SEMI { + | NAMESPACE identifier EQUAL idcolon SEMI { /* Namespace alias */ Node *n; $$ = new_node("namespace"); @@ -5810,7 +5812,7 @@ explicit_default : DEFAULT { /* Some stuff for handling enums */ -ename : ID { $$ = $1; } +ename : identifier { $$ = $1; } | empty { $$ = (char *) 0;} ; @@ -5837,7 +5839,7 @@ enumlist : enumlist COMMA optional_constant_directive edecl optional_cons } ; -edecl : ID { +edecl : identifier { SwigType *type = NewSwigType(T_INT); $$ = new_node("enumitem"); Setattr($$,"name",$1); @@ -5845,7 +5847,7 @@ edecl : ID { SetFlag($$,"feature:immutable"); Delete(type); } - | ID EQUAL etype { + | identifier EQUAL etype { SwigType *type = NewSwigType($3.type == T_BOOL ? T_BOOL : ($3.type == T_CHAR ? T_CHAR : T_INT)); $$ = new_node("enumitem"); Setattr($$,"name",$1); @@ -6263,6 +6265,20 @@ opt_virtual : VIRTUAL | empty ; +virt_specifier_seq : OVERRIDE { + $$ = 0; + } + | FINAL { + $$ = 0; + } + | FINAL OVERRIDE { + $$ = 0; + } + | OVERRIDE FINAL { + $$ = 0; + } + ; + exception_specification : THROW LPAREN parms RPAREN { $$.throws = $3; $$.throwf = NewString("1"); @@ -6273,7 +6289,16 @@ exception_specification : THROW LPAREN parms RPAREN { $$.throwf = 0; $$.nexcept = NewString("true"); } - + | virt_specifier_seq { + $$.throws = 0; + $$.throwf = 0; + $$.nexcept = 0; + } + | NOEXCEPT virt_specifier_seq { + $$.throws = 0; + $$.throwf = 0; + $$.nexcept = NewString("true"); + } | NOEXCEPT LPAREN expr RPAREN { $$.throws = 0; $$.throwf = 0; @@ -6390,7 +6415,13 @@ template_decl : LESSTHAN valparms GREATERTHAN { | empty { $$ = (char*)""; } ; -idstring : ID { $$ = $1; } +/* Identifiers including the C++11 identifiers with special meaning */ +identifier : ID { $$ = $1; } + | OVERRIDE { $$ = Swig_copy_string("override"); } + | FINAL { $$ = Swig_copy_string("final"); } + ; + +idstring : identifier { $$ = $1; } | default_delete { $$ = $1.val; } | string { $$ = $1; } ; @@ -6442,7 +6473,7 @@ idcolontail : DCOLON idtemplate idcolontail { ; -idtemplate : ID template_decl { +idtemplate : identifier template_decl { $$ = NewStringf("%s%s",$1,$2); /* if (Len($2)) { scanner_last_id(1); @@ -6451,19 +6482,19 @@ idtemplate : ID template_decl { ; /* Identifier, but no templates */ -idcolonnt : ID idcolontailnt { +idcolonnt : identifier idcolontailnt { $$ = 0; if (!$$) $$ = NewStringf("%s%s", $1,$2); Delete($2); } - | NONID DCOLON ID idcolontailnt { + | NONID DCOLON identifier idcolontailnt { $$ = NewStringf("::%s%s",$3,$4); Delete($4); } - | ID { + | identifier { $$ = NewString($1); } - | NONID DCOLON ID { + | NONID DCOLON identifier { $$ = NewStringf("::%s",$3); } | OPERATOR { @@ -6474,17 +6505,17 @@ idcolonnt : ID idcolontailnt { } ; -idcolontailnt : DCOLON ID idcolontailnt { +idcolontailnt : DCOLON identifier idcolontailnt { $$ = NewStringf("::%s%s",$2,$3); Delete($3); } - | DCOLON ID { + | DCOLON identifier { $$ = NewStringf("::%s",$2); } | DCOLON OPERATOR { $$ = NewStringf("::%s",$2); } - | DCNOT ID { + | DCNOT identifier { $$ = NewStringf("::~%s",$2); } ; From 324818030b3fab5f4e205c45adbcfcb04cda0c82 Mon Sep 17 00:00:00 2001 From: Miklos Vajna Date: Tue, 31 Dec 2013 15:18:01 +0100 Subject: [PATCH 277/481] PHP: document byref typemap attribute --- Doc/Manual/Php.html | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Doc/Manual/Php.html b/Doc/Manual/Php.html index 185883235..19bfab6ba 100644 --- a/Doc/Manual/Php.html +++ b/Doc/Manual/Php.html @@ -513,6 +513,12 @@ So if you use these REF typemaps, you should ensure that SWIG≥3.0 is used to generate wrappers from your interface file.

      +

      +In case you write your own typemaps, SWIG supports an attribute called +byref: if you set that, then SWIG will make sure that the generated +wrapper function will want the input parameter as a reference. +

      +
       %module example
       %include "phppointers.i"
      
      From d67aed42bd0a3cb71a12aec8822d69b3ebbe5599 Mon Sep 17 00:00:00 2001
      From: Olly Betts 
      Date: Mon, 6 Jan 2014 15:41:06 +1300
      Subject: [PATCH 278/481] Remove executable bit from various test-suite runme
       files
      
      ---
       Examples/guile/matrix/runme.scm                     | 0
       Examples/php/pragmas/runme.php                      | 0
       Examples/php/simple/runme.php                       | 0
       Examples/pike/class/runme.pike                      | 0
       Examples/pike/constants/runme.pike                  | 0
       Examples/pike/template/runme.pike                   | 0
       Examples/test-suite/php/threads_exception_runme.php | 0
       7 files changed, 0 insertions(+), 0 deletions(-)
       mode change 100755 => 100644 Examples/guile/matrix/runme.scm
       mode change 100755 => 100644 Examples/php/pragmas/runme.php
       mode change 100755 => 100644 Examples/php/simple/runme.php
       mode change 100755 => 100644 Examples/pike/class/runme.pike
       mode change 100755 => 100644 Examples/pike/constants/runme.pike
       mode change 100755 => 100644 Examples/pike/template/runme.pike
       mode change 100755 => 100644 Examples/test-suite/php/threads_exception_runme.php
      
      diff --git a/Examples/guile/matrix/runme.scm b/Examples/guile/matrix/runme.scm
      old mode 100755
      new mode 100644
      diff --git a/Examples/php/pragmas/runme.php b/Examples/php/pragmas/runme.php
      old mode 100755
      new mode 100644
      diff --git a/Examples/php/simple/runme.php b/Examples/php/simple/runme.php
      old mode 100755
      new mode 100644
      diff --git a/Examples/pike/class/runme.pike b/Examples/pike/class/runme.pike
      old mode 100755
      new mode 100644
      diff --git a/Examples/pike/constants/runme.pike b/Examples/pike/constants/runme.pike
      old mode 100755
      new mode 100644
      diff --git a/Examples/pike/template/runme.pike b/Examples/pike/template/runme.pike
      old mode 100755
      new mode 100644
      diff --git a/Examples/test-suite/php/threads_exception_runme.php b/Examples/test-suite/php/threads_exception_runme.php
      old mode 100755
      new mode 100644
      
      From 90eb5f9095e65a585ee839aba435a50fcaaf1801 Mon Sep 17 00:00:00 2001
      From: Ian Lance Taylor 
      Date: Mon, 6 Jan 2014 09:28:52 -0800
      Subject: [PATCH 279/481] [Go] Fix bug that broke using directors from a thread
       not created by Go.
      
      ---
       CHANGES.current       | 4 ++++
       Source/Modules/go.cxx | 2 ++
       2 files changed, 6 insertions(+)
      
      diff --git a/CHANGES.current b/CHANGES.current
      index 7856c796e..431f327bb 100644
      --- a/CHANGES.current
      +++ b/CHANGES.current
      @@ -5,6 +5,10 @@ See the RELEASENOTES file for a summary of changes in each release.
       Version 3.0.0 (in progress)
       ============================
       
      +2014-01-06: ianlancetaylor
      +	    [Go] Fix bug that broke using directors from a thread not
      +	    created by Go.
      +
       2013-12-24: ptomulik
                   [Python] SF Bug #1297
       
      diff --git a/Source/Modules/go.cxx b/Source/Modules/go.cxx
      index 3dec6503b..36e5d11d3 100644
      --- a/Source/Modules/go.cxx
      +++ b/Source/Modules/go.cxx
      @@ -2861,6 +2861,7 @@ private:
       
       	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);
      @@ -3591,6 +3592,7 @@ private:
       	  // 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);
      
      From 40bf8774997dfbd791677a9abd96e3babadef73b Mon Sep 17 00:00:00 2001
      From: Vadim Zeitlin 
      Date: Fri, 10 Jan 2014 14:38:54 +0100
      Subject: [PATCH 280/481] Work around gcc warning about function pointers
       conversions.
      
      Work around harmless (at least under POSIX systems where function pointers are
      guaranteed to have the same representation as object pointers) but annoying
      warnings given by gcc when converting between function and object pointers, e.g.
      
      Source/DOH/fio.c: In function 'DohEncoding':
      Source/DOH/fio.c:51: warning: ISO C forbids conversion of function pointer to object pointer type
      Source/DOH/fio.c: In function 'encode':
      Source/DOH/fio.c:75: warning: ISO C forbids conversion of object pointer to function pointer type
      Source/DOH/base.c: In function 'DohCall':
      Source/DOH/base.c:952: warning: ISO C forbids conversion of object pointer to function pointer type
      
      Use an extra level of pointer indirection to avoid them.
      ---
       Source/DOH/base.c | 2 +-
       Source/DOH/fio.c  | 4 ++--
       2 files changed, 3 insertions(+), 3 deletions(-)
      
      diff --git a/Source/DOH/base.c b/Source/DOH/base.c
      index 1f92b6542..e84731cd0 100644
      --- a/Source/DOH/base.c
      +++ b/Source/DOH/base.c
      @@ -949,7 +949,7 @@ DOH *DohCall(DOH *func, DOH *args) {
         DOH *result;
         DOH *(*builtin) (DOH *);
       
      -  builtin = (DOH *(*)(DOH *)) GetVoid(func, "builtin");
      +  *(void **)(&builtin) = GetVoid(func, "builtin");
         if (!builtin)
           return 0;
         result = (*builtin) (args);
      diff --git a/Source/DOH/fio.c b/Source/DOH/fio.c
      index d2a1bab19..71ce30149 100644
      --- a/Source/DOH/fio.c
      +++ b/Source/DOH/fio.c
      @@ -48,7 +48,7 @@ static int Writen(DOH *out, void *buffer, int len) {
       void DohEncoding(const char *name, DOH *(*fn) (DOH *s)) {
         if (!encodings)
           encodings = NewHash();
      -  Setattr(encodings, (void *) name, NewVoid((void *) fn, 0));
      +  Setattr(encodings, (void *) name, NewVoid(*(void **)&fn, 0));
       }
       
       /* internal function for processing an encoding */
      @@ -72,7 +72,7 @@ static DOH *encode(char *name, DOH *s) {
           s = tmp;
         pos = Tell(s);
         Seek(s, 0, SEEK_SET);
      -  fn = (DOH *(*)(DOH *)) Data(handle);
      +  *(void **)(&fn) = Data(handle);
         ns = (*fn) (s);
         assert(pos != -1);
         (void)Seek(s, pos, SEEK_SET);
      
      From e702093c70ce065b8b26d855203ca797b05c9b48 Mon Sep 17 00:00:00 2001
      From: William S Fulton 
      Date: Tue, 7 Jan 2014 20:03:14 +0000
      Subject: [PATCH 281/481] Template private assignment testcase
      
      This is broken and needs fixing at some point.
      Problem reported by Pierre-Henri Wuillemin on swig-devel mailing list.
      ---
       Examples/test-suite/common.mk                 |  1 +
       .../test-suite/template_private_assignment.i  | 24 +++++++++++++++++++
       2 files changed, 25 insertions(+)
       create mode 100644 Examples/test-suite/template_private_assignment.i
      
      diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk
      index fb53a0ec9..d96d42018 100644
      --- a/Examples/test-suite/common.mk
      +++ b/Examples/test-suite/common.mk
      @@ -87,6 +87,7 @@ CPP_TEST_BROKEN += \
       	nested_private \
       	overload_complicated \
       	template_default_pointer \
      +	template_private_assignment \
       	template_expr \
       	$(CPP11_TEST_BROKEN)
       
      diff --git a/Examples/test-suite/template_private_assignment.i b/Examples/test-suite/template_private_assignment.i
      new file mode 100644
      index 000000000..e135e3913
      --- /dev/null
      +++ b/Examples/test-suite/template_private_assignment.i
      @@ -0,0 +1,24 @@
      +%module template_private_assignment
      +
      +/*
      +swig-devel mailing list report problem explained 2014-01-07
      +A setter for the global variable deleted_bits is generated because there is no template
      +instantiation for the template and hence SWIG does not find the private assignment operator.
      +SwigValueWrapper is probably on by default for templates that are not instantiated for the
      +same reason.
      +The solution is probably to add an instantiation of the template as soon as one is parsed,
      +that is an implicit empty %template().
      +*/
      +
      +%inline %{
      +template struct DeletedBits {
      +//  DeletedBits& operator=(const DeletedBits&) = delete;
      +private:
      +  DeletedBits& operator=(const DeletedBits&);
      +};
      +
      +DeletedBits deleted_bits;
      +%}
      +
      +// This works around the problem
      +//%template() DeletedBits;
      
      From c34d7f6d23d958f37f62dda2b9162663c4ca4410 Mon Sep 17 00:00:00 2001
      From: William S Fulton 
      Date: Sat, 11 Jan 2014 13:10:30 +0000
      Subject: [PATCH 282/481] %naturalvar feature fixes and documentation
      
      Fix and document the naturalvar feature override behaviour - the naturalvar
      feature attached to a variable name has precedence over the naturalvar
      feature attached to the variable's type. The overriding was not working
      when turning the feature off on the variable's name.
      
      Fix so that any use of the naturalvar feature will override the global
      setting. Previously when set globally by -naturalvar or %module(naturalvar=1),
      use of the naturalvar feature was not always honoured.
      ---
       CHANGES.current                               | 10 +++
       Doc/Manual/SWIGPlus.html                      | 68 +++++++++++--------
       Examples/test-suite/common.mk                 |  1 +
       .../java/naturalvar_onoff_runme.java          | 37 ++++++++++
       Examples/test-suite/naturalvar_onoff.i        | 29 ++++++++
       Source/Modules/lang.cxx                       | 23 +++++--
       6 files changed, 133 insertions(+), 35 deletions(-)
       create mode 100644 Examples/test-suite/java/naturalvar_onoff_runme.java
       create mode 100644 Examples/test-suite/naturalvar_onoff.i
      
      diff --git a/CHANGES.current b/CHANGES.current
      index 431f327bb..a4fc5dbf4 100644
      --- a/CHANGES.current
      +++ b/CHANGES.current
      @@ -5,6 +5,16 @@ See the RELEASENOTES file for a summary of changes in each release.
       Version 3.0.0 (in progress)
       ============================
       
      +2014-01-11: wsfulton
      +            Fix and document the naturalvar feature override behaviour - the naturalvar
      +            feature attached to a variable name has precedence over the naturalvar
      +            feature attached to the variable's type. The overriding was not working
      +            when turning the feature off on the variable's name.
      +
      +            Fix so that any use of the naturalvar feature will override the global
      +            setting. Previously when set globally by -naturalvar or %module(naturalvar=1),
      +            use of the naturalvar feature was not always honoured.
      +
       2014-01-06: ianlancetaylor
       	    [Go] Fix bug that broke using directors from a thread not
       	    created by Go.
      diff --git a/Doc/Manual/SWIGPlus.html b/Doc/Manual/SWIGPlus.html
      index 3c3c7d564..e0e7dbcaf 100644
      --- a/Doc/Manual/SWIGPlus.html
      +++ b/Doc/Manual/SWIGPlus.html
      @@ -959,8 +959,9 @@ Similarly, all data attributes declared as const are wrapped as read-on
       

      +By default, SWIG uses the const reference typemaps for members that are primitive types. There are some subtle issues when wrapping data members that are -themselves classes. For instance, if you had another class like this, +not primitive types, such as classes. For instance, if you had another class like this,

      @@ -973,7 +974,8 @@ public:

      -then the low-level accessor to the items member actually uses pointers. For example: +then the low-level accessor to the items member actually uses pointers. +For example:

      @@ -998,31 +1000,7 @@ This can be somewhat unnatural for some types. For example, a user would expect the STL std::string class member variables to be wrapped as a string in the target language, rather than a pointer to this class. The const reference typemaps offer this type of marshalling, so there is a feature to tell SWIG to use the const reference typemaps rather than the pointer typemaps. -It is the %naturalvar directive and is used as follows: -

      - -
      -
      -// All List variables will use const List& typemaps
      -%naturalvar List;
      -
      -// Only Foo::myList will use const List& typemaps
      -%naturalvar Foo::myList;
      -struct Foo {
      -  List myList;
      -};
      -
      -// All variables will use const reference typemaps
      -%naturalvar;
      -
      -
      - -

      -The observant reader will notice that %naturalvar works like any other -feature flag directive, -except it can also be attached to class types. -The first of the example usages above show %naturalvar attaching to the List class. -Effectively this feature changes the way accessors are generated to the following: +It is the naturalvar feature and can be used to effectively change the way accessors are generated to the following:

      @@ -1037,15 +1015,45 @@ void Foo_items_set(Foo *self, const List &value) {

      -In fact it is generally a good idea to use this feature globally as the reference typemaps have extra NULL checking compared to the pointer typemaps. +The %naturalvar directive is a macro for, and hence equivalent to, %feature("naturalvar"). It can be used as follows: +

      + +
      +
      +// All List variables will use const List& typemaps
      +%naturalvar List;
      +
      +// Only Foo::myList will use const List& typemaps
      +%naturalvar Foo::myList;
      +struct Foo {
      +  List myList;
      +};
      +
      +// All non-primitive types will use const reference typemaps
      +%naturalvar;
      +
      +
      + +

      +The observant reader will notice that %naturalvar works like any other +feature flag directive but with some extra flexibility. +The first of the example usages above shows %naturalvar attaching to the myList's variable type, that is the List class. +The second usage shows %naturalvar attaching to the variable name. +Hence the naturalvar feature can be used on either the variable's name or type. +Note that using the naturalvar feature on a variable's name overrides any naturalvar feature attached to the variable's type. +

      + +

      +It is generally a good idea to use this feature globally as the reference typemaps have extra NULL checking compared to the pointer typemaps. A pointer can be NULL, whereas a reference cannot, so the extra checking ensures that the target language user does not pass in a value that translates to a NULL pointer and thereby preventing any potential NULL pointer dereferences. The %naturalvar feature will apply to global variables in addition to member variables in some language modules, eg C# and Java.

      -Other alternatives for turning this feature on globally are to use the swig -naturalvar commandline option -or the module mode option, %module(naturalvar=1) +The naturalvar behavior can also be turned on as a global setting via the -naturalvar commandline option +or the module mode option, %module(naturalvar=1). +However, any use of %feature("naturalvar") will override the global setting.

      diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index d96d42018..86d688799 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -279,6 +279,7 @@ CPP_TEST_CASES += \ nspace_extend \ naturalvar \ naturalvar_more \ + naturalvar_onoff \ nested_class \ nested_comment \ nested_scope \ diff --git a/Examples/test-suite/java/naturalvar_onoff_runme.java b/Examples/test-suite/java/naturalvar_onoff_runme.java new file mode 100644 index 000000000..d9b78af24 --- /dev/null +++ b/Examples/test-suite/java/naturalvar_onoff_runme.java @@ -0,0 +1,37 @@ + +import naturalvar_onoff.*; + +public class naturalvar_onoff_runme { + static { + try { + System.loadLibrary("naturalvar_onoff"); + } 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[]) + { + boolean fail = true; + Vars vars = new Vars(); + + fail = true; try { + vars.setMember1On(null); + } catch(NullPointerException e) {fail = false;} if (fail) throw new RuntimeException("Failed"); + + vars.setMember2Off(null); + + vars.setMember3Off(null); + + fail = true; try { + vars.setMember3On(null); + } catch(NullPointerException e) {fail = false;} if (fail) throw new RuntimeException("Failed"); + + vars.setMember4Off(null); + + fail = true; try { + vars.setMember4On(null); + } catch(NullPointerException e) {fail = false;} if (fail) throw new RuntimeException("Failed"); + } +} diff --git a/Examples/test-suite/naturalvar_onoff.i b/Examples/test-suite/naturalvar_onoff.i new file mode 100644 index 000000000..3d96dd69d --- /dev/null +++ b/Examples/test-suite/naturalvar_onoff.i @@ -0,0 +1,29 @@ +%module naturalvar_onoff + +// Test naturalvar feature override is working - +// naturalvar on the variable name has priority over naturalvar on the variable's type +// Use runtime tests to differentiate between the const ref typemaps and pointer typemap - +// using the fact that NULL cannot be passed to the ref typemaps + +%naturalvar Member1; +%nonaturalvar Member2; +%naturalvar Member3; +%nonaturalvar Vars::member3Off; +%nonaturalvar Member4; +%naturalvar Vars::member4On; + +%inline %{ +struct Member1 {}; +struct Member2 {}; +struct Member3 {}; +struct Member4 {}; + +struct Vars { + Member1 member1On; + Member2 member2Off; + Member3 member3Off; + Member3 member3On; + Member4 member4Off; + Member4 member4On; +}; +%} diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index c3c148fa5..8b8382712 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -473,12 +473,21 @@ void swig_pragma(char *lang, char *name, char *value) { /* -------------------------------------------------------------------------- * Language::use_naturalvar_mode() + * + * Determine whether to use const ref typemaps instead of pointer typemaps + * for variable access. * -------------------------------------------------------------------------- */ int Language::use_naturalvar_mode(Node *n) const { if (Getattr(n, "unnamed")) return 0; - int nvar = naturalvar_mode || GetFlag(n, "feature:naturalvar"); - if (!nvar) { + + // The naturalvar feature can be attached to either the variable name or the variable's type + // naturalvar on the variable name is more specific and overrides naturalvar on the variable's type + String *naturalvar = Getattr(n, "feature:naturalvar"); + bool explicitly_off = naturalvar && Strcmp(naturalvar, "0") == 0; + int nvar = GetFlag(n, "feature:naturalvar"); + + if (!explicitly_off && !nvar) { /* look for feature in the class */ SwigType *ty = Getattr(n, "type"); SwigType *fullty = SwigType_typedef_resolve_all(ty); @@ -490,13 +499,17 @@ int Language::use_naturalvar_mode(Node *n) const { Replaceall(tys, "class ", ""); } Node *typenode = Swig_symbol_clookup(tys, 0); - if (typenode) - nvar = GetFlag(typenode, "feature:naturalvar"); + if (typenode) { + naturalvar = Getattr(typenode, "feature:naturalvar"); + explicitly_off = naturalvar && Strcmp(naturalvar, "0") == 0; + nvar = nvar || GetFlag(typenode, "feature:naturalvar"); + } Delete(tys); } Delete(fullty); } - return nvar ? CWRAP_NATURAL_VAR : 0; + nvar = nvar || naturalvar_mode; + return explicitly_off ? 0 : nvar ? CWRAP_NATURAL_VAR : 0; } /* ---------------------------------------------------------------------- From 07ce3fb746ee49e4f2ba5ff48449daa369433550 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 11 Jan 2014 13:15:44 +0000 Subject: [PATCH 283/481] Add testcase for %attributestring on shared_ptr --- Examples/test-suite/common.mk | 1 + .../li_boost_shared_ptr_attribute_runme.java | 38 +++++++++++++++ .../li_boost_shared_ptr_attribute.i | 46 +++++++++++++++++++ Lib/typemaps/attribute.swg | 5 +- 4 files changed, 89 insertions(+), 1 deletion(-) create mode 100644 Examples/test-suite/java/li_boost_shared_ptr_attribute_runme.java create mode 100644 Examples/test-suite/li_boost_shared_ptr_attribute.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 86d688799..bf88b0035 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -245,6 +245,7 @@ CPP_TEST_CASES += \ li_boost_shared_ptr \ li_boost_shared_ptr_bits \ li_boost_shared_ptr_template \ + li_boost_shared_ptr_attribute \ li_carrays \ li_cdata \ li_cpointer \ diff --git a/Examples/test-suite/java/li_boost_shared_ptr_attribute_runme.java b/Examples/test-suite/java/li_boost_shared_ptr_attribute_runme.java new file mode 100644 index 000000000..afc23eff0 --- /dev/null +++ b/Examples/test-suite/java/li_boost_shared_ptr_attribute_runme.java @@ -0,0 +1,38 @@ +import li_boost_shared_ptr_attribute.*; + +public class li_boost_shared_ptr_attribute_runme { + static { + try { + System.loadLibrary("li_boost_shared_ptr_attribute"); + } 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 check(GetSetMe g, int expected) { + int got = g.getN(); + if (got != expected) + throw new RuntimeException("GetSetMe value is " + got + " but should be " + expected); + } + + public static void check(GetMe g, int expected) { + int got = g.getN(); + if (got != expected) + throw new RuntimeException("GetMe value is " + got + " but should be " + expected); + } + + public static void main(String argv[]) + { + GetterSetter gs = new GetterSetter(5); + check(gs.getMyval(), 25); + check(gs.getAddedAttrib(), 25); + gs.setAddedAttrib(new GetSetMe(6)); + check(gs.getMyval(), 6); + check(gs.getAddedAttrib(), 6); + + GetterOnly g = new GetterOnly(4); + check(g.getMyval(), 16); + check(g.getAddedAttrib(), 16); + } +} diff --git a/Examples/test-suite/li_boost_shared_ptr_attribute.i b/Examples/test-suite/li_boost_shared_ptr_attribute.i new file mode 100644 index 000000000..c4d3dca36 --- /dev/null +++ b/Examples/test-suite/li_boost_shared_ptr_attribute.i @@ -0,0 +1,46 @@ +%module li_boost_shared_ptr_attribute + +#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGPYTHON) || defined(SWIGD) +#define SHARED_PTR_WRAPPERS_IMPLEMENTED +#endif + +#if defined(SHARED_PTR_WRAPPERS_IMPLEMENTED) + +%include "attribute.i" +%include "boost_shared_ptr.i" + +%inline %{ +#include +using namespace boost; +%} +%shared_ptr(GetMe); +%shared_ptr(GetSetMe); +%attributestring(GetterOnly, shared_ptr, AddedAttrib, GetIt) +%attributestring(GetterSetter, shared_ptr, AddedAttrib, GetIt, SetIt) + +%inline %{ +struct GetMe { + explicit GetMe(int n) : n(n) {} + ~GetMe() {} + int n; +}; +struct GetSetMe { + explicit GetSetMe(int n) : n(n) {} + ~GetSetMe() {} + int n; +}; + +struct GetterOnly { + explicit GetterOnly(int n) : myval(new GetMe(n*n)) {} + shared_ptr GetIt() const { return myval; } + shared_ptr myval; +}; +struct GetterSetter { + explicit GetterSetter(int n) : myval(new GetSetMe(n*n)) {} + shared_ptr GetIt() const { return myval; } + void SetIt(shared_ptr newval) { myval = newval; } + shared_ptr myval; +}; +%} + +#endif diff --git a/Lib/typemaps/attribute.swg b/Lib/typemaps/attribute.swg index 46fc80fd2..f06c8c0f3 100644 --- a/Lib/typemaps/attribute.swg +++ b/Lib/typemaps/attribute.swg @@ -130,6 +130,9 @@ }; %} + 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. + */ // @@ -275,7 +278,7 @@ %ignore Class::GetMethod(); %ignore Class::GetMethod() const; %newobject Class::AttributeName; - %typemap(newfree) const AttributeType &AttributeName "delete $1;// my newfree override" + %typemap(newfree) const AttributeType &AttributeName "delete $1;" %extend Class { AttributeType AttributeName; } From 5c6bc5db3e461535c3ca01cbef7422affd06d777 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 11 Jan 2014 17:27:22 +0000 Subject: [PATCH 284/481] Remove -nonaturalvar and nonaturalvar option in %module These didn't work, were not documented and don't seem necessary --- Source/Modules/lang.cxx | 3 --- Source/Modules/main.cxx | 3 --- 2 files changed, 6 deletions(-) diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 8b8382712..a547e2bd4 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -524,9 +524,6 @@ int Language::top(Node *n) { if (Getattr(options, "naturalvar")) { naturalvar_mode = 1; } - if (Getattr(options, "nonaturalvar")) { - naturalvar_mode = 0; - } } } classhash = Getattr(n, "classes"); diff --git a/Source/Modules/main.cxx b/Source/Modules/main.cxx index f3aff2349..786763441 100644 --- a/Source/Modules/main.cxx +++ b/Source/Modules/main.cxx @@ -502,9 +502,6 @@ void SWIG_getoptions(int argc, char *argv[]) { } else if (strcmp(argv[i], "-naturalvar") == 0) { Wrapper_naturalvar_mode_set(1); Swig_mark_arg(i); - } else if (strcmp(argv[i], "-nonaturalvar") == 0) { - Wrapper_naturalvar_mode_set(0); - Swig_mark_arg(i); } else if (strcmp(argv[i], "-directors") == 0) { SWIG_setfeature("feature:director", "1"); Wrapper_director_mode_set(1); From c319ad9dd6e392833e571ae134def827cb8abc1f Mon Sep 17 00:00:00 2001 From: Yann Diorcet Date: Mon, 3 Jun 2013 15:41:54 +0200 Subject: [PATCH 285/481] Resolve prefix when resolving typedef --- Source/Swig/typesys.c | 101 ++++++++++++++++++++++++------------------ 1 file changed, 58 insertions(+), 43 deletions(-) diff --git a/Source/Swig/typesys.c b/Source/Swig/typesys.c index bcfd2feb5..e11fc781a 100644 --- a/Source/Swig/typesys.c +++ b/Source/Swig/typesys.c @@ -602,7 +602,7 @@ SwigType *SwigType_typedef_resolve(const SwigType *t) { Typetab *s; Hash *ttab; String *namebase = 0; - String *nameprefix = 0; + String *nameprefix = 0, *rnameprefix = 0; int newtype = 0; resolved_scope = 0; @@ -647,51 +647,66 @@ SwigType *SwigType_typedef_resolve(const SwigType *t) { Printf(stdout, "nameprefix = '%s'\n", nameprefix); #endif if (nameprefix) { - /* Name had a prefix on it. See if we can locate the proper scope for it */ - String *rnameprefix = template_parameters_resolve(nameprefix); - nameprefix = rnameprefix ? Copy(rnameprefix) : nameprefix; - Delete(rnameprefix); - s = SwigType_find_scope(s, nameprefix); - - /* Couldn't locate a scope for the type. */ - if (!s) { - Delete(base); - Delete(namebase); - Delete(nameprefix); - r = 0; - goto return_result; - } - /* Try to locate the name starting in the scope */ + rnameprefix = SwigType_typedef_resolve(nameprefix); + if(rnameprefix != NULL) { #ifdef SWIG_DEBUG - Printf(stdout, "namebase = '%s'\n", namebase); + Printf(stdout, "nameprefix '%s' is a typedef to '%s'\n", nameprefix, rnameprefix); #endif - type = typedef_resolve(s, namebase); - if (type && resolved_scope) { - /* we need to look for the resolved type, this will also - fix the resolved_scope if 'type' and 'namebase' are - declared in different scopes */ - String *rtype = 0; - rtype = typedef_resolve(resolved_scope, type); - if (rtype) - type = rtype; - } -#ifdef SWIG_DEBUG - Printf(stdout, "%s type = '%s'\n", Getattr(s, "name"), type); -#endif - if (type && (!Swig_scopename_check(type)) && resolved_scope) { - Typetab *rtab = resolved_scope; - String *qname = Getattr(resolved_scope, "qname"); - /* If qualified *and* the typename is defined from the resolved scope, we qualify */ - if ((qname) && typedef_resolve(resolved_scope, type)) { - type = Copy(type); - Insert(type, 0, "::"); - Insert(type, 0, qname); -#ifdef SWIG_DEBUG - Printf(stdout, "qual %s \n", type); -#endif - newtype = 1; + type = Copy(namebase); + Insert(type, 0, "::"); + Insert(type, 0, rnameprefix); + if (strncmp(Char(type), "::", 2) == 0) { + Delitem(type, 0); + Delitem(type, 0); + } + newtype = 1; + } else { + /* Name had a prefix on it. See if we can locate the proper scope for it */ + String *rnameprefix = template_parameters_resolve(nameprefix); + nameprefix = rnameprefix ? Copy(rnameprefix) : nameprefix; + Delete(rnameprefix); + s = SwigType_find_scope(s, nameprefix); + + /* Couldn't locate a scope for the type. */ + if (!s) { + Delete(base); + Delete(namebase); + Delete(nameprefix); + r = 0; + goto return_result; + } + /* Try to locate the name starting in the scope */ +#ifdef SWIG_DEBUG + Printf(stdout, "namebase = '%s'\n", namebase); +#endif + type = typedef_resolve(s, namebase); + if (type && resolved_scope) { + /* we need to look for the resolved type, this will also + fix the resolved_scope if 'type' and 'namebase' are + declared in different scopes */ + String *rtype = 0; + rtype = typedef_resolve(resolved_scope, type); + if (rtype) + type = rtype; + } +#ifdef SWIG_DEBUG + Printf(stdout, "%s type = '%s'\n", Getattr(s, "name"), type); +#endif + if ((type) && (!Swig_scopename_check(type)) && resolved_scope) { + Typetab *rtab = resolved_scope; + String *qname = Getattr(resolved_scope, "qname"); + /* If qualified *and* the typename is defined from the resolved scope, we qualify */ + if ((qname) && typedef_resolve(resolved_scope, type)) { + type = Copy(type); + Insert(type, 0, "::"); + Insert(type, 0, qname); +#ifdef SWIG_DEBUG + Printf(stdout, "qual %s \n", type); +#endif + newtype = 1; + } + resolved_scope = rtab; } - resolved_scope = rtab; } } else { /* Name is unqualified. */ From 5b167cc12daf9ea275c17fedaefc975450613ab2 Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Mon, 13 Jan 2014 18:24:17 +1300 Subject: [PATCH 286/481] octave: update support to Octave version 3.8.0 --- CHANGES.current | 26 ++++++++++ Doc/Manual/Octave.html | 7 +-- Lib/octave/octrun.swg | 102 ++++++++++++++++++++++++++++++++------ Lib/octave/octruntime.swg | 14 +++--- 4 files changed, 121 insertions(+), 28 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index a4fc5dbf4..c711536ce 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,32 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2014-01-13: kwwette + [Octave] update support to Octave version 3.8.0 + + - Octave 3.8.0 no longer defines OCTAVE_API_VERSION_NUMBER, but 3.8.1 + will define OCTAVE_{MAJOR,MINOR,PATCH}_VERSION instead: see + http://hg.savannah.gnu.org/hgweb/octave/rev/b6b6e0dc700e + So we now use a new macro SWIG_OCTAVE_PREREQ(major,minor,patch) to + enable features requiring Octave version major.minor.patch or later. + + For Octave versions prior to 3.8.1, we reconstruct values for + OCTAVE_{MAJOR,MINOR,PATCH}_VERSION based on OCTAVE_API_VERSION_NUMBER, + extracted from Octave's ChangeLogs. An additional hack is needed to + distinguish between Octave <= 3.2.x and 3.8.0, neither of which define + OCTAVE_API_VERSION_NUMBER. + + - Octave 3.8.0 deprecates symbol_table::varref(), so remove its use + for this and future versions of Octave. + + - Octave 3.8.0 removes octave_value::is_real_nd_array(), used in + octave_swig_type::dims(). Its use is not required here, so remove it. + + - Retested against Octave versions 3.0.5, 3.2.4, 3.4.3, 3.6.4, and 3.8.0. + + - Updated Octave documentation with tested Octave versions, and added a + warning against using versions <= 3.x.x, which are no longer tested. + 2014-01-11: wsfulton Fix and document the naturalvar feature override behaviour - the naturalvar feature attached to a variable name has precedence over the naturalvar diff --git a/Doc/Manual/Octave.html b/Doc/Manual/Octave.html index 84c0a0f46..3e12ce668 100644 --- a/Doc/Manual/Octave.html +++ b/Doc/Manual/Octave.html @@ -59,11 +59,8 @@ Also, there are a dozen or so examples in the Examples/octave directory, and hun

      -The SWIG implemention was first based on Octave 2.9.12, so this is the minimum version required. Testing has only been done on Linux. -

      - -

      -As of SWIG 2.0.7, the Octave module has been tested with Octave versions 3.0.5, 3.2.4, 3.4.3, and 3.6.1. +As of SWIG 3.0.0, the Octave module has been tested with Octave versions 3.0.5, 3.2.4, 3.4.3, 3.6.4, and 3.8.0. +Use of Octave versions older than 3.x.x is not recommended, as these versions are no longer tested with SWIG.

      30.2 Running SWIG

      diff --git a/Lib/octave/octrun.swg b/Lib/octave/octrun.swg index 41d1c7afa..2174a0f7f 100644 --- a/Lib/octave/octrun.swg +++ b/Lib/octave/octrun.swg @@ -1,20 +1,88 @@ #include -#ifndef OCTAVE_API_VERSION_NUMBER - // Hack to distinguish between Octave 3.2 and earlier versions before OCTAVE_API_VERSION_NUMBER existed - #define ComplexLU __ignore - #include - #undef ComplexLU - #ifdef octave_Complex_LU_h - # define OCTAVE_API_VERSION_NUMBER 36 - #else - # define OCTAVE_API_VERSION_NUMBER 37 - #endif +// Macro for enabling features which require Octave version >= major.minor.patch +#define SWIG_OCTAVE_PREREQ(major, minor, patch) \ + ( (OCTAVE_MAJOR_VERSION<<16) + (OCTAVE_MINOR_VERSION<<8) + OCTAVE_PATCH_VERSION >= ((major)<<16) + ((minor)<<8) + (patch) ) -#endif +// Reconstruct Octave major, minor, and patch versions for releases prior to 3.8.1 +#if !defined(OCTAVE_MAJOR_VERSION) -#if OCTAVE_API_VERSION_NUMBER < 37 +# if !defined(OCTAVE_API_VERSION_NUMBER) + +// Hack to distinguish between Octave 3.8.0, which removed OCTAVE_API_VERSION_NUMBER but did not yet +// introduce OCTAVE_MAJOR_VERSION, and Octave <= 3.2, which did not define OCTAVE_API_VERSION_NUMBER +# include +# if defined(octave_ov_h) +# define OCTAVE_MAJOR_VERSION 3 +# define OCTAVE_MINOR_VERSION 8 +# define OCTAVE_PATCH_VERSION 0 +# else + +// Hack to distinguish between Octave 3.2 and earlier versions, before OCTAVE_API_VERSION_NUMBER existed +# define ComplexLU __ignore +# include +# undef ComplexLU +# if defined(octave_Complex_LU_h) + +// We know only that this version is prior to Octave 3.2, i.e. OCTAVE_API_VERSION_NUMBER < 37 +# define OCTAVE_MAJOR_VERSION 3 +# define OCTAVE_MINOR_VERSION 1 +# define OCTAVE_PATCH_VERSION 99 + +# else + +// OCTAVE_API_VERSION_NUMBER == 37 +# define OCTAVE_MAJOR_VERSION 3 +# define OCTAVE_MINOR_VERSION 2 +# define OCTAVE_PATCH_VERSION 0 + +# endif // defined(octave_Complex_LU_h) + +# endif // defined(octave_ov_h) + +// Correlation between Octave API and version numbers extracted from Octave's +// ChangeLogs; version is the *earliest* released Octave with that API number +# elif OCTAVE_API_VERSION_NUMBER >= 48 +# define OCTAVE_MAJOR_VERSION 3 +# define OCTAVE_MINOR_VERSION 6 +# define OCTAVE_PATCH_VERSION 0 + +# elif OCTAVE_API_VERSION_NUMBER >= 45 +# define OCTAVE_MAJOR_VERSION 3 +# define OCTAVE_MINOR_VERSION 4 +# define OCTAVE_PATCH_VERSION 1 + +# elif OCTAVE_API_VERSION_NUMBER >= 42 +# define OCTAVE_MAJOR_VERSION 3 +# define OCTAVE_MINOR_VERSION 3 +# define OCTAVE_PATCH_VERSION 54 + +# elif OCTAVE_API_VERSION_NUMBER >= 41 +# define OCTAVE_MAJOR_VERSION 3 +# define OCTAVE_MINOR_VERSION 3 +# define OCTAVE_PATCH_VERSION 53 + +# elif OCTAVE_API_VERSION_NUMBER >= 40 +# define OCTAVE_MAJOR_VERSION 3 +# define OCTAVE_MINOR_VERSION 3 +# define OCTAVE_PATCH_VERSION 52 + +# elif OCTAVE_API_VERSION_NUMBER >= 39 +# define OCTAVE_MAJOR_VERSION 3 +# define OCTAVE_MINOR_VERSION 3 +# define OCTAVE_PATCH_VERSION 51 + +# else // OCTAVE_API_VERSION_NUMBER == 38 +# define OCTAVE_MAJOR_VERSION 3 +# define OCTAVE_MINOR_VERSION 3 +# define OCTAVE_PATCH_VERSION 50 + +# endif // !defined(OCTAVE_API_VERSION_NUMBER) + +#endif // !defined(OCTAVE_MAJOR_VERSION) + +#if !SWIG_OCTAVE_PREREQ(3,2,0) #define SWIG_DEFUN(cname, wname, doc) DEFUNX_DLD(#cname, wname, FS ## cname, args, nargout, doc) #else #define SWIG_DEFUN(cname, wname, doc) DEFUNX_DLD(#cname, wname, G ## cname, args, nargout, doc) @@ -427,7 +495,7 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); if (error_state) return dim_vector(1,1); } return d; - } else if (out.is_matrix_type() || out.is_real_nd_array() || out.is_numeric_type() ) { + } else if (out.is_matrix_type() || out.is_numeric_type() ) { if (out.rows()==1 || out.columns()==1) { Array a = out.int_vector_value(); if (error_state) return dim_vector(1,1); @@ -746,7 +814,7 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); return outarg(0).string_value(); } -#if OCTAVE_API_VERSION_NUMBER >= 40 +#if SWIG_OCTAVE_PREREQ(3,3,52) virtual octave_map map_value() const { return octave_map(); } @@ -982,7 +1050,7 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); virtual std::string string_value(bool force = false) const { return ptr->string_value(force); } -#if OCTAVE_API_VERSION_NUMBER >= 40 +#if SWIG_OCTAVE_PREREQ(3,3,52) virtual octave_map map_value() const { return ptr->map_value(); } #else @@ -1293,10 +1361,12 @@ SWIGRUNTIME void SWIG_Octave_SetGlobalValue(std::string name, const octave_value } SWIGRUNTIME void SWIG_Octave_LinkGlobalValue(std::string name) { -#if OCTAVE_API_VERSION_NUMBER < 37 +#if !SWIG_OCTAVE_PREREQ(3,2,0) link_to_global_variable(curr_sym_tab->lookup(name, true)); #else +#if !SWIG_OCTAVE_PREREQ(3,8,0) symbol_table::varref(name); +#endif symbol_table::mark_global(name); #endif } diff --git a/Lib/octave/octruntime.swg b/Lib/octave/octruntime.swg index 43313c3d4..fbf2007f6 100644 --- a/Lib/octave/octruntime.swg +++ b/Lib/octave/octruntime.swg @@ -25,7 +25,7 @@ static bool SWIG_init_user(octave_swig_type* module_ns); SWIGINTERN bool SWIG_Octave_LoadModule(std::string name) { bool retn; { -#if OCTAVE_API_VERSION_NUMBER < 38 +#if !SWIG_OCTAVE_PREREQ(3,3,50) unwind_protect::begin_frame("SWIG_Octave_LoadModule"); unwind_protect_int(error_state); unwind_protect_int(warning_state); @@ -44,7 +44,7 @@ SWIGINTERN bool SWIG_Octave_LoadModule(std::string name) { discard_warning_messages = true; feval(name, octave_value_list(), 0); retn = (error_state == 0); -#if OCTAVE_API_VERSION_NUMBER < 38 +#if !SWIG_OCTAVE_PREREQ(3,3,50) unwind_protect::run_frame("SWIG_Octave_LoadModule"); #endif } @@ -57,7 +57,7 @@ SWIGINTERN bool SWIG_Octave_LoadModule(std::string name) { SWIGINTERN bool SWIG_Octave_InstallFunction(octave_function *octloadfcn, std::string name) { bool retn; { -#if OCTAVE_API_VERSION_NUMBER < 38 +#if !SWIG_OCTAVE_PREREQ(3,3,50) unwind_protect::begin_frame("SWIG_Octave_InstallFunction"); unwind_protect_int(error_state); unwind_protect_int(warning_state); @@ -80,7 +80,7 @@ SWIGINTERN bool SWIG_Octave_InstallFunction(octave_function *octloadfcn, std::st error_state = 0; feval("autoload", args, 0); retn = (error_state == 0); -#if OCTAVE_API_VERSION_NUMBER < 38 +#if !SWIG_OCTAVE_PREREQ(3,3,50) unwind_protect::run_frame("SWIG_Octave_InstallFunction"); #endif } @@ -196,7 +196,7 @@ DEFUN_DLD( SWIG_name, args, nargout, SWIG_name_usage ) { // definitely affects version 3.2.*, not sure about 3.3.*, seems to be fixed in // version 3.4.* and above. can be turned off with macro definition. #ifndef SWIG_OCTAVE_NO_SEGFAULT_HACK -#if 36 < OCTAVE_API_VERSION_NUMBER && OCTAVE_API_VERSION_NUMBER < 45 +#if SWIG_OCTAVE_PREREQ(3,2,0) && !SWIG_OCTAVE_PREREQ(3,4,1) octave_exit = ::_Exit; #endif #endif @@ -212,7 +212,7 @@ DEFUN_DLD( SWIG_name, args, nargout, SWIG_name_usage ) { // workaround bug in octave where installing global variable of custom type and then // exiting without explicitly clearing the variable causes octave to segfault. -#if OCTAVE_API_VERSION_NUMBER > 36 +#if SWIG_OCTAVE_PREREQ(3,2,0) octave_value_list eval_args; eval_args.append("base"); eval_args.append("function __swig_atexit__; " @@ -297,7 +297,7 @@ DEFUN_DLD( SWIG_name, args, nargout, SWIG_name_usage ) { } } -#if OCTAVE_API_VERSION_NUMBER < 37 +#if !SWIG_OCTAVE_PREREQ(3,2,0) mlock(me->name()); #else mlock(); From 2f47bb8d6756f9f4d440d1bcc0a639ed8169c0ab Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 13 Jan 2014 19:46:48 +0000 Subject: [PATCH 287/481] Typedef typedef prefix test for templates As given in Diorcet Yann's example in issue #50 --- Examples/test-suite/common.mk | 1 + .../java/template_typedef_typedef_runme.java | 26 +++++++++++ .../test-suite/template_typedef_typedef.i | 43 +++++++++++++++++++ 3 files changed, 70 insertions(+) create mode 100644 Examples/test-suite/java/template_typedef_typedef_runme.java create mode 100644 Examples/test-suite/template_typedef_typedef.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index bf88b0035..fa46b9ff7 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -424,6 +424,7 @@ CPP_TEST_CASES += \ template_typedef_ns \ template_typedef_ptr \ template_typedef_rec \ + template_typedef_typedef \ template_typemaps \ template_typemaps_typedef \ template_typemaps_typedef2 \ diff --git a/Examples/test-suite/java/template_typedef_typedef_runme.java b/Examples/test-suite/java/template_typedef_typedef_runme.java new file mode 100644 index 000000000..f5f368561 --- /dev/null +++ b/Examples/test-suite/java/template_typedef_typedef_runme.java @@ -0,0 +1,26 @@ +import template_typedef_typedef.*; + +public class template_typedef_typedef_runme { + + static { + try { + System.loadLibrary("template_typedef_typedef"); + } 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[]) { + ObjectBase ob1 = new ObjectBase(); + ob1.getBlabla1(new ObjectBase()); + Object2Base ob2 = new Object2Base(); + ob2.getBlabla2(new Object2Base()); + + Factory factory = new Factory(); + factory.getBlabla3(new ObjectBase()); + factory.getBlabla4(new Object2Base()); + } +} + + diff --git a/Examples/test-suite/template_typedef_typedef.i b/Examples/test-suite/template_typedef_typedef.i new file mode 100644 index 000000000..30077c484 --- /dev/null +++ b/Examples/test-suite/template_typedef_typedef.i @@ -0,0 +1,43 @@ +%module template_typedef_typedef + +// Github issue #50 +// The Object2::getBlabla2 and Object::getBlabla1 functions were not resolving to the correct template types + +%inline%{ + +class Factory; +class Base { +public: + typedef Factory ABCD; + +}; + +namespace TT{ + template + class Object2:public T { + public: + void getBlabla2(typename T::ABCD::CC2 c) { + }; + }; + template + class Object:public T { + public: + void getBlabla1(typename T::ABCD::CC1 c) { + }; + }; +} + +class Factory { + public: + typedef TT::Object CC1; + typedef TT::Object2 CC2; + void getBlabla4(CC2 c) { + }; + void getBlabla3(CC1 c) { + }; +}; +%} + +%template(ObjectBase) TT::Object; +%template(Object2Base) TT::Object2; + From 2e186244d6ebf1867b4051519c2a5cae6fdd4433 Mon Sep 17 00:00:00 2001 From: Yann Diorcet Date: Fri, 19 Jul 2013 16:23:06 +0200 Subject: [PATCH 288/481] Add test for checking prefix resolving in typedef --- Examples/test-suite/common.mk | 1 + .../python/typedef_typedef_runme.py | 5 +++ Examples/test-suite/typedef_typedef.i | 39 +++++++++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 Examples/test-suite/python/typedef_typedef_runme.py create mode 100644 Examples/test-suite/typedef_typedef.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index fa46b9ff7..6d1d2a25b 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -443,6 +443,7 @@ CPP_TEST_CASES += \ typedef_scope \ typedef_sizet \ typedef_struct \ + typedef_typedef \ typemap_arrays \ typemap_array_qualifiers \ typemap_delete \ diff --git a/Examples/test-suite/python/typedef_typedef_runme.py b/Examples/test-suite/python/typedef_typedef_runme.py new file mode 100644 index 000000000..ac61dd163 --- /dev/null +++ b/Examples/test-suite/python/typedef_typedef_runme.py @@ -0,0 +1,5 @@ +import typedef_typedef + +b = typedef_typedef.B() +if b.getValue() == 0: + print "Failed !!!" diff --git a/Examples/test-suite/typedef_typedef.i b/Examples/test-suite/typedef_typedef.i new file mode 100644 index 000000000..bb309cb20 --- /dev/null +++ b/Examples/test-suite/typedef_typedef.i @@ -0,0 +1,39 @@ +%module typedef_typedef + +/* + + We want a specific behaviour on a Type + +*/ + +%typemap(out) A::Foo { + $result = PyInt_FromLong($1 + 1); +} + +%inline %{ + struct A + { + typedef int Foo; + }; + + struct C + { + typedef A Bar; + }; + + struct B + { + C::Bar::Foo getValue() { + return 0; + } + }; +%} + +/* + + An issue can be the steps resolution. + 1) C::Bar is A. So C::Bar::Foo should be first resolved as A::Foo. + 2) Then A::Foo should be resolved int. + If the first step is skipped the typemap is not applied. + +*/ From e531578c540c951dd4b4f9ca7e002acdf83148d9 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 13 Jan 2014 18:42:04 +0000 Subject: [PATCH 289/481] Modify typedef_typedef testcase to work for all languages Add CHANGES note Closes #112. --- CHANGES.current | 4 ++++ .../test-suite/python/typedef_typedef_runme.py | 2 +- Examples/test-suite/typedef_typedef.i | 14 ++++++-------- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index a4fc5dbf4..be3a32a6f 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,10 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2014-01-14: diorcety + Patch #112 - Fix symbol resolution involving scopes that have multiple levels + of typedefs - fixes some template resolutions as well as some typemap searches. + 2014-01-11: wsfulton Fix and document the naturalvar feature override behaviour - the naturalvar feature attached to a variable name has precedence over the naturalvar diff --git a/Examples/test-suite/python/typedef_typedef_runme.py b/Examples/test-suite/python/typedef_typedef_runme.py index ac61dd163..51a823def 100644 --- a/Examples/test-suite/python/typedef_typedef_runme.py +++ b/Examples/test-suite/python/typedef_typedef_runme.py @@ -1,5 +1,5 @@ import typedef_typedef b = typedef_typedef.B() -if b.getValue() == 0: +if b.getValue(123) == 1234: print "Failed !!!" diff --git a/Examples/test-suite/typedef_typedef.i b/Examples/test-suite/typedef_typedef.i index bb309cb20..9bfa14a23 100644 --- a/Examples/test-suite/typedef_typedef.i +++ b/Examples/test-suite/typedef_typedef.i @@ -1,13 +1,11 @@ %module typedef_typedef -/* +// Check C::Bar::Foo resolves to A::Foo in typemap search - We want a specific behaviour on a Type +%typemap(in) SWIGTYPE, int "__wrong_in_typemap__will_not_compile__" -*/ - -%typemap(out) A::Foo { - $result = PyInt_FromLong($1 + 1); +%typemap(in) A::Foo { + $1 = 1234; /* A::Foo in typemap */ } %inline %{ @@ -23,8 +21,8 @@ struct B { - C::Bar::Foo getValue() { - return 0; + C::Bar::Foo getValue(C::Bar::Foo intvalue) { + return intvalue; } }; %} From f068be89e50bc35d8a7684c04cc64ac4dd96695c Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 16 Jan 2014 06:42:34 +0000 Subject: [PATCH 290/481] Fix PHP compilation error in ZTS mode (64 bit windows) due to TSRMLS_FETCH() expansion --- CHANGES.current | 4 ++++ Lib/php/phprun.swg | 3 +-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index 5aa45704f..5dd602f35 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,10 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2014-01-16: wsfulton + [PHP] Fix compilation error in ZTS mode (64 bit windows) due to incorrect placement + of TSRMLS_FETCH() in SWIG_Php_GetModule() as reported by Mark Dawson-Butterworth. + 2014-01-14: diorcety Patch #112 - Fix symbol resolution involving scopes that have multiple levels of typedefs - fixes some template resolutions as well as some typemap searches. diff --git a/Lib/php/phprun.swg b/Lib/php/phprun.swg index a4188cc7c..063b84227 100644 --- a/Lib/php/phprun.swg +++ b/Lib/php/phprun.swg @@ -255,11 +255,10 @@ static char const_name[] = "swig_runtime_data_type_pointer"; static swig_module_info *SWIG_Php_GetModule(void *SWIGUNUSEDPARM(clientdata)) { zval *pointer; swig_module_info *ret = 0; + TSRMLS_FETCH(); MAKE_STD_ZVAL(pointer); - TSRMLS_FETCH(); - if (zend_get_constant(const_name, sizeof(const_name) - 1, pointer TSRMLS_CC)) { if (pointer->type == IS_LONG) { ret = (swig_module_info *) pointer->value.lval; From 9d003ab362a0501c3130583d0f6dcfac21e1a623 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 16 Jan 2014 19:30:48 +0000 Subject: [PATCH 291/481] Update errors expected results --- Examples/test-suite/errors/expected.log | 1 + 1 file changed, 1 insertion(+) diff --git a/Examples/test-suite/errors/expected.log b/Examples/test-suite/errors/expected.log index 5fb0e715f..da0d59778 100644 --- a/Examples/test-suite/errors/expected.log +++ b/Examples/test-suite/errors/expected.log @@ -323,6 +323,7 @@ cpp_namespace_aliasundef.i:3: Error: Unknown namespace 'blah' :::::::::::::::::::::::::::::::: cpp_nested_template.i ::::::::::::::::::::::::::::::::::: cpp_nested_template.i:9: Warning 324: Named nested template instantiations not supported. Processing as if no name was given to %template(). +cpp_nested_template.i:18: Warning 324: Named nested template instantiations not supported. Processing as if no name was given to %template(). :::::::::::::::::::::::::::::::: cpp_no_access.i ::::::::::::::::::::::::::::::::::: cpp_no_access.i:3: Warning 319: No access specifier given for base class 'foo' (ignored). From 3055a21505b6258fb9e6fc64dae16f99aa1cfff4 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 18 Jan 2014 21:35:35 +0000 Subject: [PATCH 292/481] Errors test-suite overhaul Use makefiles instead of a make.sh script Expected results are in individual .stderr files instead of the expected.log file Add errors test-suite to Travis testing and 'make check' --- .travis.yml | 3 +- Doc/Manual/Extending.html | 6 + Examples/test-suite/common.mk | 17 +- Examples/test-suite/errors/Makefile.in | 51 +++ Examples/test-suite/errors/c_bad_name.stderr | 2 + .../test-suite/errors/c_bad_native.stderr | 1 + Examples/test-suite/errors/c_class.stderr | 2 + .../test-suite/errors/c_default_error.stderr | 0 .../test-suite/errors/c_deprecated.stderr | 2 + .../test-suite/errors/c_empty_char.stderr | 1 + .../test-suite/errors/c_enum_badvalue.stderr | 1 + .../test-suite/errors/c_extra_rblock.stderr | 1 + .../test-suite/errors/c_extra_rbrace.stderr | 1 + .../test-suite/errors/c_extra_unsigned.stderr | 3 + .../test-suite/errors/c_insert_missing.stderr | 1 + .../test-suite/errors/c_long_short.stderr | 4 + .../test-suite/errors/c_missing_rbrace.stderr | 2 + .../test-suite/errors/c_missing_semi.stderr | 1 + Examples/test-suite/errors/c_redefine.stderr | 6 + Examples/test-suite/errors/c_varargs.stderr | 0 .../test-suite/errors/c_varargs_neg.stderr | 1 + .../test-suite/errors/cpp_bad_extern.stderr | 2 + .../errors/cpp_extend_destructors.stderr | 19 + .../errors/cpp_extend_redefine.stderr | 4 + .../errors/cpp_extend_undefined.stderr | 1 + Examples/test-suite/errors/cpp_inherit.stderr | 20 + .../errors/cpp_inline_namespace.stderr | 1 + .../errors/cpp_macro_locator.stderr | 20 + .../errors/cpp_missing_rparenthesis.stderr | 2 + .../errors/cpp_missing_rtemplate.stderr | 1 + .../errors/cpp_namespace_alias.stderr | 1 + .../errors/cpp_namespace_aliasnot.stderr | 1 + .../errors/cpp_namespace_aliasundef.stderr | 1 + .../errors/cpp_nested_template.stderr | 2 + .../test-suite/errors/cpp_no_access.stderr | 1 + .../errors/cpp_no_return_type.stderr | 2 + Examples/test-suite/errors/cpp_nobase.stderr | 3 + .../test-suite/errors/cpp_overload.stderr | 0 .../errors/cpp_overload_const.stderr | 10 + .../errors/cpp_private_defvalue.stderr | 0 .../errors/cpp_private_inherit.stderr | 2 + .../errors/cpp_recursive_typedef.stderr | 1 + .../test-suite/errors/cpp_shared_ptr.stderr | 3 + .../errors/cpp_template_argname.stderr | 0 .../errors/cpp_template_nargs.stderr | 2 + .../test-suite/errors/cpp_template_not.stderr | 1 + .../errors/cpp_template_partial.stderr | 1 + .../errors/cpp_template_repeat.stderr | 0 .../errors/cpp_template_undef.stderr | 1 + .../test-suite/errors/cpp_using_not.stderr | 1 + .../test-suite/errors/cpp_using_undef.stderr | 2 + Examples/test-suite/errors/expected.log | 390 ------------------ Examples/test-suite/errors/make.sh | 124 ------ Examples/test-suite/errors/nomodule.stderr | 1 + Examples/test-suite/errors/pp_badeval.stderr | 2 + Examples/test-suite/errors/pp_constant.stderr | 8 + Examples/test-suite/errors/pp_defined.stderr | 2 + .../test-suite/errors/pp_deprecated.stderr | 4 + .../errors/pp_illegal_argument.stderr | 3 + .../test-suite/errors/pp_macro_args.stderr | 0 .../test-suite/errors/pp_macro_badchar.stderr | 1 + .../pp_macro_defined_unterminated.stderr | 1 + .../errors/pp_macro_expansion.stderr | 1 + .../pp_macro_expansion_multiline.stderr | 4 + .../pp_macro_inline_unterminated.stderr | 2 + .../errors/pp_macro_missing_expression.stderr | 5 + .../test-suite/errors/pp_macro_nargs.stderr | 4 + .../test-suite/errors/pp_macro_redef.stderr | 4 + .../test-suite/errors/pp_macro_rparen.stderr | 1 + .../errors/pp_macro_unexpected_tokens.stderr | 5 + .../errors/pp_macro_unterminated.stderr | 1 + .../errors/pp_misplaced_elif.stderr | 2 + .../errors/pp_misplaced_else.stderr | 2 + .../errors/pp_missing_enddef.stderr | 1 + .../test-suite/errors/pp_missing_endif.stderr | 1 + .../test-suite/errors/pp_missing_file.stderr | 1 + .../errors/pp_missing_rblock.stderr | 1 + Examples/test-suite/errors/pp_pragma.stderr | 1 + .../test-suite/errors/pp_unterm_char.stderr | 1 + .../errors/pp_unterm_comment.stderr | 1 + .../test-suite/errors/pp_unterm_string.stderr | 1 + .../test-suite/errors/pp_variable_args.stderr | 1 + .../test-suite/errors/swig_apply_nargs.stderr | 1 + Examples/test-suite/errors/swig_extend.stderr | 8 + .../test-suite/errors/swig_identifier.stderr | 1 + .../test-suite/errors/swig_insert_bad.stderr | 1 + .../errors/swig_typemap_copy.stderr | 1 + .../test-suite/errors/swig_typemap_old.stderr | 6 + .../errors/swig_typemap_warn.stderr | 7 + Makefile.in | 4 + configure.ac | 1 + 91 files changed, 298 insertions(+), 519 deletions(-) create mode 100644 Examples/test-suite/errors/Makefile.in create mode 100644 Examples/test-suite/errors/c_bad_name.stderr create mode 100644 Examples/test-suite/errors/c_bad_native.stderr create mode 100644 Examples/test-suite/errors/c_class.stderr create mode 100644 Examples/test-suite/errors/c_default_error.stderr create mode 100644 Examples/test-suite/errors/c_deprecated.stderr create mode 100644 Examples/test-suite/errors/c_empty_char.stderr create mode 100644 Examples/test-suite/errors/c_enum_badvalue.stderr create mode 100644 Examples/test-suite/errors/c_extra_rblock.stderr create mode 100644 Examples/test-suite/errors/c_extra_rbrace.stderr create mode 100644 Examples/test-suite/errors/c_extra_unsigned.stderr create mode 100644 Examples/test-suite/errors/c_insert_missing.stderr create mode 100644 Examples/test-suite/errors/c_long_short.stderr create mode 100644 Examples/test-suite/errors/c_missing_rbrace.stderr create mode 100644 Examples/test-suite/errors/c_missing_semi.stderr create mode 100644 Examples/test-suite/errors/c_redefine.stderr create mode 100644 Examples/test-suite/errors/c_varargs.stderr create mode 100644 Examples/test-suite/errors/c_varargs_neg.stderr create mode 100644 Examples/test-suite/errors/cpp_bad_extern.stderr create mode 100644 Examples/test-suite/errors/cpp_extend_destructors.stderr create mode 100644 Examples/test-suite/errors/cpp_extend_redefine.stderr create mode 100644 Examples/test-suite/errors/cpp_extend_undefined.stderr create mode 100644 Examples/test-suite/errors/cpp_inherit.stderr create mode 100644 Examples/test-suite/errors/cpp_inline_namespace.stderr create mode 100644 Examples/test-suite/errors/cpp_macro_locator.stderr create mode 100644 Examples/test-suite/errors/cpp_missing_rparenthesis.stderr create mode 100644 Examples/test-suite/errors/cpp_missing_rtemplate.stderr create mode 100644 Examples/test-suite/errors/cpp_namespace_alias.stderr create mode 100644 Examples/test-suite/errors/cpp_namespace_aliasnot.stderr create mode 100644 Examples/test-suite/errors/cpp_namespace_aliasundef.stderr create mode 100644 Examples/test-suite/errors/cpp_nested_template.stderr create mode 100644 Examples/test-suite/errors/cpp_no_access.stderr create mode 100644 Examples/test-suite/errors/cpp_no_return_type.stderr create mode 100644 Examples/test-suite/errors/cpp_nobase.stderr create mode 100644 Examples/test-suite/errors/cpp_overload.stderr create mode 100644 Examples/test-suite/errors/cpp_overload_const.stderr create mode 100644 Examples/test-suite/errors/cpp_private_defvalue.stderr create mode 100644 Examples/test-suite/errors/cpp_private_inherit.stderr create mode 100644 Examples/test-suite/errors/cpp_recursive_typedef.stderr create mode 100644 Examples/test-suite/errors/cpp_shared_ptr.stderr create mode 100644 Examples/test-suite/errors/cpp_template_argname.stderr create mode 100644 Examples/test-suite/errors/cpp_template_nargs.stderr create mode 100644 Examples/test-suite/errors/cpp_template_not.stderr create mode 100644 Examples/test-suite/errors/cpp_template_partial.stderr create mode 100644 Examples/test-suite/errors/cpp_template_repeat.stderr create mode 100644 Examples/test-suite/errors/cpp_template_undef.stderr create mode 100644 Examples/test-suite/errors/cpp_using_not.stderr create mode 100644 Examples/test-suite/errors/cpp_using_undef.stderr delete mode 100644 Examples/test-suite/errors/expected.log delete mode 100755 Examples/test-suite/errors/make.sh create mode 100644 Examples/test-suite/errors/nomodule.stderr create mode 100644 Examples/test-suite/errors/pp_badeval.stderr create mode 100644 Examples/test-suite/errors/pp_constant.stderr create mode 100644 Examples/test-suite/errors/pp_defined.stderr create mode 100644 Examples/test-suite/errors/pp_deprecated.stderr create mode 100644 Examples/test-suite/errors/pp_illegal_argument.stderr create mode 100644 Examples/test-suite/errors/pp_macro_args.stderr create mode 100644 Examples/test-suite/errors/pp_macro_badchar.stderr create mode 100644 Examples/test-suite/errors/pp_macro_defined_unterminated.stderr create mode 100644 Examples/test-suite/errors/pp_macro_expansion.stderr create mode 100644 Examples/test-suite/errors/pp_macro_expansion_multiline.stderr create mode 100644 Examples/test-suite/errors/pp_macro_inline_unterminated.stderr create mode 100644 Examples/test-suite/errors/pp_macro_missing_expression.stderr create mode 100644 Examples/test-suite/errors/pp_macro_nargs.stderr create mode 100644 Examples/test-suite/errors/pp_macro_redef.stderr create mode 100644 Examples/test-suite/errors/pp_macro_rparen.stderr create mode 100644 Examples/test-suite/errors/pp_macro_unexpected_tokens.stderr create mode 100644 Examples/test-suite/errors/pp_macro_unterminated.stderr create mode 100644 Examples/test-suite/errors/pp_misplaced_elif.stderr create mode 100644 Examples/test-suite/errors/pp_misplaced_else.stderr create mode 100644 Examples/test-suite/errors/pp_missing_enddef.stderr create mode 100644 Examples/test-suite/errors/pp_missing_endif.stderr create mode 100644 Examples/test-suite/errors/pp_missing_file.stderr create mode 100644 Examples/test-suite/errors/pp_missing_rblock.stderr create mode 100644 Examples/test-suite/errors/pp_pragma.stderr create mode 100644 Examples/test-suite/errors/pp_unterm_char.stderr create mode 100644 Examples/test-suite/errors/pp_unterm_comment.stderr create mode 100644 Examples/test-suite/errors/pp_unterm_string.stderr create mode 100644 Examples/test-suite/errors/pp_variable_args.stderr create mode 100644 Examples/test-suite/errors/swig_apply_nargs.stderr create mode 100644 Examples/test-suite/errors/swig_extend.stderr create mode 100644 Examples/test-suite/errors/swig_identifier.stderr create mode 100644 Examples/test-suite/errors/swig_insert_bad.stderr create mode 100644 Examples/test-suite/errors/swig_typemap_copy.stderr create mode 100644 Examples/test-suite/errors/swig_typemap_old.stderr create mode 100644 Examples/test-suite/errors/swig_typemap_warn.stderr diff --git a/.travis.yml b/.travis.yml index 70cbb2f27..ad771df9c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -49,8 +49,9 @@ before_install: script: - ./autogen.sh && ./configure - make -s $SWIGJOBS - - if test -z "$SWIGLANG"; then make -s check-ccache; fi - ./swig -version + - if test -z "$SWIGLANG"; then make -s $SWIGJOBS check-ccache; fi + - if test -z "$SWIGLANG"; then make -s $SWIGJOBS check-errors-test-suite; fi - if test -n "$SWIGLANG"; then make -s check-$SWIGLANG-version; fi - if test -n "$SWIGLANG"; then make -k $SWIGJOBS check-$SWIGLANG-examples; fi - if test -n "$SWIGLANG"; then make -k $SWIGJOBS check-$SWIGLANG-test-suite; fi diff --git a/Doc/Manual/Extending.html b/Doc/Manual/Extending.html index 5ea4e51f4..1fc65d0e1 100644 --- a/Doc/Manual/Extending.html +++ b/Doc/Manual/Extending.html @@ -3496,6 +3496,12 @@ The syntax for setting environment variables varies from one shell to the next, make ret_by_value.ctest SWIG_FEATURES="-debug-tmsearch"
      +

      +There is also a special 'errors' test-suite which is a set of regression tests checking SWIG warning and error messages. +It can be run in the same way as the other language test-suites, replacing [lang] with errors, such as make check-errors-test-suite. +The test cases used and the way it works is described in Examples/test-suite/errors/Makefile.in. +

      +

      38.10.13 Documentation

      diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 6d1d2a25b..dc18852f7 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -639,12 +639,21 @@ ALL_CLEAN = $(CPP_TEST_CASES:=.clean) \ $(CPP_TEST_BROKEN:=.clean) \ $(C_TEST_BROKEN:=.clean) +####################################################################### +# Error test suite has its own set of test cases +####################################################################### +ifneq (,$(ERROR_TEST_CASES)) +check: $(ERROR_TEST_CASES) +else + ####################################################################### # The following applies for all module languages ####################################################################### -all: $(NOT_BROKEN_TEST_CASES) $(BROKEN_TEST_CASES) +all: $(NOT_BROKEN_TEST_CASES) $(BROKEN_TEST_CASES) -check: $(NOT_BROKEN_TEST_CASES) +broken: $(BROKEN_TEST_CASES) + +check: $(NOT_BROKEN_TEST_CASES) check-c: $(C_TEST_CASES:=.ctest) @@ -652,12 +661,12 @@ check-cpp: $(CPP_TEST_CASES:=.cpptest) check-cpp11: $(CPP11_TEST_CASES:=.cpptest) +endif + # partialcheck target runs SWIG only, ie no compilation or running of tests (for a subset of languages) partialcheck: $(MAKE) check CC=true CXX=true LDSHARED=true CXXSHARED=true RUNTOOL=true COMPILETOOL=true -broken: $(BROKEN_TEST_CASES) - swig_and_compile_cpp = \ $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile CXXSRCS="$(CXXSRCS)" \ SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" \ diff --git a/Examples/test-suite/errors/Makefile.in b/Examples/test-suite/errors/Makefile.in new file mode 100644 index 000000000..cbfe1c29e --- /dev/null +++ b/Examples/test-suite/errors/Makefile.in @@ -0,0 +1,51 @@ +####################################################################### +# Makefile for errors test-suite +# +# This test-suite is for checking SWIG errors and warnings and uses +# Python as the target language. +# +# It compares the stderr output from SWIG to the contents of the .stderr +# file for each test case. The test cases are different to those used by +# the language module test-suites. The .i files in this directory are +# used instead of those in the parent directory. +# +# When adding a new test case, be sure to commit the expected output +# file (.stderr) in addition to the test case itself. +####################################################################### + +LANGUAGE = python +ERROR_EXT = newerr + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ + +# All .i files with prefix 'cpp_' will be treated as C++ input and remaining .i files as C input +ALL_ERROR_TEST_CASES := $(patsubst %.i,%, $(wildcard *.i)) +CPP_ERROR_TEST_CASES := $(filter cpp_%, $(ALL_ERROR_TEST_CASES)) +C_ERROR_TEST_CASES := $(filter-out $(CPP_ERROR_TEST_CASES), $(ALL_ERROR_TEST_CASES)) + +ERROR_TEST_CASES := $(CPP_ERROR_TEST_CASES:=.cpptest) \ + $(C_ERROR_TEST_CASES:=.ctest) + +include $(srcdir)/../common.mk + + +# Rules for the different types of tests +%.cpptest: + echo "$(ACTION)ing errors testcase $*" + -$(SWIG) -c++ -python -Wall $(SWIGOPT) $*.i 2> $*.$(ERROR_EXT) + $(COMPILETOOL) diff $*.stderr $*.newerr + +%.ctest: + echo "$(ACTION)ing errors testcase $*" + -$(SWIG) -python -Wall $(SWIGOPT) $*.i 2> $*.$(ERROR_EXT) + $(COMPILETOOL) diff $*.stderr $*.newerr + +%.clean: + + +clean: + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile $(LANGUAGE)_clean + @rm -f *.newerr *.py + diff --git a/Examples/test-suite/errors/c_bad_name.stderr b/Examples/test-suite/errors/c_bad_name.stderr new file mode 100644 index 000000000..6c1f706a3 --- /dev/null +++ b/Examples/test-suite/errors/c_bad_name.stderr @@ -0,0 +1,2 @@ +c_bad_name.i:3: Warning 121: %name is deprecated. Use %rename instead. +c_bad_name.i:3: Error: Missing argument to %name directive. diff --git a/Examples/test-suite/errors/c_bad_native.stderr b/Examples/test-suite/errors/c_bad_native.stderr new file mode 100644 index 000000000..dd255dfc6 --- /dev/null +++ b/Examples/test-suite/errors/c_bad_native.stderr @@ -0,0 +1 @@ +c_bad_native.i:3: Error: %native declaration 'foo' is not a function. diff --git a/Examples/test-suite/errors/c_class.stderr b/Examples/test-suite/errors/c_class.stderr new file mode 100644 index 000000000..306e144e5 --- /dev/null +++ b/Examples/test-suite/errors/c_class.stderr @@ -0,0 +1,2 @@ +c_class.i:3: Warning 301: class keyword used, but not in C++ mode. +c_class.i:3: Warning 314: 'class' is a python keyword, renaming to '_class' diff --git a/Examples/test-suite/errors/c_default_error.stderr b/Examples/test-suite/errors/c_default_error.stderr new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/test-suite/errors/c_deprecated.stderr b/Examples/test-suite/errors/c_deprecated.stderr new file mode 100644 index 000000000..9e77c9ab2 --- /dev/null +++ b/Examples/test-suite/errors/c_deprecated.stderr @@ -0,0 +1,2 @@ +c_deprecated.i:3: Warning 102: %val directive deprecated (ignored). +c_deprecated.i:3: Warning 103: %out directive deprecated (ignored). diff --git a/Examples/test-suite/errors/c_empty_char.stderr b/Examples/test-suite/errors/c_empty_char.stderr new file mode 100644 index 000000000..9f9fa05ca --- /dev/null +++ b/Examples/test-suite/errors/c_empty_char.stderr @@ -0,0 +1 @@ +c_empty_char.i:3: Error: Empty character constant diff --git a/Examples/test-suite/errors/c_enum_badvalue.stderr b/Examples/test-suite/errors/c_enum_badvalue.stderr new file mode 100644 index 000000000..bccd02e90 --- /dev/null +++ b/Examples/test-suite/errors/c_enum_badvalue.stderr @@ -0,0 +1 @@ +c_enum_badvalue.i:6: Error: Type error. Expecting an integral type diff --git a/Examples/test-suite/errors/c_extra_rblock.stderr b/Examples/test-suite/errors/c_extra_rblock.stderr new file mode 100644 index 000000000..82877023a --- /dev/null +++ b/Examples/test-suite/errors/c_extra_rblock.stderr @@ -0,0 +1 @@ +c_extra_rblock.i:5: Error: Syntax error in input(1). diff --git a/Examples/test-suite/errors/c_extra_rbrace.stderr b/Examples/test-suite/errors/c_extra_rbrace.stderr new file mode 100644 index 000000000..23bd41f3c --- /dev/null +++ b/Examples/test-suite/errors/c_extra_rbrace.stderr @@ -0,0 +1 @@ +c_extra_rbrace.i:5: Error: Syntax error. Extraneous '}' diff --git a/Examples/test-suite/errors/c_extra_unsigned.stderr b/Examples/test-suite/errors/c_extra_unsigned.stderr new file mode 100644 index 000000000..06e9439a7 --- /dev/null +++ b/Examples/test-suite/errors/c_extra_unsigned.stderr @@ -0,0 +1,3 @@ +c_extra_unsigned.i:3: Error: Extra unsigned specifier. +c_extra_unsigned.i:4: Error: Extra signed specifier. +c_extra_unsigned.i:5: Error: Extra signed specifier. diff --git a/Examples/test-suite/errors/c_insert_missing.stderr b/Examples/test-suite/errors/c_insert_missing.stderr new file mode 100644 index 000000000..510d40e0a --- /dev/null +++ b/Examples/test-suite/errors/c_insert_missing.stderr @@ -0,0 +1 @@ +c_insert_missing.i:3: Error: Couldn't find 'missing_file.i'. diff --git a/Examples/test-suite/errors/c_long_short.stderr b/Examples/test-suite/errors/c_long_short.stderr new file mode 100644 index 000000000..eae36c3ce --- /dev/null +++ b/Examples/test-suite/errors/c_long_short.stderr @@ -0,0 +1,4 @@ +c_long_short.i:3: Error: Extra long specifier. +c_long_short.i:4: Error: Extra short specifier. +c_long_short.i:5: Error: Extra long specifier. +c_long_short.i:6: Error: Extra short specifier. diff --git a/Examples/test-suite/errors/c_missing_rbrace.stderr b/Examples/test-suite/errors/c_missing_rbrace.stderr new file mode 100644 index 000000000..28fdd263e --- /dev/null +++ b/Examples/test-suite/errors/c_missing_rbrace.stderr @@ -0,0 +1,2 @@ +c_missing_rbrace.i:3: Error: Missing '}'. Reached end of input. +c_missing_rbrace.i:3: Error: Syntax error in input(1). diff --git a/Examples/test-suite/errors/c_missing_semi.stderr b/Examples/test-suite/errors/c_missing_semi.stderr new file mode 100644 index 000000000..791b959ca --- /dev/null +++ b/Examples/test-suite/errors/c_missing_semi.stderr @@ -0,0 +1 @@ +c_missing_semi.i:3: Error: Syntax error in input(1). diff --git a/Examples/test-suite/errors/c_redefine.stderr b/Examples/test-suite/errors/c_redefine.stderr new file mode 100644 index 000000000..4fccf14ea --- /dev/null +++ b/Examples/test-suite/errors/c_redefine.stderr @@ -0,0 +1,6 @@ +c_redefine.i:4: Warning 302: Identifier 'foo' redefined (ignored), +c_redefine.i:3: Warning 302: previous definition of 'foo'. +c_redefine.i:8: Warning 302: Identifier 'bar' redefined (ignored), +c_redefine.i:6: Warning 302: previous definition of 'bar'. +c_redefine.i:14: Warning 322: Redundant redeclaration of 'bar' (Renamed from 'spam'), +c_redefine.i:6: Warning 322: previous declaration of 'bar'. diff --git a/Examples/test-suite/errors/c_varargs.stderr b/Examples/test-suite/errors/c_varargs.stderr new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/test-suite/errors/c_varargs_neg.stderr b/Examples/test-suite/errors/c_varargs_neg.stderr new file mode 100644 index 000000000..26c4cc92c --- /dev/null +++ b/Examples/test-suite/errors/c_varargs_neg.stderr @@ -0,0 +1 @@ +c_varargs_neg.i:3: Error: Argument count in %varargs must be positive. diff --git a/Examples/test-suite/errors/cpp_bad_extern.stderr b/Examples/test-suite/errors/cpp_bad_extern.stderr new file mode 100644 index 000000000..5102b71f7 --- /dev/null +++ b/Examples/test-suite/errors/cpp_bad_extern.stderr @@ -0,0 +1,2 @@ +cpp_bad_extern.i:5: Warning 313: Unrecognized extern type "INTERCAL". +cpp_bad_extern.i:7: Warning 313: Unrecognized extern type "INTERCAL". diff --git a/Examples/test-suite/errors/cpp_extend_destructors.stderr b/Examples/test-suite/errors/cpp_extend_destructors.stderr new file mode 100644 index 000000000..1eef277dc --- /dev/null +++ b/Examples/test-suite/errors/cpp_extend_destructors.stderr @@ -0,0 +1,19 @@ +cpp_extend_destructors.i:8: Warning 302: Identifier '~AStruct' redefined by %extend (ignored), +cpp_extend_destructors.i:5: Warning 302: %extend definition of '~AStruct'. +cpp_extend_destructors.i:14: Warning 302: Identifier '~BStruct' redefined (ignored), +cpp_extend_destructors.i:13: Warning 302: previous definition of '~BStruct'. +cpp_extend_destructors.i:87: Warning 302: Identifier '~JStruct' redefined (ignored), +cpp_extend_destructors.i:85: Warning 302: previous definition of '~JStruct'. +cpp_extend_destructors.i:100: Warning 302: Identifier '~LStruct' redefined (ignored), +cpp_extend_destructors.i:98: Warning 302: previous definition of '~LStruct'. +cpp_extend_destructors.i:24: Warning 521: Illegal destructor name CStruct::~NOT_CStruct(). Ignored. +cpp_extend_destructors.i:30: Warning 521: Illegal destructor name DStruct::~NOT_DStruct(). Ignored. +cpp_extend_destructors.i:44: Warning 521: Illegal destructor name EStruct::~NOT_EStruct(). Ignored. +cpp_extend_destructors.i:50: Warning 521: Illegal destructor name FStruct::~NOT_FStruct(). Ignored. +cpp_extend_destructors.i:65: Warning 521: Illegal destructor name GStruct::~NOT_GStruct(). Ignored. +cpp_extend_destructors.i:72: Warning 521: Illegal destructor name HStruct::~NOT_HStruct(). Ignored. +cpp_extend_destructors.i:81: Warning 521: Illegal destructor name IStruct::~NOT_IStruct(). Ignored. +cpp_extend_destructors.i:86: Warning 521: Illegal destructor name JStruct::~NOT_JStruct(). Ignored. +cpp_extend_destructors.i:92: Warning 521: Illegal destructor name KStruct::~NOT_KStruct(). Ignored. +cpp_extend_destructors.i:99: Warning 521: Illegal destructor name LStruct< int >::~NOT_LStruct(). Ignored. +cpp_extend_destructors.i:99: Warning 521: Illegal destructor name LStruct< short >::~NOT_LStruct(). Ignored. diff --git a/Examples/test-suite/errors/cpp_extend_redefine.stderr b/Examples/test-suite/errors/cpp_extend_redefine.stderr new file mode 100644 index 000000000..94770f5d7 --- /dev/null +++ b/Examples/test-suite/errors/cpp_extend_redefine.stderr @@ -0,0 +1,4 @@ +cpp_extend_redefine.i:9: Warning 302: Identifier 'bar' redefined by %extend (ignored), +cpp_extend_redefine.i:5: Warning 302: %extend definition of 'bar'. +cpp_extend_redefine.i:14: Warning 322: Redundant redeclaration of 'spam', +cpp_extend_redefine.i:10: Warning 322: previous declaration of 'spam'. diff --git a/Examples/test-suite/errors/cpp_extend_undefined.stderr b/Examples/test-suite/errors/cpp_extend_undefined.stderr new file mode 100644 index 000000000..aa63cb34f --- /dev/null +++ b/Examples/test-suite/errors/cpp_extend_undefined.stderr @@ -0,0 +1 @@ +cpp_extend_undefined.i:6: Warning 303: %extend defined for an undeclared class foo. diff --git a/Examples/test-suite/errors/cpp_inherit.stderr b/Examples/test-suite/errors/cpp_inherit.stderr new file mode 100644 index 000000000..50c6ed16a --- /dev/null +++ b/Examples/test-suite/errors/cpp_inherit.stderr @@ -0,0 +1,20 @@ +cpp_inherit.i:18: Warning 309: private inheritance from base 'A3' (ignored). +cpp_inherit.i:20: Warning 309: private inheritance from base 'A4' (ignored). +cpp_inherit.i:28: Warning 309: protected inheritance from base 'A8< double >' (ignored). +cpp_inherit.i:39: Warning 319: No access specifier given for base class 'B1' (ignored). +cpp_inherit.i:40: Warning 319: No access specifier given for base class 'B2< int >' (ignored). +cpp_inherit.i:15: Warning 401: Base class 'A1' undefined. +cpp_inherit.i:33: Warning 401: 'A1' must be defined before it is used as a base class. +cpp_inherit.i:17: Warning 401: Nothing known about base class 'A2'. Ignored. +cpp_inherit.i:22: Warning 402: Base class 'A5' is incomplete. +cpp_inherit.i:4: Warning 402: Only forward declaration 'A5' was found. +cpp_inherit.i:24: Error: 'A6' is not a valid base class. +cpp_inherit.i:5: Error: See definition of 'A6'. +cpp_inherit.i:24: Warning 401: Nothing known about base class 'A6'. Ignored. +cpp_inherit.i:26: Warning 401: Nothing known about base class 'A7< int >'. Ignored. +cpp_inherit.i:26: Warning 401: Maybe you forgot to instantiate 'A7< int >' using %template. +cpp_inherit.i:45: Warning 323: Recursive scope inheritance of 'Recursive'. +cpp_inherit.i:52: Warning 401: Base class 'Base< int >' has no name as it is an empty template instantiated with '%template()'. Ignored. +cpp_inherit.i:51: Warning 401: The %template directive must be written before 'Base< int >' is used as a base class and be declared with a name. +cpp_inherit.i:53: Warning 401: Base class 'Base< double >' undefined. +cpp_inherit.i:54: Warning 401: 'Base< double >' must be defined before it is used as a base class. diff --git a/Examples/test-suite/errors/cpp_inline_namespace.stderr b/Examples/test-suite/errors/cpp_inline_namespace.stderr new file mode 100644 index 000000000..be65b6b57 --- /dev/null +++ b/Examples/test-suite/errors/cpp_inline_namespace.stderr @@ -0,0 +1 @@ +cpp_inline_namespace.i:4: Error: %inline directive inside a namespace is disallowed. diff --git a/Examples/test-suite/errors/cpp_macro_locator.stderr b/Examples/test-suite/errors/cpp_macro_locator.stderr new file mode 100644 index 000000000..8a78d46af --- /dev/null +++ b/Examples/test-suite/errors/cpp_macro_locator.stderr @@ -0,0 +1,20 @@ +cpp_macro_locator.i:66: Warning 204: CPP #warning, "inline warning message one". +cpp_macro_locator.i:96: Warning 204: CPP #warning, "an inline warning message 2". +cpp_macro_locator.i:53: Warning 509: Overloaded method overload1(int const *) effectively ignored, +cpp_macro_locator.i:52: Warning 509: as it is shadowed by overload1(int *). +cpp_macro_locator.i:61: Warning 509: Overloaded method overload2(int const *) effectively ignored, +cpp_macro_locator.i:60: Warning 509: as it is shadowed by overload2(int *). +cpp_macro_locator.i:64: Warning 509: Overloaded method Klass1::methodX(int const *) effectively ignored, +cpp_macro_locator.i:64: Warning 509: as it is shadowed by Klass1::methodX(int *). +cpp_macro_locator.i:68: Warning 509: Overloaded method overload3(int const *) effectively ignored, +cpp_macro_locator.i:67: Warning 509: as it is shadowed by overload3(int *). +cpp_macro_locator.i:90: Warning 509: Overloaded method overload4(int const *) effectively ignored, +cpp_macro_locator.i:89: Warning 509: as it is shadowed by overload4(int *). +cpp_macro_locator.i:94: Warning 509: Overloaded method overloadinline1(int const *) effectively ignored, +cpp_macro_locator.i:93: Warning 509: as it is shadowed by overloadinline1(int *). +cpp_macro_locator.i:95: Warning 509: Overloaded method Klass2::methodX(int const *) effectively ignored, +cpp_macro_locator.i:95: Warning 509: as it is shadowed by Klass2::methodX(int *). +cpp_macro_locator.i:98: Warning 509: Overloaded method overloadinline2(int const *) effectively ignored, +cpp_macro_locator.i:97: Warning 509: as it is shadowed by overloadinline2(int *). +cpp_macro_locator.i:101: Warning 509: Overloaded method overload5(int const *) effectively ignored, +cpp_macro_locator.i:100: Warning 509: as it is shadowed by overload5(int *). diff --git a/Examples/test-suite/errors/cpp_missing_rparenthesis.stderr b/Examples/test-suite/errors/cpp_missing_rparenthesis.stderr new file mode 100644 index 000000000..cc97f5c68 --- /dev/null +++ b/Examples/test-suite/errors/cpp_missing_rparenthesis.stderr @@ -0,0 +1,2 @@ +cpp_missing_rparenthesis.i:5: Error: Missing ')'. Reached end of input. +cpp_missing_rparenthesis.i:5: Error: Syntax error in input(3). diff --git a/Examples/test-suite/errors/cpp_missing_rtemplate.stderr b/Examples/test-suite/errors/cpp_missing_rtemplate.stderr new file mode 100644 index 000000000..07a89bf08 --- /dev/null +++ b/Examples/test-suite/errors/cpp_missing_rtemplate.stderr @@ -0,0 +1 @@ +cpp_missing_rtemplate.i:4: Error: Syntax error in input(1). diff --git a/Examples/test-suite/errors/cpp_namespace_alias.stderr b/Examples/test-suite/errors/cpp_namespace_alias.stderr new file mode 100644 index 000000000..166d1f681 --- /dev/null +++ b/Examples/test-suite/errors/cpp_namespace_alias.stderr @@ -0,0 +1 @@ +cpp_namespace_alias.i:8: Warning 308: Namespace alias 'B' not allowed here. Assuming 'blah' diff --git a/Examples/test-suite/errors/cpp_namespace_aliasnot.stderr b/Examples/test-suite/errors/cpp_namespace_aliasnot.stderr new file mode 100644 index 000000000..a2f33c909 --- /dev/null +++ b/Examples/test-suite/errors/cpp_namespace_aliasnot.stderr @@ -0,0 +1 @@ +cpp_namespace_aliasnot.i:4: Error: 'blah' is not a namespace diff --git a/Examples/test-suite/errors/cpp_namespace_aliasundef.stderr b/Examples/test-suite/errors/cpp_namespace_aliasundef.stderr new file mode 100644 index 000000000..97d0206a8 --- /dev/null +++ b/Examples/test-suite/errors/cpp_namespace_aliasundef.stderr @@ -0,0 +1 @@ +cpp_namespace_aliasundef.i:3: Error: Unknown namespace 'blah' diff --git a/Examples/test-suite/errors/cpp_nested_template.stderr b/Examples/test-suite/errors/cpp_nested_template.stderr new file mode 100644 index 000000000..9e46cff74 --- /dev/null +++ b/Examples/test-suite/errors/cpp_nested_template.stderr @@ -0,0 +1,2 @@ +cpp_nested_template.i:9: Warning 324: Named nested template instantiations not supported. Processing as if no name was given to %template(). +cpp_nested_template.i:18: Warning 324: Named nested template instantiations not supported. Processing as if no name was given to %template(). diff --git a/Examples/test-suite/errors/cpp_no_access.stderr b/Examples/test-suite/errors/cpp_no_access.stderr new file mode 100644 index 000000000..b87aa3e51 --- /dev/null +++ b/Examples/test-suite/errors/cpp_no_access.stderr @@ -0,0 +1 @@ +cpp_no_access.i:3: Warning 319: No access specifier given for base class 'foo' (ignored). diff --git a/Examples/test-suite/errors/cpp_no_return_type.stderr b/Examples/test-suite/errors/cpp_no_return_type.stderr new file mode 100644 index 000000000..07c4d2261 --- /dev/null +++ b/Examples/test-suite/errors/cpp_no_return_type.stderr @@ -0,0 +1,2 @@ +cpp_no_return_type.i:6: Warning 504: Function S::R() must have a return type. Ignored. +cpp_no_return_type.i:10: Warning 504: Function U::UU() must have a return type. Ignored. diff --git a/Examples/test-suite/errors/cpp_nobase.stderr b/Examples/test-suite/errors/cpp_nobase.stderr new file mode 100644 index 000000000..0cc209788 --- /dev/null +++ b/Examples/test-suite/errors/cpp_nobase.stderr @@ -0,0 +1,3 @@ +cpp_nobase.i:3: Warning 401: Nothing known about base class 'Bar'. Ignored. +cpp_nobase.i:6: Warning 401: Nothing known about base class 'Bar< int >'. Ignored. +cpp_nobase.i:6: Warning 401: Maybe you forgot to instantiate 'Bar< int >' using %template. diff --git a/Examples/test-suite/errors/cpp_overload.stderr b/Examples/test-suite/errors/cpp_overload.stderr new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/test-suite/errors/cpp_overload_const.stderr b/Examples/test-suite/errors/cpp_overload_const.stderr new file mode 100644 index 000000000..696fd7482 --- /dev/null +++ b/Examples/test-suite/errors/cpp_overload_const.stderr @@ -0,0 +1,10 @@ +cpp_overload_const.i:4: Warning 509: Overloaded method check(int *) effectively ignored, +cpp_overload_const.i:3: Warning 509: as it is shadowed by check(int const *). +cpp_overload_const.i:5: Warning 509: Overloaded method check(int &) effectively ignored, +cpp_overload_const.i:3: Warning 509: as it is shadowed by check(int const *). +cpp_overload_const.i:10: Warning 509: Overloaded method check(OverStruct *) effectively ignored, +cpp_overload_const.i:9: Warning 509: as it is shadowed by check(OverStruct const *). +cpp_overload_const.i:11: Warning 509: Overloaded method check(OverStruct &) effectively ignored, +cpp_overload_const.i:9: Warning 509: as it is shadowed by check(OverStruct const *). +cpp_overload_const.i:12: Warning 509: Overloaded method check(OverStruct const &) effectively ignored, +cpp_overload_const.i:9: Warning 509: as it is shadowed by check(OverStruct const *). diff --git a/Examples/test-suite/errors/cpp_private_defvalue.stderr b/Examples/test-suite/errors/cpp_private_defvalue.stderr new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/test-suite/errors/cpp_private_inherit.stderr b/Examples/test-suite/errors/cpp_private_inherit.stderr new file mode 100644 index 000000000..f3e381aba --- /dev/null +++ b/Examples/test-suite/errors/cpp_private_inherit.stderr @@ -0,0 +1,2 @@ +cpp_private_inherit.i:6: Warning 309: private inheritance from base 'Foo' (ignored). +cpp_private_inherit.i:9: Warning 309: protected inheritance from base 'Foo' (ignored). diff --git a/Examples/test-suite/errors/cpp_recursive_typedef.stderr b/Examples/test-suite/errors/cpp_recursive_typedef.stderr new file mode 100644 index 000000000..d9135aa43 --- /dev/null +++ b/Examples/test-suite/errors/cpp_recursive_typedef.stderr @@ -0,0 +1 @@ +:1: Error: Recursive typedef detected resolving 'pds *' to 'std::set< pds > *' to 'std::set< std::set< pds > > *' and so on... diff --git a/Examples/test-suite/errors/cpp_shared_ptr.stderr b/Examples/test-suite/errors/cpp_shared_ptr.stderr new file mode 100644 index 000000000..1553af65c --- /dev/null +++ b/Examples/test-suite/errors/cpp_shared_ptr.stderr @@ -0,0 +1,3 @@ +cpp_shared_ptr.i:20: Warning 520: Base class 'A' of 'C' is not similarly marked as a smart pointer. +cpp_shared_ptr.i:24: Warning 520: Derived class 'D' of 'C' is not similarly marked as a smart pointer. +cpp_shared_ptr.i:24: Warning 520: Derived class 'D' of 'B' is not similarly marked as a smart pointer. diff --git a/Examples/test-suite/errors/cpp_template_argname.stderr b/Examples/test-suite/errors/cpp_template_argname.stderr new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/test-suite/errors/cpp_template_nargs.stderr b/Examples/test-suite/errors/cpp_template_nargs.stderr new file mode 100644 index 000000000..4ced28e05 --- /dev/null +++ b/Examples/test-suite/errors/cpp_template_nargs.stderr @@ -0,0 +1,2 @@ +cpp_template_nargs.i:5: Error: Template 'blah' undefined. +cpp_template_nargs.i:6: Error: Template 'blah' undefined. diff --git a/Examples/test-suite/errors/cpp_template_not.stderr b/Examples/test-suite/errors/cpp_template_not.stderr new file mode 100644 index 000000000..aeb058c67 --- /dev/null +++ b/Examples/test-suite/errors/cpp_template_not.stderr @@ -0,0 +1 @@ +cpp_template_not.i:5: Error: 'blah' is not defined as a template. (cdecl) diff --git a/Examples/test-suite/errors/cpp_template_partial.stderr b/Examples/test-suite/errors/cpp_template_partial.stderr new file mode 100644 index 000000000..94574e582 --- /dev/null +++ b/Examples/test-suite/errors/cpp_template_partial.stderr @@ -0,0 +1 @@ +cpp_template_partial.i:3: Warning 317: Specialization of non-template 'vector'. diff --git a/Examples/test-suite/errors/cpp_template_repeat.stderr b/Examples/test-suite/errors/cpp_template_repeat.stderr new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/test-suite/errors/cpp_template_undef.stderr b/Examples/test-suite/errors/cpp_template_undef.stderr new file mode 100644 index 000000000..2cf27c3b4 --- /dev/null +++ b/Examples/test-suite/errors/cpp_template_undef.stderr @@ -0,0 +1 @@ +cpp_template_undef.i:3: Error: Template 'blah' undefined. diff --git a/Examples/test-suite/errors/cpp_using_not.stderr b/Examples/test-suite/errors/cpp_using_not.stderr new file mode 100644 index 000000000..1b8be79ac --- /dev/null +++ b/Examples/test-suite/errors/cpp_using_not.stderr @@ -0,0 +1 @@ +cpp_using_not.i:4: Error: 'blah' is not a namespace. diff --git a/Examples/test-suite/errors/cpp_using_undef.stderr b/Examples/test-suite/errors/cpp_using_undef.stderr new file mode 100644 index 000000000..f4e5020d5 --- /dev/null +++ b/Examples/test-suite/errors/cpp_using_undef.stderr @@ -0,0 +1,2 @@ +cpp_using_undef.i:4: Error: Nothing known about namespace 'foo' +cpp_using_undef.i:3: Warning 315: Nothing known about 'foo::bar'. diff --git a/Examples/test-suite/errors/expected.log b/Examples/test-suite/errors/expected.log deleted file mode 100644 index da0d59778..000000000 --- a/Examples/test-suite/errors/expected.log +++ /dev/null @@ -1,390 +0,0 @@ -SWIG error and warning test. opts= ------------------------------------------------------------ - -:::::::::::::::::::::::::::::::: c_bad_name.i ::::::::::::::::::::::::::::::::::: -c_bad_name.i:3: Warning 121: %name is deprecated. Use %rename instead. -c_bad_name.i:3: Error: Missing argument to %name directive. - -:::::::::::::::::::::::::::::::: c_bad_native.i ::::::::::::::::::::::::::::::::::: -c_bad_native.i:3: Error: %native declaration 'foo' is not a function. - -:::::::::::::::::::::::::::::::: c_class.i ::::::::::::::::::::::::::::::::::: -c_class.i:3: Warning 301: class keyword used, but not in C++ mode. -c_class.i:3: Warning 314: 'class' is a python keyword, renaming to '_class' - -:::::::::::::::::::::::::::::::: c_default_error.i ::::::::::::::::::::::::::::::::::: - -:::::::::::::::::::::::::::::::: c_deprecated.i ::::::::::::::::::::::::::::::::::: -c_deprecated.i:3: Warning 102: %val directive deprecated (ignored). -c_deprecated.i:3: Warning 103: %out directive deprecated (ignored). - -:::::::::::::::::::::::::::::::: c_empty_char.i ::::::::::::::::::::::::::::::::::: -c_empty_char.i:3: Error: Empty character constant -0 - -:::::::::::::::::::::::::::::::: c_enum_badvalue.i ::::::::::::::::::::::::::::::::::: -c_enum_badvalue.i:6: Error: Type error. Expecting an integral type - -:::::::::::::::::::::::::::::::: c_extra_rblock.i ::::::::::::::::::::::::::::::::::: -c_extra_rblock.i:5: Error: Syntax error in input(1). - -:::::::::::::::::::::::::::::::: c_extra_rbrace.i ::::::::::::::::::::::::::::::::::: -c_extra_rbrace.i:5: Error: Syntax error. Extraneous '}' - -:::::::::::::::::::::::::::::::: c_extra_unsigned.i ::::::::::::::::::::::::::::::::::: -c_extra_unsigned.i:3: Error: Extra unsigned specifier. -c_extra_unsigned.i:4: Error: Extra signed specifier. -c_extra_unsigned.i:5: Error: Extra signed specifier. - -:::::::::::::::::::::::::::::::: c_insert_missing.i ::::::::::::::::::::::::::::::::::: -c_insert_missing.i:3: Error: Couldn't find 'missing_file.i'. - -:::::::::::::::::::::::::::::::: c_long_short.i ::::::::::::::::::::::::::::::::::: -c_long_short.i:3: Error: Extra long specifier. -c_long_short.i:4: Error: Extra short specifier. -c_long_short.i:5: Error: Extra long specifier. -c_long_short.i:6: Error: Extra short specifier. - -:::::::::::::::::::::::::::::::: c_missing_rbrace.i ::::::::::::::::::::::::::::::::::: -c_missing_rbrace.i:3: Error: Missing '}'. Reached end of input. -c_missing_rbrace.i:3: Error: Syntax error in input(1). - -:::::::::::::::::::::::::::::::: c_missing_semi.i ::::::::::::::::::::::::::::::::::: -c_missing_semi.i:3: Error: Syntax error in input(1). - -:::::::::::::::::::::::::::::::: c_redefine.i ::::::::::::::::::::::::::::::::::: -c_redefine.i:4: Warning 302: Identifier 'foo' redefined (ignored), -c_redefine.i:3: Warning 302: previous definition of 'foo'. -c_redefine.i:8: Warning 302: Identifier 'bar' redefined (ignored), -c_redefine.i:6: Warning 302: previous definition of 'bar'. -c_redefine.i:14: Warning 322: Redundant redeclaration of 'bar' (Renamed from 'spam'), -c_redefine.i:6: Warning 322: previous declaration of 'bar'. - -:::::::::::::::::::::::::::::::: c_varargs.i ::::::::::::::::::::::::::::::::::: - -:::::::::::::::::::::::::::::::: c_varargs_neg.i ::::::::::::::::::::::::::::::::::: -c_varargs_neg.i:3: Error: Argument count in %varargs must be positive. - -:::::::::::::::::::::::::::::::: nomodule.i ::::::::::::::::::::::::::::::::::: -No module name specified using %module or -module. - -:::::::::::::::::::::::::::::::: pp_badeval.i ::::::::::::::::::::::::::::::::::: -pp_badeval.i:4: Warning 202: Could not evaluate expression 'FOO==4+' -pp_badeval.i:4: Warning 202: Error: 'Expected an expression' - -:::::::::::::::::::::::::::::::: pp_constant.i ::::::::::::::::::::::::::::::::::: -pp_constant.i:9: Warning 305: Bad constant value (ignored). -pp_constant.i:15: Warning 305: Bad constant value (ignored). -pp_constant.i:23: Warning 305: Bad constant value (ignored). -pp_constant.i:29: Warning 305: Bad constant value (ignored). -pp_constant.i:35: Warning 305: Bad constant value (ignored). -pp_constant.i:42: Warning 305: Bad constant value (ignored). -pp_constant.i:46: Warning 305: Bad constant value (ignored). -pp_constant.i:49: Warning 305: Bad constant value (ignored). - -:::::::::::::::::::::::::::::::: pp_defined.i ::::::::::::::::::::::::::::::::::: -pp_defined.i:6: Error: No arguments given to defined() -pp_defined.i:6: Error: Missing expression for #if. - -:::::::::::::::::::::::::::::::: pp_deprecated.i ::::::::::::::::::::::::::::::::::: -pp_deprecated.i:4: Warning 101: %extern is deprecated. Use %import instead. -pp_deprecated.i:4: Error: Unable to find 'ext;' -pp_deprecated.i:6: Warning 204: CPP #warning, "Print this warning". -pp_deprecated.i:8: Error: CPP #error "This is an error". Use the -cpperraswarn option to continue swig processing. - -:::::::::::::::::::::::::::::::: pp_illegal_argument.i ::::::::::::::::::::::::::::::::::: -pp_illegal_argument.i:6: Error: Illegal macro argument name '..' -pp_illegal_argument.i:10: Error: Illegal macro argument name '..' -pp_illegal_argument.i:16: Error: Illegal character in macro argument name - -:::::::::::::::::::::::::::::::: pp_macro_args.i ::::::::::::::::::::::::::::::::::: - -:::::::::::::::::::::::::::::::: pp_macro_badchar.i ::::::::::::::::::::::::::::::::::: -pp_macro_badchar.i:4: Error: Illegal character in macro argument name - -:::::::::::::::::::::::::::::::: pp_macro_defined_unterminated.i ::::::::::::::::::::::::::::::::::: -pp_macro_defined_unterminated.i:4: Error: Unterminated call to 'defined' - -:::::::::::::::::::::::::::::::: pp_macro_expansion.i ::::::::::::::::::::::::::::::::::: -pp_macro_expansion.i:9: Error: Macro 'MACRO2' expects 2 arguments - -:::::::::::::::::::::::::::::::: pp_macro_expansion_multiline.i ::::::::::::::::::::::::::::::::::: -pp_macro_expansion_multiline.i:13: Warning 509: Overloaded method foo(int const *) effectively ignored, -pp_macro_expansion_multiline.i:12: Warning 509: as it is shadowed by foo(int *). -pp_macro_expansion_multiline.i:31: Warning 509: Overloaded method bar(int const *) effectively ignored, -pp_macro_expansion_multiline.i:30: Warning 509: as it is shadowed by bar(int *). - -:::::::::::::::::::::::::::::::: pp_macro_inline_unterminated.i ::::::::::::::::::::::::::::::::::: -pp_macro_inline_unterminated.i:9: Error: Unterminated call invoking macro 'foo' -pp_macro_inline_unterminated.i:12: Error: Syntax error in input(3). - -:::::::::::::::::::::::::::::::: pp_macro_missing_expression.i ::::::::::::::::::::::::::::::::::: -pp_macro_missing_expression.i:4: Error: Missing identifier for #ifdef. -pp_macro_missing_expression.i:7: Error: Missing identifier for #ifndef. -pp_macro_missing_expression.i:10: Error: Missing expression for #if. -pp_macro_missing_expression.i:14: Error: Missing expression for #elif. -pp_macro_missing_expression.i:21: Error: Missing expression for #elif. - -:::::::::::::::::::::::::::::::: pp_macro_unexpected_tokens.i ::::::::::::::::::::::::::::::::::: -pp_macro_unexpected_tokens.i:5: Warning 206: Unexpected tokens after #endif directive. -pp_macro_unexpected_tokens.i:8: Warning 206: Unexpected tokens after #endif directive. -pp_macro_unexpected_tokens.i:11: Warning 206: Unexpected tokens after #else directive. -pp_macro_unexpected_tokens.i:18: Warning 206: Unexpected tokens after #endif directive. -pp_macro_unexpected_tokens.i:21: Warning 206: Unexpected tokens after #else directive. - -:::::::::::::::::::::::::::::::: pp_macro_nargs.i ::::::::::::::::::::::::::::::::::: -pp_macro_nargs.i:7: Error: Macro 'foo' expects 2 arguments -pp_macro_nargs.i:8: Error: Macro 'foo' expects 2 arguments -pp_macro_nargs.i:10: Error: Macro 'bar' expects 1 argument -pp_macro_nargs.i:11: Error: Macro 'spam' expects no arguments - -:::::::::::::::::::::::::::::::: pp_macro_redef.i ::::::::::::::::::::::::::::::::::: -pp_macro_redef.i:4: Error: Macro 'foo' redefined, -pp_macro_redef.i:3: Error: previous definition of 'foo'. -pp_macro_redef.i:7: Error: Macro 'foo' redefined, -pp_macro_redef.i:3: Error: previous definition of 'foo'. - -:::::::::::::::::::::::::::::::: pp_macro_rparen.i ::::::::::::::::::::::::::::::::::: -pp_macro_rparen.i:3: Error: Missing ')' in macro parameters - -:::::::::::::::::::::::::::::::: pp_macro_unterminated.i ::::::::::::::::::::::::::::::::::: -pp_macro_unterminated.i:5: Error: Unterminated call invoking macro 'foo' - -:::::::::::::::::::::::::::::::: pp_misplaced_elif.i ::::::::::::::::::::::::::::::::::: -pp_misplaced_elif.i:4: Error: Misplaced #elif. -pp_misplaced_elif.i:6: Error: Extraneous #endif. - -:::::::::::::::::::::::::::::::: pp_misplaced_else.i ::::::::::::::::::::::::::::::::::: -pp_misplaced_else.i:4: Error: Misplaced #else. -pp_misplaced_else.i:6: Error: Extraneous #endif. - -:::::::::::::::::::::::::::::::: pp_missing_enddef.i ::::::::::::::::::::::::::::::::::: -pp_missing_enddef.i:EOF: Error: Missing %enddef for macro starting on line 3 - -:::::::::::::::::::::::::::::::: pp_missing_endif.i ::::::::::::::::::::::::::::::::::: -pp_missing_endif.i:EOF: Error: Missing #endif for conditional starting on line 3 - -:::::::::::::::::::::::::::::::: pp_missing_file.i ::::::::::::::::::::::::::::::::::: -pp_missing_file.i:3: Error: Unable to find 'missing_filename.i' - -:::::::::::::::::::::::::::::::: pp_missing_rblock.i ::::::::::::::::::::::::::::::::::: -pp_missing_rblock.i:EOF: Error: Unterminated %{ ... %} block starting on line 3 - -:::::::::::::::::::::::::::::::: pp_pragma.i ::::::::::::::::::::::::::::::::::: -pp_pragma.i:4: Error: Unknown SWIG pragma: rubbish() - -:::::::::::::::::::::::::::::::: pp_unterm_char.i ::::::::::::::::::::::::::::::::::: -pp_unterm_char.i:EOF: Error: Unterminated character constant starting at line 4 - -:::::::::::::::::::::::::::::::: pp_unterm_comment.i ::::::::::::::::::::::::::::::::::: -pp_unterm_comment.i:EOF: Error: Unterminated comment starting on line 3 - -:::::::::::::::::::::::::::::::: pp_unterm_string.i ::::::::::::::::::::::::::::::::::: -pp_unterm_string.i:EOF: Error: Unterminated string constant starting at line 4 - -:::::::::::::::::::::::::::::::: pp_variable_args.i ::::::::::::::::::::::::::::::::::: -pp_variable_args.i:6: Error: Variable length macro argument must be last parameter - -:::::::::::::::::::::::::::::::: swig_apply_nargs.i ::::::::::::::::::::::::::::::::::: -swig_apply_nargs.i:6: Error: Can't apply (char *str,int len) to (int x). Number of arguments don't match. - -:::::::::::::::::::::::::::::::: swig_extend.i ::::::::::::::::::::::::::::::::::: -swig_extend.i:19: Warning 326: Deprecated %extend name used - the struct name 'StructBName' should be used instead of the typedef name 'StructB'. -swig_extend.i:45: Warning 326: Deprecated %extend name used - the struct name 'stru_struct' should be used instead of the typedef name 'stru'. -swig_extend.i:56: Warning 326: Deprecated %extend name used - the union name 'uni_union' should be used instead of the typedef name 'uni'. -swig_extend.i:34: Warning 303: %extend defined for an undeclared class StructDName. -swig_extend.i:50: Warning 522: Use of an illegal constructor name 'stru' in %extend is deprecated, the constructor name should be 'stru_struct'. -swig_extend.i:53: Warning 523: Use of an illegal destructor name 'stru' in %extend is deprecated, the destructor name should be 'stru_struct'. -swig_extend.i:57: Warning 522: Use of an illegal constructor name 'uni' in %extend is deprecated, the constructor name should be 'uni_union'. -swig_extend.i:58: Warning 523: Use of an illegal destructor name 'uni' in %extend is deprecated, the destructor name should be 'uni_union'. - -:::::::::::::::::::::::::::::::: swig_identifier.i ::::::::::::::::::::::::::::::::::: -swig_identifier.i:5: Warning 503: Can't wrap 'foo bar' unless renamed to a valid identifier. - -:::::::::::::::::::::::::::::::: swig_insert_bad.i ::::::::::::::::::::::::::::::::::: -swig_insert_bad.i:5: Error: Unknown target 'foobar' for %insert directive. - -:::::::::::::::::::::::::::::::: swig_typemap_copy.i ::::::::::::::::::::::::::::::::::: -swig_typemap_copy.i:3: Error: Can't copy typemap (in) blah = int - -:::::::::::::::::::::::::::::::: swig_typemap_old.i ::::::::::::::::::::::::::::::::::: -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. -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 -Doc/Manual/Typemaps.html for complete details. - -:::::::::::::::::::::::::::::::: swig_typemap_warn.i ::::::::::::::::::::::::::::::::::: -swig_typemap_warn.i:7: Warning 1000: Test warning for 'in' typemap for int abc (arg1) - argnum: 1 &1_ltype: int * descriptor: SWIGTYPE_int -swig_typemap_warn.i:7: Warning 1000: Test warning for 'in' typemap for int arg3 (arg3) - argnum: 3 &1_ltype: int * descriptor: SWIGTYPE_int -swig_typemap_warn.i:7: Warning 1001: Test warning for 'out' typemap for double mmm (result) - name: mmm symname: mmm &1_ltype: double * descriptor: SWIGTYPE_double -swig_typemap_warn.i:7: Warning 1000: Test warning for 'in' typemap for int abc (arg1) - argnum: 1 &1_ltype: int * descriptor: SWIGTYPE_int -swig_typemap_warn.i:7: Warning 1000: Test warning for 'in' typemap for int arg3 (arg3) - argnum: 3 &1_ltype: int * descriptor: SWIGTYPE_int -swig_typemap_warn.i:7: Warning 1000: Test warning for 'in' typemap for int abc (arg1) - argnum: 1 &1_ltype: int * descriptor: SWIGTYPE_int -swig_typemap_warn.i:7: Warning 1000: Test warning for 'in' typemap for int arg3 (arg3) - argnum: 3 &1_ltype: int * descriptor: SWIGTYPE_int - -:::::::::::::::::::::::::::::::: cpp_bad_extern.i ::::::::::::::::::::::::::::::::::: -cpp_bad_extern.i:5: Warning 313: Unrecognized extern type "INTERCAL". -cpp_bad_extern.i:7: Warning 313: Unrecognized extern type "INTERCAL". - -:::::::::::::::::::::::::::::::: cpp_extend_destructors.i ::::::::::::::::::::::::::::::::::: -cpp_extend_destructors.i:8: Warning 302: Identifier '~AStruct' redefined by %extend (ignored), -cpp_extend_destructors.i:5: Warning 302: %extend definition of '~AStruct'. -cpp_extend_destructors.i:14: Warning 302: Identifier '~BStruct' redefined (ignored), -cpp_extend_destructors.i:13: Warning 302: previous definition of '~BStruct'. -cpp_extend_destructors.i:87: Warning 302: Identifier '~JStruct' redefined (ignored), -cpp_extend_destructors.i:85: Warning 302: previous definition of '~JStruct'. -cpp_extend_destructors.i:100: Warning 302: Identifier '~LStruct' redefined (ignored), -cpp_extend_destructors.i:98: Warning 302: previous definition of '~LStruct'. -cpp_extend_destructors.i:24: Warning 521: Illegal destructor name CStruct::~NOT_CStruct(). Ignored. -cpp_extend_destructors.i:30: Warning 521: Illegal destructor name DStruct::~NOT_DStruct(). Ignored. -cpp_extend_destructors.i:44: Warning 521: Illegal destructor name EStruct::~NOT_EStruct(). Ignored. -cpp_extend_destructors.i:50: Warning 521: Illegal destructor name FStruct::~NOT_FStruct(). Ignored. -cpp_extend_destructors.i:65: Warning 521: Illegal destructor name GStruct::~NOT_GStruct(). Ignored. -cpp_extend_destructors.i:72: Warning 521: Illegal destructor name HStruct::~NOT_HStruct(). Ignored. -cpp_extend_destructors.i:81: Warning 521: Illegal destructor name IStruct::~NOT_IStruct(). Ignored. -cpp_extend_destructors.i:86: Warning 521: Illegal destructor name JStruct::~NOT_JStruct(). Ignored. -cpp_extend_destructors.i:92: Warning 521: Illegal destructor name KStruct::~NOT_KStruct(). Ignored. -cpp_extend_destructors.i:99: Warning 521: Illegal destructor name LStruct< int >::~NOT_LStruct(). Ignored. -cpp_extend_destructors.i:99: Warning 521: Illegal destructor name LStruct< short >::~NOT_LStruct(). Ignored. - -:::::::::::::::::::::::::::::::: cpp_extend_redefine.i ::::::::::::::::::::::::::::::::::: -cpp_extend_redefine.i:9: Warning 302: Identifier 'bar' redefined by %extend (ignored), -cpp_extend_redefine.i:5: Warning 302: %extend definition of 'bar'. -cpp_extend_redefine.i:14: Warning 322: Redundant redeclaration of 'spam', -cpp_extend_redefine.i:10: Warning 322: previous declaration of 'spam'. - -:::::::::::::::::::::::::::::::: cpp_extend_undefined.i ::::::::::::::::::::::::::::::::::: -cpp_extend_undefined.i:6: Warning 303: %extend defined for an undeclared class foo. - -:::::::::::::::::::::::::::::::: cpp_inline_namespace.i ::::::::::::::::::::::::::::::::::: -cpp_inline_namespace.i:4: Error: %inline directive inside a namespace is disallowed. - -:::::::::::::::::::::::::::::::: cpp_inherit.i ::::::::::::::::::::::::::::::::::: -cpp_inherit.i:18: Warning 309: private inheritance from base 'A3' (ignored). -cpp_inherit.i:20: Warning 309: private inheritance from base 'A4' (ignored). -cpp_inherit.i:28: Warning 309: protected inheritance from base 'A8< double >' (ignored). -cpp_inherit.i:39: Warning 319: No access specifier given for base class 'B1' (ignored). -cpp_inherit.i:40: Warning 319: No access specifier given for base class 'B2< int >' (ignored). -cpp_inherit.i:15: Warning 401: Base class 'A1' undefined. -cpp_inherit.i:33: Warning 401: 'A1' must be defined before it is used as a base class. -cpp_inherit.i:17: Warning 401: Nothing known about base class 'A2'. Ignored. -cpp_inherit.i:22: Warning 402: Base class 'A5' is incomplete. -cpp_inherit.i:4: Warning 402: Only forward declaration 'A5' was found. -cpp_inherit.i:24: Error: 'A6' is not a valid base class. -cpp_inherit.i:5: Error: See definition of 'A6'. -cpp_inherit.i:24: Warning 401: Nothing known about base class 'A6'. Ignored. -cpp_inherit.i:26: Warning 401: Nothing known about base class 'A7< int >'. Ignored. -cpp_inherit.i:26: Warning 401: Maybe you forgot to instantiate 'A7< int >' using %template. -cpp_inherit.i:45: Warning 323: Recursive scope inheritance of 'Recursive'. -cpp_inherit.i:52: Warning 401: Base class 'Base< int >' has no name as it is an empty template instantiated with '%template()'. Ignored. -cpp_inherit.i:51: Warning 401: The %template directive must be written before 'Base< int >' is used as a base class and be declared with a name. -cpp_inherit.i:53: Warning 401: Base class 'Base< double >' undefined. -cpp_inherit.i:54: Warning 401: 'Base< double >' must be defined before it is used as a base class. - -:::::::::::::::::::::::::::::::: cpp_macro_locator.i ::::::::::::::::::::::::::::::::::: -cpp_macro_locator.i:66: Warning 204: CPP #warning, "inline warning message one". -cpp_macro_locator.i:96: Warning 204: CPP #warning, "an inline warning message 2". -cpp_macro_locator.i:53: Warning 509: Overloaded method overload1(int const *) effectively ignored, -cpp_macro_locator.i:52: Warning 509: as it is shadowed by overload1(int *). -cpp_macro_locator.i:61: Warning 509: Overloaded method overload2(int const *) effectively ignored, -cpp_macro_locator.i:60: Warning 509: as it is shadowed by overload2(int *). -cpp_macro_locator.i:64: Warning 509: Overloaded method Klass1::methodX(int const *) effectively ignored, -cpp_macro_locator.i:64: Warning 509: as it is shadowed by Klass1::methodX(int *). -cpp_macro_locator.i:68: Warning 509: Overloaded method overload3(int const *) effectively ignored, -cpp_macro_locator.i:67: Warning 509: as it is shadowed by overload3(int *). -cpp_macro_locator.i:90: Warning 509: Overloaded method overload4(int const *) effectively ignored, -cpp_macro_locator.i:89: Warning 509: as it is shadowed by overload4(int *). -cpp_macro_locator.i:94: Warning 509: Overloaded method overloadinline1(int const *) effectively ignored, -cpp_macro_locator.i:93: Warning 509: as it is shadowed by overloadinline1(int *). -cpp_macro_locator.i:95: Warning 509: Overloaded method Klass2::methodX(int const *) effectively ignored, -cpp_macro_locator.i:95: Warning 509: as it is shadowed by Klass2::methodX(int *). -cpp_macro_locator.i:98: Warning 509: Overloaded method overloadinline2(int const *) effectively ignored, -cpp_macro_locator.i:97: Warning 509: as it is shadowed by overloadinline2(int *). -cpp_macro_locator.i:101: Warning 509: Overloaded method overload5(int const *) effectively ignored, -cpp_macro_locator.i:100: Warning 509: as it is shadowed by overload5(int *). - -:::::::::::::::::::::::::::::::: cpp_missing_rparenthesis.i ::::::::::::::::::::::::::::::::::: -cpp_missing_rparenthesis.i:5: Error: Missing ')'. Reached end of input. -cpp_missing_rparenthesis.i:5: Error: Syntax error in input(3). - -:::::::::::::::::::::::::::::::: cpp_missing_rtemplate.i ::::::::::::::::::::::::::::::::::: -cpp_missing_rtemplate.i:4: Error: Syntax error in input(1). - -:::::::::::::::::::::::::::::::: cpp_namespace_alias.i ::::::::::::::::::::::::::::::::::: -cpp_namespace_alias.i:8: Warning 308: Namespace alias 'B' not allowed here. Assuming 'blah' - -:::::::::::::::::::::::::::::::: cpp_namespace_aliasnot.i ::::::::::::::::::::::::::::::::::: -cpp_namespace_aliasnot.i:4: Error: 'blah' is not a namespace - -:::::::::::::::::::::::::::::::: cpp_namespace_aliasundef.i ::::::::::::::::::::::::::::::::::: -cpp_namespace_aliasundef.i:3: Error: Unknown namespace 'blah' - -:::::::::::::::::::::::::::::::: cpp_nested_template.i ::::::::::::::::::::::::::::::::::: -cpp_nested_template.i:9: Warning 324: Named nested template instantiations not supported. Processing as if no name was given to %template(). -cpp_nested_template.i:18: Warning 324: Named nested template instantiations not supported. Processing as if no name was given to %template(). - -:::::::::::::::::::::::::::::::: cpp_no_access.i ::::::::::::::::::::::::::::::::::: -cpp_no_access.i:3: Warning 319: No access specifier given for base class 'foo' (ignored). - -:::::::::::::::::::::::::::::::: cpp_no_return_type.i ::::::::::::::::::::::::::::::::::: -cpp_no_return_type.i:6: Warning 504: Function S::R() must have a return type. Ignored. -cpp_no_return_type.i:10: Warning 504: Function U::UU() must have a return type. Ignored. - -:::::::::::::::::::::::::::::::: cpp_nobase.i ::::::::::::::::::::::::::::::::::: -cpp_nobase.i:3: Warning 401: Nothing known about base class 'Bar'. Ignored. -cpp_nobase.i:6: Warning 401: Nothing known about base class 'Bar< int >'. Ignored. -cpp_nobase.i:6: Warning 401: Maybe you forgot to instantiate 'Bar< int >' using %template. - -:::::::::::::::::::::::::::::::: cpp_overload.i ::::::::::::::::::::::::::::::::::: - -:::::::::::::::::::::::::::::::: cpp_overload_const.i ::::::::::::::::::::::::::::::::::: -cpp_overload_const.i:4: Warning 509: Overloaded method check(int *) effectively ignored, -cpp_overload_const.i:3: Warning 509: as it is shadowed by check(int const *). -cpp_overload_const.i:5: Warning 509: Overloaded method check(int &) effectively ignored, -cpp_overload_const.i:3: Warning 509: as it is shadowed by check(int const *). -cpp_overload_const.i:10: Warning 509: Overloaded method check(OverStruct *) effectively ignored, -cpp_overload_const.i:9: Warning 509: as it is shadowed by check(OverStruct const *). -cpp_overload_const.i:11: Warning 509: Overloaded method check(OverStruct &) effectively ignored, -cpp_overload_const.i:9: Warning 509: as it is shadowed by check(OverStruct const *). -cpp_overload_const.i:12: Warning 509: Overloaded method check(OverStruct const &) effectively ignored, -cpp_overload_const.i:9: Warning 509: as it is shadowed by check(OverStruct const *). - -:::::::::::::::::::::::::::::::: cpp_private_defvalue.i ::::::::::::::::::::::::::::::::::: - -:::::::::::::::::::::::::::::::: cpp_private_inherit.i ::::::::::::::::::::::::::::::::::: -cpp_private_inherit.i:6: Warning 309: private inheritance from base 'Foo' (ignored). -cpp_private_inherit.i:9: Warning 309: protected inheritance from base 'Foo' (ignored). - -:::::::::::::::::::::::::::::::: cpp_recursive_typedef.i ::::::::::::::::::::::::::::::::::: -:1: Error: Recursive typedef detected resolving 'pds *' to 'std::set< pds > *' to 'std::set< std::set< pds > > *' and so on... - -:::::::::::::::::::::::::::::::: cpp_shared_ptr.i ::::::::::::::::::::::::::::::::::: -cpp_shared_ptr.i:20: Warning 520: Base class 'A' of 'C' is not similarly marked as a smart pointer. -cpp_shared_ptr.i:24: Warning 520: Derived class 'D' of 'C' is not similarly marked as a smart pointer. -cpp_shared_ptr.i:24: Warning 520: Derived class 'D' of 'B' is not similarly marked as a smart pointer. - -:::::::::::::::::::::::::::::::: cpp_template_argname.i ::::::::::::::::::::::::::::::::::: - -:::::::::::::::::::::::::::::::: cpp_template_nargs.i ::::::::::::::::::::::::::::::::::: -cpp_template_nargs.i:5: Error: Template 'blah' undefined. -cpp_template_nargs.i:6: Error: Template 'blah' undefined. - -:::::::::::::::::::::::::::::::: cpp_template_not.i ::::::::::::::::::::::::::::::::::: -cpp_template_not.i:5: Error: 'blah' is not defined as a template. (cdecl) - -:::::::::::::::::::::::::::::::: cpp_template_partial.i ::::::::::::::::::::::::::::::::::: -cpp_template_partial.i:3: Warning 317: Specialization of non-template 'vector'. - -:::::::::::::::::::::::::::::::: cpp_template_repeat.i ::::::::::::::::::::::::::::::::::: - -:::::::::::::::::::::::::::::::: cpp_template_undef.i ::::::::::::::::::::::::::::::::::: -cpp_template_undef.i:3: Error: Template 'blah' undefined. - -:::::::::::::::::::::::::::::::: cpp_using_not.i ::::::::::::::::::::::::::::::::::: -cpp_using_not.i:4: Error: 'blah' is not a namespace. - -:::::::::::::::::::::::::::::::: cpp_using_undef.i ::::::::::::::::::::::::::::::::::: -cpp_using_undef.i:4: Error: Nothing known about namespace 'foo' -cpp_using_undef.i:3: Warning 315: Nothing known about 'foo::bar'. diff --git a/Examples/test-suite/errors/make.sh b/Examples/test-suite/errors/make.sh deleted file mode 100755 index 5f96897d9..000000000 --- a/Examples/test-suite/errors/make.sh +++ /dev/null @@ -1,124 +0,0 @@ -#!/bin/sh -echo "---------------------------------------" -echo "Testing SWIG error and warning messages" -echo "---------------------------------------" - -SWIG='../../../preinst-swig' - -# Files run in C mode -CFILES=' -c_bad_name -c_bad_native -c_class -c_default_error -c_deprecated -c_empty_char -c_enum_badvalue -c_extra_rblock -c_extra_rbrace -c_extra_unsigned -c_insert_missing -c_long_short -c_missing_rbrace -c_missing_semi -c_redefine -c_varargs -c_varargs_neg -nomodule -pp_badeval -pp_constant -pp_defined -pp_deprecated -pp_illegal_argument -pp_macro_args -pp_macro_badchar -pp_macro_defined_unterminated -pp_macro_expansion -pp_macro_expansion_multiline -pp_macro_inline_unterminated -pp_macro_missing_expression -pp_macro_unexpected_tokens -pp_macro_nargs -pp_macro_redef -pp_macro_rparen -pp_macro_unterminated -pp_misplaced_elif -pp_misplaced_else -pp_missing_enddef -pp_missing_endif -pp_missing_file -pp_missing_rblock -pp_pragma -pp_unterm_char -pp_unterm_comment -pp_unterm_string -pp_variable_args -swig_apply_nargs -swig_extend -swig_identifier -swig_insert_bad -swig_typemap_copy -swig_typemap_old -swig_typemap_warn -' - -# Files run in C++ mode -CPPFILES=' -cpp_bad_extern -cpp_extend_destructors -cpp_extend_redefine -cpp_extend_undefined -cpp_inline_namespace -cpp_inherit -cpp_macro_locator -cpp_missing_rparenthesis -cpp_missing_rtemplate -cpp_namespace_alias -cpp_namespace_aliasnot -cpp_namespace_aliasundef -cpp_nested_template -cpp_no_access -cpp_no_return_type -cpp_nobase -cpp_overload -cpp_overload_const -cpp_private_defvalue -cpp_private_inherit -cpp_recursive_typedef -cpp_shared_ptr -cpp_template_argname -cpp_template_nargs -cpp_template_not -cpp_template_partial -cpp_template_repeat -cpp_template_undef -cpp_using_not -cpp_using_undef -' - -LOGFILE='test.log' -SWIGOPT=$* - -rm -f ${LOGFILE} - -echo "SWIG error and warning test. opts=${SWIGOPT}" >> ${LOGFILE} -echo "-----------------------------------------------------------" >> ${LOGFILE} - -for i in ${CFILES}; do - echo " Testing : ${i}.i"; - echo "" >> ${LOGFILE}; - echo ":::::::::::::::::::::::::::::::: ${i}.i :::::::::::::::::::::::::::::::::::" >> ${LOGFILE}; - ${SWIG} -python -Wall ${SWIGOPT} ${i}.i >>${LOGFILE} 2>&1 -done - -for i in ${CPPFILES}; do - echo " Testing : ${i}.i"; - echo "" >> ${LOGFILE} - echo ":::::::::::::::::::::::::::::::: ${i}.i :::::::::::::::::::::::::::::::::::" >> ${LOGFILE}; - ${SWIG} -python -Wall -c++ ${SWIGOPT} ${i}.i >>${LOGFILE} 2>&1 -done - -echo "" -echo "Results written to '${LOGFILE}'" - - diff --git a/Examples/test-suite/errors/nomodule.stderr b/Examples/test-suite/errors/nomodule.stderr new file mode 100644 index 000000000..5f0bcbf7c --- /dev/null +++ b/Examples/test-suite/errors/nomodule.stderr @@ -0,0 +1 @@ +No module name specified using %module or -module. diff --git a/Examples/test-suite/errors/pp_badeval.stderr b/Examples/test-suite/errors/pp_badeval.stderr new file mode 100644 index 000000000..80f5037ea --- /dev/null +++ b/Examples/test-suite/errors/pp_badeval.stderr @@ -0,0 +1,2 @@ +pp_badeval.i:4: Warning 202: Could not evaluate expression 'FOO==4+' +pp_badeval.i:4: Warning 202: Error: 'Expected an expression' diff --git a/Examples/test-suite/errors/pp_constant.stderr b/Examples/test-suite/errors/pp_constant.stderr new file mode 100644 index 000000000..9c79ec2be --- /dev/null +++ b/Examples/test-suite/errors/pp_constant.stderr @@ -0,0 +1,8 @@ +pp_constant.i:9: Warning 305: Bad constant value (ignored). +pp_constant.i:15: Warning 305: Bad constant value (ignored). +pp_constant.i:23: Warning 305: Bad constant value (ignored). +pp_constant.i:29: Warning 305: Bad constant value (ignored). +pp_constant.i:35: Warning 305: Bad constant value (ignored). +pp_constant.i:42: Warning 305: Bad constant value (ignored). +pp_constant.i:46: Warning 305: Bad constant value (ignored). +pp_constant.i:49: Warning 305: Bad constant value (ignored). diff --git a/Examples/test-suite/errors/pp_defined.stderr b/Examples/test-suite/errors/pp_defined.stderr new file mode 100644 index 000000000..b707084e9 --- /dev/null +++ b/Examples/test-suite/errors/pp_defined.stderr @@ -0,0 +1,2 @@ +pp_defined.i:6: Error: No arguments given to defined() +pp_defined.i:6: Error: Missing expression for #if. diff --git a/Examples/test-suite/errors/pp_deprecated.stderr b/Examples/test-suite/errors/pp_deprecated.stderr new file mode 100644 index 000000000..6eff001ac --- /dev/null +++ b/Examples/test-suite/errors/pp_deprecated.stderr @@ -0,0 +1,4 @@ +pp_deprecated.i:4: Warning 101: %extern is deprecated. Use %import instead. +pp_deprecated.i:4: Error: Unable to find 'ext;' +pp_deprecated.i:6: Warning 204: CPP #warning, "Print this warning". +pp_deprecated.i:8: Error: CPP #error "This is an error". Use the -cpperraswarn option to continue swig processing. diff --git a/Examples/test-suite/errors/pp_illegal_argument.stderr b/Examples/test-suite/errors/pp_illegal_argument.stderr new file mode 100644 index 000000000..78995d805 --- /dev/null +++ b/Examples/test-suite/errors/pp_illegal_argument.stderr @@ -0,0 +1,3 @@ +pp_illegal_argument.i:6: Error: Illegal macro argument name '..' +pp_illegal_argument.i:10: Error: Illegal macro argument name '..' +pp_illegal_argument.i:16: Error: Illegal character in macro argument name diff --git a/Examples/test-suite/errors/pp_macro_args.stderr b/Examples/test-suite/errors/pp_macro_args.stderr new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/test-suite/errors/pp_macro_badchar.stderr b/Examples/test-suite/errors/pp_macro_badchar.stderr new file mode 100644 index 000000000..3c00583af --- /dev/null +++ b/Examples/test-suite/errors/pp_macro_badchar.stderr @@ -0,0 +1 @@ +pp_macro_badchar.i:4: Error: Illegal character in macro argument name diff --git a/Examples/test-suite/errors/pp_macro_defined_unterminated.stderr b/Examples/test-suite/errors/pp_macro_defined_unterminated.stderr new file mode 100644 index 000000000..230175bf8 --- /dev/null +++ b/Examples/test-suite/errors/pp_macro_defined_unterminated.stderr @@ -0,0 +1 @@ +pp_macro_defined_unterminated.i:4: Error: Unterminated call to 'defined' diff --git a/Examples/test-suite/errors/pp_macro_expansion.stderr b/Examples/test-suite/errors/pp_macro_expansion.stderr new file mode 100644 index 000000000..b8e718919 --- /dev/null +++ b/Examples/test-suite/errors/pp_macro_expansion.stderr @@ -0,0 +1 @@ +pp_macro_expansion.i:9: Error: Macro 'MACRO2' expects 2 arguments diff --git a/Examples/test-suite/errors/pp_macro_expansion_multiline.stderr b/Examples/test-suite/errors/pp_macro_expansion_multiline.stderr new file mode 100644 index 000000000..bf5fbfbbf --- /dev/null +++ b/Examples/test-suite/errors/pp_macro_expansion_multiline.stderr @@ -0,0 +1,4 @@ +pp_macro_expansion_multiline.i:13: Warning 509: Overloaded method foo(int const *) effectively ignored, +pp_macro_expansion_multiline.i:12: Warning 509: as it is shadowed by foo(int *). +pp_macro_expansion_multiline.i:31: Warning 509: Overloaded method bar(int const *) effectively ignored, +pp_macro_expansion_multiline.i:30: Warning 509: as it is shadowed by bar(int *). diff --git a/Examples/test-suite/errors/pp_macro_inline_unterminated.stderr b/Examples/test-suite/errors/pp_macro_inline_unterminated.stderr new file mode 100644 index 000000000..f7452de14 --- /dev/null +++ b/Examples/test-suite/errors/pp_macro_inline_unterminated.stderr @@ -0,0 +1,2 @@ +pp_macro_inline_unterminated.i:9: Error: Unterminated call invoking macro 'foo' +pp_macro_inline_unterminated.i:12: Error: Syntax error in input(3). diff --git a/Examples/test-suite/errors/pp_macro_missing_expression.stderr b/Examples/test-suite/errors/pp_macro_missing_expression.stderr new file mode 100644 index 000000000..1e07b6542 --- /dev/null +++ b/Examples/test-suite/errors/pp_macro_missing_expression.stderr @@ -0,0 +1,5 @@ +pp_macro_missing_expression.i:4: Error: Missing identifier for #ifdef. +pp_macro_missing_expression.i:7: Error: Missing identifier for #ifndef. +pp_macro_missing_expression.i:10: Error: Missing expression for #if. +pp_macro_missing_expression.i:14: Error: Missing expression for #elif. +pp_macro_missing_expression.i:21: Error: Missing expression for #elif. diff --git a/Examples/test-suite/errors/pp_macro_nargs.stderr b/Examples/test-suite/errors/pp_macro_nargs.stderr new file mode 100644 index 000000000..23e1bf439 --- /dev/null +++ b/Examples/test-suite/errors/pp_macro_nargs.stderr @@ -0,0 +1,4 @@ +pp_macro_nargs.i:7: Error: Macro 'foo' expects 2 arguments +pp_macro_nargs.i:8: Error: Macro 'foo' expects 2 arguments +pp_macro_nargs.i:10: Error: Macro 'bar' expects 1 argument +pp_macro_nargs.i:11: Error: Macro 'spam' expects no arguments diff --git a/Examples/test-suite/errors/pp_macro_redef.stderr b/Examples/test-suite/errors/pp_macro_redef.stderr new file mode 100644 index 000000000..6de0ca4bc --- /dev/null +++ b/Examples/test-suite/errors/pp_macro_redef.stderr @@ -0,0 +1,4 @@ +pp_macro_redef.i:4: Error: Macro 'foo' redefined, +pp_macro_redef.i:3: Error: previous definition of 'foo'. +pp_macro_redef.i:7: Error: Macro 'foo' redefined, +pp_macro_redef.i:3: Error: previous definition of 'foo'. diff --git a/Examples/test-suite/errors/pp_macro_rparen.stderr b/Examples/test-suite/errors/pp_macro_rparen.stderr new file mode 100644 index 000000000..755aeba48 --- /dev/null +++ b/Examples/test-suite/errors/pp_macro_rparen.stderr @@ -0,0 +1 @@ +pp_macro_rparen.i:3: Error: Missing ')' in macro parameters diff --git a/Examples/test-suite/errors/pp_macro_unexpected_tokens.stderr b/Examples/test-suite/errors/pp_macro_unexpected_tokens.stderr new file mode 100644 index 000000000..d0efd9f12 --- /dev/null +++ b/Examples/test-suite/errors/pp_macro_unexpected_tokens.stderr @@ -0,0 +1,5 @@ +pp_macro_unexpected_tokens.i:5: Warning 206: Unexpected tokens after #endif directive. +pp_macro_unexpected_tokens.i:8: Warning 206: Unexpected tokens after #endif directive. +pp_macro_unexpected_tokens.i:11: Warning 206: Unexpected tokens after #else directive. +pp_macro_unexpected_tokens.i:18: Warning 206: Unexpected tokens after #endif directive. +pp_macro_unexpected_tokens.i:21: Warning 206: Unexpected tokens after #else directive. diff --git a/Examples/test-suite/errors/pp_macro_unterminated.stderr b/Examples/test-suite/errors/pp_macro_unterminated.stderr new file mode 100644 index 000000000..a3ba264f5 --- /dev/null +++ b/Examples/test-suite/errors/pp_macro_unterminated.stderr @@ -0,0 +1 @@ +pp_macro_unterminated.i:5: Error: Unterminated call invoking macro 'foo' diff --git a/Examples/test-suite/errors/pp_misplaced_elif.stderr b/Examples/test-suite/errors/pp_misplaced_elif.stderr new file mode 100644 index 000000000..06f1c457e --- /dev/null +++ b/Examples/test-suite/errors/pp_misplaced_elif.stderr @@ -0,0 +1,2 @@ +pp_misplaced_elif.i:4: Error: Misplaced #elif. +pp_misplaced_elif.i:6: Error: Extraneous #endif. diff --git a/Examples/test-suite/errors/pp_misplaced_else.stderr b/Examples/test-suite/errors/pp_misplaced_else.stderr new file mode 100644 index 000000000..455d90f0f --- /dev/null +++ b/Examples/test-suite/errors/pp_misplaced_else.stderr @@ -0,0 +1,2 @@ +pp_misplaced_else.i:4: Error: Misplaced #else. +pp_misplaced_else.i:6: Error: Extraneous #endif. diff --git a/Examples/test-suite/errors/pp_missing_enddef.stderr b/Examples/test-suite/errors/pp_missing_enddef.stderr new file mode 100644 index 000000000..bb4ea3c75 --- /dev/null +++ b/Examples/test-suite/errors/pp_missing_enddef.stderr @@ -0,0 +1 @@ +pp_missing_enddef.i:EOF: Error: Missing %enddef for macro starting on line 3 diff --git a/Examples/test-suite/errors/pp_missing_endif.stderr b/Examples/test-suite/errors/pp_missing_endif.stderr new file mode 100644 index 000000000..0bbfad7f2 --- /dev/null +++ b/Examples/test-suite/errors/pp_missing_endif.stderr @@ -0,0 +1 @@ +pp_missing_endif.i:EOF: Error: Missing #endif for conditional starting on line 3 diff --git a/Examples/test-suite/errors/pp_missing_file.stderr b/Examples/test-suite/errors/pp_missing_file.stderr new file mode 100644 index 000000000..2325a33fa --- /dev/null +++ b/Examples/test-suite/errors/pp_missing_file.stderr @@ -0,0 +1 @@ +pp_missing_file.i:3: Error: Unable to find 'missing_filename.i' diff --git a/Examples/test-suite/errors/pp_missing_rblock.stderr b/Examples/test-suite/errors/pp_missing_rblock.stderr new file mode 100644 index 000000000..8f4a54c0a --- /dev/null +++ b/Examples/test-suite/errors/pp_missing_rblock.stderr @@ -0,0 +1 @@ +pp_missing_rblock.i:EOF: Error: Unterminated %{ ... %} block starting on line 3 diff --git a/Examples/test-suite/errors/pp_pragma.stderr b/Examples/test-suite/errors/pp_pragma.stderr new file mode 100644 index 000000000..5f4526c42 --- /dev/null +++ b/Examples/test-suite/errors/pp_pragma.stderr @@ -0,0 +1 @@ +pp_pragma.i:4: Error: Unknown SWIG pragma: rubbish() diff --git a/Examples/test-suite/errors/pp_unterm_char.stderr b/Examples/test-suite/errors/pp_unterm_char.stderr new file mode 100644 index 000000000..4386e933d --- /dev/null +++ b/Examples/test-suite/errors/pp_unterm_char.stderr @@ -0,0 +1 @@ +pp_unterm_char.i:EOF: Error: Unterminated character constant starting at line 4 diff --git a/Examples/test-suite/errors/pp_unterm_comment.stderr b/Examples/test-suite/errors/pp_unterm_comment.stderr new file mode 100644 index 000000000..4ff34230c --- /dev/null +++ b/Examples/test-suite/errors/pp_unterm_comment.stderr @@ -0,0 +1 @@ +pp_unterm_comment.i:EOF: Error: Unterminated comment starting on line 3 diff --git a/Examples/test-suite/errors/pp_unterm_string.stderr b/Examples/test-suite/errors/pp_unterm_string.stderr new file mode 100644 index 000000000..16b4034f3 --- /dev/null +++ b/Examples/test-suite/errors/pp_unterm_string.stderr @@ -0,0 +1 @@ +pp_unterm_string.i:EOF: Error: Unterminated string constant starting at line 4 diff --git a/Examples/test-suite/errors/pp_variable_args.stderr b/Examples/test-suite/errors/pp_variable_args.stderr new file mode 100644 index 000000000..68d3fe580 --- /dev/null +++ b/Examples/test-suite/errors/pp_variable_args.stderr @@ -0,0 +1 @@ +pp_variable_args.i:6: Error: Variable length macro argument must be last parameter diff --git a/Examples/test-suite/errors/swig_apply_nargs.stderr b/Examples/test-suite/errors/swig_apply_nargs.stderr new file mode 100644 index 000000000..e0eff6d6a --- /dev/null +++ b/Examples/test-suite/errors/swig_apply_nargs.stderr @@ -0,0 +1 @@ +swig_apply_nargs.i:6: Error: Can't apply (char *str,int len) to (int x). Number of arguments don't match. diff --git a/Examples/test-suite/errors/swig_extend.stderr b/Examples/test-suite/errors/swig_extend.stderr new file mode 100644 index 000000000..aa42d7828 --- /dev/null +++ b/Examples/test-suite/errors/swig_extend.stderr @@ -0,0 +1,8 @@ +swig_extend.i:19: Warning 326: Deprecated %extend name used - the struct name 'StructBName' should be used instead of the typedef name 'StructB'. +swig_extend.i:45: Warning 326: Deprecated %extend name used - the struct name 'stru_struct' should be used instead of the typedef name 'stru'. +swig_extend.i:56: Warning 326: Deprecated %extend name used - the union name 'uni_union' should be used instead of the typedef name 'uni'. +swig_extend.i:34: Warning 303: %extend defined for an undeclared class StructDName. +swig_extend.i:50: Warning 522: Use of an illegal constructor name 'stru' in %extend is deprecated, the constructor name should be 'stru_struct'. +swig_extend.i:53: Warning 523: Use of an illegal destructor name 'stru' in %extend is deprecated, the destructor name should be 'stru_struct'. +swig_extend.i:57: Warning 522: Use of an illegal constructor name 'uni' in %extend is deprecated, the constructor name should be 'uni_union'. +swig_extend.i:58: Warning 523: Use of an illegal destructor name 'uni' in %extend is deprecated, the destructor name should be 'uni_union'. diff --git a/Examples/test-suite/errors/swig_identifier.stderr b/Examples/test-suite/errors/swig_identifier.stderr new file mode 100644 index 000000000..60ea5451b --- /dev/null +++ b/Examples/test-suite/errors/swig_identifier.stderr @@ -0,0 +1 @@ +swig_identifier.i:5: Warning 503: Can't wrap 'foo bar' unless renamed to a valid identifier. diff --git a/Examples/test-suite/errors/swig_insert_bad.stderr b/Examples/test-suite/errors/swig_insert_bad.stderr new file mode 100644 index 000000000..cb65c356d --- /dev/null +++ b/Examples/test-suite/errors/swig_insert_bad.stderr @@ -0,0 +1 @@ +swig_insert_bad.i:5: Error: Unknown target 'foobar' for %insert directive. diff --git a/Examples/test-suite/errors/swig_typemap_copy.stderr b/Examples/test-suite/errors/swig_typemap_copy.stderr new file mode 100644 index 000000000..a849e3162 --- /dev/null +++ b/Examples/test-suite/errors/swig_typemap_copy.stderr @@ -0,0 +1 @@ +swig_typemap_copy.i:3: Error: Can't copy typemap (in) blah = int diff --git a/Examples/test-suite/errors/swig_typemap_old.stderr b/Examples/test-suite/errors/swig_typemap_old.stderr new file mode 100644 index 000000000..23741164e --- /dev/null +++ b/Examples/test-suite/errors/swig_typemap_old.stderr @@ -0,0 +1,6 @@ +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. +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 +Doc/Manual/Typemaps.html for complete details. diff --git a/Examples/test-suite/errors/swig_typemap_warn.stderr b/Examples/test-suite/errors/swig_typemap_warn.stderr new file mode 100644 index 000000000..5116dbc91 --- /dev/null +++ b/Examples/test-suite/errors/swig_typemap_warn.stderr @@ -0,0 +1,7 @@ +swig_typemap_warn.i:7: Warning 1000: Test warning for 'in' typemap for int abc (arg1) - argnum: 1 &1_ltype: int * descriptor: SWIGTYPE_int +swig_typemap_warn.i:7: Warning 1000: Test warning for 'in' typemap for int arg3 (arg3) - argnum: 3 &1_ltype: int * descriptor: SWIGTYPE_int +swig_typemap_warn.i:7: Warning 1001: Test warning for 'out' typemap for double mmm (result) - name: mmm symname: mmm &1_ltype: double * descriptor: SWIGTYPE_double +swig_typemap_warn.i:7: Warning 1000: Test warning for 'in' typemap for int abc (arg1) - argnum: 1 &1_ltype: int * descriptor: SWIGTYPE_int +swig_typemap_warn.i:7: Warning 1000: Test warning for 'in' typemap for int arg3 (arg3) - argnum: 3 &1_ltype: int * descriptor: SWIGTYPE_int +swig_typemap_warn.i:7: Warning 1000: Test warning for 'in' typemap for int abc (arg1) - argnum: 1 &1_ltype: int * descriptor: SWIGTYPE_int +swig_typemap_warn.i:7: Warning 1000: Test warning for 'in' typemap for int arg3 (arg3) - argnum: 3 &1_ltype: int * descriptor: SWIGTYPE_int diff --git a/Makefile.in b/Makefile.in index aa1c3d63f..ea7814242 100644 --- a/Makefile.in +++ b/Makefile.in @@ -89,6 +89,9 @@ skip-d = test -n "@SKIP_D@" skip-gcj = test -n "@SKIP_GCJ@" skip-android = test -n "@SKIP_ANDROID@" +# Special errors test-case +skip-errors = test -n "" + ##################################################################### # CHECK ##################################################################### @@ -249,6 +252,7 @@ java.actionexample: # Checks testcases in the test-suite excluding those which are known to be broken check-test-suite: \ + check-errors-test-suite \ check-tcl-test-suite \ check-perl5-test-suite \ check-python-test-suite \ diff --git a/configure.ac b/configure.ac index 3acc2aa9e..f048ccda5 100644 --- a/configure.ac +++ b/configure.ac @@ -2388,6 +2388,7 @@ AC_CONFIG_FILES([ \ Source/Makefile \ Examples/Makefile \ Examples/xml/Makefile \ + Examples/test-suite/errors/Makefile \ Examples/test-suite/chicken/Makefile \ Examples/test-suite/csharp/Makefile \ Examples/test-suite/d/Makefile \ From d7e614f71654d1ca744b96ce553e58bd447fbef7 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 19 Jan 2014 00:23:42 +0000 Subject: [PATCH 293/481] Remove debug output on 'Empty character constant' error --- Source/CParse/cscanner.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/Source/CParse/cscanner.c b/Source/CParse/cscanner.c index 4e02b4b62..de00e2b1f 100644 --- a/Source/CParse/cscanner.c +++ b/Source/CParse/cscanner.c @@ -315,7 +315,6 @@ static int yylook(void) { yylval.str = NewString(Scanner_text(scan)); if (Len(yylval.str) == 0) { Swig_error(cparse_file, cparse_line, "Empty character constant\n"); - Printf(stdout,"%d\n", Len(Scanner_text(scan))); } return CHARCONST; @@ -323,7 +322,6 @@ static int yylook(void) { yylval.str = NewString(Scanner_text(scan)); if (Len(yylval.str) == 0) { Swig_error(cparse_file, cparse_line, "Empty character constant\n"); - Printf(stdout,"%d\n", Len(Scanner_text(scan))); } return WCHARCONST; From e323d9d7b391e4a48fb15a5d8a089a293c7b3742 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 19 Jan 2014 20:45:22 +0000 Subject: [PATCH 294/481] Add 'make install' to Travis testing --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index ad771df9c..46ffb9fd8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -52,6 +52,7 @@ script: - ./swig -version - if test -z "$SWIGLANG"; then make -s $SWIGJOBS check-ccache; fi - if test -z "$SWIGLANG"; then make -s $SWIGJOBS check-errors-test-suite; fi + - if test -z "$SWIGLANG"; then make -s install && swig -version && ccache-swig -version; fi - if test -n "$SWIGLANG"; then make -s check-$SWIGLANG-version; fi - if test -n "$SWIGLANG"; then make -k $SWIGJOBS check-$SWIGLANG-examples; fi - if test -n "$SWIGLANG"; then make -k $SWIGJOBS check-$SWIGLANG-test-suite; fi From af6bee1e8c39eb80ad54a021380f2af32902f99b Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 19 Jan 2014 22:09:52 +0000 Subject: [PATCH 295/481] Travis build fixes for checking 'make install' --- .travis.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 46ffb9fd8..fd0a95b94 100644 --- a/.travis.yml +++ b/.travis.yml @@ -38,6 +38,7 @@ before_install: - uname -a - sudo apt-get -qq update - time sudo apt-get -qq install libboost-dev + - if test -z "$SWIGLANG"; then sudo apt-get -qq install yodl; fi - if test "$SWIGLANG" = "csharp"; then sudo apt-get -qq install mono-devel; fi - if test "$SWIGLANG" = "go"; then go env | sed -e 's/^/export /' > goenvsetup && source goenvsetup && rm -f goenvsetup; fi # Until configure.ac is fixed - if test "$SWIGLANG" = "guile"; then sudo apt-get -qq install guile-2.0-dev; fi @@ -52,7 +53,7 @@ script: - ./swig -version - if test -z "$SWIGLANG"; then make -s $SWIGJOBS check-ccache; fi - if test -z "$SWIGLANG"; then make -s $SWIGJOBS check-errors-test-suite; fi - - if test -z "$SWIGLANG"; then make -s install && swig -version && ccache-swig -version; fi + - if test -z "$SWIGLANG"; then sudo make -s install && swig -version && ccache-swig -V; fi - if test -n "$SWIGLANG"; then make -s check-$SWIGLANG-version; fi - if test -n "$SWIGLANG"; then make -k $SWIGJOBS check-$SWIGLANG-examples; fi - if test -n "$SWIGLANG"; then make -k $SWIGJOBS check-$SWIGLANG-test-suite; fi From cc650e692e3e1201092d99a34a04e3af11ee2347 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 20 Jan 2014 19:40:52 +0000 Subject: [PATCH 296/481] Director exceptions now derive from std::exception --- CHANGES.current | 5 +++++ Lib/csharp/director.swg | 11 ++++++----- Lib/d/director.swg | 16 +++++++--------- Lib/java/director.swg | 4 ++-- Lib/ocaml/director.swg | 33 +++++++++++++++++---------------- Lib/octave/director.swg | 2 ++ Lib/perl5/director.swg | 29 +++++++++++++++-------------- Lib/php/director.swg | 19 ++++++++++++++----- Lib/python/director.swg | 28 ++++++++++++++++++---------- Lib/ruby/director.swg | 30 ++++++++++++++++++------------ 10 files changed, 104 insertions(+), 73 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index 5dd602f35..68b34270a 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,11 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2014-01-20: wsfulton + Director exceptions (Swig::DirectorException) now derive from std::exception + and hence provide the what() method. In Python and Ruby, this replaces the now + deprecated DirectorException::getMessage() method. + 2014-01-16: wsfulton [PHP] Fix compilation error in ZTS mode (64 bit windows) due to incorrect placement of TSRMLS_FETCH() in SWIG_Php_GetModule() as reported by Mark Dawson-Butterworth. diff --git a/Lib/csharp/director.swg b/Lib/csharp/director.swg index 403a0ac34..3438f2bf0 100644 --- a/Lib/csharp/director.swg +++ b/Lib/csharp/director.swg @@ -9,6 +9,7 @@ #include #endif #include +#include namespace Swig { /* Director base class - not currently used in C# directors */ @@ -16,7 +17,7 @@ namespace Swig { }; /* Base class for director exceptions */ - class DirectorException { + class DirectorException : public std::exception { protected: std::string swig_msg; @@ -27,16 +28,16 @@ namespace Swig { DirectorException(const std::string &msg) : swig_msg(msg) { } - const std::string& what() const { - return swig_msg; + virtual ~DirectorException() throw() { } - virtual ~DirectorException() { + const char *what() const throw() { + return swig_msg.c_str(); } }; /* Pure virtual method exception */ - class DirectorPureVirtualException : public Swig::DirectorException { + class DirectorPureVirtualException : public DirectorException { public: DirectorPureVirtualException(const char *msg) : DirectorException(std::string("Attempt to invoke pure virtual method ") + msg) { } diff --git a/Lib/d/director.swg b/Lib/d/director.swg index 6b6537103..a7d9c7688 100644 --- a/Lib/d/director.swg +++ b/Lib/d/director.swg @@ -9,6 +9,7 @@ #include #endif #include +#include namespace Swig { @@ -17,28 +18,25 @@ namespace Swig { }; // Base class for director exceptions. - class DirectorException { + class DirectorException : public std::exception { protected: std::string swig_msg; public: - DirectorException(const char *msg) : swig_msg(msg) { - } - DirectorException(const std::string &msg) : swig_msg(msg) { } - const std::string& what() const { - return swig_msg; + virtual ~DirectorException() throw() { } - virtual ~DirectorException() { + const char *what() const throw() { + return swig_msg.c_str(); } }; // Exception which is thrown when attempting to call a pure virtual method - // from D code thorugh the director layer. - class DirectorPureVirtualException : public Swig::DirectorException { + // from D code through the director layer. + class DirectorPureVirtualException : public DirectorException { public: DirectorPureVirtualException(const char *msg) : DirectorException(std::string("Attempted to invoke pure virtual method ") + msg) { } diff --git a/Lib/java/director.swg b/Lib/java/director.swg index 72f166406..819ad903d 100644 --- a/Lib/java/director.swg +++ b/Lib/java/director.swg @@ -1,8 +1,8 @@ /* ----------------------------------------------------------------------------- * director.swg * - * This file contains support for director classes that proxy - * method calls from C++ to Java extensions. + * This file contains support for director classes so that Java proxy + * methods can be called from C++. * ----------------------------------------------------------------------------- */ #if defined(DEBUG_DIRECTOR_OWNED) || defined(DEBUG_DIRECTOR_EXCEPTION) diff --git a/Lib/ocaml/director.swg b/Lib/ocaml/director.swg index 0f997acd0..fea0cada6 100644 --- a/Lib/ocaml/director.swg +++ b/Lib/ocaml/director.swg @@ -1,46 +1,47 @@ /* ----------------------------------------------------------------------------- * director.swg * - * This file contains support for director classes that proxy - * method calls from C++ to Ocaml extensions. - * + * This file contains support for director classes so that Ocaml proxy + * methods can be called from C++. * ----------------------------------------------------------------------------- */ #include +#include # define SWIG_DIRECTOR_CAST(ARG) dynamic_cast(ARG) namespace Swig { /* base class for director exceptions */ - class DirectorException { + class DirectorException : public std::exception { protected: std::string swig_msg; + public: - DirectorException(const char *msg="") { + DirectorException(const char *msg="") : swig_msg(msg) { } - const char *getMessage() const { + virtual ~DirectorException() throw() { + } + + const char *what() const throw() { return swig_msg.c_str(); } - - virtual ~DirectorException() { - } }; - /* type mismatch in the return value from a python method call */ - class DirectorTypeMismatchException : public Swig::DirectorException { + /* type mismatch in the return value from a Ocaml method call */ + class DirectorTypeMismatchException : public DirectorException { public: - DirectorTypeMismatchException(const char *msg="") { + DirectorTypeMismatchException(const char *msg="") : DirectorException(msg) { } }; - /* any python exception that occurs during a director method call */ - class DirectorMethodException : public Swig::DirectorException {}; + /* any Ocaml exception that occurs during a director method call */ + class DirectorMethodException : public DirectorException {}; /* attempt to call a pure virtual method via a director method */ - class DirectorPureVirtualException : public Swig::DirectorException { + class DirectorPureVirtualException : public DirectorException { public: - DirectorPureVirtualException(const char *msg="") { + DirectorPureVirtualException(const char *msg="") : DirectorException(msg) { } static void raise(const char *msg) { diff --git a/Lib/octave/director.swg b/Lib/octave/director.swg index 96bbf03cc..c399a6a89 100644 --- a/Lib/octave/director.swg +++ b/Lib/octave/director.swg @@ -7,6 +7,8 @@ # define SWIG_DIRECTOR_CAST(ARG) dynamic_cast(ARG) +#include + namespace Swig { class Director { diff --git a/Lib/perl5/director.swg b/Lib/perl5/director.swg index 9fa64e147..a66869725 100644 --- a/Lib/perl5/director.swg +++ b/Lib/perl5/director.swg @@ -1,8 +1,8 @@ /* ----------------------------------------------------------------------------- * director.swg * - * This file contains support for director classes that proxy - * method calls from C++ to Perl extensions. + * This file contains support for director classes so that Perl proxy + * methods can be called from C++. * ----------------------------------------------------------------------------- */ #ifndef SWIG_DIRECTOR_PERL_HEADER_ @@ -138,14 +138,13 @@ namespace Swig { }; /* base class for director exceptions */ - class DirectorException { + class DirectorException : public std::exception { public: - virtual const char *getMessage() const = 0; virtual SV *getNative() const = 0; }; /* exceptions emitted by Perl */ - class DirectorMethodException : public Swig::DirectorException { + class DirectorMethodException : public DirectorException { protected: SV *err; public: @@ -153,11 +152,7 @@ namespace Swig { SvREFCNT_inc(err); } - ~DirectorMethodException() { - SvREFCNT_dec(err); - } - - const char *getMessage() const { + const char *what() const throw() { return SvPV_nolen(err); } @@ -169,15 +164,19 @@ namespace Swig { throw DirectorMethodException(sv); } }; + /* exceptions emitted by wrap code */ - class DirectorWrapException : public Swig::DirectorException { + class DirectorWrapException : public DirectorException { protected: std::string msg; DirectorWrapException(const char *str) : msg(str) { } public: - virtual const char *getMessage() const { + virtual ~DirectorWrapException() throw() { + } + + const char *what() const throw() { return msg.c_str(); } @@ -186,10 +185,11 @@ namespace Swig { } }; - class DirectorTypeMismatchException : public Swig::DirectorWrapException { + class DirectorTypeMismatchException : public DirectorWrapException { public: DirectorTypeMismatchException(const char *str) : DirectorWrapException(str) { } + static void raise(const char *type, const char *msg) { std::string err = std::string(type); err += ": "; @@ -198,12 +198,13 @@ namespace Swig { } }; - class DirectorPureVirtualException : public Swig::DirectorWrapException { + class DirectorPureVirtualException : public DirectorWrapException { public: DirectorPureVirtualException(const char *name) : DirectorWrapException("SWIG director pure virtual method called: ") { msg += name; } + static void raise(const char *name) { throw DirectorPureVirtualException(name); } diff --git a/Lib/php/director.swg b/Lib/php/director.swg index 2b176ed09..50b433e47 100644 --- a/Lib/php/director.swg +++ b/Lib/php/director.swg @@ -1,14 +1,15 @@ /* ----------------------------------------------------------------------------- * director.swg * - * This file contains support for director classes that proxy - * method calls from C++ to PHP extensions. + * This file contains support for director classes so that PHP proxy + * methods can be called from C++. * ----------------------------------------------------------------------------- */ #ifndef SWIG_DIRECTOR_PHP_HEADER_ #define SWIG_DIRECTOR_PHP_HEADER_ #include +#include #include /* @@ -122,7 +123,7 @@ namespace Swig { }; /* base class for director exceptions */ - class DirectorException { + class DirectorException : public std::exception { protected: std::string swig_msg; public: @@ -135,13 +136,20 @@ namespace Swig { SWIG_ErrorMsg() = swig_msg.c_str(); } + virtual ~DirectorException() throw() { + } + + const char *what() const throw() { + return swig_msg.c_str(); + } + static void raise(int code, const char *hdr, const char *msg TSRMLS_DC) { throw DirectorException(code, hdr, msg TSRMLS_CC); } }; /* attempt to call a pure virtual method via a director method */ - class DirectorPureVirtualException : public Swig::DirectorException { + class DirectorPureVirtualException : public DirectorException { public: DirectorPureVirtualException(const char *msg TSRMLS_DC) : DirectorException(E_ERROR, "SWIG director pure virtual method called", msg TSRMLS_CC) { @@ -151,8 +159,9 @@ namespace Swig { throw DirectorPureVirtualException(msg TSRMLS_CC); } }; + /* any php exception that occurs during a director method call */ - class DirectorMethodException : public Swig::DirectorException + class DirectorMethodException : public DirectorException { public: DirectorMethodException(const char *msg TSRMLS_DC) diff --git a/Lib/python/director.swg b/Lib/python/director.swg index 3eac683f9..bca22af4e 100644 --- a/Lib/python/director.swg +++ b/Lib/python/director.swg @@ -1,8 +1,8 @@ /* ----------------------------------------------------------------------------- * director.swg * - * This file contains support for director classes that proxy - * method calls from C++ to Python extensions. + * This file contains support for director classes so that Python proxy + * methods can be called from C++. * ----------------------------------------------------------------------------- */ #ifndef SWIG_DIRECTOR_PYTHON_HEADER_ @@ -173,7 +173,7 @@ namespace Swig { }; /* base class for director exceptions */ - class DirectorException { + class DirectorException : public std::exception { protected: std::string swig_msg; public: @@ -184,12 +184,20 @@ namespace Swig { swig_msg += msg; } if (!PyErr_Occurred()) { - PyErr_SetString(error, getMessage()); + PyErr_SetString(error, what()); } SWIG_PYTHON_THREAD_END_BLOCK; } + virtual ~DirectorException() throw() { + } + + /* Deprecated, use what() instead */ const char *getMessage() const { + return what(); + } + + const char *what() const throw() { return swig_msg.c_str(); } @@ -210,7 +218,7 @@ namespace Swig { throw; } catch (DirectorException& e) { std::cerr << "SWIG Director exception caught:" << std::endl - << e.getMessage() << std::endl; + << e.what() << std::endl; } catch (std::exception& e) { std::cerr << "std::exception caught: "<< e.what() << std::endl; } catch (...) { @@ -243,14 +251,14 @@ namespace Swig { }; /* type mismatch in the return value from a python method call */ - class DirectorTypeMismatchException : public Swig::DirectorException { + class DirectorTypeMismatchException : public DirectorException { public: DirectorTypeMismatchException(PyObject *error, const char *msg="") - : Swig::DirectorException(error, "SWIG director type mismatch", msg) { + : DirectorException(error, "SWIG director type mismatch", msg) { } DirectorTypeMismatchException(const char *msg="") - : Swig::DirectorException(PyExc_TypeError, "SWIG director type mismatch", msg) { + : DirectorException(PyExc_TypeError, "SWIG director type mismatch", msg) { } static void raise(PyObject *error, const char *msg) { @@ -263,7 +271,7 @@ namespace Swig { }; /* any python exception that occurs during a director method call */ - class DirectorMethodException : public Swig::DirectorException { + class DirectorMethodException : public DirectorException { public: DirectorMethodException(const char *msg = "") : DirectorException(PyExc_RuntimeError, "SWIG director method error.", msg) { @@ -275,7 +283,7 @@ namespace Swig { }; /* attempt to call a pure virtual method via a director method */ - class DirectorPureVirtualException : public Swig::DirectorException { + class DirectorPureVirtualException : public DirectorException { public: DirectorPureVirtualException(const char *msg = "") : DirectorException(PyExc_RuntimeError, "SWIG director pure virtual method called", msg) { diff --git a/Lib/ruby/director.swg b/Lib/ruby/director.swg index 23aa6da48..3b1837374 100644 --- a/Lib/ruby/director.swg +++ b/Lib/ruby/director.swg @@ -1,8 +1,8 @@ /* ----------------------------------------------------------------------------- * director.swg * - * This file contains support for director classes that proxy - * method calls from C++ to Ruby extensions. + * This file contains support for director classes so that Ruby proxy + * methods can be called from C++. * ----------------------------------------------------------------------------- */ /* @@ -17,6 +17,7 @@ #include #include +#include #include # define SWIG_DIRECTOR_CAST(ARG) dynamic_cast(ARG) @@ -108,7 +109,7 @@ namespace Swig { }; /* Base class for director exceptions */ - class DirectorException { + class DirectorException : public std::exception { protected: VALUE swig_error; std::string swig_msg; @@ -130,6 +131,9 @@ namespace Swig { } public: + virtual ~DirectorException() throw() { + } + VALUE getType() const { return CLASS_OF(swig_error); } @@ -138,11 +142,13 @@ namespace Swig { return swig_error; } + /* Deprecated, use what() instead */ const std::string& getMessage() const { return swig_msg; } - virtual ~DirectorException() { + const char *what() const throw() { + return swig_msg.c_str(); } }; @@ -154,7 +160,7 @@ namespace Swig { throw; } catch (DirectorException& e) { std::cerr << "SWIG Director exception caught:" << std::endl - << e.getMessage() << std::endl; + << e.what() << std::endl; } catch (std::exception& e) { std::cerr << "std::exception caught: "<< e.what() << std::endl; } catch (...) { @@ -184,14 +190,14 @@ namespace Swig { /* Type mismatch in the return value from a Ruby method call */ - class DirectorTypeMismatchException : public Swig::DirectorException { + class DirectorTypeMismatchException : public DirectorException { public: DirectorTypeMismatchException(VALUE error, const char *msg="") - : Swig::DirectorException(error, "SWIG director type mismatch", msg) { + : DirectorException(error, "SWIG director type mismatch", msg) { } DirectorTypeMismatchException(const char *msg="") - : Swig::DirectorException(rb_eTypeError, "SWIG director type mismatch", msg) { + : DirectorException(rb_eTypeError, "SWIG director type mismatch", msg) { } static void raise(VALUE error, const char *msg) { @@ -204,14 +210,14 @@ namespace Swig { }; /* Any Ruby exception that occurs during a director method call */ - class DirectorMethodException : public Swig::DirectorException { + class DirectorMethodException : public DirectorException { public: DirectorMethodException(VALUE error) - : Swig::DirectorException(error) { + : DirectorException(error) { } DirectorMethodException(const char *msg = "") - : Swig::DirectorException(rb_eRuntimeError, "SWIG director method error.", msg) { + : DirectorException(rb_eRuntimeError, "SWIG director method error.", msg) { } static void raise(VALUE error) { @@ -220,7 +226,7 @@ namespace Swig { }; /* Attempted to call a pure virtual method via a director method */ - class DirectorPureVirtualException : public Swig::DirectorException + class DirectorPureVirtualException : public DirectorException { public: DirectorPureVirtualException(const char *msg = "") From 3785454a87eb2d4eaafcf0439cdc3da10efcbc02 Mon Sep 17 00:00:00 2001 From: Ian Lance Taylor Date: Tue, 21 Jan 2014 11:18:55 -0800 Subject: [PATCH 297/481] [Go] Add support for Go 1.3, not yet released. --- CHANGES.current | 3 +++ Examples/Makefile.in | 21 ++++++++++++++------- Examples/test-suite/go/Makefile.in | 7 ++++--- configure.ac | 10 ++++++++-- 4 files changed, 29 insertions(+), 12 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index 68b34270a..1945e9292 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,9 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2014-01-21: ianlancetaylor + [Go] Add support for Go 1.3, not yet released. + 2014-01-20: wsfulton Director exceptions (Swig::DirectorException) now derive from std::exception and hence provide the what() method. In Python and Ruby, this replaces the now diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 4c1a11ca4..fc17d8784 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -1556,12 +1556,13 @@ GO = @GO@ GOGCC = @GOGCC@ GO1 = @GO1@ GO12 = @GO12@ +GO13 = @GO13@ GOC = @GOC@ GOOPT = @GOOPT@ GOVERSIONOPTION = @GOVERSIONOPTION@ GOSWIGARG = `if $(GOGCC) ; then echo -gccgo; fi` -GOCOMPILEARG = `if $(GOGCC) ; then echo -c -g; elif $(GO1) ; then echo tool $(GOC:c=g) ; fi` +GOCOMPILEARG = `if $(GOGCC) ; then echo -c -g; elif $(GO1) ; then echo tool $(GOC:c=g) ; fi` `if $(GO13) ; then echo -pack ; fi` GOSRCS = $(INTERFACE:.i=.go) GOCSRCS = $(INTERFACE:.i=_gc.c) @@ -1582,7 +1583,7 @@ GOGCCOBJS = $(GOSRCS:.go=.@OBJEXT@) go: $(SRCS) $(SWIG) -go $(GOOPT) $(GOSWIGARG) $(SWIGOPT) $(INTERFACEPATH) - if $(GO12) || $(GOGCC); then \ + if $(GO12) || $(GO13) || $(GOGCC); then \ $(CC) -g -c $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES); \ else \ $(CC) -g -c $(CCSHARED) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES); \ @@ -1592,7 +1593,10 @@ go: $(SRCS) if ! $(GOGCC) ; then \ $(COMPILETOOL) $(GOTOOL) $(GOC) -I $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`} $(GOCSRCS); \ rm -f $(GOPACKAGE); \ - if $(GO12); then \ + if $(GO13); then \ + cp $(GOGCOBJS) $(GOPACKAGE); \ + $(COMPILETOOL) $(GOPACK) r $(GOPACKAGE) $(GOCSRCS:.c=.$(GOOBJEXT)) $(OBJS) $(IOBJS); \ + elif $(GO12); then \ $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)) $(OBJS) $(IOBJS); \ else \ $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)); \ @@ -1602,7 +1606,7 @@ go: $(SRCS) $(GO) $(GOCOMPILEARG) $(RUNME).go; \ if $(GOGCC) ; then \ $(COMPILETOOL) $(GO) -o $(RUNME) $(RUNME).@OBJEXT@ $(GOGCCOBJS) $(OBJS) $(IOBJS); \ - elif $(GO12); then \ + elif $(GO12) || $(GO13); then \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CC) -extldflags "$(CFLAGS)" -o $(RUNME) $(RUNME).$(GOOBJEXT); \ else \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $(RUNME) $(RUNME).$(GOOBJEXT); \ @@ -1615,7 +1619,7 @@ go: $(SRCS) go_cpp: $(SRCS) $(SWIG) -go -c++ $(GOOPT) $(GOSWIGARG) $(SWIGOPT) $(INTERFACEPATH) - if $(GO12) || $(GOGCC); then \ + if $(GO12) || $(GO13) || $(GOGCC); then \ $(CXX) -g -c $(CXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES); \ else \ $(CXX) -g -c $(CCSHARED) $(CXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES); \ @@ -1625,7 +1629,10 @@ go_cpp: $(SRCS) if ! $(GOGCC) ; then \ $(COMPILETOOL) $(GOTOOL) $(GOC) -I $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`} $(GOCSRCS); \ rm -f $(GOPACKAGE); \ - if $(GO12); then \ + if $(GO13); then \ + cp $(GOGCOBJS) $(GOPACKAGE); \ + $(COMPILETOOL) $(GOPACK) r $(GOPACKAGE) $(GOCSRCS:.c=.$(GOOBJEXT)) $(OBJS) $(IOBJS); \ + elif $(GO12); then \ $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)) $(OBJS) $(IOBJS); \ else \ $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)); \ @@ -1635,7 +1642,7 @@ go_cpp: $(SRCS) $(GO) $(GOCOMPILEARG) $(RUNME).go; \ if $(GOGCC) ; then \ $(COMPILETOOL) $(GO) -o $(RUNME) $(RUNME).@OBJEXT@ $(GOGCCOBJS) $(OBJS) $(IOBJS) -lstdc++; \ - elif $(GO12); then \ + elif $(GO12) || $(GO13); then \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CXX) -extldflags "$(CXXFLAGS)" -o $(RUNME) $(RUNME).$(GOOBJEXT); \ else \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $(RUNME) $(RUNME).$(GOOBJEXT); \ diff --git a/Examples/test-suite/go/Makefile.in b/Examples/test-suite/go/Makefile.in index 35937bcdb..535d05a6e 100644 --- a/Examples/test-suite/go/Makefile.in +++ b/Examples/test-suite/go/Makefile.in @@ -7,6 +7,7 @@ GO = @GO@ GOGCC = @GOGCC@ GO1 = @GO1@ GO12 = @GO12@ +GO13 = @GO13@ GOC = @GOC@ SCRIPTSUFFIX = _runme.go @@ -60,7 +61,7 @@ run_testcase = \ $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ if $(GOGCC) ; then \ $(COMPILETOOL) $(GO) -o $*_runme $(SCRIPTPREFIX)$*_runme.@OBJEXT@ $*.@OBJEXT@ $*_wrap.@OBJEXT@; \ - elif $(GO12); then \ + elif $(GO12) || $(GO13); then \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CC) -extldflags "$(CFLAGS)" -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ else \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ @@ -73,7 +74,7 @@ run_testcase_cpp = \ $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ if $(GOGCC) ; then \ $(COMPILETOOL) $(GO) -o $*_runme $(SCRIPTPREFIX)$*_runme.@OBJEXT@ $*.@OBJEXT@ $*_wrap.@OBJEXT@ -lstdc++; \ - elif $(GO12); then \ + elif $(GO12) || $(GO13); then \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CXX) -extldflags "$(CXXFLAGS)" -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ else \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ @@ -87,7 +88,7 @@ run_multi_testcase = \ if $(GOGCC) ; then \ files=`cat $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$*.list`; \ $(COMPILETOOL) $(GO) -o $*_runme $(SCRIPTPREFIX)$*_runme.@OBJEXT@ `for f in $$files; do echo $$f.@OBJEXT@ $${f}_wrap.@OBJEXT@; done` -lstdc++; \ - elif $(GO12); then \ + elif $(GO12) || $(GO13); then \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -linkmode external -extld $(CXX) -extldflags "$(CXXFLAGS)" -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ else \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ diff --git a/configure.ac b/configure.ac index f048ccda5..03677f90d 100644 --- a/configure.ac +++ b/configure.ac @@ -1997,6 +1997,7 @@ if test x"${GOBIN}" = xno -o x"${with_alllang}" = xno ; then GOC= GO1=false GO12=false + GO13=false GOGCC=false GOOPT= GOVERSIONOPTION= @@ -2011,6 +2012,7 @@ else GOGCC=false GO1=false GO12=false + GO13=false GOOPT= GOVERSIONOPTION= if test -n "$GO" ; then @@ -2050,12 +2052,14 @@ else esac case $go_version in go1.0* | go1.1*) - GO12=false GOOPT="$GOOPT -use-shlib" ;; - *) + go1.2*) GO12=true ;; + *) + GO13=true + ;; esac else GOC=`echo $GO | sed -e 's/g/c/'` @@ -2071,6 +2075,7 @@ else fi GOOPT="-intgosize 32" GO12=false + GO13=false fi fi fi @@ -2080,6 +2085,7 @@ AC_SUBST(GO) AC_SUBST(GOC) AC_SUBST(GO1) AC_SUBST(GO12) +AC_SUBST(GO13) AC_SUBST(GOOPT) AC_SUBST(GOVERSIONOPTION) From f2dc3a9c1f1e2ef5242be594c5cee6502b3e2547 Mon Sep 17 00:00:00 2001 From: Ian Lance Taylor Date: Tue, 21 Jan 2014 11:27:09 -0800 Subject: [PATCH 298/481] [Go] Add %go_import directive. --- CHANGES.current | 3 +++ Doc/Manual/Go.html | 30 +++++++++++++++++++++++++---- Lib/go/go.swg | 3 +++ Lib/go/goruntime.swg | 22 +++++++++------------ Source/Modules/go.cxx | 45 +++++++++++++++++++++++++++++++++++++++++-- 5 files changed, 84 insertions(+), 19 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index 1945e9292..ca7503d41 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,9 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2014-01-21: ianlancetaylor + [Go] Add %go_import directive. + 2014-01-21: ianlancetaylor [Go] Add support for Go 1.3, not yet released. diff --git a/Doc/Manual/Go.html b/Doc/Manual/Go.html index 43bfc6971..240db2b61 100644 --- a/Doc/Manual/Go.html +++ b/Doc/Manual/Go.html @@ -666,9 +666,31 @@ func (arg SwigcptrWrapped_MyClass) GetAValue() (int, bool) { few, then you might as well define your own struct that includes the swig-wrapped object, instead of adding methods to the swig-generated object.

      -

      This only works if your wrappers do not need to import other go modules. -There is at present no way to insert import statements in the correct place -in swig-generated go. If you need to do that, you must put your go code -in a separate file.

      +

      If you need to import other go packages, you can do this with +%go_import. For example,

      +
      +
      +%go_import("fmt", _ "unusedPackage", rp "renamed/package")
      +
      +%insert(go_wrapper) %{
      +
      +func foo() {
      +  fmt.Println("Some string:", rp.GetString())
      +}
      +
      +// Importing the same package twice is permitted,
      +// Go code will be generated with only the first instance of the import.
      +%go_import("fmt")
      +
      +%insert(go_wrapper) %{
      +
      +func bar() {
      +  fmt.Println("Hello world!")
      +}
      +
      +%}
      +
      +
      + diff --git a/Lib/go/go.swg b/Lib/go/go.swg index b9086caac..c9dc34361 100644 --- a/Lib/go/go.swg +++ b/Lib/go/go.swg @@ -4,6 +4,9 @@ * Go configuration module. * ------------------------------------------------------------ */ +/* Code insertion directives */ +#define %go_import(...) %insert(go_imports) %{__VA_ARGS__%} + /* Basic types */ %typemap(gotype) bool, const bool & "bool" diff --git a/Lib/go/goruntime.swg b/Lib/go/goruntime.swg index 3e639cdc2..612f83086 100644 --- a/Lib/go/goruntime.swg +++ b/Lib/go/goruntime.swg @@ -192,30 +192,26 @@ static _gostring_ _swig_makegostring(const char *p, size_t l) { #ifndef SWIGGO_GCCGO -%insert(go_header) %{ - -import _ "runtime/cgo" -import "unsafe" - -type _ unsafe.Pointer - -%} +%go_import("unsafe", _ "runtime/cgo") #else +%go_import("syscall", "unsafe") + %insert(go_header) %{ -import "syscall" -import "unsafe" - type _ syscall.Sockaddr -type _ unsafe.Pointer - %} #endif +%insert(go_header) %{ + +type _ unsafe.Pointer + +%} + /* Function pointers are translated by the code in go.cxx into _swig_fnptr. Member pointers are translated to _swig_memberptr. */ diff --git a/Source/Modules/go.cxx b/Source/Modules/go.cxx index 36e5d11d3..77c5418d2 100644 --- a/Source/Modules/go.cxx +++ b/Source/Modules/go.cxx @@ -45,6 +45,7 @@ class GO:public Language { File *f_c_init; File *f_c_directors; File *f_c_directors_h; + File *f_go_imports; File *f_go_runtime; File *f_go_header; File *f_go_wrappers; @@ -84,6 +85,9 @@ class GO:public Language { // A hash table of classes which were defined. The index is a Go // type name. Hash *defined_types; + // A hash table of all the go_imports already imported. The index is a full + // import name e.g. '"runtime"' or '_ "runtime/cgo"' or 'sc "syscall"'. + Hash *go_imports; public: GO():package(NULL), @@ -104,6 +108,7 @@ public: f_c_init(NULL), f_c_directors(NULL), f_c_directors_h(NULL), + f_go_imports(NULL), f_go_runtime(NULL), f_go_header(NULL), f_go_wrappers(NULL), @@ -120,7 +125,8 @@ public: making_variable_wrappers(false), is_static_member_function(false), undefined_types(NULL), - defined_types(NULL) { + defined_types(NULL), + go_imports(NULL) { director_multiple_inheritance = 1; director_language = 1; director_prot_ctor_code = NewString("_swig_gopanic(\"accessing abstract class or protected constructor\");"); @@ -362,6 +368,7 @@ private: f_c_wrappers = NewString(""); f_c_init = NewString(""); f_c_directors = NewString(""); + f_go_imports = NewString(""); f_go_runtime = NewString(""); f_go_header = NewString(""); f_go_wrappers = NewString(""); @@ -379,6 +386,7 @@ private: Swig_register_filebyname("director", f_c_directors); Swig_register_filebyname("director_h", f_c_directors_h); Swig_register_filebyname("go_begin", f_go_begin); + Swig_register_filebyname("go_imports", f_go_imports); Swig_register_filebyname("go_runtime", f_go_runtime); Swig_register_filebyname("go_header", f_go_header); Swig_register_filebyname("go_wrapper", f_go_wrappers); @@ -445,11 +453,14 @@ private: undefined_types = NewHash(); defined_types = NewHash(); + go_imports = NewHash(); // Emit code. Language::top(n); + Delete(go_imports); + // Write out definitions for the types not defined by SWIG. Printv(f_go_wrappers, "\n", NULL); @@ -493,6 +504,7 @@ private: Dump(f_c_runtime, f_c_begin); Dump(f_c_wrappers, f_c_begin); Dump(f_c_init, f_c_begin); + Dump(f_go_imports, f_go_begin); Dump(f_go_header, f_go_begin); Dump(f_go_runtime, f_go_begin); Dump(f_go_wrappers, f_go_begin); @@ -506,6 +518,7 @@ private: Delete(f_c_header); Delete(f_c_wrappers); Delete(f_c_init); + Delete(f_go_imports); Delete(f_go_runtime); Delete(f_go_header); Delete(f_go_wrappers); @@ -535,7 +548,10 @@ private: String *hold_import = imported_package; String *modname = Getattr(n, "module"); if (modname) { - Printv(f_go_begin, "import \"", modname, "\"\n", NULL); + if (!Getattr(go_imports, modname)) { + Setattr(go_imports, modname, modname); + Printv(f_go_imports, "import \"", modname, "\"\n", NULL); + } imported_package = modname; saw_import = true; } @@ -544,6 +560,31 @@ private: return r; } + /* ---------------------------------------------------------------------- + * Language::insertDirective() + * + * If the section is go_imports, store them for later. + * ---------------------------------------------------------------------- */ + virtual int insertDirective(Node *n) { + char *section = Char(Getattr(n, "section")); + if ((ImportMode && !Getattr(n, "generated")) || + !section || (strcmp(section, "go_imports") != 0)) { + return Language::insertDirective(n); + } + + char *code = Char(Getattr(n, "code")); + char *pch = strtok(code, ","); + while (pch != NULL) { + // Do not import same thing more than once. + if (!Getattr(go_imports, pch)) { + Setattr(go_imports, pch, pch); + Printv(f_go_imports, "import ", pch, "\n", NULL); + } + pch = strtok(NULL, ","); + } + return SWIG_OK; + } + /* ---------------------------------------------------------------------- * functionWrapper() * From fa9a6d58ede53813c981c941e2c51a792a239a6d Mon Sep 17 00:00:00 2001 From: Ian Lance Taylor Date: Mon, 27 Jan 2014 17:49:35 -0800 Subject: [PATCH 299/481] [Go] Fix handling of C type "long" on 32-bit systems. It was broken for C++ long& and for big-endian systems in general. --- Lib/go/go.swg | 7 +++++-- Source/Modules/go.cxx | 3 +++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/Lib/go/go.swg b/Lib/go/go.swg index c9dc34361..0c03ae576 100644 --- a/Lib/go/go.swg +++ b/Lib/go/go.swg @@ -48,14 +48,17 @@ const unsigned short &, const int &, const unsigned int &, - const long &, - const unsigned long &, const long long &, const unsigned long long &, const float &, const double & %{ $1 = ($1_ltype)&$input; %} +%typemap(in) const long & ($*1_ltype temp), + const unsigned long & ($*1_ltype temp) +%{ temp = ($*1_ltype)$input; + $1 = ($1_ltype)&temp; %} + %typemap(out) bool, char, signed char, diff --git a/Source/Modules/go.cxx b/Source/Modules/go.cxx index 77c5418d2..2f28fcb03 100644 --- a/Source/Modules/go.cxx +++ b/Source/Modules/go.cxx @@ -4794,6 +4794,9 @@ private: if (is_int) { ret = NewString("intgo "); Append(ret, name); + } else if (is_int64) { + ret = NewString("long long "); + Append(ret, name); } else { ret = SwigType_lstr(t, name); } From 7c5275a0f146faa2127526eba9ecb58ea1935ced Mon Sep 17 00:00:00 2001 From: Marvin Greenberg Date: Thu, 30 Jan 2014 16:17:30 -0500 Subject: [PATCH 300/481] Make sure tests are built with same stdlib flag as used to configure swig --- Examples/Makefile.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index fc17d8784..7680908ab 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -25,7 +25,7 @@ TARGET = CC = @CC@ CXX = @CXX@ CFLAGS = @PLATCFLAGS@ -CXXFLAGS = @BOOST_CPPFLAGS@ @PLATCXXFLAGS@ +CXXFLAGS = @BOOST_CPPFLAGS@ @PLATCXXFLAGS@ $(filter -stdlib%,@CXXFLAGS@) prefix = @prefix@ exec_prefix= @exec_prefix@ SRCS = From 9fd42e0e67701795e3b9017084e36298158ef39b Mon Sep 17 00:00:00 2001 From: Marvin Greenberg Date: Thu, 30 Jan 2014 16:18:21 -0500 Subject: [PATCH 301/481] Work around clang bugs with symbol resolution --- Examples/test-suite/nested_scope.i | 12 +++- ..._using_directive_and_declaration_forward.i | 58 ++++++++++++++++++ .../using_directive_and_declaration_forward.i | 60 +++++++++++++++++++ 3 files changed, 129 insertions(+), 1 deletion(-) diff --git a/Examples/test-suite/nested_scope.i b/Examples/test-suite/nested_scope.i index 358dbbb61..04945a7b6 100644 --- a/Examples/test-suite/nested_scope.i +++ b/Examples/test-suite/nested_scope.i @@ -3,12 +3,22 @@ %inline %{ namespace ns { struct Global { +#ifdef __clang__ + struct Outer { + struct Nested; + struct Nested { + int data; + }; + }; + struct Outer::Nested instance; +#else struct Outer { struct Nested; }; struct Outer::Nested { int data; } instance; +#endif }; } -%} \ No newline at end of file +%} diff --git a/Examples/test-suite/template_using_directive_and_declaration_forward.i b/Examples/test-suite/template_using_directive_and_declaration_forward.i index a5a7fbf31..dcc1d6ab4 100644 --- a/Examples/test-suite/template_using_directive_and_declaration_forward.i +++ b/Examples/test-suite/template_using_directive_and_declaration_forward.i @@ -9,7 +9,15 @@ namespace Outer1 { } using namespace Outer1::Space1; using Outer1::Space1::Thing1; +#ifdef __clang__ +namespace Outer1 { + namespace Space1 { + template class Thing1 {}; + } +} +#else template class Thing1 {}; +#endif void useit1(Thing1 t) {} void useit1a(Outer1::Space1::Thing1 t) {} void useit1b(::Outer1::Space1::Thing1 t) {} @@ -25,7 +33,15 @@ namespace Outer2 { } using namespace Outer2; using Space2::Thing2; +#ifdef __clang__ +namespace Outer2 { + namespace Space2 { + template class Thing2 {}; + } +} +#else template class Thing2 {}; +#endif void useit2(Thing2 t) {} void useit2a(Outer2::Space2::Thing2 t) {} void useit2b(::Outer2::Space2::Thing2 t) {} @@ -45,7 +61,17 @@ namespace Outer3 { using namespace Outer3; using namespace Space3; using Middle3::Thing3; +#ifdef __clang__ +namespace Outer3 { + namespace Space3 { + namespace Middle3 { + template class Thing3 {}; + } + } +} +#else template class Thing3 {}; +#endif void useit3(Thing3 t) {} void useit3a(Outer3::Space3::Middle3::Thing3 t) {} void useit3b(::Outer3::Space3::Middle3::Thing3 t) {} @@ -66,7 +92,17 @@ namespace Outer4 { } using namespace Outer4::Space4; using Middle4::Thing4; +#ifdef __clang__ +namespace Outer4 { + namespace Space4 { + namespace Middle4 { + template class Thing4 {}; + } + } +} +#else template class Thing4 {}; +#endif void useit4(Thing4 t) {} void useit4a(Outer4::Space4::Middle4::Thing4 t) {} void useit4b(::Outer4::Space4::Middle4::Thing4 t) {} @@ -90,7 +126,19 @@ namespace Outer5 { using namespace ::Outer5::Space5; using namespace Middle5; using More5::Thing5; +#ifdef __clang__ +namespace Outer5 { + namespace Space5 { + namespace Middle5 { + namespace More5 { + template class Thing5 {}; + } + } + } +} +#else template class Thing5 {}; +#endif void useit5(Thing5 t) {} void useit5a(Outer5::Space5::Middle5::More5::Thing5 t) {} void useit5b(::Outer5::Space5::Middle5::More5::Thing5 t) {} @@ -109,7 +157,17 @@ namespace Outer7 { } } using namespace Outer7::Space7; +#ifdef __clang__ +namespace Outer7 { + namespace Space7 { + namespace Middle7 { + template class Thing7 {}; + } + } +} +#else template class Middle7::Thing7 {}; +#endif using Middle7::Thing7; void useit7(Thing7 t) {} void useit7a(Outer7::Space7::Middle7::Thing7 t) {} diff --git a/Examples/test-suite/using_directive_and_declaration_forward.i b/Examples/test-suite/using_directive_and_declaration_forward.i index 238b3b77f..1f219e671 100644 --- a/Examples/test-suite/using_directive_and_declaration_forward.i +++ b/Examples/test-suite/using_directive_and_declaration_forward.i @@ -9,7 +9,15 @@ namespace Outer1 { } using namespace Outer1::Space1; using Outer1::Space1::Thing1; +#ifdef __clang__ +namespace Outer1 { + namespace Space1 { + class Thing1 {}; + } +} +#else class Thing1 {}; +#endif void useit1(Thing1 t) {} void useit1a(Outer1::Space1::Thing1 t) {} void useit1b(::Outer1::Space1::Thing1 t) {} @@ -25,7 +33,17 @@ namespace Outer2 { } using namespace Outer2; using Space2::Thing2; +using namespace Outer1::Space1; +using Outer1::Space1::Thing1; +#ifdef __clang__ +namespace Outer2 { + namespace Space2 { + class Thing2 {}; + } +} +#else class Thing2 {}; +#endif void useit2(Thing2 t) {} void useit2a(Outer2::Space2::Thing2 t) {} void useit2b(::Outer2::Space2::Thing2 t) {} @@ -45,7 +63,17 @@ namespace Outer3 { using namespace Outer3; using namespace Space3; using Middle3::Thing3; +#ifdef __clang__ +namespace Outer3 { + namespace Space3 { + namespace Middle3 { + class Thing3 {}; + } + } +} +#else class Thing3 {}; +#endif void useit3(Thing3 t) {} void useit3a(Outer3::Space3::Middle3::Thing3 t) {} void useit3b(::Outer3::Space3::Middle3::Thing3 t) {} @@ -66,7 +94,17 @@ namespace Outer4 { } using namespace Outer4::Space4; using Middle4::Thing4; +#ifdef __clang__ +namespace Outer4 { + namespace Space4 { + namespace Middle4 { + class Thing4 {}; + } + } +} +#else class Thing4 {}; +#endif void useit4(Thing4 t) {} void useit4a(Outer4::Space4::Middle4::Thing4 t) {} void useit4b(::Outer4::Space4::Middle4::Thing4 t) {} @@ -90,7 +128,19 @@ namespace Outer5 { using namespace ::Outer5::Space5; using namespace Middle5; using More5::Thing5; +#ifdef __clang__ +namespace Outer5 { + namespace Space5 { + namespace Middle5 { + namespace More5 { + class Thing5 {}; + } + } + } +} +#else class Thing5 {}; +#endif void useit5(Thing5 t) {} void useit5a(Outer5::Space5::Middle5::More5::Thing5 t) {} void useit5b(::Outer5::Space5::Middle5::More5::Thing5 t) {} @@ -109,7 +159,17 @@ namespace Outer7 { } } using namespace Outer7::Space7; +#ifdef __clang__ +namespace Outer7 { + namespace Space7 { + namespace Middle7 { + class Thing7 {}; + } + } +} +#else class Middle7::Thing7 {}; +#endif using Middle7::Thing7; void useit7(Thing7 t) {} void useit7a(Outer7::Space7::Middle7::Thing7 t) {} From a1fe8a6501abb2f9592681a035bc3a8b22b9738c Mon Sep 17 00:00:00 2001 From: Vadim Zeitlin Date: Sat, 1 Feb 2014 15:00:15 +0100 Subject: [PATCH 302/481] Fix gcc strict aliasing warnings with function pointers too. The commit 40bf877 fixed warnings about converting between function and object pointers but introduced warnings about breaking strict-aliasing rules which appear with -Wstrict-aliasing which is implicitly enabled by -O2. Avoid these warnings as well by using an intermediate union for conversion instead of casts trickery. --- Source/DOH/base.c | 9 +++++---- Source/DOH/doh.h | 6 ++++++ Source/DOH/fio.c | 13 +++++++++---- 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/Source/DOH/base.c b/Source/DOH/base.c index e84731cd0..4034e5626 100644 --- a/Source/DOH/base.c +++ b/Source/DOH/base.c @@ -947,11 +947,12 @@ int DohGetmark(DOH *ho) { DOH *DohCall(DOH *func, DOH *args) { DOH *result; - DOH *(*builtin) (DOH *); + DohFuncPtr_t builtin; - *(void **)(&builtin) = GetVoid(func, "builtin"); - if (!builtin) + builtin.p = GetVoid(func, "builtin"); + + if (!builtin.p) return 0; - result = (*builtin) (args); + result = (*builtin.func) (args); return result; } diff --git a/Source/DOH/doh.h b/Source/DOH/doh.h index 8071edd4d..5a9bae2b3 100644 --- a/Source/DOH/doh.h +++ b/Source/DOH/doh.h @@ -336,6 +336,12 @@ extern DOHList *DohSplit(DOHFile * input, char ch, int nsplits); extern DOHList *DohSplitLines(DOHFile * input); extern DOH *DohNone; +/* Helper union for converting between function and object pointers. */ +typedef union DohFuncPtr { + void* p; + DOH *(*func)(DOH *); +} DohFuncPtr_t; + extern void DohMemoryDebug(void); #ifndef DOH_LONG_NAMES diff --git a/Source/DOH/fio.c b/Source/DOH/fio.c index 71ce30149..7055ffc85 100644 --- a/Source/DOH/fio.c +++ b/Source/DOH/fio.c @@ -46,15 +46,19 @@ static int Writen(DOH *out, void *buffer, int len) { * ----------------------------------------------------------------------------- */ void DohEncoding(const char *name, DOH *(*fn) (DOH *s)) { + DohFuncPtr_t fp; + if (!encodings) encodings = NewHash(); - Setattr(encodings, (void *) name, NewVoid(*(void **)&fn, 0)); + + fp.func = fn; + Setattr(encodings, (void *) name, NewVoid(fp.p, 0)); } /* internal function for processing an encoding */ static DOH *encode(char *name, DOH *s) { DOH *handle, *ns; - DOH *(*fn) (DOH *); + DohFuncPtr_t fp; long pos; char *cfmt = strchr(name, ':'); DOH *tmp = 0; @@ -72,8 +76,9 @@ static DOH *encode(char *name, DOH *s) { s = tmp; pos = Tell(s); Seek(s, 0, SEEK_SET); - *(void **)(&fn) = Data(handle); - ns = (*fn) (s); + + fp.p = Data(handle); + ns = (*fp.func) (s); assert(pos != -1); (void)Seek(s, pos, SEEK_SET); if (tmp) From 2f3d93e93afaa9bf68ac83cb5614511000433247 Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Sun, 2 Feb 2014 22:38:13 +0400 Subject: [PATCH 303/481] Nested classes support is diversified, depending on the language capability. If the language cannot support nested classes, they will be unconditionally moved to the global namespace. If language module does not override Language::nestedClassesSupport() function, nested classes will be ignored, unless "feature:flatnested" is used. --- Source/CParse/parser.y | 48 +++++++++++++++++++++++++------------ Source/Include/swigwarn.h | 1 + Source/Modules/csharp.cxx | 4 ++-- Source/Modules/java.cxx | 4 ++-- Source/Modules/lang.cxx | 4 ++-- Source/Modules/main.cxx | 13 ++++------ Source/Modules/nested.cxx | 4 ++-- Source/Modules/swigmod.h | 18 +++++++++----- Source/Modules/typepass.cxx | 3 ++- 9 files changed, 60 insertions(+), 39 deletions(-) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index fe8b7f97f..0f2cfdec9 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -59,7 +59,7 @@ static int extendmode = 0; static int compact_default_args = 0; static int template_reduce = 0; static int cparse_externc = 0; - +int ignore_nested_classes = 0; /* ----------------------------------------------------------------------------- * Assist Functions * ----------------------------------------------------------------------------- */ @@ -3564,19 +3564,26 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { Namespaceprefix = Swig_symbol_qualifiedscopename(0); yyrename = Copy(Getattr($$, "class_rename")); add_symbols($$); - Delattr($$, "class_rename"); - /* but the variable definition in the current scope */ - Swig_symbol_setscope(cscope); - Delete(Namespaceprefix); - Namespaceprefix = Swig_symbol_qualifiedscopename(0); - add_symbols($9); - if (nscope) { - $$ = nscope; /* here we return recreated namespace tower instead of the class itself */ - if ($9) - appendSibling($$, $9); + if (currentOuterClass && ignore_nested_classes && !GetFlag($$, "feature:flatnested")) { + SetFlag($$,"feature:ignore"); + Swig_warning(WARN_PARSE_NESTED_CLASS, cparse_file, cparse_line, "Nested %s not currently supported (ignored).\n", Getattr($$, "name")); + $$ = 0; + } else { + Delattr($$, "class_rename"); + /* but the variable definition in the current scope */ + Swig_symbol_setscope(cscope); + Delete(Namespaceprefix); + Namespaceprefix = Swig_symbol_qualifiedscopename(0); + add_symbols($9); + if (nscope) { + $$ = nscope; /* here we return recreated namespace tower instead of the class itself */ + if ($9) { + appendSibling($$, $9); + } + } else if (!SwigType_istemplate(ty) && template_parameters == 0) { /* for tempalte we need the class itself */ + $$ = $9; + } } - else if (!SwigType_istemplate(ty) && template_parameters == 0) /* for tempalte we need the class itself */ - $$ = $9; } else { Delete(yyrename); yyrename = 0; @@ -3600,8 +3607,14 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { } else { yyrename = Copy(Getattr($$, "class_rename")); add_symbols($$); - add_symbols($9); - Delattr($$, "class_rename"); + if (cparse_cplusplus && currentOuterClass && ignore_nested_classes && !GetFlag($$, "feature:flatnested")) { + SetFlag($$,"feature:ignore"); + Swig_warning(WARN_PARSE_NESTED_CLASS, cparse_file, cparse_line, "Nested %s not currently supported (ignored).\n", Getattr($$, "name")); + $$ = 0; + } else { + add_symbols($9); + Delattr($$, "class_rename"); + } } } Delete(ty); @@ -3734,6 +3747,11 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { add_symbols($$); add_symbols(n); Delattr($$, "class_rename"); + if (cparse_cplusplus && currentOuterClass && ignore_nested_classes && !GetFlag($$, "feature:flatnested")) { + SetFlag($$,"feature:ignore"); + Swig_warning(WARN_PARSE_NESTED_CLASS, cparse_file, cparse_line, "Nested %s not currently supported (ignored).\n", name); + $$ = 0; + } }else if (cparse_cplusplus) $$ = 0; /* ignore unnamed structs for C++ */ Delete(unnamed); diff --git a/Source/Include/swigwarn.h b/Source/Include/swigwarn.h index ea1cf7fe4..7ae067da1 100644 --- a/Source/Include/swigwarn.h +++ b/Source/Include/swigwarn.h @@ -76,6 +76,7 @@ #define WARN_PARSE_PRIVATE_INHERIT 309 #define WARN_PARSE_TEMPLATE_REPEAT 310 #define WARN_PARSE_TEMPLATE_PARTIAL 311 +#define WARN_PARSE_NESTED_CLASS 312 #define WARN_PARSE_UNDEFINED_EXTERN 313 #define WARN_PARSE_KEYWORD 314 #define WARN_PARSE_USING_UNDEF 315 diff --git a/Source/Modules/csharp.cxx b/Source/Modules/csharp.cxx index 1713e6f3f..4a105aa16 100644 --- a/Source/Modules/csharp.cxx +++ b/Source/Modules/csharp.cxx @@ -4288,8 +4288,8 @@ public: Delete(dirclassname); } - bool nestedClassesSupported() const { - return true; + NestedClassSupport nestedClassesSupport() const { + return NCS_Full; } }; /* class CSHARP */ diff --git a/Source/Modules/java.cxx b/Source/Modules/java.cxx index c47dd3e48..601cbb20e 100644 --- a/Source/Modules/java.cxx +++ b/Source/Modules/java.cxx @@ -4607,8 +4607,8 @@ public: Setattr(n, "director:ctor", class_ctor); } - bool nestedClassesSupported() const { - return true; + NestedClassSupport nestedClassesSupport() const { + return NCS_Full; } }; /* class JAVA */ diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index a547e2bd4..3940a3001 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -3441,8 +3441,8 @@ bool Language::extraDirectorProtectedCPPMethodsRequired() const { return true; } -bool Language::nestedClassesSupported() const { - return false; +Language::NestedClassSupport Language::nestedClassesSupport() const { + return NCS_Unknown; } /* ----------------------------------------------------------------------------- * Language::is_wrapping_class() diff --git a/Source/Modules/main.cxx b/Source/Modules/main.cxx index 786763441..66e2548dc 100644 --- a/Source/Modules/main.cxx +++ b/Source/Modules/main.cxx @@ -49,6 +49,7 @@ int SwigRuntime = 0; // 0 = no option, 1 = -runtime, 2 = -noruntime extern "C" { extern String *ModuleName; + extern int ignore_nested_classes; } /* usage string split into multiple parts otherwise string is too big for some compilers */ @@ -856,11 +857,6 @@ void SWIG_getoptions(int argc, char *argv[]) { } } -static void flatten_nested() { - Swig_feature_set(Swig_cparse_features(), "", 0, "feature:flatnested", "1", 0); -} - - int SWIG_main(int argc, char *argv[], Language *l) { char *c; @@ -905,6 +901,9 @@ int SWIG_main(int argc, char *argv[], Language *l) { Wrapper_director_mode_set(0); Wrapper_director_protected_mode_set(1); + // Inform the parser if the nested classes should be ignored unless explicitly told otherwise via feature:flatnested + ignore_nested_classes = l->nestedClassesSupport() == Language::NCS_Unknown ? 1 : 0; + // Create Library search directories // Check for SWIG_LIB environment variable @@ -1158,10 +1157,6 @@ int SWIG_main(int argc, char *argv[], Language *l) { fflush(stdout); } - // add "ignore" directive if nested classes are not supported - if (!lang->nestedClassesSupported()) - flatten_nested(); - Node *top = Swig_cparse(cpps); if (dump_top & STAGE1) { diff --git a/Source/Modules/nested.cxx b/Source/Modules/nested.cxx index 37248608c..3b45e9f90 100644 --- a/Source/Modules/nested.cxx +++ b/Source/Modules/nested.cxx @@ -416,7 +416,7 @@ void Swig_nested_name_unnamed_c_structs(Node *n) { static void remove_outer_class_reference(Node *n) { for (Node *c = firstChild(n); c; c = nextSibling(c)) { - if (GetFlag(c, "feature:flatnested")) { + if (GetFlag(c, "feature:flatnested") || Language::instance()->nestedClassesSupport() == Language::NCS_None) { Delattr(c, "nested:outer"); remove_outer_class_reference(c); } @@ -428,7 +428,7 @@ void Swig_nested_process_classes(Node *n) { while (c) { Node *next = nextSibling(c); if (!Getattr(c, "templatetype")) { - if (GetFlag(c, "nested") && GetFlag(c, "feature:flatnested")) { + if (GetFlag(c, "nested") && (GetFlag(c, "feature:flatnested") || Language::instance()->nestedClassesSupport() == Language::NCS_None)) { removeNode(c); if (!checkAttribute(c, "access", "public")) SetFlag(c, "feature:ignore"); diff --git a/Source/Modules/swigmod.h b/Source/Modules/swigmod.h index 7ebcfeee1..2929993b3 100644 --- a/Source/Modules/swigmod.h +++ b/Source/Modules/swigmod.h @@ -298,13 +298,19 @@ protected: virtual bool extraDirectorProtectedCPPMethodsRequired() const; public: - /* Does target language support nested classes? Default is 'false'. If 'false' is returned, then - %rename("$ignore", %$isnested) statement will be issued at the top, and the nested classes - will be ignored. Note that even if the target language does not support the notion of class - nesting, the language module may nevertheless return true from this function, and use - %feature "flatnested" to move nested classes to the global scope, instead of ignoring them. + enum NestedClassSupport { + NCS_None, // Target language does not have an equivalent to nested classes + NCS_Full, // Target language does have an equivalent to nested classes and is fully implemented + NCS_Unknown // Target language may or may not have an equivalent to nested classes. If it does, it has not been implemented yet. + }; + /* Does target language support nested classes? Default is NCS_Unknown. + If NCS_Unknown is returned, then the nested classes will be ignored unless + %feature "flatnested" is applied to them, in which case they will appear in global space. + If the target language does not support the notion of class + nesting, the language module should return NCS_None from this function, and + the nested classes will be moved to the global scope (like implicit global %feature "flatnested"). */ - virtual bool nestedClassesSupported() const; + virtual NestedClassSupport nestedClassesSupport() const; protected: /* Identifies if a protected members that are generated when the allprotected option is used. diff --git a/Source/Modules/typepass.cxx b/Source/Modules/typepass.cxx index e918c0770..49f95090d 100644 --- a/Source/Modules/typepass.cxx +++ b/Source/Modules/typepass.cxx @@ -504,7 +504,8 @@ class TypePass:private Dispatcher { SwigType_attach_symtab(Getattr(n, "symtab")); /* Inherit type definitions into the class */ - if (name && !(GetFlag(n, "nested") && GetFlag(n, "feature:flatnested") && !checkAttribute(n, "access", "public"))) { + if (name && !(GetFlag(n, "nested") && !checkAttribute(n, "access", "public") && + (GetFlag(n, "feature:flatnested") || Language::instance()->nestedClassesSupport() == Language::NCS_None))) { cplus_inherit_types(n, 0, nname ? nname : (fname ? fname : name)); } From 69d849b56ca6507326ad4ed802a98c32dc17403f Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Sun, 2 Feb 2014 23:38:23 +0400 Subject: [PATCH 304/481] filtered warnings, turned on "flatnested" for nested template test --- Examples/test-suite/derived_nested.i | 5 +++++ Examples/test-suite/namespace_class.i | 2 ++ Examples/test-suite/nested_class.i | 20 ++++++++++++++++++++ Examples/test-suite/template_nested.i | 11 +++++++++++ 4 files changed, 38 insertions(+) diff --git a/Examples/test-suite/derived_nested.i b/Examples/test-suite/derived_nested.i index e374cf70f..2b3698045 100644 --- a/Examples/test-suite/derived_nested.i +++ b/Examples/test-suite/derived_nested.i @@ -3,6 +3,11 @@ This was reported in bug #909389 */ %module derived_nested +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) BB::CC; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) BB::DD; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) BB::EE; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) BB::FF; + %inline %{ class A { diff --git a/Examples/test-suite/namespace_class.i b/Examples/test-suite/namespace_class.i index 113bbeb35..cc9940d13 100644 --- a/Examples/test-suite/namespace_class.i +++ b/Examples/test-suite/namespace_class.i @@ -1,6 +1,8 @@ %module namespace_class +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Ala::Ola; + #ifdef SWIGD %warnfilter(SWIGWARN_IGNORE_OPERATOR_LT); #endif diff --git a/Examples/test-suite/nested_class.i b/Examples/test-suite/nested_class.i index 282875531..ccb7ecac1 100644 --- a/Examples/test-suite/nested_class.i +++ b/Examples/test-suite/nested_class.i @@ -1,5 +1,25 @@ %module nested_class +#pragma SWIG nowarn=SWIGWARN_PARSE_UNNAMED_NESTED_CLASS +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerStruct1; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerClass1; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerUnion1; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerClass2; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerStruct2; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerUnion2; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerClass4Typedef; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerStruct4Typedef; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerUnion4Typedef; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerClass5; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerStruct5; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerUnion5; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerMultiple; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerMultipleDerived; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerMultipleAnonTypedef1; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerMultipleNamedTypedef; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerSameName; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer2::IgnoreMe; + %inline %{ struct Outer { typedef int Integer; diff --git a/Examples/test-suite/template_nested.i b/Examples/test-suite/template_nested.i index c33018e0f..f9b070270 100644 --- a/Examples/test-suite/template_nested.i +++ b/Examples/test-suite/template_nested.i @@ -1,7 +1,18 @@ %module template_nested +#if !defined(SWIGCSHARP) && !defined(SWIGJAVA) +%feature ("flatnested"); +#endif + // Test nested templates - that is template classes and template methods within a class. +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) ns::OuterClass::Inner1; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) ns::OuterClass::Inner2; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) ns::OuterTemplate::NestedInnerTemplate1; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) ns::OuterTemplate::NestedInnerTemplate2; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) ns::OuterTemplate::NestedInnerTemplate3; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) ns::OuterTemplate::NestedStruct; + namespace ns { template struct ForwardTemplate; } From 4744ea8903f300e5afd1030922a7be62e4cb1c9b Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Mon, 3 Feb 2014 01:03:37 +0400 Subject: [PATCH 305/481] added forward declaration instead of ignored nested class (resurrected old code) --- Source/CParse/parser.y | 123 +++++++++++++++++++++++++++----------- Source/Include/swigwarn.h | 3 +- 2 files changed, 91 insertions(+), 35 deletions(-) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 0f2cfdec9..102cba368 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1069,6 +1069,71 @@ static void update_nested_classes(Node *n) } } +/* ----------------------------------------------------------------------------- + * nested_forward_declaration() + * + * Nested struct handling for C++ code if the nested classes are diasbled. + * Create the nested class/struct/union as a forward declaration. + * ----------------------------------------------------------------------------- */ + +static Node *nested_forward_declaration(const char *storage, const char *kind, String *sname, String *name, Node *cpp_opt_declarators) { + Node *nn = 0; + int warned = 0; + + if (sname) { + /* Add forward declaration of the nested type */ + Node *n = new_node("classforward"); + Setattr(n, "kind", kind); + Setattr(n, "name", sname); + Setattr(n, "storage", storage); + Setattr(n, "sym:weak", "1"); + add_symbols(n); + nn = n; + } + + /* Add any variable instances. Also add in any further typedefs of the nested type. + Note that anonymous typedefs (eg typedef struct {...} a, b;) are treated as class forward declarations */ + if (cpp_opt_declarators) { + int storage_typedef = (storage && (strcmp(storage, "typedef") == 0)); + int variable_of_anonymous_type = !sname && !storage_typedef; + if (!variable_of_anonymous_type) { + int anonymous_typedef = !sname && (storage && (strcmp(storage, "typedef") == 0)); + Node *n = cpp_opt_declarators; + SwigType *type = name; + while (n) { + Setattr(n, "type", type); + Setattr(n, "storage", storage); + if (anonymous_typedef) { + Setattr(n, "nodeType", "classforward"); + Setattr(n, "sym:weak", "1"); + } + n = nextSibling(n); + } + add_symbols(cpp_opt_declarators); + + if (nn) { + set_nextSibling(nn, cpp_opt_declarators); + } else { + nn = cpp_opt_declarators; + } + } + } + + if (nn && Equal(nodeType(nn), "classforward")) { + Node *n = nn; + SWIG_WARN_NODE_BEGIN(n); + Swig_warning(WARN_PARSE_NAMED_NESTED_CLASS, cparse_file, cparse_line,"Nested %s not currently supported (%s ignored)\n", kind, sname ? sname : name); + SWIG_WARN_NODE_END(n); + warned = 1; + } + + if (!warned) + Swig_warning(WARN_PARSE_UNNAMED_NESTED_CLASS, cparse_file, cparse_line, "Nested %s not currently supported (ignored).\n", kind); + + return nn; +} + + Node *Swig_cparse(File *f) { scanner_file(f); top = 0; @@ -3553,8 +3618,13 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { Setattr($$, "symtab", Swig_symbol_popscope()); Classprefix = Getattr($$, "Classprefix"); Delattr($$, "Classprefix"); + Delete(Namespaceprefix); + Namespaceprefix = Swig_symbol_qualifiedscopename(0); + Swig_features_get(Swig_cparse_features(), Namespaceprefix, Getattr($$, "name"), 0, $$); if (cplus_mode == CPLUS_PRIVATE) { $$ = 0; /* skip private nested classes */ + } else if (cparse_cplusplus && currentOuterClass && ignore_nested_classes && !GetFlag($$, "feature:flatnested")) { + $$ = nested_forward_declaration($1, $2, $3, Copy($3), $9); } else if (nscope_inner) { /* this is tricky */ /* we add the declaration in the original namespace */ @@ -3564,31 +3634,23 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { Namespaceprefix = Swig_symbol_qualifiedscopename(0); yyrename = Copy(Getattr($$, "class_rename")); add_symbols($$); - if (currentOuterClass && ignore_nested_classes && !GetFlag($$, "feature:flatnested")) { - SetFlag($$,"feature:ignore"); - Swig_warning(WARN_PARSE_NESTED_CLASS, cparse_file, cparse_line, "Nested %s not currently supported (ignored).\n", Getattr($$, "name")); - $$ = 0; - } else { - Delattr($$, "class_rename"); - /* but the variable definition in the current scope */ - Swig_symbol_setscope(cscope); - Delete(Namespaceprefix); - Namespaceprefix = Swig_symbol_qualifiedscopename(0); - add_symbols($9); - if (nscope) { - $$ = nscope; /* here we return recreated namespace tower instead of the class itself */ - if ($9) { - appendSibling($$, $9); - } - } else if (!SwigType_istemplate(ty) && template_parameters == 0) { /* for tempalte we need the class itself */ - $$ = $9; + Delattr($$, "class_rename"); + /* but the variable definition in the current scope */ + Swig_symbol_setscope(cscope); + Delete(Namespaceprefix); + Namespaceprefix = Swig_symbol_qualifiedscopename(0); + add_symbols($9); + if (nscope) { + $$ = nscope; /* here we return recreated namespace tower instead of the class itself */ + if ($9) { + appendSibling($$, $9); } + } else if (!SwigType_istemplate(ty) && template_parameters == 0) { /* for tempalte we need the class itself */ + $$ = $9; } } else { Delete(yyrename); yyrename = 0; - Delete(Namespaceprefix); - Namespaceprefix = Swig_symbol_qualifiedscopename(0); if (!cparse_cplusplus && currentOuterClass) { /* nested C structs go into global scope*/ Node *outer = currentOuterClass; while (Getattr(outer, "nested:outer")) @@ -3607,14 +3669,8 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { } else { yyrename = Copy(Getattr($$, "class_rename")); add_symbols($$); - if (cparse_cplusplus && currentOuterClass && ignore_nested_classes && !GetFlag($$, "feature:flatnested")) { - SetFlag($$,"feature:ignore"); - Swig_warning(WARN_PARSE_NESTED_CLASS, cparse_file, cparse_line, "Nested %s not currently supported (ignored).\n", Getattr($$, "name")); - $$ = 0; - } else { - add_symbols($9); - Delattr($$, "class_rename"); - } + add_symbols($9); + Delattr($$, "class_rename"); } } Delete(ty); @@ -3678,7 +3734,11 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { /* Check for pure-abstract class */ Setattr($$,"abstracts", pure_abstracts($6)); n = $8; - if (n) { + Swig_features_get(Swig_cparse_features(), Namespaceprefix, 0, 0, $$); + if (cparse_cplusplus && currentOuterClass && ignore_nested_classes && !GetFlag($$, "feature:flatnested")) { + String *name = n ? Copy(Getattr(n, "name")) : 0; + $$ = nested_forward_declaration($1, $2, 0, name, n); + } else if (n) { appendSibling($$,n); /* If a proper typedef name was given, we'll use it to set the scope name */ name = try_to_find_a_name_for_unnamed_structure($1, n); @@ -3747,11 +3807,6 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { add_symbols($$); add_symbols(n); Delattr($$, "class_rename"); - if (cparse_cplusplus && currentOuterClass && ignore_nested_classes && !GetFlag($$, "feature:flatnested")) { - SetFlag($$,"feature:ignore"); - Swig_warning(WARN_PARSE_NESTED_CLASS, cparse_file, cparse_line, "Nested %s not currently supported (ignored).\n", name); - $$ = 0; - } }else if (cparse_cplusplus) $$ = 0; /* ignore unnamed structs for C++ */ Delete(unnamed); diff --git a/Source/Include/swigwarn.h b/Source/Include/swigwarn.h index 7ae067da1..1210d64a6 100644 --- a/Source/Include/swigwarn.h +++ b/Source/Include/swigwarn.h @@ -76,7 +76,7 @@ #define WARN_PARSE_PRIVATE_INHERIT 309 #define WARN_PARSE_TEMPLATE_REPEAT 310 #define WARN_PARSE_TEMPLATE_PARTIAL 311 -#define WARN_PARSE_NESTED_CLASS 312 +#define WARN_PARSE_UNNAMED_NESTED_CLASS 312 #define WARN_PARSE_UNDEFINED_EXTERN 313 #define WARN_PARSE_KEYWORD 314 #define WARN_PARSE_USING_UNDEF 315 @@ -89,6 +89,7 @@ #define WARN_PARSE_REDUNDANT 322 #define WARN_PARSE_REC_INHERITANCE 323 #define WARN_PARSE_NESTED_TEMPLATE 324 +#define WARN_PARSE_NAMED_NESTED_CLASS 325 #define WARN_PARSE_EXTEND_NAME 326 #define WARN_CPP11_LAMBDA 340 From 8fc4fd2893111f7e35c00632bb51dd26a96951e4 Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Mon, 3 Feb 2014 01:15:05 +0400 Subject: [PATCH 306/481] %feature ("flatnested") is set for nested scope test --- Examples/test-suite/nested_scope.i | 4 ++++ Examples/test-suite/template_nested.i | 7 ------- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/Examples/test-suite/nested_scope.i b/Examples/test-suite/nested_scope.i index 358dbbb61..be93ad8c6 100644 --- a/Examples/test-suite/nested_scope.i +++ b/Examples/test-suite/nested_scope.i @@ -1,5 +1,9 @@ %module nested_scope +#if !defined(SWIGCSHARP) && !defined(SWIGJAVA) +%feature ("flatnested"); +#endif + %inline %{ namespace ns { struct Global { diff --git a/Examples/test-suite/template_nested.i b/Examples/test-suite/template_nested.i index f9b070270..81a551a41 100644 --- a/Examples/test-suite/template_nested.i +++ b/Examples/test-suite/template_nested.i @@ -6,13 +6,6 @@ // Test nested templates - that is template classes and template methods within a class. -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) ns::OuterClass::Inner1; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) ns::OuterClass::Inner2; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) ns::OuterTemplate::NestedInnerTemplate1; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) ns::OuterTemplate::NestedInnerTemplate2; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) ns::OuterTemplate::NestedInnerTemplate3; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) ns::OuterTemplate::NestedStruct; - namespace ns { template struct ForwardTemplate; } From bda9c90e2bea477f03be4715c9f92fcf856bff69 Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Mon, 3 Feb 2014 02:21:44 +0400 Subject: [PATCH 307/481] warnfilter fixed scoping for "anonymous forward declaration" fixed --- Examples/test-suite/namespace_union.i | 2 ++ Examples/test-suite/nested_class.i | 1 + Examples/test-suite/nested_comment.i | 2 ++ Source/CParse/parser.y | 17 ++++++++++++----- 4 files changed, 17 insertions(+), 5 deletions(-) diff --git a/Examples/test-suite/namespace_union.i b/Examples/test-suite/namespace_union.i index 84e38b4d5..85885f399 100644 --- a/Examples/test-suite/namespace_union.i +++ b/Examples/test-suite/namespace_union.i @@ -1,5 +1,7 @@ %module namespace_union +#pragma SWIG nowarn=SWIGWARN_PARSE_UNNAMED_NESTED_CLASS + %inline %{ namespace SpatialIndex { diff --git a/Examples/test-suite/nested_class.i b/Examples/test-suite/nested_class.i index ccb7ecac1..1cdfaade6 100644 --- a/Examples/test-suite/nested_class.i +++ b/Examples/test-suite/nested_class.i @@ -19,6 +19,7 @@ %warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerMultipleNamedTypedef; %warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerSameName; %warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer2::IgnoreMe; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerSameName2; %inline %{ struct Outer { diff --git a/Examples/test-suite/nested_comment.i b/Examples/test-suite/nested_comment.i index df160b157..99d0ffb43 100644 --- a/Examples/test-suite/nested_comment.i +++ b/Examples/test-suite/nested_comment.i @@ -1,5 +1,7 @@ %module nested_comment +#pragma SWIG nowarn=SWIGWARN_PARSE_UNNAMED_NESTED_CLASS + // this example shows a problem with 'dump_nested' (parser.y). // bug #949654 diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 102cba368..77d253299 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1076,7 +1076,7 @@ static void update_nested_classes(Node *n) * Create the nested class/struct/union as a forward declaration. * ----------------------------------------------------------------------------- */ -static Node *nested_forward_declaration(const char *storage, const char *kind, String *sname, String *name, Node *cpp_opt_declarators) { +static Node *nested_forward_declaration(const char *storage, const char *kind, String *sname, String *name, Node *cpp_opt_declarators, Node* nested) { Node *nn = 0; int warned = 0; @@ -1120,15 +1120,19 @@ static Node *nested_forward_declaration(const char *storage, const char *kind, S } if (nn && Equal(nodeType(nn), "classforward")) { - Node *n = nn; + Node *n = nested; SWIG_WARN_NODE_BEGIN(n); Swig_warning(WARN_PARSE_NAMED_NESTED_CLASS, cparse_file, cparse_line,"Nested %s not currently supported (%s ignored)\n", kind, sname ? sname : name); SWIG_WARN_NODE_END(n); warned = 1; } - if (!warned) + if (!warned) { + Node *n = nested; + SWIG_WARN_NODE_BEGIN(n); Swig_warning(WARN_PARSE_UNNAMED_NESTED_CLASS, cparse_file, cparse_line, "Nested %s not currently supported (ignored).\n", kind); + SWIG_WARN_NODE_END(n); + } return nn; } @@ -3624,7 +3628,7 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { if (cplus_mode == CPLUS_PRIVATE) { $$ = 0; /* skip private nested classes */ } else if (cparse_cplusplus && currentOuterClass && ignore_nested_classes && !GetFlag($$, "feature:flatnested")) { - $$ = nested_forward_declaration($1, $2, $3, Copy($3), $9); + $$ = nested_forward_declaration($1, $2, $3, Copy($3), $9, $$); } else if (nscope_inner) { /* this is tricky */ /* we add the declaration in the original namespace */ @@ -3737,7 +3741,10 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { Swig_features_get(Swig_cparse_features(), Namespaceprefix, 0, 0, $$); if (cparse_cplusplus && currentOuterClass && ignore_nested_classes && !GetFlag($$, "feature:flatnested")) { String *name = n ? Copy(Getattr(n, "name")) : 0; - $$ = nested_forward_declaration($1, $2, 0, name, n); + $$ = nested_forward_declaration($1, $2, 0, name, n, $$); + Swig_symbol_popscope(); + Delete(Namespaceprefix); + Namespaceprefix = Swig_symbol_qualifiedscopename(0); } else if (n) { appendSibling($$,n); /* If a proper typedef name was given, we'll use it to set the scope name */ From 03203783878bf818056031865789d25ba0606629 Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Mon, 3 Feb 2014 02:31:17 +0400 Subject: [PATCH 308/481] more warnings removed --- Examples/test-suite/nested_class.i | 20 +------------------- 1 file changed, 1 insertion(+), 19 deletions(-) diff --git a/Examples/test-suite/nested_class.i b/Examples/test-suite/nested_class.i index 1cdfaade6..73bf89eb0 100644 --- a/Examples/test-suite/nested_class.i +++ b/Examples/test-suite/nested_class.i @@ -1,25 +1,7 @@ %module nested_class #pragma SWIG nowarn=SWIGWARN_PARSE_UNNAMED_NESTED_CLASS -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerStruct1; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerClass1; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerUnion1; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerClass2; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerStruct2; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerUnion2; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerClass4Typedef; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerStruct4Typedef; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerUnion4Typedef; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerClass5; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerStruct5; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerUnion5; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerMultiple; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerMultipleDerived; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerMultipleAnonTypedef1; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerMultipleNamedTypedef; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerSameName; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer2::IgnoreMe; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerSameName2; +#pragma SWIG nowarn=SWIGWARN_PARSE_NAMED_NESTED_CLASS %inline %{ struct Outer { From b7fd1eacb223950ae93ebdf9f4e119ac9b7df105 Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Mon, 3 Feb 2014 02:50:19 +0400 Subject: [PATCH 309/481] WARN_PARSE_UNNAMED_NESTED_CLASS check fixed --- Examples/test-suite/errors/cpp_macro_locator.stderr | 1 + 1 file changed, 1 insertion(+) diff --git a/Examples/test-suite/errors/cpp_macro_locator.stderr b/Examples/test-suite/errors/cpp_macro_locator.stderr index 8a78d46af..f4fc2c7d0 100644 --- a/Examples/test-suite/errors/cpp_macro_locator.stderr +++ b/Examples/test-suite/errors/cpp_macro_locator.stderr @@ -1,3 +1,4 @@ +cpp_macro_locator.i:50: Warning 325: Nested struct not currently supported (Inner ignored) cpp_macro_locator.i:66: Warning 204: CPP #warning, "inline warning message one". cpp_macro_locator.i:96: Warning 204: CPP #warning, "an inline warning message 2". cpp_macro_locator.i:53: Warning 509: Overloaded method overload1(int const *) effectively ignored, From 87c1e093eef273b2a278169d72d899d79e68058a Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 24 Jan 2014 01:09:04 +0000 Subject: [PATCH 310/481] Travis display pcre version --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index fd0a95b94..9cf525f6e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -50,7 +50,7 @@ before_install: script: - ./autogen.sh && ./configure - make -s $SWIGJOBS - - ./swig -version + - ./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 - if test -z "$SWIGLANG"; then sudo make -s install && swig -version && ccache-swig -V; fi From 0383d08444eed8fa7e4476fe421c9ed14f92fba0 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 31 Jan 2014 22:47:12 +0000 Subject: [PATCH 311/481] Add new swigtype_inout.i library containing SWIGTYPE *& OUTPUT typemaps. --- CHANGES.current | 14 +++++ Examples/test-suite/common.mk | 1 + .../csharp/li_swigtype_inout_runme.cs | 56 +++++++++++++++++++ Examples/test-suite/li_swigtype_inout.i | 53 ++++++++++++++++++ Lib/csharp/swigtype_inout.i | 34 +++++++++++ 5 files changed, 158 insertions(+) create mode 100644 Examples/test-suite/csharp/li_swigtype_inout_runme.cs create mode 100644 Examples/test-suite/li_swigtype_inout.i create mode 100644 Lib/csharp/swigtype_inout.i diff --git a/CHANGES.current b/CHANGES.current index ca7503d41..c76a0c19f 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,20 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2014-01-30: wsfulton + [C#] Add new swigtype_inout.i library containing SWIGTYPE *& OUTPUT typemaps. + + Example usage wrapping: + + void f(XXX *& x) { x = new XXX(111); } + + would be: + + XXX x = null; + f(out x); + // use x + x.Dispose(); // manually clear memory or otherwise leave out and leave it to the garbage collector + 2014-01-21: ianlancetaylor [Go] Add %go_import directive. diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index dc18852f7..5ce9a7031 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -251,6 +251,7 @@ CPP_TEST_CASES += \ li_cpointer \ li_std_auto_ptr \ li_stdint \ + li_swigtype_inout \ li_typemaps \ li_typemaps_apply \ li_windows \ diff --git a/Examples/test-suite/csharp/li_swigtype_inout_runme.cs b/Examples/test-suite/csharp/li_swigtype_inout_runme.cs new file mode 100644 index 000000000..0f9520d48 --- /dev/null +++ b/Examples/test-suite/csharp/li_swigtype_inout_runme.cs @@ -0,0 +1,56 @@ + +using System; +using li_swigtype_inoutNamespace; + +public class li_swigtype_inout_runme { + + public static void Main() { + XXX xxx = new XXX(999); + check_count(1); + XXX x1 = null; + XXX x2 = null; + XXX x3 = null; + XXX x4 = null; + li_swigtype_inout.ptr_ref_out(out x1, out x2, out x3, out x4); + check_value(111, x1.value); + check_value(222, x2.value); + check_value(333, x3.value); + check_value(444, x4.value); + check_count(5); + x1.Dispose(); + x2.Dispose(); + x3.Dispose(); + x4.Dispose(); + xxx.Dispose(); + check_count(0); + + x1 = null; + x2 = null; + x3 = null; + x4 = null; + new ConstructorTest(out x1, out x2, out x3, out x4); + check_count(4); + check_value(111, x1.value); + check_value(222, x2.value); + check_value(333, x3.value); + check_value(444, x4.value); + x1.Dispose(); + x2.Dispose(); + x3.Dispose(); + x4.Dispose(); + check_count(0); + } + + public static void check_count(int count) { + int actual = XXX.count; + if( count != actual ) { + throw new Exception(String.Format("Count wrong. Expected: {0} Got: {1}", count, actual)); + } + } + + public static void check_value(int expected, int actual) { + if( expected != actual ) { + throw new Exception(String.Format("Wrong value. Expected: {0} Got: {1}", expected, actual)); + } + } +} diff --git a/Examples/test-suite/li_swigtype_inout.i b/Examples/test-suite/li_swigtype_inout.i new file mode 100644 index 000000000..8b695a925 --- /dev/null +++ b/Examples/test-suite/li_swigtype_inout.i @@ -0,0 +1,53 @@ +%module li_swigtype_inout + +// Test SWIGTYPE *& typemaps in swigtype_inout.i library + +#ifdef SWIGCSHARP +%include +%apply SWIGTYPE *& OUTPUT { SWIGTYPE *& } +#endif + +%ignore XXX::operator=; + +%inline %{ +#include +struct XXX { + XXX(int value) : value(value) { + if (debug) std::cout << "Default Constructor " << value << " " << this << std::endl; + count++; + } + XXX(const XXX &other) { + value = other.value; + if (debug) std::cout << "Copy Constructor " << value << " " << this << std::endl; + count++; + } + XXX& operator=(const XXX &other) { + value = other.value; + if (debug) std::cout << "Assignment operator " << value << " " << this << std::endl; + return *this; + } + ~XXX() { + if (debug) std::cout << "Destructor " << value << " " << this << std::endl; + count--; + } + void showInfo() { + if (debug) std::cout << "Info " << value << " " << this << std::endl; + } + int value; + static const bool debug = false; + static int count; +}; +int XXX::count = 0; + +void ptr_ref_out(XXX *& x1, XXX *& x2, XXX const*& x3, XXX const*& x4) { + x1 = new XXX(111); + x2 = new XXX(222); + x3 = new XXX(333); + x4 = new XXX(444); +} +struct ConstructorTest { + ConstructorTest(XXX *& x1, XXX *& x2, XXX const*& x3, XXX const*& x4) { + ptr_ref_out(x1, x2, x3, x4); + } +}; +%} diff --git a/Lib/csharp/swigtype_inout.i b/Lib/csharp/swigtype_inout.i new file mode 100644 index 000000000..e7312e8fe --- /dev/null +++ b/Lib/csharp/swigtype_inout.i @@ -0,0 +1,34 @@ +/* ----------------------------------------------------------------------------- + * swigtype_inout.i + * + * Pointer pointer and pointer reference handling typemap library for non-primitive types + * + * These mappings provide support for input/output arguments and common + * uses for C/C++ pointer references and pointer to pointers. + * + * These are named typemaps (OUTPUT) and can be used like any named typemap. + * Alternatively they can be made the default by using %apply: + * %apply SWIGTYPE *& OUTPUT { SWIGTYPE *& } + * ----------------------------------------------------------------------------- */ + +/* + * OUTPUT typemaps. Example usage wrapping: + * + * void f(XXX *& x) { x = new XXX(111); } + * + * would be: + * + * XXX x = null; + * f(out x); + * // use x + * x.Dispose(); // manually clear memory or otherwise leave out and leave it to the garbage collector + */ +%typemap(ctype) SWIGTYPE *& OUTPUT "void **" +%typemap(imtype, out="global::System.IntPtr") SWIGTYPE *& OUTPUT "out global::System.IntPtr" +%typemap(cstype) SWIGTYPE *& OUTPUT "out $*csclassname" +%typemap(csin, + pre=" global::System.IntPtr cPtr_$csinput = global::System.IntPtr.Zero;", + post=" $csinput = (cPtr_$csinput == global::System.IntPtr.Zero) ? null : new $*csclassname(cPtr_$csinput, true);", + cshin="out $csinput") SWIGTYPE *& OUTPUT "out cPtr_$csinput" +%typemap(in) SWIGTYPE *& OUTPUT %{ $1 = ($1_ltype)$input; %} +%typemap(freearg) SWIGTYPE *& OUTPUT "" From c3eff9234c5aaca49be12758bb6b2cc4dc18623f Mon Sep 17 00:00:00 2001 From: Marvin Greenberg Date: Fri, 31 Jan 2014 16:03:14 -0500 Subject: [PATCH 312/481] Workaround for clang 3.2 libc++ empty struct bug. Certain tests have empty structs or classes. This encounters a bug with clang: http://llvm.org/bugs/show_bug.cgi?id=16764 This is fixed in later versions of clang, but not the version currently bundled with Mavericks and XCode 5 --- Examples/test-suite/constructor_copy.i | 6 ++++-- Examples/test-suite/ignore_template_constructor.i | 10 ++++++---- Examples/test-suite/smart_pointer_inherit.i | 1 + Examples/test-suite/std_containers.i | 3 ++- Examples/test-suite/template_matrix.i | 1 + Examples/test-suite/template_opaque.i | 1 + 6 files changed, 15 insertions(+), 7 deletions(-) diff --git a/Examples/test-suite/constructor_copy.i b/Examples/test-suite/constructor_copy.i index f6bdcb240..bfbd706f4 100644 --- a/Examples/test-suite/constructor_copy.i +++ b/Examples/test-suite/constructor_copy.i @@ -94,14 +94,16 @@ public: namespace Space { class Flow { +int x; public: - Flow(int i) {} + Flow(int i) : x(i) {} }; class FlowFlow { +int x; public: - FlowFlow(int i) {} + FlowFlow(int i) : x(i) {} }; } diff --git a/Examples/test-suite/ignore_template_constructor.i b/Examples/test-suite/ignore_template_constructor.i index ffd541986..31a5505fb 100644 --- a/Examples/test-suite/ignore_template_constructor.i +++ b/Examples/test-suite/ignore_template_constructor.i @@ -17,9 +17,10 @@ #if defined(SWIG_GOOD_VECTOR) %inline %{ class Flow { - Flow() {} +double x; + Flow():x(0.0) {} public: - Flow(double d) {} + Flow(double d) : x(d) {} }; %} @@ -28,9 +29,10 @@ public: %inline %{ class Flow { +double x; public: - Flow() {} - Flow(double d) {} + Flow(): x(0.0) {} + Flow(double d) : x(d) {} }; %} diff --git a/Examples/test-suite/smart_pointer_inherit.i b/Examples/test-suite/smart_pointer_inherit.i index a81d72268..52df5a92b 100644 --- a/Examples/test-suite/smart_pointer_inherit.i +++ b/Examples/test-suite/smart_pointer_inherit.i @@ -47,6 +47,7 @@ %inline %{ class ItkLevelSetNodeUS2 { + int x; }; %} diff --git a/Examples/test-suite/std_containers.i b/Examples/test-suite/std_containers.i index 0955226ad..ae69b6418 100644 --- a/Examples/test-suite/std_containers.i +++ b/Examples/test-suite/std_containers.i @@ -191,7 +191,8 @@ template struct Param struct Foo { - Foo(int i) { + int x; + Foo(int i) : x(i) { } }; diff --git a/Examples/test-suite/template_matrix.i b/Examples/test-suite/template_matrix.i index 27696542a..535193819 100644 --- a/Examples/test-suite/template_matrix.i +++ b/Examples/test-suite/template_matrix.i @@ -21,6 +21,7 @@ namespace simuPOP template class Operator { + int x; }; } diff --git a/Examples/test-suite/template_opaque.i b/Examples/test-suite/template_opaque.i index 5918fe069..b910e47e3 100644 --- a/Examples/test-suite/template_opaque.i +++ b/Examples/test-suite/template_opaque.i @@ -6,6 +6,7 @@ { struct OpaqueStruct { + int x; }; } From 213774e0b63810b318bbaaa577e10a3de02263d5 Mon Sep 17 00:00:00 2001 From: Marvin Greenberg Date: Mon, 3 Feb 2014 11:34:55 -0500 Subject: [PATCH 313/481] Fix issue on clang about implicit instantiation of undefined template Generated code does not include , which is referenced in templates. Clang may be incorrectly or aggresively instantiating some template. E.g., import_stl_b_wrap.cxx:3199:51: error: implicit instantiation of undefined template 'std::__1::basic_string --- Lib/std/std_common.i | 8 +++++++- Lib/typemaps/traits.swg | 8 +++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/Lib/std/std_common.i b/Lib/std/std_common.i index 7c52880e9..cb91bc632 100644 --- a/Lib/std/std_common.i +++ b/Lib/std/std_common.i @@ -73,7 +73,13 @@ namespace std { #endif %} -%fragment("StdTraitsCommon","header") %{ +%fragment("StdStringInclude","header") %{ +#ifdef __clang__ +#include +#endif +%} + +%fragment("StdTraitsCommon","header",fragment="StdStringInclude") %{ namespace swig { template struct noconst_traits { diff --git a/Lib/typemaps/traits.swg b/Lib/typemaps/traits.swg index b39eb3946..584d480c2 100644 --- a/Lib/typemaps/traits.swg +++ b/Lib/typemaps/traits.swg @@ -26,7 +26,13 @@ #include %} -%fragment("Traits","header") +%fragment("StdStringInclude","header") %{ +#ifdef __clang__ +#include +#endif +%} + +%fragment("Traits","header",fragment="StdStringInclude") { namespace swig { /* From 843aa7cd65985319a64d4f1297778f93f96a5008 Mon Sep 17 00:00:00 2001 From: Marvin Greenberg Date: Thu, 30 Jan 2014 16:37:07 -0500 Subject: [PATCH 314/481] Work around differences in clang libc++ std::vector::const_reference clang++ using -stdlib=libc++ defines const_reference as a class, to map boolean vectors onto a bit set. Because swig does not "see" the type as "const &" it generates incorrect code for this case, generating a declaration like: const_reference result; When const_reference is a typedef to 'bool' as is the case with stdlibc++ this works. When this is actually a constant reference, this is clearly invalid since it is not initialized. For libc++, this is a class which cannot be default constructed, resulting in an error. The fix is to explicitly define the various accessor extensions as having a bool return type for this specialization. --- Lib/csharp/std_vector.i | 2 +- Lib/d/std_vector.i | 12 ++++++------ Lib/go/std_vector.i | 2 +- Lib/java/std_vector.i | 2 +- Lib/php/std_vector.i | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Lib/csharp/std_vector.i b/Lib/csharp/std_vector.i index 9d52a962b..467a2ade8 100644 --- a/Lib/csharp/std_vector.i +++ b/Lib/csharp/std_vector.i @@ -217,7 +217,7 @@ else throw std::out_of_range("index"); } - const_reference getitem(int index) throw (std::out_of_range) { + CONST_REFERENCE getitem(int index) throw (std::out_of_range) { if (index>=0 && index<(int)$self->size()) return (*$self)[index]; else diff --git a/Lib/d/std_vector.i b/Lib/d/std_vector.i index b7d4e223f..50942f289 100644 --- a/Lib/d/std_vector.i +++ b/Lib/d/std_vector.i @@ -128,7 +128,7 @@ public void capacity(size_t value) { return $self->capacity() - $self->size(); } - const_reference remove() throw (std::out_of_range) { + CONST_REFERENCE remove() throw (std::out_of_range) { if ($self->empty()) { throw std::out_of_range("Tried to remove last element from empty vector."); } @@ -138,7 +138,7 @@ public void capacity(size_t value) { return value; } - const_reference remove(size_type index) throw (std::out_of_range) { + CONST_REFERENCE remove(size_type index) throw (std::out_of_range) { if (index >= $self->size()) { throw std::out_of_range("Tried to remove element with invalid index."); } @@ -153,7 +153,7 @@ public void capacity(size_t value) { // Wrappers for setting/getting items with the possibly thrown exception // specified (important for SWIG wrapper generation). %extend { - const_reference getElement(size_type index) throw (std::out_of_range) { + CONST_REFERENCE getElement(size_type index) throw (std::out_of_range) { if ((index < 0) || ($self->size() <= index)) { throw std::out_of_range("Tried to get value of element with invalid index."); } @@ -464,7 +464,7 @@ int opApply(int delegate(ref size_t index, ref $typemap(dtype, CTYPE) value) dg) return pv; } - const_reference remove() throw (std::out_of_range) { + CONST_REFERENCE remove() throw (std::out_of_range) { if ($self->empty()) { throw std::out_of_range("Tried to remove last element from empty vector."); } @@ -474,7 +474,7 @@ int opApply(int delegate(ref size_t index, ref $typemap(dtype, CTYPE) value) dg) return value; } - const_reference remove(size_type index) throw (std::out_of_range) { + CONST_REFERENCE remove(size_type index) throw (std::out_of_range) { if (index >= $self->size()) { throw std::out_of_range("Tried to remove element with invalid index."); } @@ -506,7 +506,7 @@ int opApply(int delegate(ref size_t index, ref $typemap(dtype, CTYPE) value) dg) // Wrappers for setting/getting items with the possibly thrown exception // specified (important for SWIG wrapper generation). %extend { - const_reference getElement(size_type index) throw (std::out_of_range) { + CONST_REFERENCE getElement(size_type index) throw (std::out_of_range) { if ((index < 0) || ($self->size() <= index)) { throw std::out_of_range("Tried to get value of element with invalid index."); } diff --git a/Lib/go/std_vector.i b/Lib/go/std_vector.i index f4ce8431c..29bcd1391 100644 --- a/Lib/go/std_vector.i +++ b/Lib/go/std_vector.i @@ -59,7 +59,7 @@ namespace std { %rename(add) push_back; void push_back(const value_type& x); %extend { - const_reference get(int i) throw (std::out_of_range) { + bool get(int i) throw (std::out_of_range) { int size = int(self->size()); if (i>=0 && isize()); if (i>=0 && ipop_back(); return x; } - const_reference get(int i) throw (std::out_of_range) { + bool get(int i) throw (std::out_of_range) { int size = int(self->size()); if (i>=0 && i Date: Wed, 5 Feb 2014 02:30:48 +0400 Subject: [PATCH 315/481] error order foxed --- Examples/test-suite/errors/cpp_macro_locator.stderr | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Examples/test-suite/errors/cpp_macro_locator.stderr b/Examples/test-suite/errors/cpp_macro_locator.stderr index f4fc2c7d0..0d91ba5ae 100644 --- a/Examples/test-suite/errors/cpp_macro_locator.stderr +++ b/Examples/test-suite/errors/cpp_macro_locator.stderr @@ -1,6 +1,6 @@ -cpp_macro_locator.i:50: Warning 325: Nested struct not currently supported (Inner ignored) cpp_macro_locator.i:66: Warning 204: CPP #warning, "inline warning message one". cpp_macro_locator.i:96: Warning 204: CPP #warning, "an inline warning message 2". +cpp_macro_locator.i:50: Warning 325: Nested struct not currently supported (Inner ignored) cpp_macro_locator.i:53: Warning 509: Overloaded method overload1(int const *) effectively ignored, cpp_macro_locator.i:52: Warning 509: as it is shadowed by overload1(int *). cpp_macro_locator.i:61: Warning 509: Overloaded method overload2(int const *) effectively ignored, From a54674eeca8c5173b915e6bd21de4ccd4298fcf5 Mon Sep 17 00:00:00 2001 From: Geert Janssens Date: Wed, 5 Feb 2014 11:52:26 +0100 Subject: [PATCH 316/481] Guile: illustrate bug in non-ascii string handling --- Examples/test-suite/schemerunme/li_std_string.scm | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Examples/test-suite/schemerunme/li_std_string.scm b/Examples/test-suite/schemerunme/li_std_string.scm index e77c32870..343b9b8e8 100644 --- a/Examples/test-suite/schemerunme/li_std_string.scm +++ b/Examples/test-suite/schemerunme/li_std_string.scm @@ -1,4 +1,6 @@ -(define x "hello") +; The test string has some non-ascii characters added +; because our guile wrappers had bugs in that area +(define x "hello - æææ") (if (not (string=? (test-value x) x)) (begin (error "Error 1") (exit 1))) From c6d03a6a9fd4af3bd22b9754f82abe0bd5555e84 Mon Sep 17 00:00:00 2001 From: Geert Janssens Date: Fri, 13 Dec 2013 17:48:26 +0100 Subject: [PATCH 317/481] Guile: make scm to string conversion work with non-ascii strings --- .../test-suite/guile/li_std_string_runme.scm | 4 ++++ Lib/guile/guile_scm_run.swg | 22 ++++++++----------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/Examples/test-suite/guile/li_std_string_runme.scm b/Examples/test-suite/guile/li_std_string_runme.scm index 5dde68f8d..5b5563281 100644 --- a/Examples/test-suite/guile/li_std_string_runme.scm +++ b/Examples/test-suite/guile/li_std_string_runme.scm @@ -2,4 +2,8 @@ ;; Guile modules (namespaces) but simply put all the bindings into the ;; current module. That's enough for such a simple test. (dynamic-call "scm_init_li_std_string_module" (dynamic-link "./libli_std_string")) +; Note: when working with non-ascii strings in guile 2 +; locale must be set explicitly +; The setlocale call below takes care of that +(setlocale LC_ALL "") (load "../schemerunme/li_std_string.scm") diff --git a/Lib/guile/guile_scm_run.swg b/Lib/guile/guile_scm_run.swg index 2f8f3ae98..322d660c5 100644 --- a/Lib/guile/guile_scm_run.swg +++ b/Lib/guile/guile_scm_run.swg @@ -41,10 +41,14 @@ typedef struct swig_guile_clientdata { SCM goops_class; } swig_guile_clientdata; +#if SCM_MAJOR_VERSION <= 2 +#define scm_to_utf8_string scm_to_locale_string +#define scm_from_utf8_string scm_from_locale_string +#endif #define SWIG_scm2str(s) \ SWIG_Guile_scm2newstr(s, NULL) #define SWIG_str02scm(str) \ - str ? scm_from_locale_string(str) : SCM_BOOL_F + str ? scm_from_utf8_string(str) : SCM_BOOL_F # define SWIG_malloc(size) \ scm_malloc(size) # define SWIG_free(mem) \ @@ -84,21 +88,13 @@ SWIGINTERN char * SWIG_Guile_scm2newstr(SCM str, size_t *len) { #define FUNC_NAME "SWIG_Guile_scm2newstr" char *ret; - char *tmp; - size_t l; SCM_ASSERT (scm_is_string(str), str, 1, FUNC_NAME); - l = scm_c_string_length(str); - ret = (char *) SWIG_malloc( (l + 1) * sizeof(char)); + ret = scm_to_utf8_string(str); if (!ret) return NULL; - tmp = scm_to_locale_string(str); - memcpy(ret, tmp, l); - free(tmp); - - ret[l] = '\0'; - if (len) *len = l; + if (len) *len = strlen(ret) - 1; return ret; #undef FUNC_NAME } @@ -473,7 +469,7 @@ SWIG_Guile_GetArgs (SCM *dest, SCM rest, int num_args_passed = 0; for (i = 0; i Date: Wed, 5 Feb 2014 15:18:51 -0800 Subject: [PATCH 318/481] Move setting required -stdlib argument into configure.ac --- Examples/Makefile.in | 2 +- configure.ac | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 7680908ab..fc17d8784 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -25,7 +25,7 @@ TARGET = CC = @CC@ CXX = @CXX@ CFLAGS = @PLATCFLAGS@ -CXXFLAGS = @BOOST_CPPFLAGS@ @PLATCXXFLAGS@ $(filter -stdlib%,@CXXFLAGS@) +CXXFLAGS = @BOOST_CPPFLAGS@ @PLATCXXFLAGS@ prefix = @prefix@ exec_prefix= @exec_prefix@ SRCS = diff --git a/configure.ac b/configure.ac index 03677f90d..d05eb1802 100644 --- a/configure.ac +++ b/configure.ac @@ -352,6 +352,15 @@ if test x"$enable_cpp11_testing" = xyes; then fi fi +# On darwin before Mavericks when using clang, need to ensure using +# libc++ for tests and examples to run under mono +case $host in + *-*-darwin*) if test "$CXX" = "clang++"; + then PLATCXXFLAGS="$PLATCXXFLAGS -stdlib=libc++" + fi;; + *) ;; +esac + # Set info about shared libraries. AC_SUBST(SO) AC_SUBST(LDSHARED) From fd85d12a2cd5dc31e6f9a0d0a29bfd61bd8865f4 Mon Sep 17 00:00:00 2001 From: Marvin Greenberg Date: Wed, 5 Feb 2014 15:31:57 -0800 Subject: [PATCH 319/481] Allow csharp examples to run under mono --- Examples/Makefile.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index fc17d8784..dac3f2c37 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -1205,7 +1205,7 @@ CSHARPCOMPILER = @CSHARPCOMPILER@ CSHARPCILINTERPRETER = @CSHARPCILINTERPRETER@ CSHARPCFLAGS = @CSHARPCFLAGS@ CSHARPSO = @CSHARPSO@ -CSHARP_RUNME = ./$(RUNME).exe +CSHARP_RUNME = $(CSHARPCILINTERPRETER) ./$(RUNME).exe # ---------------------------------------------------------------- # Build a CSharp dynamically loadable module (C) From 844695b674d67e2c3bb0b1db48286a7dcea40423 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 6 Feb 2014 19:28:28 +0000 Subject: [PATCH 320/481] Fix typedef_typedef test --- Examples/test-suite/python/typedef_typedef_runme.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Examples/test-suite/python/typedef_typedef_runme.py b/Examples/test-suite/python/typedef_typedef_runme.py index 51a823def..1d83065a6 100644 --- a/Examples/test-suite/python/typedef_typedef_runme.py +++ b/Examples/test-suite/python/typedef_typedef_runme.py @@ -1,5 +1,5 @@ import typedef_typedef b = typedef_typedef.B() -if b.getValue(123) == 1234: - print "Failed !!!" +if b.getValue(123) != 1234: + raise Exception("Failed") From 56cea1821d2df2a4c0931bde072bbeba90b13ec5 Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Thu, 6 Feb 2014 23:47:01 +0400 Subject: [PATCH 321/481] warning filter fixed --- Examples/test-suite/nested_class.i | 20 +++++++++++++++++++- Source/CParse/parser.y | 11 ++++------- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/Examples/test-suite/nested_class.i b/Examples/test-suite/nested_class.i index 73bf89eb0..1cdfaade6 100644 --- a/Examples/test-suite/nested_class.i +++ b/Examples/test-suite/nested_class.i @@ -1,7 +1,25 @@ %module nested_class #pragma SWIG nowarn=SWIGWARN_PARSE_UNNAMED_NESTED_CLASS -#pragma SWIG nowarn=SWIGWARN_PARSE_NAMED_NESTED_CLASS +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerStruct1; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerClass1; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerUnion1; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerClass2; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerStruct2; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerUnion2; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerClass4Typedef; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerStruct4Typedef; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerUnion4Typedef; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerClass5; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerStruct5; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerUnion5; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerMultiple; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerMultipleDerived; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerMultipleAnonTypedef1; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerMultipleNamedTypedef; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerSameName; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer2::IgnoreMe; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerSameName2; %inline %{ struct Outer { diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 77d253299..b8ff59f0b 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1076,7 +1076,7 @@ static void update_nested_classes(Node *n) * Create the nested class/struct/union as a forward declaration. * ----------------------------------------------------------------------------- */ -static Node *nested_forward_declaration(const char *storage, const char *kind, String *sname, String *name, Node *cpp_opt_declarators, Node* nested) { +static Node *nested_forward_declaration(const char *storage, const char *kind, String *sname, String *name, Node *cpp_opt_declarators) { Node *nn = 0; int warned = 0; @@ -1120,7 +1120,7 @@ static Node *nested_forward_declaration(const char *storage, const char *kind, S } if (nn && Equal(nodeType(nn), "classforward")) { - Node *n = nested; + Node *n = nn; SWIG_WARN_NODE_BEGIN(n); Swig_warning(WARN_PARSE_NAMED_NESTED_CLASS, cparse_file, cparse_line,"Nested %s not currently supported (%s ignored)\n", kind, sname ? sname : name); SWIG_WARN_NODE_END(n); @@ -1128,10 +1128,7 @@ static Node *nested_forward_declaration(const char *storage, const char *kind, S } if (!warned) { - Node *n = nested; - SWIG_WARN_NODE_BEGIN(n); Swig_warning(WARN_PARSE_UNNAMED_NESTED_CLASS, cparse_file, cparse_line, "Nested %s not currently supported (ignored).\n", kind); - SWIG_WARN_NODE_END(n); } return nn; @@ -3628,7 +3625,7 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { if (cplus_mode == CPLUS_PRIVATE) { $$ = 0; /* skip private nested classes */ } else if (cparse_cplusplus && currentOuterClass && ignore_nested_classes && !GetFlag($$, "feature:flatnested")) { - $$ = nested_forward_declaration($1, $2, $3, Copy($3), $9, $$); + $$ = nested_forward_declaration($1, $2, $3, Copy($3), $9); } else if (nscope_inner) { /* this is tricky */ /* we add the declaration in the original namespace */ @@ -3741,7 +3738,7 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { Swig_features_get(Swig_cparse_features(), Namespaceprefix, 0, 0, $$); if (cparse_cplusplus && currentOuterClass && ignore_nested_classes && !GetFlag($$, "feature:flatnested")) { String *name = n ? Copy(Getattr(n, "name")) : 0; - $$ = nested_forward_declaration($1, $2, 0, name, n, $$); + $$ = nested_forward_declaration($1, $2, 0, name, n); Swig_symbol_popscope(); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); From 6b5e3665677327479c4a1181a2bf82984f211656 Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Thu, 6 Feb 2014 23:53:33 +0400 Subject: [PATCH 322/481] nested nested class warning filtered --- Examples/test-suite/nested_class.i | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Examples/test-suite/nested_class.i b/Examples/test-suite/nested_class.i index 1cdfaade6..b95db40cd 100644 --- a/Examples/test-suite/nested_class.i +++ b/Examples/test-suite/nested_class.i @@ -19,7 +19,7 @@ %warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerMultipleNamedTypedef; %warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerSameName; %warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer2::IgnoreMe; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerSameName2; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerSameName::InnerSameName2; %inline %{ struct Outer { From b457f8f290528368b21ef8e3ab28528446ef280c Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 6 Feb 2014 20:02:05 +0000 Subject: [PATCH 323/481] Changes entry for guile non-ascii strings fix --- CHANGES.current | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGES.current b/CHANGES.current index c76a0c19f..7c257dfde 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,11 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2014-02-06: gjanssens + [Guile] Patch #133. Make scm to string conversion work with non-ascii strings. + Guile 2 has a completely rewritten string implementation. SWIG made some assumptions + that are no longer valid as to the internals of guile's string representation. + 2014-01-30: wsfulton [C#] Add new swigtype_inout.i library containing SWIGTYPE *& OUTPUT typemaps. From e9ecac929842033de4dc1149a4cb2aaba28afdbf Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Fri, 7 Feb 2014 07:39:07 +0400 Subject: [PATCH 324/481] warnings suppressed for deeply nested classes --- Examples/test-suite/nested_class.i | 1 - Source/CParse/parser.y | 20 +++++++++++--------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/Examples/test-suite/nested_class.i b/Examples/test-suite/nested_class.i index b95db40cd..ccb7ecac1 100644 --- a/Examples/test-suite/nested_class.i +++ b/Examples/test-suite/nested_class.i @@ -19,7 +19,6 @@ %warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerMultipleNamedTypedef; %warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerSameName; %warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer2::IgnoreMe; -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::InnerSameName::InnerSameName2; %inline %{ struct Outer { diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index b8ff59f0b..231b51cb3 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1119,16 +1119,18 @@ static Node *nested_forward_declaration(const char *storage, const char *kind, S } } - if (nn && Equal(nodeType(nn), "classforward")) { - Node *n = nn; - SWIG_WARN_NODE_BEGIN(n); - Swig_warning(WARN_PARSE_NAMED_NESTED_CLASS, cparse_file, cparse_line,"Nested %s not currently supported (%s ignored)\n", kind, sname ? sname : name); - SWIG_WARN_NODE_END(n); - warned = 1; - } + if (!GetFlag(currentOuterClass, "nested")) { + if (nn && Equal(nodeType(nn), "classforward")) { + Node *n = nn; + SWIG_WARN_NODE_BEGIN(n); + Swig_warning(WARN_PARSE_NAMED_NESTED_CLASS, cparse_file, cparse_line,"Nested %s not currently supported (%s ignored)\n", kind, sname ? sname : name); + SWIG_WARN_NODE_END(n); + warned = 1; + } - if (!warned) { - Swig_warning(WARN_PARSE_UNNAMED_NESTED_CLASS, cparse_file, cparse_line, "Nested %s not currently supported (ignored).\n", kind); + if (!warned) { + Swig_warning(WARN_PARSE_UNNAMED_NESTED_CLASS, cparse_file, cparse_line, "Nested %s not currently supported (ignored).\n", kind); + } } return nn; From 3518cbfd333945981bd98454c80be11975c965f0 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 8 Feb 2014 09:00:52 +0000 Subject: [PATCH 325/481] Typo in comment fix --- Source/CParse/parser.y | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 231b51cb3..4c6d11e64 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -1072,7 +1072,7 @@ static void update_nested_classes(Node *n) /* ----------------------------------------------------------------------------- * nested_forward_declaration() * - * Nested struct handling for C++ code if the nested classes are diasbled. + * Nested struct handling for C++ code if the nested classes are disabled. * Create the nested class/struct/union as a forward declaration. * ----------------------------------------------------------------------------- */ From 88de9f16101cb0fd8806b0a7b55ee80f24c1c04f Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 8 Feb 2014 09:45:20 +0000 Subject: [PATCH 326/481] Restore warning suppression in testcase --- Examples/test-suite/union_scope.i | 1 + 1 file changed, 1 insertion(+) diff --git a/Examples/test-suite/union_scope.i b/Examples/test-suite/union_scope.i index 67093eff6..b7307cb29 100644 --- a/Examples/test-suite/union_scope.i +++ b/Examples/test-suite/union_scope.i @@ -2,6 +2,7 @@ %warnfilter(SWIGWARN_RUBY_WRONG_NAME) nRState; // Ruby, wrong class name %warnfilter(SWIGWARN_RUBY_WRONG_NAME) nRState_rstate; // Ruby, wrong class name +#pragma SWIG nowarn=SWIGWARN_PARSE_UNNAMED_NESTED_CLASS %inline %{ class nRState { From 3cf3be24abd8f5cf696c9eaf2d9d58785f05cf8a Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 8 Feb 2014 11:08:56 +0000 Subject: [PATCH 327/481] mkdist script tweaks to support releasing from any named branch --- Tools/mkdist.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/Tools/mkdist.py b/Tools/mkdist.py index 234c768f2..2e69dbece 100755 --- a/Tools/mkdist.py +++ b/Tools/mkdist.py @@ -1,7 +1,7 @@ #!/usr/bin/env python # This script builds a swig-x.y.z distribution. -# Usage : mkdist.py version, where version should be x.y.z +# Usage: mkdist.py version branch, where version should be x.y.z and branch is normally 'master' import sys import string @@ -16,10 +16,16 @@ def failed(): try: version = sys.argv[1] dirname = "swig-" + version + branch = sys.argv[2] except: - print "Usage: mkdist.py version, where version should be x.y.z" + print "Usage: mkdist.py version branch, where version should be x.y.z and branch is normally 'master'" sys.exit(1) +if sys.version_info[0:2] < (2, 7): + print "Error: Python 2.7 is required" + sys.exit(3) + + # Check name matches normal unix conventions if string.lower(dirname) != dirname: print "directory name ("+dirname+") should be in lowercase" @@ -38,7 +44,7 @@ os.system("rm -f "+dirname+".tar") # Grab the code from git print "Checking git repository is in sync with remote repository" -os.system("git remote update") == 0 or failed() +os.system("git remote update origin") == 0 or failed() command = ["git", "status", "--porcelain", "-uno"] out = subprocess.check_output(command) if out.strip() != "": @@ -47,7 +53,7 @@ if out.strip() != "": print out sys.exit(3) -command = ["git", "log", "--oneline", "master..origin/master"] +command = ["git", "log", "--oneline", branch + "..origin/" + branch] out = subprocess.check_output(command) if out.strip() != "": print "Remote repository has additional modifications to local repository" @@ -55,7 +61,7 @@ if out.strip() != "": print out sys.exit(3) -command = ["git", "log", "--oneline", "origin/master..master"] +command = ["git", "log", "--oneline", "origin/" + branch + ".." + branch] out = subprocess.check_output(command) if out.strip() != "": print "Local repository has modifications not pushed to the remote repository" From 4e9ee78d3eace3f234a3fd5e08e410bb3ca092a5 Mon Sep 17 00:00:00 2001 From: Atri Date: Tue, 1 Oct 2013 01:28:26 +0530 Subject: [PATCH 328/481] Lua: Fix void return for non-void functions Commit #c3f3880d caused the functions SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State* L, swig_lua_namespace* ns) and SWIGINTERN int SWIG_Lua_namespace_register(lua_State* L, swig_lua_namespace* ns) to return void when int returns were expected resulting in the build failures for plplot's lua bindings for example. This commit fixes the issue. Closes #92 --- Lib/lua/luarun.swg | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index 4d851bdb1..8485ed499 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -524,7 +524,7 @@ SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State* L, swig_lua_namespace* /* clear stack - remove metatble */ lua_pop(L,1); - + return 0; } /* helper function. creates namespace table and add it to module table */ @@ -555,6 +555,7 @@ SWIGINTERN int SWIG_Lua_namespace_register(lua_State* L, swig_lua_namespace* ns) lua_setmetatable(L,-2); /* set metatable */ lua_rawset(L,-3); /* add namespace to module table */ + return 0; } /* ----------------------------------------------------------------------------- * global variable support code: classes From f0b60d0ec9fc46cdb17c1f84b2d42231a7313572 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 8 Feb 2014 14:36:10 +0000 Subject: [PATCH 329/481] Bump version to 2.0.12 --- ANNOUNCE | 8 +-- CHANGES | 137 ++++++++++++++++++++++++++++++++++++++ CHANGES.current | 138 +-------------------------------------- Doc/Manual/Sections.html | 2 +- README | 2 +- configure.ac | 2 +- 6 files changed, 146 insertions(+), 143 deletions(-) diff --git a/ANNOUNCE b/ANNOUNCE index caaa55d8c..06a24ccb7 100644 --- a/ANNOUNCE +++ b/ANNOUNCE @@ -1,8 +1,8 @@ -*** ANNOUNCE: SWIG 2.0.11 (15 Sep 2013) *** +*** ANNOUNCE: SWIG 2.0.12 (9 Feb 2014) *** http://www.swig.org -We're pleased to announce SWIG-2.0.11, the latest SWIG release. +We're pleased to announce SWIG-2.0.12, the latest SWIG release. What is SWIG? ============= @@ -21,11 +21,11 @@ Availability ============ The release is available for download on Sourceforge at - http://prdownloads.sourceforge.net/swig/swig-2.0.11.tar.gz + http://prdownloads.sourceforge.net/swig/swig-2.0.12.tar.gz A Windows version is also available at - http://prdownloads.sourceforge.net/swig/swigwin-2.0.11.zip + http://prdownloads.sourceforge.net/swig/swigwin-2.0.12.zip Please report problems with this release to the swig-devel mailing list, details at http://www.swig.org/mail.html. diff --git a/CHANGES b/CHANGES index 488bf7286..b40597e26 100644 --- a/CHANGES +++ b/CHANGES @@ -3,6 +3,143 @@ SWIG (Simplified Wrapper and Interface Generator) See the CHANGES.current file for changes in the current version. See the RELEASENOTES file for a summary of changes in each release. +Version 2.0.11 (15 Sep 2013) +============================ + +2013-09-15: wsfulton + [R] Fix attempt to free a non-heap object in OUTPUT typemaps for: + unsigned short *OUTPUT + unsigned long *OUTPUT + signed long long *OUTPUT + char *OUTPUT + signed char*OUTPUT + unsigned char*OUTPUT + +2013-09-12: wsfulton + [Lua] Pull Git patch #62. + 1) Static members and static functions inside class can be accessed as + ModuleName.ClassName.FunctionName (MemberName respectively). Old way such as + ModuleName.ClassName_FunctionName still works. + 2) Same goes for enums inside classes: ModuleName.ClassName.EnumValue1 etc. + +2013-09-12: wsfulton + [UTL] Infinity is now by default an acceptable value for type 'float'. This fix makes + the handling of type 'float' and 'double' the same. The implementation requires the + C99 isfinite() macro, or otherwise some platform dependent equivalents, to be available. + + Users requiring the old behaviour of not accepting infinity, can define a 'check' typemap + wherever a float is used, such as: + + %typemap(check,fragment="") float, const float & %{ + if ($1 < -FLT_MAX || $1 > FLT_MAX) { + SWIG_exception_fail(SWIG_TypeError, "Overflow in type float"); + } + %} + + *** POTENTIAL INCOMPATIBILITY *** + +2013-08-30: wsfulton + [Lua] Pull Git patch #81: Include Lua error locus in SWIG error messages. + This is standard information in Lua error messages, and makes it much + easier to find bugs. + +2013-08-29: wsfulton + Pull Git patch #75: Handle UTF-8 files with BOM at beginning of file. Was giving an + 'Illegal token' syntax error. + +2013-08-29: wsfulton + [C#] Pull Git patch #77: Allow exporting std::map using non-default comparison function. + +2013-08-28: wsfulton + [Python] %implicitconv is improved for overloaded functions. Like in C++, the methods + with the actual types are considered before trying implicit conversions. Example: + + %implicitconv A; + struct A { + A(int i); + }; + class CCC { + public: + int xx(int i) { return 11; } + int xx(const A& i) { return 22; } + }; + + The following python code: + + CCC().xx(-1) + + will now return 11 instead of 22 - the implicit conversion is not done. + +2013-08-23: olly + [Python] Fix clang++ warning in generated wrapper code. + +2013-08-16: wsfulton + [Python] %implicitconv will now accept None where the implicit conversion takes a C/C++ pointer. + Problem highlighted by Bo Peng. Closes SF patch #230. + +2013-08-07: wsfulton + [Python] SF Patch #326 from Kris Thielemans - Remove SwigPyObject_print and SwigPyObject_str and + make the generated wrapper use the default python implementations, which will fall back to repr + (for -builtin option). + + Advantages: + - it avoids the swig user having to jump through hoops to get print to work as expected when + redefining repr/str slots. + - typing the name of a variable on the python prompt now prints the result of a (possibly redefined) + repr, without the swig user having to do any extra work. + - when redefining repr, the swig user doesn't necessarily have to redefine str as it will call the + redefined repr + - the behaviour is exactly the same as without the -builtin option while requiring no extra work + by the user (aside from adding the %feature("python:slot...) statements of course) + + Disadvantage: + - default str() will give different (but clearer?) output on swigged classes + +2013-07-30: wsfulton + [Python, Ruby] Fix #64 #65: Missing code in std::multimap wrappers. Previously an instantiation + of a std::map was erroneously required in addition to an instantiation of std::multimap with the + same template parameters to prevent compilation errors for the wrappers of a std::multimap. + +2013-07-14: joequant + [R] Change types file to allow for SEXP return values + +2013-07-05: wsfulton + [Python] Add %pythonbegin directive which works like %pythoncode, except the specified code is + added at the beginning of the generated .py file. This is primarily needed for importing from + __future__ statements required to be at the very beginning of the file. Example: + + %pythonbegin %{ + from __future__ import print_function + print("Loading", "Whizz", "Bang", sep=' ... ') + %} + +2013-07-01: wsfulton + [Python] Apply SF patch #340 - Uninitialized variable fix in SWIG_Python_NonDynamicSetAttr + when using -builtin. + +2013-07-01: wsfulton + [Python, Ruby, Ocaml] Apply SF patch #341 - fix a const_cast in generated code that was generating + a <:: digraph when using the unary scope operator (::) (global scope) in a template type. + +2013-07-01: wsfulton + [Python] Add SF patch #342 from Christian Delbaere to fix some director classes crashing on + object deletion when using -builtin. Fixes SF bug #1301. + +2013-06-11: wsfulton + [Python] Add SWIG_PYTHON_INTERPRETER_NO_DEBUG macro which can be defined to use the Release version + of the Python interpreter in Debug builds of the wrappers. The Visual Studio .dsp example + files have been modified to use this so that Debug builds will now work without having + to install or build a Debug build of the interpreter. + +2013-06-07: wsfulton + [Ruby] Git issue #52. Fix regression with missing rb_complex_new function for Ruby + versions prior to 1.9 using std::complex wrappers if just using std::complex as an output type. + Also fix the Complex helper functions external visibility (to static by default). + +2013-06-04: olly + [PHP] Fix SWIG_ZTS_ConvertResourcePtr() not to dereference NULL + if the type lookup fails. + Version 2.0.10 (27 May 2013) ============================ diff --git a/CHANGES.current b/CHANGES.current index 1727ecb2c..f2dfaea26 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -2,140 +2,6 @@ Below are the changes for the current release. See the CHANGES file for changes in older releases. See the RELEASENOTES file for a summary of changes in each release. -Version 2.0.11 (15 Sep 2013) -============================ - -2013-09-15: wsfulton - [R] Fix attempt to free a non-heap object in OUTPUT typemaps for: - unsigned short *OUTPUT - unsigned long *OUTPUT - signed long long *OUTPUT - char *OUTPUT - signed char*OUTPUT - unsigned char*OUTPUT - -2013-09-12: wsfulton - [Lua] Pull Git patch #62. - 1) Static members and static functions inside class can be accessed as - ModuleName.ClassName.FunctionName (MemberName respectively). Old way such as - ModuleName.ClassName_FunctionName still works. - 2) Same goes for enums inside classes: ModuleName.ClassName.EnumValue1 etc. - -2013-09-12: wsfulton - [UTL] Infinity is now by default an acceptable value for type 'float'. This fix makes - the handling of type 'float' and 'double' the same. The implementation requires the - C99 isfinite() macro, or otherwise some platform dependent equivalents, to be available. - - Users requiring the old behaviour of not accepting infinity, can define a 'check' typemap - wherever a float is used, such as: - - %typemap(check,fragment="") float, const float & %{ - if ($1 < -FLT_MAX || $1 > FLT_MAX) { - SWIG_exception_fail(SWIG_TypeError, "Overflow in type float"); - } - %} - - *** POTENTIAL INCOMPATIBILITY *** - -2013-08-30: wsfulton - [Lua] Pull Git patch #81: Include Lua error locus in SWIG error messages. - This is standard information in Lua error messages, and makes it much - easier to find bugs. - -2013-08-29: wsfulton - Pull Git patch #75: Handle UTF-8 files with BOM at beginning of file. Was giving an - 'Illegal token' syntax error. - -2013-08-29: wsfulton - [C#] Pull Git patch #77: Allow exporting std::map using non-default comparison function. - -2013-08-28: wsfulton - [Python] %implicitconv is improved for overloaded functions. Like in C++, the methods - with the actual types are considered before trying implicit conversions. Example: - - %implicitconv A; - struct A { - A(int i); - }; - class CCC { - public: - int xx(int i) { return 11; } - int xx(const A& i) { return 22; } - }; - - The following python code: - - CCC().xx(-1) - - will now return 11 instead of 22 - the implicit conversion is not done. - -2013-08-23: olly - [Python] Fix clang++ warning in generated wrapper code. - -2013-08-16: wsfulton - [Python] %implicitconv will now accept None where the implicit conversion takes a C/C++ pointer. - Problem highlighted by Bo Peng. Closes SF patch #230. - -2013-08-07: wsfulton - [Python] SF Patch #326 from Kris Thielemans - Remove SwigPyObject_print and SwigPyObject_str and - make the generated wrapper use the default python implementations, which will fall back to repr - (for -builtin option). - - Advantages: - - it avoids the swig user having to jump through hoops to get print to work as expected when - redefining repr/str slots. - - typing the name of a variable on the python prompt now prints the result of a (possibly redefined) - repr, without the swig user having to do any extra work. - - when redefining repr, the swig user doesn't necessarily have to redefine str as it will call the - redefined repr - - the behaviour is exactly the same as without the -builtin option while requiring no extra work - by the user (aside from adding the %feature("python:slot...) statements of course) - - Disadvantage: - - default str() will give different (but clearer?) output on swigged classes - -2013-07-30: wsfulton - [Python, Ruby] Fix #64 #65: Missing code in std::multimap wrappers. Previously an instantiation - of a std::map was erroneously required in addition to an instantiation of std::multimap with the - same template parameters to prevent compilation errors for the wrappers of a std::multimap. - -2013-07-14: joequant - [R] Change types file to allow for SEXP return values - -2013-07-05: wsfulton - [Python] Add %pythonbegin directive which works like %pythoncode, except the specified code is - added at the beginning of the generated .py file. This is primarily needed for importing from - __future__ statements required to be at the very beginning of the file. Example: - - %pythonbegin %{ - from __future__ import print_function - print("Loading", "Whizz", "Bang", sep=' ... ') - %} - -2013-07-01: wsfulton - [Python] Apply SF patch #340 - Uninitialized variable fix in SWIG_Python_NonDynamicSetAttr - when using -builtin. - -2013-07-01: wsfulton - [Python, Ruby, Ocaml] Apply SF patch #341 - fix a const_cast in generated code that was generating - a <:: digraph when using the unary scope operator (::) (global scope) in a template type. - -2013-07-01: wsfulton - [Python] Add SF patch #342 from Christian Delbaere to fix some director classes crashing on - object deletion when using -builtin. Fixes SF bug #1301. - -2013-06-11: wsfulton - [Python] Add SWIG_PYTHON_INTERPRETER_NO_DEBUG macro which can be defined to use the Release version - of the Python interpreter in Debug builds of the wrappers. The Visual Studio .dsp example - files have been modified to use this so that Debug builds will now work without having - to install or build a Debug build of the interpreter. - -2013-06-07: wsfulton - [Ruby] Git issue #52. Fix regression with missing rb_complex_new function for Ruby - versions prior to 1.9 using std::complex wrappers if just using std::complex as an output type. - Also fix the Complex helper functions external visibility (to static by default). - -2013-06-04: olly - [PHP] Fix SWIG_ZTS_ConvertResourcePtr() not to dereference NULL - if the type lookup fails. +Version 2.0.12 (9 Feb 2014) +=========================== diff --git a/Doc/Manual/Sections.html b/Doc/Manual/Sections.html index 2dfb438f8..9a9c0cc68 100644 --- a/Doc/Manual/Sections.html +++ b/Doc/Manual/Sections.html @@ -6,7 +6,7 @@

      SWIG-2.0 Documentation

      -Last update : SWIG-2.0.11 (15 Sep 2013) +Last update : SWIG-2.0.12 (9 Feb 2014)

      Sections

      diff --git a/README b/README index 946bd9a8f..664e78046 100644 --- a/README +++ b/README @@ -1,6 +1,6 @@ SWIG (Simplified Wrapper and Interface Generator) -Version: 2.0.11 (15 Sep 2013) +Version: 2.0.12 (9 Feb 2014) Tagline: SWIG is a compiler that integrates C and C++ with languages including Perl, Python, Tcl, Ruby, PHP, Java, C#, D, Go, Lua, diff --git a/configure.ac b/configure.ac index c4db3ce98..0c984b70b 100644 --- a/configure.ac +++ b/configure.ac @@ -2,7 +2,7 @@ dnl Process this file with autoconf to produce a configure script. dnl The macros which aren't shipped with the autotools are stored in the dnl Tools/config directory in .m4 files. -AC_INIT([swig],[2.0.11],[http://www.swig.org]) +AC_INIT([swig],[2.0.12],[http://www.swig.org]) dnl NB: When this requirement is increased to 2.60 or later, AC_PROG_SED dnl definition below can be removed From d94924a5c45237ce6cfa1104538f3cdd837680bd Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 12 Oct 2013 17:50:29 +0100 Subject: [PATCH 330/481] Add change note for missing Lua return statements Conflicts: CHANGES.current --- CHANGES.current | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGES.current b/CHANGES.current index f2dfaea26..41d02270c 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,3 +5,7 @@ See the RELEASENOTES file for a summary of changes in each release. Version 2.0.12 (9 Feb 2014) =========================== +2013-10-12: wsfulton + [Lua] Apply #92 - missing return statements for SWIG_Lua_add_namespace_details() + and SWIG_Lua_namespace_register(). + From c2f5813ffaf92e098b4fbc980b3e102744fcd4b9 Mon Sep 17 00:00:00 2001 From: Robert Stone Date: Thu, 14 Nov 2013 11:19:11 -0800 Subject: [PATCH 331/481] fix "long long" tests for perl v5.6 --- Examples/test-suite/perl5/li_typemaps_runme.pl | 18 +++++++++++------- .../perl5/reference_global_vars_runme.pl | 11 ++++++----- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/Examples/test-suite/perl5/li_typemaps_runme.pl b/Examples/test-suite/perl5/li_typemaps_runme.pl index c182cdbb1..a573b89a0 100644 --- a/Examples/test-suite/perl5/li_typemaps_runme.pl +++ b/Examples/test-suite/perl5/li_typemaps_runme.pl @@ -41,8 +41,8 @@ batch('schar', -0x80, 0, 1, 12, 0x7f); use Math::BigInt qw(); # the pack dance is to get plain old NVs out of the # Math::BigInt objects. - my $inf = unpack 'd', pack 'd', Math::BigInt->binf(); - my $nan = unpack 'd', pack 'd', Math::BigInt->bnan(); + my $inf = unpack 'd', pack 'd', Math::BigInt->new('Inf'); + my $nan = unpack 'd', pack 'd', Math::BigInt->new('NaN'); batch('float', -(2 - 2 ** -23) * 2 ** 127, -1, -2 ** -149, 0, 2 ** -149, 1, @@ -63,12 +63,16 @@ batch('schar', -0x80, 0, 1, 12, 0x7f); batch('longlong', -1, 0, 1, 12); batch('ulonglong', 0, 1, 12); SKIP: { - my $a = "8000000000000000"; - my $b = "7fffffffffffffff"; - my $c = "ffffffffffffffff"; + use Math::BigInt qw(); skip "not a 64bit Perl", 18 unless eval { pack 'q', 1 }; - batch('longlong', -hex($a), hex($b)); - batch('ulonglong', hex($c)); + my $a = unpack 'q', pack 'q', + Math::BigInt->new('-9223372036854775808'); + my $b = unpack 'q', pack 'q', + Math::BigInt->new('9223372036854775807'); + my $c = unpack 'Q', pack 'Q', + Math::BigInt->new('18446744073709551615'); + batch('longlong', $a, $b); + batch('ulonglong', $c); } my($foo, $int) = li_typemaps::out_foo(10); diff --git a/Examples/test-suite/perl5/reference_global_vars_runme.pl b/Examples/test-suite/perl5/reference_global_vars_runme.pl index dfbcf15bb..89d73b03d 100755 --- a/Examples/test-suite/perl5/reference_global_vars_runme.pl +++ b/Examples/test-suite/perl5/reference_global_vars_runme.pl @@ -53,12 +53,13 @@ $cvar->{var_unsigned_long} = createref_unsigned_long(10); is(value_unsigned_long($cvar->{var_unsigned_long}), 10); SKIP: { - my $a = "6FFFFFFFFFFFFFF8"; + use Math::BigInt qw(); skip "64 bit int support", 1 unless eval { pack 'q', 1 }; - # using hex() here instead of a literal because non 64bit Perls will - # be noisy about big constants. - $cvar->{var_long_long} = createref_long_long(hex $a); - is(value_long_long($cvar->{var_long_long}), hex $a); + # the pack dance is to get plain old IVs out of the + # Math::BigInt objects. + my $a = unpack 'q', pack 'q', Math::BigInt->new('8070450532247928824'); + $cvar->{var_long_long} = createref_long_long($a); + is(value_long_long($cvar->{var_long_long}), $a); } #ull = abs(0xFFFFFFF2FFFFFFF0) From 5602a61bb6fa2b6de419c251fceb2e5cd499893d Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 17 Oct 2013 19:56:18 +0100 Subject: [PATCH 332/481] Add missing #include for offsetof when using -builtin. Fixes SF #1345 Conflicts: CHANGES.current --- CHANGES.current | 3 +++ Lib/python/pyinit.swg | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/CHANGES.current b/CHANGES.current index 41d02270c..bde32009e 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,9 @@ See the RELEASENOTES file for a summary of changes in each release. Version 2.0.12 (9 Feb 2014) =========================== +2013-10-17: wsfulton + [Python] Fix SF #1345 - Missing #include for offsetof when using -builtin. + 2013-10-12: wsfulton [Lua] Apply #92 - missing return statements for SWIG_Lua_add_namespace_details() and SWIG_Lua_namespace_register(). diff --git a/Lib/python/pyinit.swg b/Lib/python/pyinit.swg index 6a6de0963..79df023de 100644 --- a/Lib/python/pyinit.swg +++ b/Lib/python/pyinit.swg @@ -4,6 +4,10 @@ %insert(init) "swiginit.swg" +#if defined(SWIGPYTHON_BUILTIN) +%fragment(""); // For offsetof +#endif + %init %{ #ifdef __cplusplus From 122f61cb0bcedb15db0612f9519de4d396f75efc Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 17 Oct 2013 21:54:58 +0100 Subject: [PATCH 333/481] Fix Visual Studio compile error in C++ wrappers due to #include within extern "C" block. Fixes SF #1340 --- CHANGES.current | 4 ++++ Lib/r/rrun.swg | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGES.current b/CHANGES.current index bde32009e..0507350cd 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,10 @@ See the RELEASENOTES file for a summary of changes in each release. Version 2.0.12 (9 Feb 2014) =========================== +2013-10-17: wsfulton + [R] Fix SF #1340 - Visual Studio compile error in C++ wrappers due to #include + within extern "C" block. + 2013-10-17: wsfulton [Python] Fix SF #1345 - Missing #include for offsetof when using -builtin. diff --git a/Lib/r/rrun.swg b/Lib/r/rrun.swg index f8bc9f497..990443e23 100644 --- a/Lib/r/rrun.swg +++ b/Lib/r/rrun.swg @@ -1,5 +1,6 @@ #ifdef __cplusplus +#include extern "C" { #endif @@ -369,7 +370,6 @@ SWIG_R_ConvertPacked(SEXP obj, void *ptr, size_t sz, swig_type_info *ty) { } #ifdef __cplusplus -#include #define SWIG_exception_noreturn(code, msg) do { throw std::runtime_error(msg); } while(0) #else #define SWIG_exception_noreturn(code, msg) do { return result; } while(0) From 7b5eb19ca98be89440c661944b53211096542bda Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 18 Oct 2013 06:49:20 +0100 Subject: [PATCH 334/481] Fix unused variable warning in Ruby wrappers when using gcc -Wall --- Lib/ruby/rubyprimtypes.swg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/ruby/rubyprimtypes.swg b/Lib/ruby/rubyprimtypes.swg index df72e97f4..aa4f7ad37 100644 --- a/Lib/ruby/rubyprimtypes.swg +++ b/Lib/ruby/rubyprimtypes.swg @@ -193,7 +193,7 @@ SWIG_AsVal_dec(unsigned long long)(VALUE obj, unsigned long long *val) } %fragment(SWIG_AsVal_frag(double),"header",fragment="SWIG_ruby_failed") { -%ruby_aux_method(double, NUM2DBL, NUM2DBL(obj)) +%ruby_aux_method(double, NUM2DBL, NUM2DBL(obj); (void)type) SWIGINTERN int SWIG_AsVal_dec(double)(VALUE obj, double *val) From acc5a5eb2d9ba7ab95cf5bb22221ba503c249de1 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 22 Dec 2013 19:39:21 +0000 Subject: [PATCH 335/481] C++11 support for new versions of erase and insert in the STL containers. The erase and insert methods in the containers use const_iterator instead of iterator in C++11. There are times when the methods wrapped must match the parameters exactly. Specifically when full type information for template types is missing or SWIG fails to look up the type correctly, for example: %include typedef float Real; %template(RealVector) std::vector; SWIG does not find std::vector::iterator because %template using typedefs does not always work and so SWIG doesn't know if the type is copyable and so uses SwigValueWrapper which does not support conversion to another type (const_iterator). This resulted in compilation errors when using the C++11 version of the containers. Closes #73 Conflicts: CHANGES.current Lib/std/std_unordered_map.i Lib/std/std_unordered_set.i --- CHANGES.current | 21 +++++++++++++++++++++ Lib/std/std_container.i | 21 +++++++++++++++------ Lib/std/std_map.i | 8 +++++--- Lib/std/std_set.i | 7 +++++-- 4 files changed, 46 insertions(+), 11 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index 0507350cd..d23246f6c 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,27 @@ See the RELEASENOTES file for a summary of changes in each release. Version 2.0.12 (9 Feb 2014) =========================== +2013-12-22: wsfulton + C++11 support for new versions of erase and insert in the STL containers. + + The erase and insert methods in the containers use const_iterator instead + of iterator in C++11. There are times when the methods wrapped must match + the parameters exactly. Specifically when full type information for + template types is missing or SWIG fails to look up the type correctly, + for example: + + %include + typedef float Real; + %template(RealVector) std::vector; + + SWIG does not find std::vector::iterator because %template using + typedefs does not always work and so SWIG doesn't know if the type is + copyable and so uses SwigValueWrapper which does + not support conversion to another type (const_iterator). This resulted + in compilation errors when using the C++11 version of the containers. + + Closes #73 + 2013-10-17: wsfulton [R] Fix SF #1340 - Visual Studio compile error in C++ wrappers due to #include within extern "C" block. diff --git a/Lib/std/std_container.i b/Lib/std/std_container.i index 73d0c6ad9..8ed327bbe 100644 --- a/Lib/std/std_container.i +++ b/Lib/std/std_container.i @@ -46,8 +46,11 @@ void resize(size_type new_size); #ifdef SWIG_EXPORT_ITERATOR_METHODS - iterator erase(iterator pos); - iterator erase(iterator first, iterator last); +%extend { + // %extend wrapper used for differing definitions of these methods introduced in C++11 + iterator erase(iterator pos) { return $self->erase(pos); } + iterator erase(iterator first, iterator last) { return $self->erase(first, last); } +} #endif %enddef @@ -68,8 +71,11 @@ void resize(size_type new_size, const value_type& x); #ifdef SWIG_EXPORT_ITERATOR_METHODS - iterator insert(iterator pos, const value_type& x); - void insert(iterator pos, size_type n, const value_type& x); +%extend { + // %extend wrapper used for differing definitions of these methods introduced in C++11 + iterator insert(iterator pos, const value_type& x) { return $self->insert(pos, x); } + void insert(iterator pos, size_type n, const value_type& x) { $self->insert(pos, n, x); } +} #endif %enddef @@ -89,8 +95,11 @@ void resize(size_type new_size, value_type x); #ifdef SWIG_EXPORT_ITERATOR_METHODS - iterator insert(iterator pos, value_type x); - void insert(iterator pos, size_type n, value_type x); +%extend { + // %extend wrapper used for differing definitions of these methods introduced in C++11 + iterator insert(iterator pos, value_type x) { return $self->insert(pos, x); } + void insert(iterator pos, size_type n, value_type x) { $self->insert(pos, n, x); } +} #endif %enddef diff --git a/Lib/std/std_map.i b/Lib/std/std_map.i index 05208418f..e523c3deb 100644 --- a/Lib/std/std_map.i +++ b/Lib/std/std_map.i @@ -12,9 +12,11 @@ size_type count(const key_type& x) const; #ifdef SWIG_EXPORT_ITERATOR_METHODS -// iterator insert(iterator position, const value_type& x); - void erase(iterator position); - void erase(iterator first, iterator last); +%extend { + // %extend wrapper used for differing definitions of these methods introduced in C++11 + void erase(iterator position) { $self->erase(position); } + void erase(iterator first, iterator last) { $self->erase(first, last); } +} iterator find(const key_type& x); iterator lower_bound(const key_type& x); diff --git a/Lib/std/std_set.i b/Lib/std/std_set.i index 16f0f1482..f96ddd9f1 100644 --- a/Lib/std/std_set.i +++ b/Lib/std/std_set.i @@ -29,8 +29,11 @@ reverse_iterator rbegin(); reverse_iterator rend(); - void erase(iterator pos); - void erase(iterator first, iterator last); +%extend { + // %extend wrapper used for differing definitions of these methods introduced in C++11 + void erase(iterator pos) { $self->erase(pos); } + void erase(iterator first, iterator last) { $self->erase(first, last); } +} iterator find(const key_type& x); iterator lower_bound(const key_type& x); From 78f92962e207c152a40783181aaf0c77e506cb3b Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Mon, 13 Jan 2014 18:24:17 +1300 Subject: [PATCH 336/481] octave: update support to Octave version 3.8.0 Conflicts: CHANGES.current --- CHANGES.current | 26 ++++++++++ Doc/Manual/Octave.html | 7 +-- Lib/octave/octrun.swg | 102 ++++++++++++++++++++++++++++++++------ Lib/octave/octruntime.swg | 14 +++--- 4 files changed, 121 insertions(+), 28 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index d23246f6c..28b403a6d 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,32 @@ See the RELEASENOTES file for a summary of changes in each release. Version 2.0.12 (9 Feb 2014) =========================== +2014-01-13: kwwette + [Octave] update support to Octave version 3.8.0 + + - Octave 3.8.0 no longer defines OCTAVE_API_VERSION_NUMBER, but 3.8.1 + will define OCTAVE_{MAJOR,MINOR,PATCH}_VERSION instead: see + http://hg.savannah.gnu.org/hgweb/octave/rev/b6b6e0dc700e + So we now use a new macro SWIG_OCTAVE_PREREQ(major,minor,patch) to + enable features requiring Octave version major.minor.patch or later. + + For Octave versions prior to 3.8.1, we reconstruct values for + OCTAVE_{MAJOR,MINOR,PATCH}_VERSION based on OCTAVE_API_VERSION_NUMBER, + extracted from Octave's ChangeLogs. An additional hack is needed to + distinguish between Octave <= 3.2.x and 3.8.0, neither of which define + OCTAVE_API_VERSION_NUMBER. + + - Octave 3.8.0 deprecates symbol_table::varref(), so remove its use + for this and future versions of Octave. + + - Octave 3.8.0 removes octave_value::is_real_nd_array(), used in + octave_swig_type::dims(). Its use is not required here, so remove it. + + - Retested against Octave versions 3.0.5, 3.2.4, 3.4.3, 3.6.4, and 3.8.0. + + - Updated Octave documentation with tested Octave versions, and added a + warning against using versions <= 3.x.x, which are no longer tested. + 2013-12-22: wsfulton C++11 support for new versions of erase and insert in the STL containers. diff --git a/Doc/Manual/Octave.html b/Doc/Manual/Octave.html index 84c0a0f46..3e12ce668 100644 --- a/Doc/Manual/Octave.html +++ b/Doc/Manual/Octave.html @@ -59,11 +59,8 @@ Also, there are a dozen or so examples in the Examples/octave directory, and hun

      -The SWIG implemention was first based on Octave 2.9.12, so this is the minimum version required. Testing has only been done on Linux. -

      - -

      -As of SWIG 2.0.7, the Octave module has been tested with Octave versions 3.0.5, 3.2.4, 3.4.3, and 3.6.1. +As of SWIG 3.0.0, the Octave module has been tested with Octave versions 3.0.5, 3.2.4, 3.4.3, 3.6.4, and 3.8.0. +Use of Octave versions older than 3.x.x is not recommended, as these versions are no longer tested with SWIG.

      30.2 Running SWIG

      diff --git a/Lib/octave/octrun.swg b/Lib/octave/octrun.swg index 41d1c7afa..2174a0f7f 100644 --- a/Lib/octave/octrun.swg +++ b/Lib/octave/octrun.swg @@ -1,20 +1,88 @@ #include -#ifndef OCTAVE_API_VERSION_NUMBER - // Hack to distinguish between Octave 3.2 and earlier versions before OCTAVE_API_VERSION_NUMBER existed - #define ComplexLU __ignore - #include - #undef ComplexLU - #ifdef octave_Complex_LU_h - # define OCTAVE_API_VERSION_NUMBER 36 - #else - # define OCTAVE_API_VERSION_NUMBER 37 - #endif +// Macro for enabling features which require Octave version >= major.minor.patch +#define SWIG_OCTAVE_PREREQ(major, minor, patch) \ + ( (OCTAVE_MAJOR_VERSION<<16) + (OCTAVE_MINOR_VERSION<<8) + OCTAVE_PATCH_VERSION >= ((major)<<16) + ((minor)<<8) + (patch) ) -#endif +// Reconstruct Octave major, minor, and patch versions for releases prior to 3.8.1 +#if !defined(OCTAVE_MAJOR_VERSION) -#if OCTAVE_API_VERSION_NUMBER < 37 +# if !defined(OCTAVE_API_VERSION_NUMBER) + +// Hack to distinguish between Octave 3.8.0, which removed OCTAVE_API_VERSION_NUMBER but did not yet +// introduce OCTAVE_MAJOR_VERSION, and Octave <= 3.2, which did not define OCTAVE_API_VERSION_NUMBER +# include +# if defined(octave_ov_h) +# define OCTAVE_MAJOR_VERSION 3 +# define OCTAVE_MINOR_VERSION 8 +# define OCTAVE_PATCH_VERSION 0 +# else + +// Hack to distinguish between Octave 3.2 and earlier versions, before OCTAVE_API_VERSION_NUMBER existed +# define ComplexLU __ignore +# include +# undef ComplexLU +# if defined(octave_Complex_LU_h) + +// We know only that this version is prior to Octave 3.2, i.e. OCTAVE_API_VERSION_NUMBER < 37 +# define OCTAVE_MAJOR_VERSION 3 +# define OCTAVE_MINOR_VERSION 1 +# define OCTAVE_PATCH_VERSION 99 + +# else + +// OCTAVE_API_VERSION_NUMBER == 37 +# define OCTAVE_MAJOR_VERSION 3 +# define OCTAVE_MINOR_VERSION 2 +# define OCTAVE_PATCH_VERSION 0 + +# endif // defined(octave_Complex_LU_h) + +# endif // defined(octave_ov_h) + +// Correlation between Octave API and version numbers extracted from Octave's +// ChangeLogs; version is the *earliest* released Octave with that API number +# elif OCTAVE_API_VERSION_NUMBER >= 48 +# define OCTAVE_MAJOR_VERSION 3 +# define OCTAVE_MINOR_VERSION 6 +# define OCTAVE_PATCH_VERSION 0 + +# elif OCTAVE_API_VERSION_NUMBER >= 45 +# define OCTAVE_MAJOR_VERSION 3 +# define OCTAVE_MINOR_VERSION 4 +# define OCTAVE_PATCH_VERSION 1 + +# elif OCTAVE_API_VERSION_NUMBER >= 42 +# define OCTAVE_MAJOR_VERSION 3 +# define OCTAVE_MINOR_VERSION 3 +# define OCTAVE_PATCH_VERSION 54 + +# elif OCTAVE_API_VERSION_NUMBER >= 41 +# define OCTAVE_MAJOR_VERSION 3 +# define OCTAVE_MINOR_VERSION 3 +# define OCTAVE_PATCH_VERSION 53 + +# elif OCTAVE_API_VERSION_NUMBER >= 40 +# define OCTAVE_MAJOR_VERSION 3 +# define OCTAVE_MINOR_VERSION 3 +# define OCTAVE_PATCH_VERSION 52 + +# elif OCTAVE_API_VERSION_NUMBER >= 39 +# define OCTAVE_MAJOR_VERSION 3 +# define OCTAVE_MINOR_VERSION 3 +# define OCTAVE_PATCH_VERSION 51 + +# else // OCTAVE_API_VERSION_NUMBER == 38 +# define OCTAVE_MAJOR_VERSION 3 +# define OCTAVE_MINOR_VERSION 3 +# define OCTAVE_PATCH_VERSION 50 + +# endif // !defined(OCTAVE_API_VERSION_NUMBER) + +#endif // !defined(OCTAVE_MAJOR_VERSION) + +#if !SWIG_OCTAVE_PREREQ(3,2,0) #define SWIG_DEFUN(cname, wname, doc) DEFUNX_DLD(#cname, wname, FS ## cname, args, nargout, doc) #else #define SWIG_DEFUN(cname, wname, doc) DEFUNX_DLD(#cname, wname, G ## cname, args, nargout, doc) @@ -427,7 +495,7 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); if (error_state) return dim_vector(1,1); } return d; - } else if (out.is_matrix_type() || out.is_real_nd_array() || out.is_numeric_type() ) { + } else if (out.is_matrix_type() || out.is_numeric_type() ) { if (out.rows()==1 || out.columns()==1) { Array a = out.int_vector_value(); if (error_state) return dim_vector(1,1); @@ -746,7 +814,7 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); return outarg(0).string_value(); } -#if OCTAVE_API_VERSION_NUMBER >= 40 +#if SWIG_OCTAVE_PREREQ(3,3,52) virtual octave_map map_value() const { return octave_map(); } @@ -982,7 +1050,7 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); virtual std::string string_value(bool force = false) const { return ptr->string_value(force); } -#if OCTAVE_API_VERSION_NUMBER >= 40 +#if SWIG_OCTAVE_PREREQ(3,3,52) virtual octave_map map_value() const { return ptr->map_value(); } #else @@ -1293,10 +1361,12 @@ SWIGRUNTIME void SWIG_Octave_SetGlobalValue(std::string name, const octave_value } SWIGRUNTIME void SWIG_Octave_LinkGlobalValue(std::string name) { -#if OCTAVE_API_VERSION_NUMBER < 37 +#if !SWIG_OCTAVE_PREREQ(3,2,0) link_to_global_variable(curr_sym_tab->lookup(name, true)); #else +#if !SWIG_OCTAVE_PREREQ(3,8,0) symbol_table::varref(name); +#endif symbol_table::mark_global(name); #endif } diff --git a/Lib/octave/octruntime.swg b/Lib/octave/octruntime.swg index 43313c3d4..fbf2007f6 100644 --- a/Lib/octave/octruntime.swg +++ b/Lib/octave/octruntime.swg @@ -25,7 +25,7 @@ static bool SWIG_init_user(octave_swig_type* module_ns); SWIGINTERN bool SWIG_Octave_LoadModule(std::string name) { bool retn; { -#if OCTAVE_API_VERSION_NUMBER < 38 +#if !SWIG_OCTAVE_PREREQ(3,3,50) unwind_protect::begin_frame("SWIG_Octave_LoadModule"); unwind_protect_int(error_state); unwind_protect_int(warning_state); @@ -44,7 +44,7 @@ SWIGINTERN bool SWIG_Octave_LoadModule(std::string name) { discard_warning_messages = true; feval(name, octave_value_list(), 0); retn = (error_state == 0); -#if OCTAVE_API_VERSION_NUMBER < 38 +#if !SWIG_OCTAVE_PREREQ(3,3,50) unwind_protect::run_frame("SWIG_Octave_LoadModule"); #endif } @@ -57,7 +57,7 @@ SWIGINTERN bool SWIG_Octave_LoadModule(std::string name) { SWIGINTERN bool SWIG_Octave_InstallFunction(octave_function *octloadfcn, std::string name) { bool retn; { -#if OCTAVE_API_VERSION_NUMBER < 38 +#if !SWIG_OCTAVE_PREREQ(3,3,50) unwind_protect::begin_frame("SWIG_Octave_InstallFunction"); unwind_protect_int(error_state); unwind_protect_int(warning_state); @@ -80,7 +80,7 @@ SWIGINTERN bool SWIG_Octave_InstallFunction(octave_function *octloadfcn, std::st error_state = 0; feval("autoload", args, 0); retn = (error_state == 0); -#if OCTAVE_API_VERSION_NUMBER < 38 +#if !SWIG_OCTAVE_PREREQ(3,3,50) unwind_protect::run_frame("SWIG_Octave_InstallFunction"); #endif } @@ -196,7 +196,7 @@ DEFUN_DLD( SWIG_name, args, nargout, SWIG_name_usage ) { // definitely affects version 3.2.*, not sure about 3.3.*, seems to be fixed in // version 3.4.* and above. can be turned off with macro definition. #ifndef SWIG_OCTAVE_NO_SEGFAULT_HACK -#if 36 < OCTAVE_API_VERSION_NUMBER && OCTAVE_API_VERSION_NUMBER < 45 +#if SWIG_OCTAVE_PREREQ(3,2,0) && !SWIG_OCTAVE_PREREQ(3,4,1) octave_exit = ::_Exit; #endif #endif @@ -212,7 +212,7 @@ DEFUN_DLD( SWIG_name, args, nargout, SWIG_name_usage ) { // workaround bug in octave where installing global variable of custom type and then // exiting without explicitly clearing the variable causes octave to segfault. -#if OCTAVE_API_VERSION_NUMBER > 36 +#if SWIG_OCTAVE_PREREQ(3,2,0) octave_value_list eval_args; eval_args.append("base"); eval_args.append("function __swig_atexit__; " @@ -297,7 +297,7 @@ DEFUN_DLD( SWIG_name, args, nargout, SWIG_name_usage ) { } } -#if OCTAVE_API_VERSION_NUMBER < 37 +#if !SWIG_OCTAVE_PREREQ(3,2,0) mlock(me->name()); #else mlock(); From c569210dd59e252be5176cb3224cc7e354bb97c1 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 16 Jan 2014 06:42:34 +0000 Subject: [PATCH 337/481] Fix PHP compilation error in ZTS mode (64 bit windows) due to TSRMLS_FETCH() expansion Conflicts: CHANGES.current --- CHANGES.current | 4 ++++ Lib/php/phprun.swg | 3 +-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index 28b403a6d..d55bb9716 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,10 @@ See the RELEASENOTES file for a summary of changes in each release. Version 2.0.12 (9 Feb 2014) =========================== +2014-01-16: wsfulton + [PHP] Fix compilation error in ZTS mode (64 bit windows) due to incorrect placement + of TSRMLS_FETCH() in SWIG_Php_GetModule() as reported by Mark Dawson-Butterworth. + 2014-01-13: kwwette [Octave] update support to Octave version 3.8.0 diff --git a/Lib/php/phprun.swg b/Lib/php/phprun.swg index a4188cc7c..063b84227 100644 --- a/Lib/php/phprun.swg +++ b/Lib/php/phprun.swg @@ -255,11 +255,10 @@ static char const_name[] = "swig_runtime_data_type_pointer"; static swig_module_info *SWIG_Php_GetModule(void *SWIGUNUSEDPARM(clientdata)) { zval *pointer; swig_module_info *ret = 0; + TSRMLS_FETCH(); MAKE_STD_ZVAL(pointer); - TSRMLS_FETCH(); - if (zend_get_constant(const_name, sizeof(const_name) - 1, pointer TSRMLS_CC)) { if (pointer->type == IS_LONG) { ret = (swig_module_info *) pointer->value.lval; From 36f5117b25fd6689e76bb0e2854e9df696631a2c Mon Sep 17 00:00:00 2001 From: Geert Janssens Date: Fri, 13 Dec 2013 17:48:26 +0100 Subject: [PATCH 338/481] Guile: make scm to string conversion work with non-ascii strings --- .../test-suite/guile/li_std_string_runme.scm | 4 ++++ Lib/guile/guile_scm_run.swg | 22 ++++++++----------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/Examples/test-suite/guile/li_std_string_runme.scm b/Examples/test-suite/guile/li_std_string_runme.scm index 5dde68f8d..5b5563281 100644 --- a/Examples/test-suite/guile/li_std_string_runme.scm +++ b/Examples/test-suite/guile/li_std_string_runme.scm @@ -2,4 +2,8 @@ ;; Guile modules (namespaces) but simply put all the bindings into the ;; current module. That's enough for such a simple test. (dynamic-call "scm_init_li_std_string_module" (dynamic-link "./libli_std_string")) +; Note: when working with non-ascii strings in guile 2 +; locale must be set explicitly +; The setlocale call below takes care of that +(setlocale LC_ALL "") (load "../schemerunme/li_std_string.scm") diff --git a/Lib/guile/guile_scm_run.swg b/Lib/guile/guile_scm_run.swg index 0ac51f919..4978ab114 100644 --- a/Lib/guile/guile_scm_run.swg +++ b/Lib/guile/guile_scm_run.swg @@ -41,10 +41,14 @@ typedef struct swig_guile_clientdata { SCM goops_class; } swig_guile_clientdata; +#if SCM_MAJOR_VERSION <= 2 +#define scm_to_utf8_string scm_to_locale_string +#define scm_from_utf8_string scm_from_locale_string +#endif #define SWIG_scm2str(s) \ SWIG_Guile_scm2newstr(s, NULL) #define SWIG_str02scm(str) \ - str ? scm_from_locale_string(str) : SCM_BOOL_F + str ? scm_from_utf8_string(str) : SCM_BOOL_F # define SWIG_malloc(size) \ scm_malloc(size) # define SWIG_free(mem) \ @@ -84,21 +88,13 @@ SWIGINTERN char * SWIG_Guile_scm2newstr(SCM str, size_t *len) { #define FUNC_NAME "SWIG_Guile_scm2newstr" char *ret; - char *tmp; - size_t l; SCM_ASSERT (scm_is_string(str), str, 1, FUNC_NAME); - l = scm_c_string_length(str); - ret = (char *) SWIG_malloc( (l + 1) * sizeof(char)); + ret = scm_to_utf8_string(str); if (!ret) return NULL; - tmp = scm_to_locale_string(str); - memcpy(ret, tmp, l); - free(tmp); - - ret[l] = '\0'; - if (len) *len = l; + if (len) *len = strlen(ret) - 1; return ret; #undef FUNC_NAME } @@ -482,7 +478,7 @@ SWIG_Guile_GetArgs (SCM *dest, SCM rest, int num_args_passed = 0; for (i = 0; i Date: Wed, 5 Feb 2014 11:52:26 +0100 Subject: [PATCH 339/481] Guile: illustrate bug in non-ascii string handling --- Examples/test-suite/schemerunme/li_std_string.scm | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Examples/test-suite/schemerunme/li_std_string.scm b/Examples/test-suite/schemerunme/li_std_string.scm index e77c32870..343b9b8e8 100644 --- a/Examples/test-suite/schemerunme/li_std_string.scm +++ b/Examples/test-suite/schemerunme/li_std_string.scm @@ -1,4 +1,6 @@ -(define x "hello") +; The test string has some non-ascii characters added +; because our guile wrappers had bugs in that area +(define x "hello - æææ") (if (not (string=? (test-value x) x)) (begin (error "Error 1") (exit 1))) From 7f8cb93092640ead96b3da60a6fb8c42eb0c13d9 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 8 Feb 2014 11:08:56 +0000 Subject: [PATCH 340/481] mkdist script tweaks to support releasing from any named branch --- Tools/mkdist.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/Tools/mkdist.py b/Tools/mkdist.py index 234c768f2..2e69dbece 100755 --- a/Tools/mkdist.py +++ b/Tools/mkdist.py @@ -1,7 +1,7 @@ #!/usr/bin/env python # This script builds a swig-x.y.z distribution. -# Usage : mkdist.py version, where version should be x.y.z +# Usage: mkdist.py version branch, where version should be x.y.z and branch is normally 'master' import sys import string @@ -16,10 +16,16 @@ def failed(): try: version = sys.argv[1] dirname = "swig-" + version + branch = sys.argv[2] except: - print "Usage: mkdist.py version, where version should be x.y.z" + print "Usage: mkdist.py version branch, where version should be x.y.z and branch is normally 'master'" sys.exit(1) +if sys.version_info[0:2] < (2, 7): + print "Error: Python 2.7 is required" + sys.exit(3) + + # Check name matches normal unix conventions if string.lower(dirname) != dirname: print "directory name ("+dirname+") should be in lowercase" @@ -38,7 +44,7 @@ os.system("rm -f "+dirname+".tar") # Grab the code from git print "Checking git repository is in sync with remote repository" -os.system("git remote update") == 0 or failed() +os.system("git remote update origin") == 0 or failed() command = ["git", "status", "--porcelain", "-uno"] out = subprocess.check_output(command) if out.strip() != "": @@ -47,7 +53,7 @@ if out.strip() != "": print out sys.exit(3) -command = ["git", "log", "--oneline", "master..origin/master"] +command = ["git", "log", "--oneline", branch + "..origin/" + branch] out = subprocess.check_output(command) if out.strip() != "": print "Remote repository has additional modifications to local repository" @@ -55,7 +61,7 @@ if out.strip() != "": print out sys.exit(3) -command = ["git", "log", "--oneline", "origin/master..master"] +command = ["git", "log", "--oneline", "origin/" + branch + ".." + branch] out = subprocess.check_output(command) if out.strip() != "": print "Local repository has modifications not pushed to the remote repository" From 3cd7055895c396701ca574de7cd46329728c26a5 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 8 Feb 2014 16:24:15 +0000 Subject: [PATCH 341/481] Temporary workaround for bug in Travis build environment --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 26758304f..e3d345972 100644 --- a/.travis.yml +++ b/.travis.yml @@ -46,6 +46,7 @@ before_install: - if test "$SWIGLANG" = "python" -a "$PY3"; then sudo apt-get install python3-dev; fi - if test "$SWIGLANG" = "tcl"; then sudo apt-get -qq install tcl8.4-dev; fi script: + - export PS4="+ " #Temporary workaround bug in Travis build environment - ./autogen.sh && ./configure - make -s $SWIGJOBS - if test -z "$SWIGLANG"; then make -s check-ccache; fi From 3c5de3457341f5eba0ddfc462df066c7974593e2 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 8 Feb 2014 19:13:43 +0000 Subject: [PATCH 342/481] Turn on Travis testing for maintenance-2.0 branch --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index e3d345972..50fd3b66b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -57,3 +57,4 @@ script: branches: only: - master + - maintenance-2.0 From 885a7002835f447e87350e7601ea1518e31c8759 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Klaus=20K=C3=A4mpf?= Date: Fri, 29 Nov 2013 13:48:07 +0100 Subject: [PATCH 343/481] Make string encoding explitic Ruby 2.0 enforces explicit string encodings. The char_constant testcase fails because the internal (SWIG_FromCharPtrAndSize, using rb_str_new) defaults to ASCII-8BIT while the test-suite file defaults to the current shell LOCALE setting. This patch sets the char_constant_runme.rb encoding to ASCII-8BIT. --- Examples/test-suite/ruby/char_constant_runme.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Examples/test-suite/ruby/char_constant_runme.rb b/Examples/test-suite/ruby/char_constant_runme.rb index 4e9d9d59c..4c56ecbf7 100644 --- a/Examples/test-suite/ruby/char_constant_runme.rb +++ b/Examples/test-suite/ruby/char_constant_runme.rb @@ -1,5 +1,5 @@ #!/usr/bin/env ruby -# +#Encoding: ASCII-8BIT # Put description here # # From 08639f7f248c5e0a7621750452ef53a6f6834378 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 9 Feb 2014 09:34:18 +0000 Subject: [PATCH 344/481] Add release summary for 2.0.12 --- RELEASENOTES | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/RELEASENOTES b/RELEASENOTES index 720dc9d34..756df81ff 100644 --- a/RELEASENOTES +++ b/RELEASENOTES @@ -4,6 +4,14 @@ and CHANGES files. Release Notes ============= +SWIG-2.0.12 summary: +- This is a maintenance release backporting some fixes from the pending + 3.0.0 release. +- Octave 3.8 support added. +- C++11 support for new versions of erase/insert in the STL containers. +- Compilation fixes on some systems for the generated Lua, PHP, Python + and R wrappers. + SWIG-2.0.11 summary: - Minor bug fixes and enhancements mostly in Python, but also C#, Lua, Ocaml, Octave, Perl, PHP, Python, R, Ruby, Tcl. From 1c4213594a6d12484553506b1f81c67e5a84d904 Mon Sep 17 00:00:00 2001 From: William Fulton Date: Sun, 9 Feb 2014 22:09:05 +0000 Subject: [PATCH 345/481] Release scripts to release from any branch --- Tools/mkrelease.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Tools/mkrelease.py b/Tools/mkrelease.py index 9eceba07e..3f49ffd9d 100755 --- a/Tools/mkrelease.py +++ b/Tools/mkrelease.py @@ -15,9 +15,10 @@ def failed(message): try: version = sys.argv[1] - username = sys.argv[2] + branch = sys.argv[2] + username = sys.argv[3] except: - print "Usage: python mkrelease.py version username" + print "Usage: python mkrelease.py version branch username" print "where version should be x.y.z and username is your SF username" sys.exit(1) @@ -25,7 +26,7 @@ print "Looking for rsync" os.system("which rsync") and failed("rsync not installed/found. Please install.") print "Making source tarball" -os.system("python ./mkdist.py " + version) and failed("") +os.system("python ./mkdist.py " + version + " " + branch) and failed("") print "Build Windows package" os.system("./mkwindows.sh " + version) and failed("") From 05f92e9fbd5718a8b6e9698aa467e6c047256da2 Mon Sep 17 00:00:00 2001 From: William Fulton Date: Sun, 9 Feb 2014 22:09:05 +0000 Subject: [PATCH 346/481] Release scripts to release from any branch --- Tools/mkrelease.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Tools/mkrelease.py b/Tools/mkrelease.py index 0623fe786..ec9a2b76a 100755 --- a/Tools/mkrelease.py +++ b/Tools/mkrelease.py @@ -15,9 +15,10 @@ def failed(message): try: version = sys.argv[1] - username = sys.argv[2] + branch = sys.argv[2] + username = sys.argv[3] except: - print "Usage: python mkrelease.py version username" + print "Usage: python mkrelease.py version branch username" print "where version should be x.y.z and username is your SF username" sys.exit(1) @@ -25,7 +26,7 @@ print "Looking for rsync" os.system("which rsync") and failed("rsync not installed/found. Please install.") print "Making source tarball" -os.system("python ./mkdist.py " + version) and failed("") +os.system("python ./mkdist.py " + version + " " + branch) and failed("") print "Build Windows package" os.system("./mkwindows.sh " + version) and failed("") From d35af986468da6f61d5a660f13b260810323fb55 Mon Sep 17 00:00:00 2001 From: Marvin Greenberg Date: Wed, 12 Feb 2014 14:16:43 -0500 Subject: [PATCH 347/481] Change to only add -stdlib on OSX versions that have libc++ Use better test for clang --- configure.ac | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/configure.ac b/configure.ac index d05eb1802..aead05c21 100644 --- a/configure.ac +++ b/configure.ac @@ -352,10 +352,14 @@ if test x"$enable_cpp11_testing" = xyes; then fi fi -# On darwin before Mavericks when using clang, need to ensure using -# libc++ for tests and examples to run under mono +# On darwin 10.7,10.8,10.9 using clang++, need to ensure using +# libc++ for tests and examples to run under mono. May affect +# other language targets as well - problem is an OSX incompatibility +# between libraries depending on libstdc++ and libc++. +CLANGXX= +$CXX -v 2>&1 | grep -i clang >/dev/null && CLANGXX=yes case $host in - *-*-darwin*) if test "$CXX" = "clang++"; + *-*-darwin11* | *-*-darwin12* |*-*-darwin13* ) if test "$CLANGXX" = "yes"; then PLATCXXFLAGS="$PLATCXXFLAGS -stdlib=libc++" fi;; *) ;; From b83d285793be072a6e6088a5c16f59b24cd68d5d Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 13 Feb 2014 22:05:10 +0000 Subject: [PATCH 348/481] Compiler flags for Octave tests/examples change The Octave examples and test-suite were picking up any CXXFLAGS and CPPFLAGS exported into the environment creating way too many warnings running the Octave tests if the compiler flags for building SWIG were exported rather than passed to configure. --- configure.ac | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/configure.ac b/configure.ac index 03677f90d..549ac1390 100644 --- a/configure.ac +++ b/configure.ac @@ -912,13 +912,13 @@ if test -n "$OCTAVE"; then AC_MSG_CHECKING([for Octave preprocessor flags]) OCTAVE_CPPFLAGS= for n in CPPFLAGS INCFLAGS; do - OCTAVE_CPPFLAGS="${OCTAVE_CPPFLAGS} "`${mkoctfile} -p $n` + OCTAVE_CPPFLAGS="${OCTAVE_CPPFLAGS} "`unset CPPFLAGS; ${mkoctfile} -p $n` done AC_MSG_RESULT([$OCTAVE_CPPFLAGS]) AC_MSG_CHECKING([for Octave compiler flags]) OCTAVE_CXXFLAGS= for n in ALL_CXXFLAGS; do - OCTAVE_CXXFLAGS="${OCTAVE_CXXFLAGS} "`${mkoctfile} -p $n` + OCTAVE_CXXFLAGS="${OCTAVE_CXXFLAGS} "`unset CXXFLAGS; ${mkoctfile} -p $n` done AC_MSG_RESULT([$OCTAVE_CXXFLAGS]) AC_MSG_CHECKING([for Octave linker flags]) From ead4d695f007fd6835d2f5d62e8c28ddfc1f7d29 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 13 Feb 2014 23:56:01 +0000 Subject: [PATCH 349/481] Add openSUSE Build Service script For updating SWIG tarball on OBS to latest from master. Slightly modified from script received from Karl Kaempf. --- Tools/obs-update | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100755 Tools/obs-update diff --git a/Tools/obs-update b/Tools/obs-update new file mode 100755 index 000000000..2a7a48cf7 --- /dev/null +++ b/Tools/obs-update @@ -0,0 +1,26 @@ +#!/bin/bash + +# Update SWIG tarball on openSUSE Build Service to contain the latest from master +# Requires the openSUSE Build Service command-line tool (osc) +# See http://openbuildservice.org/download/ +# And these packages: obs-service-tar_scm obs-service-recompress obs-service-set_version + +# Results appear at https://build.opensuse.org/package/show/home:kwk:swig/swig-raw + +set -e +set -x + +rm -rf home-kwk-swig/swig-raw +mkdir -p home-kwk-swig +cd home-kwk-swig +# check out 'swig-raw' +osc co -o swig-raw home:kwk:swig swig-raw +cd swig-raw +# remove existing tarball +osc rm swig*tar.bz2 +# fetch latest master branch from git and create tarball +osc service disabledrun +# add new tarball +osc addremove +# check changes into build service, triggers build +osc ci From 49da10eca77ec1eec5c2a6a1711db9610cbc9e39 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 14 Feb 2014 18:57:12 +0000 Subject: [PATCH 350/481] Don't run perl examples/tests if Test::More is not available The test-suite requires Test::More and the local versions of Test::More were removed in 1d1e8650a31ae90ca44564565a7c5fa680bc1cba. They are not always distributed with Perl, such as Perl 5.16 in Fedora. --- Examples/test-suite/perl5/README | 32 +++++++++----------------------- configure.ac | 9 ++++++++- 2 files changed, 17 insertions(+), 24 deletions(-) diff --git a/Examples/test-suite/perl5/README b/Examples/test-suite/perl5/README index 14eb5277e..804dec8e8 100644 --- a/Examples/test-suite/perl5/README +++ b/Examples/test-suite/perl5/README @@ -5,28 +5,14 @@ Any testcases which have _runme.pl appended after the testcase name will be dete Test::More Support == -Test::More and Test::Harness are two of the standard perl test harness -tools. Support has been added for these modules as of 1.3.28. If -adding a new test to this suite, please use Test::More. +Test::More is a standard perl test harness tool. +Support was added for for using Test::More in 1.3.28. +If adding a new test to this suite, please use Test::More. -Currently converted test cases include: +There are a few legacy test cases which do not use Test::More and these ought to be converted: -* operator_overload -* operator_overload_break -* package -* overload_simple -* apply_strings -* char_strings -* default_args -* enum_thorough -* global_vars -* import_nomodule -* inherit -* li_cdata_carrays -* li_std_string -* member_pointer -* multiple_inheritance -* primitive_ref -* template_default_arg -* unions -* voidtest +disown +imports +overload_copy +profiletest +template_ref_type diff --git a/configure.ac b/configure.ac index 549ac1390..02775b0f0 100644 --- a/configure.ac +++ b/configure.ac @@ -850,6 +850,13 @@ if test -n "$PERL"; then AC_MSG_RESULT(not found) else AC_MSG_RESULT($PERL5LDFLAGS) + fi + AC_MSG_CHECKING(for Perl5 Test::More module) # For test-suite + PERL5TESTMORE=`($PERL -e 'use Test::More; print "good";') 2>/dev/null` + if test -z "$PERL5TESTMORE" ; then + AC_MSG_RESULT(not found) + else + AC_MSG_RESULT(found) fi else AC_MSG_RESULT(unable to determine perl5 configuration) @@ -2185,7 +2192,7 @@ AC_SUBST(SKIP_TCL) SKIP_PERL5= -if test -z "$PERL" || test -z "$PERL5EXT" ; then +if test -z "$PERL" || test -z "$PERL5EXT" || test -z "$PERL5TESTMORE"; then SKIP_PERL5="1" fi AC_SUBST(SKIP_PERL5) From c063bb838488a01d1cddc850cd9eab8545a6e8db Mon Sep 17 00:00:00 2001 From: Harvey Falcic Date: Fri, 14 Feb 2014 19:19:09 -0500 Subject: [PATCH 351/481] Fix shadow instance creation failure in Python 3 I managed to trace a very nasty Python interpreter segfault to an allocation failure here. Adding this after the tp_new call: if (PyErr_Occurred()) { PyErr_Print(); } results in output of 'TypeError: object() takes no parameters', followed by a segfault that takes down the Python interpeter. The 'object' constructor doesn't seem to be suitable for instantiating SWIG shadow instances in this way, so simply use the constructor function in the PyTypeObject 'tp_new' slot of data->newargs. The 'if (inst)' check after this doesn't hurt in as much as it prevented a segfault immediately after this failed allocation, but it doesn't help much since the null pointer dereference will probably happen sooner or later anyway. --- Lib/python/pyrun.swg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/python/pyrun.swg b/Lib/python/pyrun.swg index b077fad32..53fc3a75b 100644 --- a/Lib/python/pyrun.swg +++ b/Lib/python/pyrun.swg @@ -1310,7 +1310,7 @@ SWIG_Python_NewShadowInstance(SwigPyClientData *data, PyObject *swig_this) } } else { #if PY_VERSION_HEX >= 0x03000000 - inst = PyBaseObject_Type.tp_new((PyTypeObject*) data->newargs, Py_None, Py_None); + inst = ((PyTypeObject*) data->newargs)->tp_new((PyTypeObject*) data->newargs, Py_None, Py_None); if (inst) { PyObject_SetAttr(inst, SWIG_This(), swig_this); Py_TYPE(inst)->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG; From 44670c2b969ed80742b938217b800e1d16850c08 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 15 Feb 2014 12:01:40 +0000 Subject: [PATCH 352/481] Only enable Ruby testing if Ruby header files are found --- configure.ac | 25 ++++++++++--------------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/configure.ac b/configure.ac index 02775b0f0..41c1026f0 100644 --- a/configure.ac +++ b/configure.ac @@ -1274,7 +1274,7 @@ fi AC_MSG_CHECKING(for Ruby header files) if test -n "$RUBY"; then - # Try Ruby1.9 first + # Try Ruby1.9+ first RUBYDIR=`($RUBY -rrbconfig -e 'print RbConfig::CONFIG[["rubyhdrdir"]] || $rubyhdrdir') 2>/dev/null` if test x"$RUBYDIR" = x"" || test x"$RUBYDIR" = x"nil"; then RUBYDIR=`($RUBY -rmkmf -e 'print Config::CONFIG[["archdir"]] || $archdir') 2>/dev/null` @@ -1283,20 +1283,20 @@ if test -n "$RUBY"; then fi if test x"$RUBYDIR" != x""; then dirs="$RUBYDIR" - RUBYINCLUDE=none + RUBYINCLUDE= for i in $dirs; do if test -r $i/ruby.h; then - AC_MSG_RESULT($i) - RUBYINCLUDE="-I$i" + if test x"$RUBYARCH" = x""; then + RUBYINCLUDE="-I$i" + else + RUBYINCLUDE="-I$i -I$i/$RUBYARCH" + fi + AC_MSG_RESULT($RUBYINCLUDE) break fi done - if test x"$RUBYARCH" != x""; then - RUBYINCLUDE="-I$RUBYDIR -I$RUBYDIR/$RUBYARCH" - fi - if test "$RUBYINCLUDE" = none; then - RUBYINCLUDE="-I$RUBYDIR" - AC_MSG_RESULT(could not locate ruby.h...using $RUBYINCLUDE) + if test x"$RUBYINCLUDE" = x""; then + AC_MSG_RESULT(could not locate ruby.h) fi # Find library and path for linking. @@ -1350,8 +1350,6 @@ if test -n "$RUBY"; then fi else AC_MSG_RESULT(unable to determine ruby configuration) - RUBYINCLUDE="-I$RUBYDIR" - RUBYLIB="$RUBYDIR" fi case $host in @@ -1363,9 +1361,6 @@ if test -n "$RUBY"; then RUBYSO=.`($RUBY -rrbconfig -e 'print Config::CONFIG[["DLEXT"]]') 2>/dev/null` else AC_MSG_RESULT(could not figure out how to run ruby) - RUBYINCLUDE="-I/usr/local/lib/ruby/1.4/arch" - RUBYLIB="/usr/local/lib/ruby/1.4/arch" - RUBYLINK="-lruby -lm" fi case $host in From 85f91128ffd692a1b5691e59caf70b3c85550ee0 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 15 Feb 2014 14:31:05 +0000 Subject: [PATCH 353/481] Locate tclConfig.sh on 64 bit openSUSE - /usr/lib64/tclConfig.sh --- configure.ac | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/configure.ac b/configure.ac index 41c1026f0..b41d2ace7 100644 --- a/configure.ac +++ b/configure.ac @@ -481,10 +481,10 @@ if test x"${with_tclconfig}" != x ; then fi # check in a few common install locations if test x"${TCLCONFIG}" = x ; then - for i in `ls -d /usr/lib/ 2>/dev/null` \ - `ls -d -r /usr/lib/tcl*/ 2>/dev/null` \ - `ls -d /usr/local/lib/ 2>/dev/null` \ - `ls -d -r /usr/local/lib/tcl*/ 2>/dev/null` ; do + for i in `ls -d -r /usr/lib*/ 2>/dev/null` \ + `ls -d -r /usr/lib*/tcl*/ 2>/dev/null` \ + `ls -d -r /usr/local/lib*/ 2>/dev/null` \ + `ls -d -r /usr/local/lib*/tcl*/ 2>/dev/null` ; do if test -f $i"tclConfig.sh" ; then TCLCONFIG=`(cd $i; pwd)` break From 1ff6301fdca38574cfc126aede5b6d0a3bed8e0b Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 15 Feb 2014 15:19:04 +0000 Subject: [PATCH 354/481] Look for jni.h under /usr/lib64/jvm --- configure.ac | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/configure.ac b/configure.ac index b41d2ace7..b99245222 100644 --- a/configure.ac +++ b/configure.ac @@ -982,7 +982,7 @@ AC_MSG_CHECKING(for java include file jni.h) AC_ARG_WITH(javaincl, [ --with-javaincl=path Set location of Java include directory], [JAVAINCDIR="$withval"], [JAVAINCDIR=]) if test -z "$JAVAINCDIR" ; then - JAVAINCDIR="/usr/j2sdk*/include /usr/local/j2sdk*/include /usr/jdk*/include /usr/local/jdk*/include /opt/j2sdk*/include /opt/jdk*/include /usr/java/include /usr/java/j2sdk*/include /usr/java/jdk*/include /usr/local/java/include /opt/java/include /usr/include/java /usr/local/include/java /usr/lib/java/include /usr/lib/jvm/java*/include /usr/include/kaffe /usr/local/include/kaffe /usr/include" + JAVAINCDIR="/usr/j2sdk*/include /usr/local/j2sdk*/include /usr/jdk*/include /usr/local/jdk*/include /opt/j2sdk*/include /opt/jdk*/include /usr/java/include /usr/java/j2sdk*/include /usr/java/jdk*/include /usr/local/java/include /opt/java/include /usr/include/java /usr/local/include/java /usr/lib/java/include /usr/lib/jvm/java*/include /usr/lib64/jvm/java*/include /usr/include/kaffe /usr/local/include/kaffe /usr/include" # Add in default installation directory on Windows for Cygwin case $host in From 4ba4a02e93521821aba8591343fdb3a5c9e5e1a3 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 15 Feb 2014 18:36:01 +0000 Subject: [PATCH 355/481] Fix unused method warning in Octave --- Lib/octave/octrun.swg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/octave/octrun.swg b/Lib/octave/octrun.swg index 2174a0f7f..dc9b6b6e6 100644 --- a/Lib/octave/octrun.swg +++ b/Lib/octave/octrun.swg @@ -1171,7 +1171,7 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); DEFINE_OCTAVE_ALLOCATOR(octave_swig_packed); DEFINE_OV_TYPEID_FUNCTIONS_AND_DATA(octave_swig_packed, "swig_packed", "swig_packed"); - static octave_value_list octave_set_immutable(const octave_value_list &args, int nargout) { + SWIGRUNTIME octave_value_list octave_set_immutable(const octave_value_list &args, int nargout) { error("attempt to set immutable member variable"); return octave_value_list(); } From cd2e301ea425ffb16ef5f12e926e6f35981a7ebf Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 15 Feb 2014 18:54:28 +0000 Subject: [PATCH 356/481] Remove nspace feature not yet supported warning --- Examples/test-suite/csharp_namespace_system_collision.i | 2 +- Examples/test-suite/director_nspace.i | 2 +- Examples/test-suite/director_nspace_director_name_collision.i | 2 +- Examples/test-suite/nspace.i | 2 +- Examples/test-suite/nspace_extend.i | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Examples/test-suite/csharp_namespace_system_collision.i b/Examples/test-suite/csharp_namespace_system_collision.i index 6f94f8471..675aefb4e 100644 --- a/Examples/test-suite/csharp_namespace_system_collision.i +++ b/Examples/test-suite/csharp_namespace_system_collision.i @@ -23,7 +23,7 @@ namespace TopLevel #if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGD) %nspace; #else -#warning nspace feature not yet supported in this target language +//#warning nspace feature not yet supported in this target language #endif namespace TopLevel diff --git a/Examples/test-suite/director_nspace.i b/Examples/test-suite/director_nspace.i index 121a06f1f..512077e8b 100644 --- a/Examples/test-suite/director_nspace.i +++ b/Examples/test-suite/director_nspace.i @@ -44,7 +44,7 @@ namespace TopLevel %nspace TopLevel::Bar::Foo; %nspace TopLevel::Bar::FooBar; #else -#warning nspace feature not yet supported in this target language +//#warning nspace feature not yet supported in this target language #endif %feature("director") TopLevel::Bar::Foo; diff --git a/Examples/test-suite/director_nspace_director_name_collision.i b/Examples/test-suite/director_nspace_director_name_collision.i index e7abffcb1..c6f13b451 100644 --- a/Examples/test-suite/director_nspace_director_name_collision.i +++ b/Examples/test-suite/director_nspace_director_name_collision.i @@ -38,7 +38,7 @@ namespace TopLevel %nspace TopLevel::A::Foo; %nspace TopLevel::B::Foo; #else -#warning nspace feature not yet supported in this target language +//#warning nspace feature not yet supported in this target language %ignore TopLevel::B::Foo; #endif diff --git a/Examples/test-suite/nspace.i b/Examples/test-suite/nspace.i index 2e10542d3..c60a45df5 100644 --- a/Examples/test-suite/nspace.i +++ b/Examples/test-suite/nspace.i @@ -104,6 +104,6 @@ void test_classes(Outer::SomeClass c, Outer::Inner2::Color cc) {} %} #else -#warning nspace feature not yet supported in this target language +//#warning nspace feature not yet supported in this target language #endif diff --git a/Examples/test-suite/nspace_extend.i b/Examples/test-suite/nspace_extend.i index 1965ef8f6..782ce90ca 100644 --- a/Examples/test-suite/nspace_extend.i +++ b/Examples/test-suite/nspace_extend.i @@ -50,6 +50,6 @@ namespace Outer { } #else -#warning nspace feature not yet supported in this target language +//#warning nspace feature not yet supported in this target language #endif From 8e6a539d89bc44e47ec75f8cf5d47f824e35c869 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 15 Feb 2014 19:34:42 +0000 Subject: [PATCH 357/481] Fix crash in php example Declaration and definition of the add function were different --- Examples/php/cpointer/example.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Examples/php/cpointer/example.c b/Examples/php/cpointer/example.c index 3326dec3e..04dd08df0 100644 --- a/Examples/php/cpointer/example.c +++ b/Examples/php/cpointer/example.c @@ -1,6 +1,6 @@ /* File : example.c */ -void add(double *x, double *y, double *result) { +void add(int *x, int *y, int *result) { *result = *x + *y; } From 90a9d750c9e6ee67cdde95e5c76c18e15379cebe Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 15 Feb 2014 22:05:40 +0000 Subject: [PATCH 358/481] Add support for cdata library for Java --- CHANGES.current | 3 ++ Examples/test-suite/java/li_cdata_runme.java | 24 ++++++++++++++ Lib/cdata.i | 33 ++++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 Examples/test-suite/java/li_cdata_runme.java diff --git a/CHANGES.current b/CHANGES.current index 7c257dfde..63f575a9d 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,9 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2014-02-15: wsfulton + [Java] Add support for the cdata library. + 2014-02-06: gjanssens [Guile] Patch #133. Make scm to string conversion work with non-ascii strings. Guile 2 has a completely rewritten string implementation. SWIG made some assumptions diff --git a/Examples/test-suite/java/li_cdata_runme.java b/Examples/test-suite/java/li_cdata_runme.java new file mode 100644 index 000000000..c0ea8ecc7 --- /dev/null +++ b/Examples/test-suite/java/li_cdata_runme.java @@ -0,0 +1,24 @@ +import li_cdata.*; + +public class li_cdata_runme { + + static { + try { + System.loadLibrary("li_cdata"); + } 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[]) throws Throwable + { + byte[] s = "ABC abc".getBytes(); + SWIGTYPE_p_void m = li_cdata.malloc(256); + li_cdata.memmove(m, s); + byte[] ss = li_cdata.cdata(m, 7); + String ss_string = new String(ss); + if (!ss_string.equals("ABC abc")) + throw new RuntimeException("failed got: " + ss_string); + } +} diff --git a/Lib/cdata.i b/Lib/cdata.i index 22a6d9de8..b9b8e1887 100644 --- a/Lib/cdata.i +++ b/Lib/cdata.i @@ -20,17 +20,50 @@ typedef struct SWIGCDATA { $result = scm_from_locale_stringn($1.data,$1.len); } %typemap(in) (const void *indata, int inlen) = (char *STRING, int LENGTH); + #elif SWIGCHICKEN + %typemap(out) SWIGCDATA { C_word *string_space = C_alloc(C_SIZEOF_STRING($1.len)); $result = C_string(&string_space, $1.len, $1.data); } %typemap(in) (const void *indata, int inlen) = (char *STRING, int LENGTH); + #elif SWIGPHP + %typemap(out) SWIGCDATA { ZVAL_STRINGL($result, $1.data, $1.len, 1); } %typemap(in) (const void *indata, int inlen) = (char *STRING, int LENGTH); + +#elif SWIGJAVA + +%apply (char *STRING, int LENGTH) { (const void *indata, int inlen) } +%typemap(jni) SWIGCDATA "jbyteArray" +%typemap(jtype) SWIGCDATA "byte[]" +%typemap(jstype) SWIGCDATA "byte[]" +%fragment("SWIG_JavaArrayOutCDATA", "header") { +static jbyteArray SWIG_JavaArrayOutCDATA(JNIEnv *jenv, char *result, jsize sz) { + jbyte *arr; + int i; + jbyteArray jresult = JCALL1(NewByteArray, jenv, sz); + if (!jresult) + return NULL; + arr = JCALL2(GetByteArrayElements, jenv, jresult, 0); + if (!arr) + return NULL; + for (i=0; i Date: Sat, 15 Feb 2014 23:30:14 +0000 Subject: [PATCH 359/481] Add fragment Removes include specifically for clang Cuts down on duplicate #include in general --- Lib/perl5/std_common.i | 3 +-- Lib/python/pystdcommon.swg | 3 +-- Lib/std/std_basic_string.i | 5 +---- Lib/std/std_common.i | 10 ++-------- Lib/tcl/std_vector.i | 2 +- Lib/typemaps/fragments.swg | 8 ++++++-- Lib/typemaps/std_string.swg | 6 ++---- Lib/typemaps/std_wstring.swg | 2 +- Lib/typemaps/traits.swg | 10 ++-------- 9 files changed, 17 insertions(+), 32 deletions(-) diff --git a/Lib/perl5/std_common.i b/Lib/perl5/std_common.i index c36513912..bb280688e 100644 --- a/Lib/perl5/std_common.i +++ b/Lib/perl5/std_common.i @@ -8,9 +8,8 @@ %apply size_t { std::size_t }; +%fragment(""); %{ -#include - double SwigSvToNumber(SV* sv) { return SvIOK(sv) ? double(SvIVX(sv)) : SvNVX(sv); } diff --git a/Lib/python/pystdcommon.swg b/Lib/python/pystdcommon.swg index 4e2ae56f4..2af22e2a4 100644 --- a/Lib/python/pystdcommon.swg +++ b/Lib/python/pystdcommon.swg @@ -195,9 +195,8 @@ namespace swig { // #ifdef SWIG_PYTHON_BACKWARD_COMP +%fragment(""); %{ -#include - PyObject* SwigInt_FromBool(bool b) { return PyInt_FromLong(b ? 1L : 0L); } diff --git a/Lib/std/std_basic_string.i b/Lib/std/std_basic_string.i index 7b0898a3e..1aa5721c9 100644 --- a/Lib/std/std_basic_string.i +++ b/Lib/std/std_basic_string.i @@ -3,10 +3,7 @@ %include %include - -%{ -#include -%} +%fragment(""); namespace std { diff --git a/Lib/std/std_common.i b/Lib/std/std_common.i index cb91bc632..35baf2206 100644 --- a/Lib/std/std_common.i +++ b/Lib/std/std_common.i @@ -23,8 +23,8 @@ // Common code for supporting the C++ std namespace // +%fragment(""); %{ -#include #include #include %} @@ -73,13 +73,7 @@ namespace std { #endif %} -%fragment("StdStringInclude","header") %{ -#ifdef __clang__ -#include -#endif -%} - -%fragment("StdTraitsCommon","header",fragment="StdStringInclude") %{ +%fragment("StdTraitsCommon","header",fragment="") %{ namespace swig { template struct noconst_traits { diff --git a/Lib/tcl/std_vector.i b/Lib/tcl/std_vector.i index de99a36d0..37e23ba71 100644 --- a/Lib/tcl/std_vector.i +++ b/Lib/tcl/std_vector.i @@ -28,11 +28,11 @@ // is returned // ------------------------------------------------------------------------ +%fragment(""); %{ #include #include #include -#include Tcl_Obj* SwigString_FromString(const std::string &s) { return Tcl_NewStringObj(s.data(), (int)s.length()); diff --git a/Lib/typemaps/fragments.swg b/Lib/typemaps/fragments.swg index 8f887e34e..ce87c8cc0 100644 --- a/Lib/typemaps/fragments.swg +++ b/Lib/typemaps/fragments.swg @@ -149,8 +149,12 @@ #endif %} -%fragment("", "header") %{ - #include +%fragment("", "header") %{ +#include +%} + +%fragment("", "header") %{ +#include %} %fragment("SWIG_isfinite","header",fragment=",") %{ diff --git a/Lib/typemaps/std_string.swg b/Lib/typemaps/std_string.swg index 691bf2ccf..5b57beab5 100644 --- a/Lib/typemaps/std_string.swg +++ b/Lib/typemaps/std_string.swg @@ -8,10 +8,8 @@ %include -%{ -#include -%} - +%fragment(""); + namespace std { %naturalvar string; diff --git a/Lib/typemaps/std_wstring.swg b/Lib/typemaps/std_wstring.swg index 670685fca..4a2830bb9 100644 --- a/Lib/typemaps/std_wstring.swg +++ b/Lib/typemaps/std_wstring.swg @@ -7,8 +7,8 @@ %{ #include -#include %} +%fragment(""); namespace std { diff --git a/Lib/typemaps/traits.swg b/Lib/typemaps/traits.swg index 584d480c2..09cc7e295 100644 --- a/Lib/typemaps/traits.swg +++ b/Lib/typemaps/traits.swg @@ -21,18 +21,12 @@ // Common code for supporting the STD C++ namespace // +%fragment(""); %{ -#include #include %} -%fragment("StdStringInclude","header") %{ -#ifdef __clang__ -#include -#endif -%} - -%fragment("Traits","header",fragment="StdStringInclude") +%fragment("Traits","header",fragment="") { namespace swig { /* From 8a5fb0fe7be4471512e27b5fe0d3c6057546df16 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 16 Feb 2014 09:33:51 +0000 Subject: [PATCH 360/481] brew install workarounds on Travis 'brew install guile' does not complete within 10 minutes and the build is then killed by Travis Suggestion and original script from travis-ci/travis-ci#1961 --- Tools/brew-install | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100755 Tools/brew-install diff --git a/Tools/brew-install b/Tools/brew-install new file mode 100755 index 000000000..408ae13bb --- /dev/null +++ b/Tools/brew-install @@ -0,0 +1,25 @@ +#!/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 $? From 60501fe077815568a7124906f360841b8e9be8d0 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 8 Feb 2014 21:41:44 +0000 Subject: [PATCH 361/481] Errors tests more visibly show failures as the output of diff diff -u would be better, but it is not posix, so diff -e is chosen as second best choice. --- Examples/test-suite/errors/Makefile.in | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Examples/test-suite/errors/Makefile.in b/Examples/test-suite/errors/Makefile.in index cbfe1c29e..fe6aff534 100644 --- a/Examples/test-suite/errors/Makefile.in +++ b/Examples/test-suite/errors/Makefile.in @@ -35,12 +35,12 @@ include $(srcdir)/../common.mk %.cpptest: echo "$(ACTION)ing errors testcase $*" -$(SWIG) -c++ -python -Wall $(SWIGOPT) $*.i 2> $*.$(ERROR_EXT) - $(COMPILETOOL) diff $*.stderr $*.newerr + $(COMPILETOOL) diff -c $*.stderr $*.newerr %.ctest: echo "$(ACTION)ing errors testcase $*" -$(SWIG) -python -Wall $(SWIGOPT) $*.i 2> $*.$(ERROR_EXT) - $(COMPILETOOL) diff $*.stderr $*.newerr + $(COMPILETOOL) diff -c $*.stderr $*.newerr %.clean: From 0e4f2dad0f52d3397d971c511ec7b258ffe5bf49 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 10 Feb 2014 20:50:00 +0000 Subject: [PATCH 362/481] C# examples to use debug flags when using mono interpreter --- Examples/Makefile.in | 3 ++- Examples/test-suite/csharp/Makefile.in | 6 +++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index dac3f2c37..5c7884a8f 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -1203,9 +1203,10 @@ CSHARP_DLNK = @CSHARPDYNAMICLINKING@ CSHARP_LIBPREFIX = @CSHARPLIBRARYPREFIX@ CSHARPCOMPILER = @CSHARPCOMPILER@ CSHARPCILINTERPRETER = @CSHARPCILINTERPRETER@ +CSHARPCILINTERPRETER_FLAGS = @CSHARPCILINTERPRETER_FLAGS@ CSHARPCFLAGS = @CSHARPCFLAGS@ CSHARPSO = @CSHARPSO@ -CSHARP_RUNME = $(CSHARPCILINTERPRETER) ./$(RUNME).exe +CSHARP_RUNME = $(CSHARPCILINTERPRETER) $(CSHARPCILINTERPRETER_FLAGS) ./$(RUNME).exe # ---------------------------------------------------------------- # Build a CSharp dynamically loadable module (C) diff --git a/Examples/test-suite/csharp/Makefile.in b/Examples/test-suite/csharp/Makefile.in index 22d78ee1c..4284a775d 100644 --- a/Examples/test-suite/csharp/Makefile.in +++ b/Examples/test-suite/csharp/Makefile.in @@ -4,8 +4,8 @@ LANGUAGE = csharp SCRIPTSUFFIX = _runme.cs -INTERPRETER = @CSHARPCILINTERPRETER@ -INTERPRETER_FLAGS = @CSHARPCILINTERPRETER_FLAGS@ +CSHARPCILINTERPRETER = @CSHARPCILINTERPRETER@ +CSHARPCILINTERPRETER_FLAGS = @CSHARPCILINTERPRETER_FLAGS@ CSHARPPATHSEPARATOR = "@CSHARPPATHSEPARATOR@" CSHARPCYGPATH_W = @CSHARPCYGPATH_W@ srcdir = @srcdir@ @@ -75,7 +75,7 @@ run_testcase = \ $(MAKE) -f $*/$(top_builddir)/$(EXAMPLES)/Makefile \ CSHARPFLAGS='-nologo -debug+ $(CSHARPFLAGSSPECIAL) -out:$*_runme.exe' \ CSHARPSRCS='`$(CSHARPCYGPATH_W) $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX)` `find $* -name "*.cs" -exec $(CSHARPCYGPATH_W) "{}" \+`' csharp_compile && \ - env LD_LIBRARY_PATH="$*:$$LD_LIBRARY_PATH" PATH="$*:$$PATH" SHLIB_PATH="$*:$$SHLIB_PATH" DYLD_FALLBACK_LIBRARY_PATH= $(RUNTOOL) $(INTERPRETER) $(INTERPRETER_FLAGS) ./$*_runme.exe; \ + env LD_LIBRARY_PATH="$*:$$LD_LIBRARY_PATH" PATH="$*:$$PATH" SHLIB_PATH="$*:$$SHLIB_PATH" DYLD_FALLBACK_LIBRARY_PATH= $(RUNTOOL) $(CSHARPCILINTERPRETER) $(CSHARPCILINTERPRETER_FLAGS) ./$*_runme.exe; \ else \ cd $* && \ $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile \ From d73513cb7ad5fcdab4fbaa9dd4c2e5fd96faf091 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 16 Feb 2014 15:40:02 +0000 Subject: [PATCH 363/481] Travis testing of Python 3.3 added --- .travis.yml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 9cf525f6e..7c61dc299 100644 --- a/.travis.yml +++ b/.travis.yml @@ -26,12 +26,15 @@ matrix: env: SWIGLANG=python - compiler: gcc env: SWIGLANG=python PY3=1 + - compiler: gcc + env: SWIGLANG=python PY3=1 VER=3.3 - compiler: gcc env: SWIGLANG=ruby - compiler: gcc env: SWIGLANG=tcl allow_failures: - # None + env: SWIGLANG=python PY3=1 VER=3.3 + - compiler: gcc before_install: - date -u - lsb_release -a @@ -45,7 +48,8 @@ before_install: - if test "$SWIGLANG" = "lua"; then sudo apt-get -qq install lua5.1 liblua5.1-dev; fi - if test "$SWIGLANG" = "octave"; then sudo apt-get -qq install octave3.2 octave3.2-headers; fi - if test "$SWIGLANG" = "php"; then sudo apt-get install php5-cli php5-dev; fi - - if test "$SWIGLANG" = "python" -a "$PY3"; then sudo apt-get install python3-dev; fi + - if test "$SWIGLANG" = "python" -a "$PY3" -a -z "$VER"; then sudo apt-get install -qq python3-dev; fi + - if test "$SWIGLANG" = "python" -a "$VER"; then sudo add-apt-repository -y ppa:fkrull/deadsnakes && sudo apt-get -qq update && sudo apt-get -qq install python${VER}-dev; fi - if test "$SWIGLANG" = "tcl"; then sudo apt-get -qq install tcl8.4-dev; fi script: - ./autogen.sh && ./configure From 53a3d12227ba4146d57c208389d28c3f3e6c5ca3 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 16 Feb 2014 17:13:54 +0000 Subject: [PATCH 364/481] Fix typo in .travis.yml --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 7c61dc299..51c24e0e4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -33,8 +33,8 @@ matrix: - compiler: gcc env: SWIGLANG=tcl allow_failures: - env: SWIGLANG=python PY3=1 VER=3.3 - compiler: gcc + env: SWIGLANG=python PY3=1 VER=3.3 before_install: - date -u - lsb_release -a From b1707884592807e89a133035c1571e1b75746ece Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 16 Feb 2014 14:52:45 +0000 Subject: [PATCH 365/481] Executable bits and shebang fixes --- Examples/python/performance/constructor/runme.py | 2 -- Examples/python/performance/func/runme.py | 2 -- Examples/python/performance/harness.py | 2 -- Examples/python/performance/hierarchy/runme.py | 2 -- Examples/python/performance/hierarchy_operator/runme.py | 2 -- Examples/python/performance/operator/runme.py | 2 -- Examples/ruby/constants/runme.rb | 0 Examples/ruby/hashargs/runme.rb | 0 Examples/ruby/multimap/runme.rb | 0 Examples/ruby/simple/runme.rb | 0 10 files changed, 12 deletions(-) mode change 100755 => 100644 Examples/ruby/constants/runme.rb mode change 100755 => 100644 Examples/ruby/hashargs/runme.rb mode change 100755 => 100644 Examples/ruby/multimap/runme.rb mode change 100755 => 100644 Examples/ruby/simple/runme.rb diff --git a/Examples/python/performance/constructor/runme.py b/Examples/python/performance/constructor/runme.py index 23577a14d..274cbf85e 100644 --- a/Examples/python/performance/constructor/runme.py +++ b/Examples/python/performance/constructor/runme.py @@ -1,5 +1,3 @@ -#!/usr/bin/env - import sys sys.path.append('..') import harness diff --git a/Examples/python/performance/func/runme.py b/Examples/python/performance/func/runme.py index fd2fb175b..f9032b9d2 100644 --- a/Examples/python/performance/func/runme.py +++ b/Examples/python/performance/func/runme.py @@ -1,5 +1,3 @@ -#!/usr/bin/env - import sys sys.path.append('..') import harness diff --git a/Examples/python/performance/harness.py b/Examples/python/performance/harness.py index 8e9b6041b..00f48e66a 100644 --- a/Examples/python/performance/harness.py +++ b/Examples/python/performance/harness.py @@ -1,5 +1,3 @@ -#!/usr/bin/env - import sys import time import imp diff --git a/Examples/python/performance/hierarchy/runme.py b/Examples/python/performance/hierarchy/runme.py index 8a57da05e..9b22586a1 100644 --- a/Examples/python/performance/hierarchy/runme.py +++ b/Examples/python/performance/hierarchy/runme.py @@ -1,5 +1,3 @@ -#!/usr/bin/env - import sys sys.path.append('..') import harness diff --git a/Examples/python/performance/hierarchy_operator/runme.py b/Examples/python/performance/hierarchy_operator/runme.py index cf200362f..5a8c52557 100644 --- a/Examples/python/performance/hierarchy_operator/runme.py +++ b/Examples/python/performance/hierarchy_operator/runme.py @@ -1,5 +1,3 @@ -#!/usr/bin/env - import sys sys.path.append('..') import harness diff --git a/Examples/python/performance/operator/runme.py b/Examples/python/performance/operator/runme.py index 61a0e8edc..4a6031f48 100644 --- a/Examples/python/performance/operator/runme.py +++ b/Examples/python/performance/operator/runme.py @@ -1,5 +1,3 @@ -#!/usr/bin/env - import sys sys.path.append('..') import harness diff --git a/Examples/ruby/constants/runme.rb b/Examples/ruby/constants/runme.rb old mode 100755 new mode 100644 diff --git a/Examples/ruby/hashargs/runme.rb b/Examples/ruby/hashargs/runme.rb old mode 100755 new mode 100644 diff --git a/Examples/ruby/multimap/runme.rb b/Examples/ruby/multimap/runme.rb old mode 100755 new mode 100644 diff --git a/Examples/ruby/simple/runme.rb b/Examples/ruby/simple/runme.rb old mode 100755 new mode 100644 From a161e5ab4ef310d0639f10cf75a490b5106bfe0a Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 16 Feb 2014 15:53:08 +0000 Subject: [PATCH 366/481] Fix configure for binary specified by --with-python3 --- configure.ac | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/configure.ac b/configure.ac index 736395ac7..bb62068ae 100644 --- a/configure.ac +++ b/configure.ac @@ -707,15 +707,21 @@ AS_HELP_STRING([--with-python3=path], [Set location of Python 3.x executable]),[ if test x"${PY3BIN}" = xno -o x"${with_alllang}" = xno ; then AC_MSG_NOTICE([Disabling Python 3.x support]) else - for py_ver in 3 3.6 3.5 3.4 3.3 3.2 3.1 3.0; do - AC_CHECK_PROGS(PYTHON3, [python$py_ver]) - if test -n "$PYTHON3"; then - AC_CHECK_PROGS(PY3CONFIG, [$PYTHON3-config]) - if test -n "$PY3CONFIG"; then - break + if test "x$PY3BIN" = xyes; then + for py_ver in 3 3.6 3.5 3.4 3.3 3.2 3.1 3.0; do + AC_CHECK_PROGS(PYTHON3, [python$py_ver]) + if test -n "$PYTHON3"; then + AC_CHECK_PROGS(PY3CONFIG, [$PYTHON3-config]) + if test -n "$PY3CONFIG"; then + break + fi fi - fi - done + done + else + PYTHON3="$PY3BIN" + AC_CHECK_PROGS(PY3CONFIG, [$PYTHON3-config]) + fi + if test -n "$PYTHON3" -a -n "$PY3CONFIG"; then AC_MSG_CHECKING([for Python 3.x prefix]) From 8cdae65ee9de33436ca2cd44744fdee2c9870590 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 16 Feb 2014 17:17:50 +0000 Subject: [PATCH 367/481] C++ exception (wrapped by a Python exception as a shadow instance) segfaulting Python Patch #137 --- CHANGES.current | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGES.current b/CHANGES.current index 63f575a9d..3248541c4 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,9 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2014-02-16: hfalcic + [Python] Patch #133 - fix crashes/exceptions in exception handling in Python 3.3 + 2014-02-15: wsfulton [Java] Add support for the cdata library. From 81cc95155ea3c542f18ba32758c48e2b46577f76 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 16 Feb 2014 18:11:17 +0000 Subject: [PATCH 368/481] Python 3.3 should now work on Travis --- .travis.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 51c24e0e4..5d47074e9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -33,8 +33,7 @@ matrix: - compiler: gcc env: SWIGLANG=tcl allow_failures: - - compiler: gcc - env: SWIGLANG=python PY3=1 VER=3.3 + # None before_install: - date -u - lsb_release -a From c7187c6a2d453e59222eb41ca31f93099053cedd Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 9 Feb 2014 09:34:18 +0000 Subject: [PATCH 369/481] Add release summary for 2.0.12 --- RELEASENOTES | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/RELEASENOTES b/RELEASENOTES index 720dc9d34..756df81ff 100644 --- a/RELEASENOTES +++ b/RELEASENOTES @@ -4,6 +4,14 @@ and CHANGES files. Release Notes ============= +SWIG-2.0.12 summary: +- This is a maintenance release backporting some fixes from the pending + 3.0.0 release. +- Octave 3.8 support added. +- C++11 support for new versions of erase/insert in the STL containers. +- Compilation fixes on some systems for the generated Lua, PHP, Python + and R wrappers. + SWIG-2.0.11 summary: - Minor bug fixes and enhancements mostly in Python, but also C#, Lua, Ocaml, Octave, Perl, PHP, Python, R, Ruby, Tcl. From d7f91bc47a98f5b2afa71315e8c7636c3a029be5 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 16 Feb 2014 22:28:57 +0000 Subject: [PATCH 370/481] CHANGES files corrections since 2.0.12 release A number of fixes committed since 2.0.11 release were intended for the 3.0.0 release were backported to the maintenance-2.0 branch for 2.0.12. --- CHANGES | 65 +++++++++++++++++++++++++++++++++++++++++++++++++ CHANGES.current | 62 ---------------------------------------------- 2 files changed, 65 insertions(+), 62 deletions(-) diff --git a/CHANGES b/CHANGES index da5fb1f07..988f0fb5e 100644 --- a/CHANGES +++ b/CHANGES @@ -4,6 +4,71 @@ See the CHANGES.current file for changes in the current version. See the RELEASENOTES file for a summary of changes in each release. +Version 2.0.12 (9 Feb 2014) +=========================== + +2014-01-16: wsfulton + [PHP] Fix compilation error in ZTS mode (64 bit windows) due to incorrect placement + of TSRMLS_FETCH() in SWIG_Php_GetModule() as reported by Mark Dawson-Butterworth. + +2014-01-13: kwwette + [Octave] update support to Octave version 3.8.0 + + - Octave 3.8.0 no longer defines OCTAVE_API_VERSION_NUMBER, but 3.8.1 + will define OCTAVE_{MAJOR,MINOR,PATCH}_VERSION instead: see + http://hg.savannah.gnu.org/hgweb/octave/rev/b6b6e0dc700e + So we now use a new macro SWIG_OCTAVE_PREREQ(major,minor,patch) to + enable features requiring Octave version major.minor.patch or later. + + For Octave versions prior to 3.8.1, we reconstruct values for + OCTAVE_{MAJOR,MINOR,PATCH}_VERSION based on OCTAVE_API_VERSION_NUMBER, + extracted from Octave's ChangeLogs. An additional hack is needed to + distinguish between Octave <= 3.2.x and 3.8.0, neither of which define + OCTAVE_API_VERSION_NUMBER. + + - Octave 3.8.0 deprecates symbol_table::varref(), so remove its use + for this and future versions of Octave. + + - Octave 3.8.0 removes octave_value::is_real_nd_array(), used in + octave_swig_type::dims(). Its use is not required here, so remove it. + + - Retested against Octave versions 3.0.5, 3.2.4, 3.4.3, 3.6.4, and 3.8.0. + + - Updated Octave documentation with tested Octave versions, and added a + warning against using versions <= 3.x.x, which are no longer tested. + +2013-12-22: wsfulton + C++11 support for new versions of erase and insert in the STL containers. + + The erase and insert methods in the containers use const_iterator instead + of iterator in C++11. There are times when the methods wrapped must match + the parameters exactly. Specifically when full type information for + template types is missing or SWIG fails to look up the type correctly, + for example: + + %include + typedef float Real; + %template(RealVector) std::vector; + + SWIG does not find std::vector::iterator because %template using + typedefs does not always work and so SWIG doesn't know if the type is + copyable and so uses SwigValueWrapper which does + not support conversion to another type (const_iterator). This resulted + in compilation errors when using the C++11 version of the containers. + + Closes #73 + +2013-10-17: wsfulton + [R] Fix SF #1340 - Visual Studio compile error in C++ wrappers due to #include + within extern "C" block. + +2013-10-17: wsfulton + [Python] Fix SF #1345 - Missing #include for offsetof when using -builtin. + +2013-10-12: wsfulton + [Lua] Apply #92 - missing return statements for SWIG_Lua_add_namespace_details() + and SWIG_Lua_namespace_register(). + Version 2.0.11 (15 Sep 2013) ============================ diff --git a/CHANGES.current b/CHANGES.current index 3248541c4..013bf6257 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -40,41 +40,10 @@ Version 3.0.0 (in progress) Director exceptions (Swig::DirectorException) now derive from std::exception and hence provide the what() method. In Python and Ruby, this replaces the now deprecated DirectorException::getMessage() method. - -2014-01-16: wsfulton - [PHP] Fix compilation error in ZTS mode (64 bit windows) due to incorrect placement - of TSRMLS_FETCH() in SWIG_Php_GetModule() as reported by Mark Dawson-Butterworth. - 2014-01-14: diorcety Patch #112 - Fix symbol resolution involving scopes that have multiple levels of typedefs - fixes some template resolutions as well as some typemap searches. -2014-01-13: kwwette - [Octave] update support to Octave version 3.8.0 - - - Octave 3.8.0 no longer defines OCTAVE_API_VERSION_NUMBER, but 3.8.1 - will define OCTAVE_{MAJOR,MINOR,PATCH}_VERSION instead: see - http://hg.savannah.gnu.org/hgweb/octave/rev/b6b6e0dc700e - So we now use a new macro SWIG_OCTAVE_PREREQ(major,minor,patch) to - enable features requiring Octave version major.minor.patch or later. - - For Octave versions prior to 3.8.1, we reconstruct values for - OCTAVE_{MAJOR,MINOR,PATCH}_VERSION based on OCTAVE_API_VERSION_NUMBER, - extracted from Octave's ChangeLogs. An additional hack is needed to - distinguish between Octave <= 3.2.x and 3.8.0, neither of which define - OCTAVE_API_VERSION_NUMBER. - - - Octave 3.8.0 deprecates symbol_table::varref(), so remove its use - for this and future versions of Octave. - - - Octave 3.8.0 removes octave_value::is_real_nd_array(), used in - octave_swig_type::dims(). Its use is not required here, so remove it. - - - Retested against Octave versions 3.0.5, 3.2.4, 3.4.3, 3.6.4, and 3.8.0. - - - Updated Octave documentation with tested Octave versions, and added a - warning against using versions <= 3.x.x, which are no longer tested. - 2014-01-11: wsfulton Fix and document the naturalvar feature override behaviour - the naturalvar feature attached to a variable name has precedence over the naturalvar @@ -126,27 +95,6 @@ Version 3.0.0 (in progress) 2013-12-23: talby [Perl] Add support for directors. -2013-12-22: wsfulton - C++11 support for new versions of erase and insert in the STL containers. - - The erase and insert methods in the containers use const_iterator instead - of iterator in C++11. There are times when the methods wrapped must match - the parameters exactly. Specifically when full type information for - template types is missing or SWIG fails to look up the type correctly, - for example: - - %include - typedef float Real; - %template(RealVector) std::vector; - - SWIG does not find std::vector::iterator because %template using - typedefs does not always work and so SWIG doesn't know if the type is - copyable and so uses SwigValueWrapper which does - not support conversion to another type (const_iterator). This resulted - in compilation errors when using the C++11 version of the containers. - - Closes #73 - 2013-12-18: ianlancetaylor [Go] Don't require that Go environment variables be set when running examples or testsuite when using Go 1 or @@ -217,20 +165,10 @@ Version 3.0.0 (in progress) [Java] Apply patch #91 from Marvin Greenberg - Add director:except feature for improved exception handling in director methods for Java. -2013-10-17: wsfulton - [R] Fix SF #1340 - Visual Studio compile error in C++ wrappers due to #include - within extern "C" block. - -2013-10-17: wsfulton - [Python] Fix SF #1345 - Missing #include for offsetof when using -builtin. - 2013-10-15: vadz Allow using \l, \L, \u, \U and \E in the substitution part of %(regex:/pattern/subst/) inside %rename to change the case of the text being replaced. -2013-10-12: wsfulton - [Lua] Apply #92 - missing return statements for SWIG_Lua_add_namespace_details() - and SWIG_Lua_namespace_register(). 2013-10-12: wsfulton [CFFI] Apply #96 - superclass not lispify From 052d0057c2d96f013dbc3a477a46a10672db9094 Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Mon, 17 Feb 2014 16:24:04 +1300 Subject: [PATCH 371/481] Only call strlen(lc_fname) if we are going to use the result --- Lib/php/director.swg | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Lib/php/director.swg b/Lib/php/director.swg index 50b433e47..6671f5580 100644 --- a/Lib/php/director.swg +++ b/Lib/php/director.swg @@ -102,12 +102,11 @@ namespace Swig { TSRMLS_FETCH_FROM_CTX(swig_zts_ctx); zend_class_entry **ce; zend_function *mptr; - int name_len = strlen(lc_fname); if (zend_lookup_class(cname, strlen(cname), &ce TSRMLS_CC) != SUCCESS) { return false; } - if (zend_hash_find(&(*ce)->function_table, lc_fname, name_len + 1, (void **) &mptr) != SUCCESS) { + if (zend_hash_find(&(*ce)->function_table, lc_fname, strlen(lc_fname) + 1, (void **) &mptr) != SUCCESS) { return false; } // common.scope points to the declaring class From 7af8b13ef7f9120988c1cbff9d72f2236d971089 Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Mon, 17 Feb 2014 16:25:29 +1300 Subject: [PATCH 372/481] Just call strcmp() rather than strlen() twice plus zend_binary_strcmp() --- Lib/php/globalvar.i | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Lib/php/globalvar.i b/Lib/php/globalvar.i index 1378ae60b..988559857 100644 --- a/Lib/php/globalvar.i +++ b/Lib/php/globalvar.i @@ -164,7 +164,7 @@ zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); convert_to_string_ex(z_var); s1 = Z_STRVAL_PP(z_var); - if ((s1 == NULL) || ($1 == NULL) || zend_binary_strcmp(s1, strlen(s1), $1, strlen($1))) { + if ((s1 == NULL) || ($1 == NULL) || strcmp(s1, $1)) { if (s1) $1 = estrdup(s1); else @@ -190,9 +190,9 @@ zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); s1 = Z_STRVAL_PP(z_var); - if((s1 == NULL) || ($1 == NULL) || zend_binary_strcmp(s1, strlen(s1), $1, strlen($1))) { - if(s1) - strncpy($1, s1, $1_dim0); + if ((s1 == NULL) || ($1 == NULL) || strcmp(s1, $1)) { + if (s1) + strncpy($1, s1, $1_dim0); } } @@ -288,7 +288,7 @@ zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); s1 = Z_STRVAL_PP(z_var); - if((s1 == NULL) || ($1 == NULL) || zend_binary_strcmp(s1, strlen(s1), $1, strlen($1) )) { + if((s1 == NULL) || ($1 == NULL) || strcmp(s1, $1)) { if(s1) efree(s1); if($1) { @@ -325,7 +325,7 @@ deliberate error cos this code looks bogus to me zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); s1 = Z_STRVAL_PP(z_var); - if((s1 == NULL) || zend_binary_strcmp(s1, strlen(s1), $1, strlen($1))) { + if((s1 == NULL) || strcmp(s1, $1)) { if($1) { (*z_var)->value.str.val = estrdup($1); (*z_var)->value.str.len = strlen($1)+1; From b761131fecf82634e925e63898d8d5bc3c5e860f Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Mon, 17 Feb 2014 16:26:48 +1300 Subject: [PATCH 373/481] "if (strlen(msg))" -> "if (msg[0])" --- Lib/php/director.swg | 2 +- Lib/python/director.swg | 2 +- Lib/ruby/director.swg | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Lib/php/director.swg b/Lib/php/director.swg index 6671f5580..06eeb73b0 100644 --- a/Lib/php/director.swg +++ b/Lib/php/director.swg @@ -127,7 +127,7 @@ namespace Swig { std::string swig_msg; public: DirectorException(int code, const char *hdr, const char *msg TSRMLS_DC) : swig_msg(hdr) { - if (strlen(msg)) { + if (msg[0]) { swig_msg += " "; swig_msg += msg; } diff --git a/Lib/python/director.swg b/Lib/python/director.swg index bca22af4e..50f735a89 100644 --- a/Lib/python/director.swg +++ b/Lib/python/director.swg @@ -179,7 +179,7 @@ namespace Swig { public: DirectorException(PyObject *error, const char *hdr ="", const char *msg ="") : swig_msg(hdr) { SWIG_PYTHON_THREAD_BEGIN_BLOCK; - if (strlen(msg)) { + if (msg[0]) { swig_msg += " "; swig_msg += msg; } diff --git a/Lib/ruby/director.swg b/Lib/ruby/director.swg index 3b1837374..c2c4150e6 100644 --- a/Lib/ruby/director.swg +++ b/Lib/ruby/director.swg @@ -118,7 +118,7 @@ namespace Swig { } DirectorException(VALUE error, const char *hdr, const char *msg ="") : swig_error(error), swig_msg(hdr) { - if (strlen(msg)) { + if (msg[0]) { swig_msg += " "; swig_msg += msg; } From fcf818075111d06936f0bd5541152f006ef30ba2 Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Mon, 17 Feb 2014 16:27:39 +1300 Subject: [PATCH 374/481] Whitespace tweaks --- Lib/php/globalvar.i | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Lib/php/globalvar.i b/Lib/php/globalvar.i index 988559857..56f921434 100644 --- a/Lib/php/globalvar.i +++ b/Lib/php/globalvar.i @@ -216,7 +216,7 @@ $1_ltype _temp; zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); - if (SWIG_ConvertPtr(*z_var, (void **)&_temp, $1_descriptor, 0) < 0) { + 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"); } @@ -293,7 +293,7 @@ efree(s1); if($1) { (*z_var)->value.str.val = estrdup($1); - (*z_var)->value.str.len = strlen($1) +1; + (*z_var)->value.str.len = strlen($1) + 1; } else { (*z_var)->value.str.val = 0; (*z_var)->value.str.len = 0; @@ -314,7 +314,7 @@ zval **z_var; zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); - if($1) + if($1) SWIG_SetPointerZval(*z_var, (void*)$1, $1_descriptor, 0); } @@ -328,7 +328,7 @@ 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; + (*z_var)->value.str.len = strlen($1) + 1; } else { (*z_var)->value.str.val = 0; (*z_var)->value.str.len = 0; From fcda732437c556927470adf5f116fda6d32532cf Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Mon, 17 Feb 2014 19:44:20 +1300 Subject: [PATCH 375/481] fix typo --- Doc/Manual/Go.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Doc/Manual/Go.html b/Doc/Manual/Go.html index 240db2b61..226acaabf 100644 --- a/Doc/Manual/Go.html +++ b/Doc/Manual/Go.html @@ -55,7 +55,7 @@ there is no convenient way to call C++ code. SWIG fills this gap.

      There are (at least) two different Go compilers. One is the gc -compiler, normally invoked under via the go tool. The other +compiler, normally invoked via the go tool. The other 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. SWIG supports both, selected by a command line option. From 9cbd742b66b839d110af9b85ee210d60c7023f68 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 18 Feb 2014 07:30:55 +0000 Subject: [PATCH 376/481] Fix %$ismember %rename predicate for members added via %extend Bug reported was incorrect renaming of PHP built-in functions, such as next. See PHPFN in phpkw.swg. Add some tests for the %rename predicates. --- CHANGES.current | 3 ++ Examples/test-suite/common.mk | 2 + .../python/rename_predicates_runme.py | 35 +++++++++++++ Examples/test-suite/rename_predicates.i | 50 +++++++++++++++++++ Source/CParse/parser.y | 7 ++- 5 files changed, 95 insertions(+), 2 deletions(-) create mode 100644 Examples/test-suite/python/rename_predicates_runme.py create mode 100644 Examples/test-suite/rename_predicates.i diff --git a/CHANGES.current b/CHANGES.current index 013bf6257..770187d5e 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,9 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2014-02-15: wsfulton + Fix the %$ismember %rename predicates to also apply to members added via %extend. + 2014-02-16: hfalcic [Python] Patch #133 - fix crashes/exceptions in exception handling in Python 3.3 diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 5ce9a7031..836984476 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -86,6 +86,7 @@ CPP_TEST_BROKEN += \ li_boost_shared_ptr_template \ nested_private \ overload_complicated \ + rename_camel \ template_default_pointer \ template_private_assignment \ template_expr \ @@ -323,6 +324,7 @@ CPP_TEST_CASES += \ rename_strip_encoder \ rename_pcre_encoder \ rename_pcre_enum \ + rename_predicates \ restrict_cplusplus \ return_const_value \ return_value_scope \ diff --git a/Examples/test-suite/python/rename_predicates_runme.py b/Examples/test-suite/python/rename_predicates_runme.py new file mode 100644 index 000000000..f21f32348 --- /dev/null +++ b/Examples/test-suite/python/rename_predicates_runme.py @@ -0,0 +1,35 @@ +from rename_predicates import * + +r = RenamePredicates(123) +r.MF_member_function() +r.MF_static_member_function() +r.MF_extend_function_before() +r.MF_extend_function_after() +GF_global_function() + +if r.MV_member_variable != 123: + raise RuntimeError("variable wrong") +r.MV_member_variable = 1234; +if r.MV_member_variable != 1234: + raise RuntimeError("variable wrong") + +if cvar.RenamePredicates_MV_static_member_variable != 456: + raise RuntimeError("variable wrong") +cvar.RenamePredicates_MV_static_member_variable = 4567; +if cvar.RenamePredicates_MV_static_member_variable != 4567: + raise RuntimeError("variable wrong") + +if cvar.GV_global_variable != 789: + raise RuntimeError("variable wrong") +cvar.GV_global_variable = 7890; +if cvar.GV_global_variable != 7890: + raise RuntimeError("variable wrong") + +UC_UPPERCASE() +LC_lowercase() +TI_Title() +FU_FirstUpperCase() +FL_firstLowerCase() +CA_CamelCase() +LC_lowerCamelCase() +UC_under_case_it() diff --git a/Examples/test-suite/rename_predicates.i b/Examples/test-suite/rename_predicates.i new file mode 100644 index 000000000..a80f3c565 --- /dev/null +++ b/Examples/test-suite/rename_predicates.i @@ -0,0 +1,50 @@ +%module rename_predicates + +%rename("AF_%(utitle)s", %$isfunction) ""; +%rename("MF_%(utitle)s", %$isfunction, %$ismember) ""; +%rename("GF_%(utitle)s", %$isfunction, %$not %$ismember) ""; +%rename("MV_%(utitle)s", %$isvariable) ""; +%rename("GV_%(utitle)s", %$isvariable, %$isglobal) ""; + + +%extend RenamePredicates { + void extend_function_before() {} +} + +%inline %{ +struct RenamePredicates { + RenamePredicates(int v = 0) : member_variable(v) {} + void member_function() {} + static void static_member_function() {} + int member_variable; + static int static_member_variable; +}; +int RenamePredicates::static_member_variable = 456; +int global_variable = 789; +void global_function() {} +%} + +%extend RenamePredicates { + void extend_function_after() {} +} + +%rename("UC_%(upper)s") "uppercase"; +%rename("LC_%(lower)s") "LOWERcase"; +%rename("TI_%(title)s") "title"; +%rename("FU_%(firstuppercase)s") "firstUpperCase"; +%rename("FL_%(firstlowercase)s") "FirstLowerCase"; +%rename("CA_%(camelcase)s") "camel_Case"; +%rename("LC_%(lowercamelcase)s") "Lower_camel_Case"; +%rename("UC_%(undercase)s") "UnderCaseIt"; + +%inline %{ +void uppercase() {} +void LOWERcase() {} +void title() {} +void firstUpperCase() {} +void FirstLowerCase() {} +void camel_Case() {} +void Lower_camel_Case() {} +void UnderCaseIt() {} +%} + diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 4c6d11e64..467f78587 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -356,10 +356,13 @@ static void add_symbols(Node *n) { } Delete(prefix); } - - Setattr(n,"ismember","1"); } } + + if (!isfriend && (inclass || extendmode)) { + Setattr(n,"ismember","1"); + } + if (!isfriend && inclass) { if ((cplus_mode != CPLUS_PUBLIC)) { only_csymbol = 1; From 43c8f2351c90574b02bff07c339e5cd530712f9b Mon Sep 17 00:00:00 2001 From: Geert Janssens Date: Tue, 18 Feb 2014 16:35:58 +0100 Subject: [PATCH 377/481] guile std_string test: run test in utf8 locale Guile can't properly handle non-ascii strings in the default C locale --- Examples/test-suite/guile/li_std_string_runme.scm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Examples/test-suite/guile/li_std_string_runme.scm b/Examples/test-suite/guile/li_std_string_runme.scm index 5b5563281..237caccbe 100644 --- a/Examples/test-suite/guile/li_std_string_runme.scm +++ b/Examples/test-suite/guile/li_std_string_runme.scm @@ -5,5 +5,5 @@ ; Note: when working with non-ascii strings in guile 2 ; locale must be set explicitly ; The setlocale call below takes care of that -(setlocale LC_ALL "") +(setlocale LC_ALL "en_US.utf8") (load "../schemerunme/li_std_string.scm") From c5911cc08da116482ddb3a498cc8deffd7f3f6ce Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 18 Feb 2014 20:36:24 +0000 Subject: [PATCH 378/481] Add %$isextendmember for %rename of members added via %extend --- CHANGES.current | 6 +++++ .../python/rename_predicates_runme.py | 7 ++++++ Examples/test-suite/rename_predicates.i | 23 ++++++++++++++++++- Lib/swig.swg | 1 + Source/CParse/parser.y | 18 +++++++++++---- 5 files changed, 49 insertions(+), 6 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index 770187d5e..0ac740062 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -8,6 +8,12 @@ Version 3.0.0 (in progress) 2014-02-15: wsfulton Fix the %$ismember %rename predicates to also apply to members added via %extend. + Add %$isextendmember for %rename of members added via %extend. This can be used to + distinguish between normal class/struct members and %extend members. For example + '%$ismember, %$not %$isextendmember' will now identify just class/struct members. + + *** POTENTIAL INCOMPATIBILITY *** + 2014-02-16: hfalcic [Python] Patch #133 - fix crashes/exceptions in exception handling in Python 3.3 diff --git a/Examples/test-suite/python/rename_predicates_runme.py b/Examples/test-suite/python/rename_predicates_runme.py index f21f32348..2ce097737 100644 --- a/Examples/test-suite/python/rename_predicates_runme.py +++ b/Examples/test-suite/python/rename_predicates_runme.py @@ -33,3 +33,10 @@ FL_firstLowerCase() CA_CamelCase() LC_lowerCamelCase() UC_under_case_it() + +ex = ExtendCheck() +ex.MF_real_member1() +ex.MF_real_member2() +ex.EX_EXTENDMETHOD1() +ex.EX_EXTENDMETHOD2() +ex.EX_EXTENDMETHOD3() diff --git a/Examples/test-suite/rename_predicates.i b/Examples/test-suite/rename_predicates.i index a80f3c565..13fb3e1e4 100644 --- a/Examples/test-suite/rename_predicates.i +++ b/Examples/test-suite/rename_predicates.i @@ -1,12 +1,12 @@ %module rename_predicates +// Test a few of the predicates - %$isfunction etc %rename("AF_%(utitle)s", %$isfunction) ""; %rename("MF_%(utitle)s", %$isfunction, %$ismember) ""; %rename("GF_%(utitle)s", %$isfunction, %$not %$ismember) ""; %rename("MV_%(utitle)s", %$isvariable) ""; %rename("GV_%(utitle)s", %$isvariable, %$isglobal) ""; - %extend RenamePredicates { void extend_function_before() {} } @@ -28,6 +28,7 @@ void global_function() {} void extend_function_after() {} } +// Test the various %rename functions - %(upper) etc %rename("UC_%(upper)s") "uppercase"; %rename("LC_%(lower)s") "LOWERcase"; %rename("TI_%(title)s") "title"; @@ -48,3 +49,23 @@ void Lower_camel_Case() {} void UnderCaseIt() {} %} +// Test renaming only member functions in %extend +%rename("EX_%(upper)s", %$isfunction, %$isextendmember) ""; +%extend ExtendCheck { + void ExtendMethod1() {} +} +%inline %{ +struct ExtendCheck { + void RealMember1() {} +#ifdef SWIG + %extend { + void ExtendMethod2() {} + } +#endif + void RealMember2() {} +}; +%} +%extend ExtendCheck { + void ExtendMethod3() {} +} + diff --git a/Lib/swig.swg b/Lib/swig.swg index edadf036d..3ddbb85a0 100644 --- a/Lib/swig.swg +++ b/Lib/swig.swg @@ -297,6 +297,7 @@ static int NAME(TYPE x) { %define %$ismember "match$ismember"="1" %enddef %define %$isglobal %$not %$ismember %enddef +%define %$isextendmember "match$isextendmember"="1" %enddef %define %$innamespace "match$parentNode$nodeType"="namespace" %enddef %define %$ispublic "match$access"="public" %enddef diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 467f78587..dd8de45ff 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -363,6 +363,10 @@ static void add_symbols(Node *n) { Setattr(n,"ismember","1"); } + if (extendmode) { + Setattr(n,"isextendmember","1"); + } + if (!isfriend && inclass) { if ((cplus_mode != CPLUS_PUBLIC)) { only_csymbol = 1; @@ -1392,6 +1396,7 @@ static void mark_nodes_as_extend(Node *n) { for (; n; n = nextSibling(n)) { if (Getattr(n, "template") && Strcmp(nodeType(n), "class") == 0) continue; + /* Fix me: extend is not a feature. Replace with isextendmember? */ Setattr(n, "feature:extend", "1"); mark_nodes_as_extend(firstChild(n)); } @@ -4350,14 +4355,17 @@ cpp_members : cpp_member cpp_members { } } | EXTEND LBRACE { - if (cplus_mode != CPLUS_PUBLIC) { - Swig_error(cparse_file,cparse_line,"%%extend can only be used in a public section\n"); - } - } cpp_members RBRACE cpp_members { + extendmode = 1; + if (cplus_mode != CPLUS_PUBLIC) { + Swig_error(cparse_file,cparse_line,"%%extend can only be used in a public section\n"); + } + } cpp_members RBRACE { + extendmode = 0; + } cpp_members { $$ = new_node("extend"); mark_nodes_as_extend($4); appendChild($$,$4); - set_nextSibling($$,$6); + set_nextSibling($$,$7); } | include_directive { $$ = $1; } | empty { $$ = 0;} From f8a028517dbe21170bef7c2b951ed091e87d16ce Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Wed, 19 Feb 2014 00:12:55 +1300 Subject: [PATCH 379/481] Fix comment typos --- Lib/allkw.swg | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Lib/allkw.swg b/Lib/allkw.swg index 2e0dad6cf..b85b64579 100644 --- a/Lib/allkw.swg +++ b/Lib/allkw.swg @@ -4,14 +4,14 @@ /* Include all the known keyword warnings. Very useful for adding test - files to the test-suite, or check if your own library is ok for all + files to the test-suite, or checking if your own library is ok for all the swig supported languages. Use as swig -Wallkw ... - If you add a new language, remember to create a separete languagekw.swg + If you add a new language, remember to create a separate languagekw.swg file, and add it here. */ From 36c22b70bd37170c024bb742125a7647ab437754 Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Wed, 19 Feb 2014 16:51:31 +1300 Subject: [PATCH 380/481] Make PHP %keywordwarn message wording consistent with other languages --- Examples/test-suite/wallkw.i | 2 +- Lib/php/phpkw.swg | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Examples/test-suite/wallkw.i b/Examples/test-suite/wallkw.i index 1a5866088..345aeeb0a 100644 --- a/Examples/test-suite/wallkw.i +++ b/Examples/test-suite/wallkw.i @@ -2,7 +2,7 @@ // test the -Wallkw option -%warnfilter(SWIGWARN_PARSE_KEYWORD) clone; // 'clone' is a php keyword, renamed as 'c_clone' +%warnfilter(SWIGWARN_PARSE_KEYWORD) clone; // 'clone' is a PHP keyword, renaming to 'c_clone' %warnfilter(SWIGWARN_PARSE_KEYWORD) delegate; // 'delegate' is a C# keyword, renaming to '_delegate' %warnfilter(SWIGWARN_PARSE_KEYWORD) pass; // 'pass' is a python keyword, renaming to '_pass' %warnfilter(SWIGWARN_PARSE_KEYWORD) alias; // 'alias' is a D keyword, renaming to '_alias' diff --git a/Lib/php/phpkw.swg b/Lib/php/phpkw.swg index 78a93369f..032559504 100644 --- a/Lib/php/phpkw.swg +++ b/Lib/php/phpkw.swg @@ -2,9 +2,9 @@ * phpkw.swg * ----------------------------------------------------------------------------- */ -#define PHPKW(x) %keywordwarn("'" `x` "' is a PHP keyword, renamed as 'c_" `x` "'",sourcefmt="%(lower)s",rename="c_%s") `x` +#define PHPKW(x) %keywordwarn("'" `x` "' is a PHP keyword, renaming to 'c_" `x` "'",sourcefmt="%(lower)s",rename="c_%s") `x` -#define PHPCN(x) %keywordwarn("'" `x` "' is a PHP reserved class name, class renamed as 'c_" `x` "'",%$isclass,sourcefmt="%(lower)s",rename="c_%s") `x` +#define PHPCN(x) %keywordwarn("'" `x` "' is a PHP reserved class name, renaming to 'c_" `x` "'",%$isclass,sourcefmt="%(lower)s",rename="c_%s") `x` #define PHPBN1(x) %builtinwarn("'" `x` "' conflicts with a built-in name in PHP",sourcefmt="%(lower)s") `x` #define PHPBN2(x) %builtinwarn("'" `x` "' conflicts with a built-in name in PHP") "::" `x` From 06e5a5fb0da2383a7e5405b3fbdc53e0494f7aed Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Wed, 19 Feb 2014 17:21:34 +1300 Subject: [PATCH 381/481] [PHP] Update the lists of PHP keywords with new ones from PHP 5.4 and newer (and some missing ones from 5.3). Reserved PHP constants names are now checked against enum values and constants, instead of against function and method names. Built-in PHP function names no longer match methods added by %extend. Functions and methods named '__sleep', '__wakeup', 'not', 'parent', or 'virtual' are no longer needlessly renamed. --- CHANGES.current | 9 ++ Lib/php/phpkw.swg | 296 ++++++++++++++++++++++++++++++++++------------ 2 files changed, 232 insertions(+), 73 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index 0ac740062..58efd5e5d 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,15 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2014-02-19: olly + [PHP] Update the lists of PHP keywords with new ones from PHP 5.4 + and newer (and some missing ones from 5.3). Reserved PHP constants + names are now checked against enum values and constants, instead + of against function and method names. Built-in PHP function names + no longer match methods added by %extend. Functions and methods + named '__sleep', '__wakeup', 'not', 'parent', or 'virtual' are no + longer needlessly renamed. + 2014-02-15: wsfulton Fix the %$ismember %rename predicates to also apply to members added via %extend. diff --git a/Lib/php/phpkw.swg b/Lib/php/phpkw.swg index 032559504..14f37d2ff 100644 --- a/Lib/php/phpkw.swg +++ b/Lib/php/phpkw.swg @@ -2,37 +2,41 @@ * phpkw.swg * ----------------------------------------------------------------------------- */ +/* Keyword (case insensitive) */ #define PHPKW(x) %keywordwarn("'" `x` "' is a PHP keyword, renaming to 'c_" `x` "'",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 PHPBN1(x) %builtinwarn("'" `x` "' conflicts with a built-in name in PHP",sourcefmt="%(lower)s") `x` -#define PHPBN2(x) %builtinwarn("'" `x` "' conflicts with a built-in name in PHP") "::" `x` -#define PHPFN(x) %keywordwarn("'" `x` "' is a PHP built-in function, renamed as 'c_" `x` "'",sourcefmt="%(lower)s",%$isfunction,%$not %$ismember,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` +#define PHPBN1b(x) %namewarn(%warningmsg(SWIGWARN_PARSE_BUILTIN_NAME, "constant conflicts with a built-in constant '"`x`"' in PHP"),%$isconstant,sourcefmt="%(lower)s") `x` +%define PHPBN1(X) + PHPBN1a(X); PHPBN1b(X) +%enddef -/* - From +/* Constant (case sensitive) */ +#define PHPBN2a(x) %namewarn(%warningmsg(SWIGWARN_PARSE_BUILTIN_NAME, "enum conflicts with a built-in constant '"`x`"' in PHP"),%$isenumitem) `x` +#define PHPBN2b(x) %namewarn(%warningmsg(SWIGWARN_PARSE_BUILTIN_NAME, "constant conflicts with a built-in constant '"`x`"' in PHP"),%$isconstant) `x` +%define PHPBN2(X) + PHPBN2a(X); PHPBN2b(X) +%enddef - http://aspn.activestate.com/ASPN/docs/PHP/reserved.html - http://php.net/manual/en/reserved.keywords.php +#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` - and reviewed by Olly Betts. - - Further updates from the PHP manual on php.net. -*/ - -/* We classify these as kw since PHP will not run if used globally. */ -/* "You cannot use any of the following words as constants, class names, +/* From: http://php.net/manual/en/reserved.keywords.php + * "You cannot use any of the following words as constants, class names, * function or method names. Using them as variable names is generally OK, but * could lead to confusion." */ -/* case insensitive */ +/* Check is case insensitive - these *MUST* be listed in lower case here */ PHPKW(__halt_compiler); PHPKW(abstract); PHPKW(and); PHPKW(array); PHPKW(as); PHPKW(break); +PHPKW(callable); // As of PHP 5.4 PHPKW(case); PHPKW(catch); PHPKW(class); @@ -57,20 +61,22 @@ PHPKW(eval); // "Language construct" PHPKW(exit); // "Language construct" PHPKW(extends); PHPKW(final); +PHPKW(finally); // As of PHP 5.5 PHPKW(for); PHPKW(foreach); PHPKW(function); PHPKW(global); -PHPKW(goto); // As of PHP5.3 +PHPKW(goto); // As of PHP 5.3 PHPKW(if); PHPKW(implements); PHPKW(include); // "Language construct" PHPKW(include_once); // "Language construct" PHPKW(instanceof); +PHPKW(insteadof); // As of PHP 5.4 PHPKW(interface); PHPKW(isset); // "Language construct" PHPKW(list); // "Language construct" -PHPKW(namespace); // As of PHP5.3 +PHPKW(namespace); // As of PHP 5.3 PHPKW(new); PHPKW(or); PHPKW(print); // "Language construct" @@ -83,39 +89,70 @@ PHPKW(return); // "Language construct" PHPKW(static); PHPKW(switch); PHPKW(throw); +PHPKW(trait); // As of PHP 5.4 PHPKW(try); PHPKW(unset); // "Language construct" PHPKW(use); PHPKW(var); PHPKW(while); PHPKW(xor); -// Compile-time constants -PHPKW(__CLASS__); -PHPKW(__DIR__); // As of PHP5.3 -PHPKW(__FILE__); -PHPKW(__FUNCTION__); -PHPKW(__METHOD__); -PHPKW(__NAMESPACE__); // As of PHP5.3 -PHPKW(__LINE__); +PHPKW(yield); // As of PHP 5.5 + +// Compile-time "magic" constants +// From: http://php.net/manual/en/reserved.keywords.php +// also at: http://php.net/manual/en/language.constants.predefined.php +/* These *MUST* be listed in lower case here */ +PHPKW(__class__); +PHPKW(__dir__); // As of PHP 5.3 +PHPKW(__file__); +PHPKW(__function__); +PHPKW(__line__); +PHPKW(__method__); +PHPKW(__namespace__); // As of PHP 5.3 +PHPKW(__trait__); // As of PHP 5.4 /* We classify these as built-in names since they conflict, but PHP still runs */ -/* Type 1: case insensitive */ -PHPBN1(__sleep); -PHPBN1(__wakeup); -PHPBN1(not); -PHPBN1(parent); -PHPBN1(virtual); -PHPBN1(NULL); -PHPBN1(TRUE); -PHPBN1(FALSE); +/* Predefined case-insensitive constants */ +/* These *MUST* be listed in lower case here */ +PHPBN1(null); +PHPBN1(true); +PHPBN1(false); -/* Type 2: case sensitive */ -/* "Core Predefined Constants" from http://uk2.php.net/manual/en/reserved.constants.php */ -PHPBN2(E_ALL); +/* "Core Predefined Constants" from http://php.net/manual/en/reserved.constants.php */ +/* These are case sensitive */ +PHPBN2(PHP_VERSION); +PHPBN2(PHP_MAJOR_VERSION); // As of PHP 5.2.7 +PHPBN2(PHP_MINOR_VERSION); // As of PHP 5.2.7 +PHPBN2(PHP_RELEASE_VERSION); // As of PHP 5.2.7 +PHPBN2(PHP_VERSION_ID); // As of PHP 5.2.7 +PHPBN2(PHP_EXTRA_VERSION); // As of PHP 5.2.7 +PHPBN2(PHP_ZTS); // As of PHP 5.2.7 +PHPBN2(PHP_DEBUG); // As of PHP 5.2.7 +PHPBN2(PHP_MAXPATHLEN); // As of PHP 5.3.0 +PHPBN2(PHP_OS); +PHPBN2(PHP_SAPI); +PHPBN2(PHP_EOL); // As of PHP 5.0.2 +PHPBN2(PHP_INT_MAX); // As of PHP 5.0.5 +PHPBN2(PHP_INT_SIZE); // As of PHP 5.0.5 +PHPBN2(DEFAULT_INCLUDE_PATH); +PHPBN2(PEAR_INSTALL_DIR); +PHPBN2(PEAR_EXTENSION_DIR); +PHPBN2(PHP_EXTENSION_DIR); +PHPBN2(PHP_PREFIX); +PHPBN2(PHP_BINDIR); +PHPBN2(PHP_BINARY); // As of PHP 5.4 +PHPBN2(PHP_MANDIR); // As of PHP 5.3.7 +PHPBN2(PHP_LIBDIR); +PHPBN2(PHP_DATADIR); +PHPBN2(PHP_SYSCONFDIR); +PHPBN2(PHP_LOCALSTATEDIR); +PHPBN2(PHP_CONFIG_FILE_PATH); +PHPBN2(PHP_CONFIG_FILE_SCAN_DIR); +PHPBN2(PHP_SHLIB_SUFFIX); PHPBN2(E_ERROR); -PHPBN2(E_PARSE); PHPBN2(E_WARNING); +PHPBN2(E_PARSE); PHPBN2(E_NOTICE); PHPBN2(E_CORE_ERROR); PHPBN2(E_CORE_WARNING); @@ -124,31 +161,17 @@ PHPBN2(E_COMPILE_WARNING); PHPBN2(E_USER_ERROR); PHPBN2(E_USER_WARNING); PHPBN2(E_USER_NOTICE); -PHPBN2(E_DEPRECATED); // As of PHP 5.3 -PHPBN2(E_USER_DEPRECATED); // As of PHP 5.3 -PHPBN2(PHP_OS); -PHPBN2(PHP_VERSION); -PHPBN2(PHP_SAPI); -PHPBN2(PHP_EOL); -PHPBN2(PHP_INT_MAX); -PHPBN2(PHP_INT_SIZE); -PHPBN2(DEFAULT_INCLUDE_PATH); -PHPBN2(PEAR_INSTALL_DIR); -PHPBN2(PEAR_EXTENSION_DIR); -PHPBN2(PHP_EXTENSION_DIR); -PHPBN2(PHP_PREFIX); -PHPBN2(PHP_BINDIR); -PHPBN2(PHP_LIBDIR); -PHPBN2(PHP_DATADIR); -PHPBN2(PHP_SYSCONFDIR); -PHPBN2(PHP_LOCALSTATEDIR); -PHPBN2(PHP_CONFIG_FILE_PATH); -PHPBN2(PHP_CONFIG_FILE_SCAN_DIR); -PHPBN2(PHP_SHLIB_SUFFIX); +PHPBN2(E_DEPRECATED); // As of PHP 5.3.0 +PHPBN2(E_USER_DEPRECATED); // As of PHP 5.3.0 +PHPBN2(E_ALL); +PHPBN2(E_STRICT); +PHPBN2(__COMPILER_HALT_OFFSET__); // As of PHP 5.1.0 +// TRUE, FALSE, NULL are listed on the same page, but are actually +// case-insensitive, whereas all the other constants listed there seem to be +// case-sensitive, so we handle TRUE, FALSE, NULL in PHPBN1. PHPBN2(PHP_OUTPUT_HANDLER_START); PHPBN2(PHP_OUTPUT_HANDLER_CONT); PHPBN2(PHP_OUTPUT_HANDLER_END); -PHPBN2(PHP_MAXPATHLEN); // As of PHP 5.3 /* These don't actually seem to be set (tested on Linux, I guess they're * Windows only?) */ PHPBN2(PHP_WINDOWS_NT_DOMAIN_CONTROLLER); // As of PHP 5.3 @@ -162,7 +185,7 @@ PHPBN2(PHP_WINDOWS_VERSION_PRODUCTTYPE); // As of PHP 5.3 PHPBN2(PHP_WINDOWS_VERSION_SP_MAJOR); // As of PHP 5.3 PHPBN2(PHP_WINDOWS_VERSION_SP_MINOR); // As of PHP 5.3 PHPBN2(PHP_WINDOWS_VERSION_SUITEMASK); // As of PHP 5.3 -/* "Standard Predefined Constants" from http://uk2.php.net/manual/en/reserved.constants.php */ +/* "Standard Predefined Constants" from http://php.net/manual/en/reserved.constants.php */ PHPBN2(EXTR_OVERWRITE); PHPBN2(EXTR_SKIP); PHPBN2(EXTR_PREFIX_SAME); @@ -370,10 +393,6 @@ PHPBN2(LOG_NDELAY); PHPBN2(LOG_NOWAIT); PHPBN2(LOG_PERROR); -/* Added in PHP5 */ -PHPBN2(E_STRICT); -PHPBN2(__COMPILER_HALT_OFFSET__); - /* Added in PHP 5.2 */ PHPBN2(PREG_BACKTRACK_LIMIT_ERROR); PHPBN2(PREG_BAD_UTF8_ERROR); @@ -485,17 +504,143 @@ PHPBN2(SIG_UNBLOCK); PHPBN2(TRAP_BRKPT); PHPBN2(TRAP_TRACE); -/* Class names reserved by PHP */ -/* case insensitive */ +/* Added in PHP 5.4 */ +PHPBN2(ENT_DISALLOWED); +PHPBN2(ENT_HTML401); +PHPBN2(ENT_HTML5); +PHPBN2(ENT_SUBSTITUTE); +PHPBN2(ENT_XML1); +PHPBN2(ENT_XHTML); +PHPBN2(IPPROTO_IP); +PHPBN2(IPPROTO_IPV6); +PHPBN2(IPV6_MULTICAST_HOPS); +PHPBN2(IPV6_MULTICAST_IF); +PHPBN2(IPV6_MULTICAST_LOOP); +PHPBN2(IP_MULTICAST_IF); +PHPBN2(IP_MULTICAST_LOOP); +PHPBN2(IP_MULTICAST_TTL); +PHPBN2(MCAST_JOIN_GROUP); +PHPBN2(MCAST_LEAVE_GROUP); +PHPBN2(MCAST_BLOCK_SOURCE); +PHPBN2(MCAST_UNBLOCK_SOURCE); +PHPBN2(MCAST_JOIN_SOURCE_GROUP); +PHPBN2(MCAST_LEAVE_SOURCE_GROUP); +PHPBN2(CURLOPT_MAX_RECV_SPEED_LARGE); +PHPBN2(CURLOPT_MAX_SEND_SPEED_LARGE); +PHPBN2(LIBXML_HTML_NODEFDTD); +PHPBN2(LIBXML_HTML_NOIMPLIED); +PHPBN2(LIBXML_PEDANTIC); +PHPBN2(OPENSSL_CIPHER_AES_128_CBC); +PHPBN2(OPENSSL_CIPHER_AES_192_CBC); +PHPBN2(OPENSSL_CIPHER_AES_256_CBC); +PHPBN2(OPENSSL_RAW_DATA); +PHPBN2(OPENSSL_ZERO_PADDING); +PHPBN2(PHP_OUTPUT_HANDLER_CLEAN); +PHPBN2(PHP_OUTPUT_HANDLER_CLEANABLE); +PHPBN2(PHP_OUTPUT_HANDLER_DISABLED); +PHPBN2(PHP_OUTPUT_HANDLER_FINAL); +PHPBN2(PHP_OUTPUT_HANDLER_FLUSH); +PHPBN2(PHP_OUTPUT_HANDLER_FLUSHABLE); +PHPBN2(PHP_OUTPUT_HANDLER_REMOVABLE); +PHPBN2(PHP_OUTPUT_HANDLER_STARTED); +PHPBN2(PHP_OUTPUT_HANDLER_STDFLAGS); +PHPBN2(PHP_OUTPUT_HANDLER_WRITE); +PHPBN2(PHP_SESSION_ACTIVE); +PHPBN2(PHP_SESSION_DISABLED); +PHPBN2(PHP_SESSION_NONE); +PHPBN2(STREAM_META_ACCESS); +PHPBN2(STREAM_META_GROUP); +PHPBN2(STREAM_META_GROUP_NAME); +PHPBN2(STREAM_META_OWNER); +PHPBN2(STREAM_META_OWNER_NAME); +PHPBN2(STREAM_META_TOUCH); +PHPBN2(ZLIB_ENCODING_DEFLATE); +PHPBN2(ZLIB_ENCODING_GZIP); +PHPBN2(ZLIB_ENCODING_RAW); +PHPBN2(U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR); +PHPBN2(IDNA_CHECK_BIDI); +PHPBN2(IDNA_CHECK_CONTEXTJ); +PHPBN2(IDNA_NONTRANSITIONAL_TO_ASCII); +PHPBN2(IDNA_NONTRANSITIONAL_TO_UNICODE); +PHPBN2(INTL_IDNA_VARIANT_2003); +PHPBN2(INTL_IDNA_VARIANT_UTS46); +PHPBN2(IDNA_ERROR_EMPTY_LABEL); +PHPBN2(IDNA_ERROR_LABEL_TOO_LONG); +PHPBN2(IDNA_ERROR_DOMAIN_NAME_TOO_LONG); +PHPBN2(IDNA_ERROR_LEADING_HYPHEN); +PHPBN2(IDNA_ERROR_TRAILING_HYPHEN); +PHPBN2(IDNA_ERROR_HYPHEN_3_4); +PHPBN2(IDNA_ERROR_LEADING_COMBINING_MARK); +PHPBN2(IDNA_ERROR_DISALLOWED); +PHPBN2(IDNA_ERROR_PUNYCODE); +PHPBN2(IDNA_ERROR_LABEL_HAS_DOT); +PHPBN2(IDNA_ERROR_INVALID_ACE_LABEL); +PHPBN2(IDNA_ERROR_BIDI); +PHPBN2(IDNA_ERROR_CONTEXTJ); +PHPBN2(JSON_PRETTY_PRINT); +PHPBN2(JSON_UNESCAPED_SLASHES); +PHPBN2(JSON_NUMERIC_CHECK); +PHPBN2(JSON_UNESCAPED_UNICODE); +PHPBN2(JSON_BIGINT_AS_STRING); + +/* Added in PHP 5.5 */ +PHPBN2(IMG_AFFINE_TRANSLATE); +PHPBN2(IMG_AFFINE_SCALE); +PHPBN2(IMG_AFFINE_ROTATE); +PHPBN2(IMG_AFFINE_SHEAR_HORIZONTAL); +PHPBN2(IMG_AFFINE_SHEAR_VERTICAL); +PHPBN2(IMG_CROP_DEFAULT); +PHPBN2(IMG_CROP_TRANSPARENT); +PHPBN2(IMG_CROP_BLACK); +PHPBN2(IMG_CROP_WHITE); +PHPBN2(IMG_CROP_SIDES); +PHPBN2(IMG_FLIP_BOTH); +PHPBN2(IMG_FLIP_HORIZONTAL); +PHPBN2(IMG_FLIP_VERTICAL); +PHPBN2(IMG_BELL); +PHPBN2(IMG_BESSEL); +PHPBN2(IMG_BICUBIC); +PHPBN2(IMG_BICUBIC_FIXED); +PHPBN2(IMG_BLACKMAN); +PHPBN2(IMG_BOX); +PHPBN2(IMG_BSPLINE); +PHPBN2(IMG_CATMULLROM); +PHPBN2(IMG_GAUSSIAN); +PHPBN2(IMG_GENERALIZED_CUBIC); +PHPBN2(IMG_HERMITE); +PHPBN2(IMG_HAMMING); +PHPBN2(IMG_HANNING); +PHPBN2(IMG_MITCHELL); +PHPBN2(IMG_POWER); +PHPBN2(IMG_QUADRATIC); +PHPBN2(IMG_SINC); +PHPBN2(IMG_NEAREST_NEIGHBOUR); +PHPBN2(IMG_WEIGHTED4); +PHPBN2(IMG_TRIANGLE); +PHPBN2(JSON_ERROR_RECURSION); +PHPBN2(JSON_ERROR_INF_OR_NAN); +PHPBN2(JSON_ERROR_UNSUPPORTED_TYPE); +PHPBN2(MYSQLI_SERVER_PUBLIC_KEY); + +/* Added in PHP 5.6 */ +PHPBN2(LDAP_ESCAPE_DN); +PHPBN2(LDAP_ESCAPE_FILTER); + +/* Class names reserved by PHP (case insensitive) */ +PHPCN(directory); PHPCN(stdclass); PHPCN(__php_incomplete_class); -PHPCN(directory); -/* Added in PHP5 (this list apparently depends which extensions you load by default). */ -PHPCN(parent); -PHPCN(self); +/* Added in PHP5. */ PHPCN(exception); +PHPCN(errorexception); // As of PHP 5.1 PHPCN(php_user_filter); -PHPCN(errorexception); +PHPCN(closure); // As of PHP 5.3 +PHPCN(generator); // As of PHP 5.5 +PHPCN(self); +PHPCN(static); +PHPCN(parent); +/* From extensions (which of these are actually predefined depends which + * extensions are loaded by default). */ PHPCN(xmlwriter); PHPCN(libxmlerror); PHPCN(simplexmlelement); @@ -588,7 +733,8 @@ PHPCN(sqliteexception); PHPCN(datetime); /* Built-in PHP functions (incomplete). */ -/* Includes Array Functions - http://us3.php.net/manual/en/ref.array.php */ +/* Includes Array Functions - http://php.net/manual/en/ref.array.php */ +/* Check is case insensitive - these *MUST* be listed in lower case here */ PHPFN(acos); PHPFN(array_change_key_case); PHPFN(array_chunk); @@ -688,7 +834,11 @@ PHPFN(uksort); PHPFN(usort); #undef PHPKW +#undef PHPBN1a +#undef PHPBN1b #undef PHPBN1 +#undef PHPBN2a +#undef PHPBN2b #undef PHPBN2 #undef PHPCN #undef PHPFN From 1aa6220041567e4260b60cde3238be3e3228dfac Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Wed, 19 Feb 2014 17:22:28 +1300 Subject: [PATCH 382/481] Fix incorrect patch number --- CHANGES.current | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGES.current b/CHANGES.current index 58efd5e5d..9f6d40689 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -24,7 +24,7 @@ Version 3.0.0 (in progress) *** POTENTIAL INCOMPATIBILITY *** 2014-02-16: hfalcic - [Python] Patch #133 - fix crashes/exceptions in exception handling in Python 3.3 + [Python] Patch #137 - fix crashes/exceptions in exception handling in Python 3.3 2014-02-15: wsfulton [Java] Add support for the cdata library. From ae14ad0c4ab934379dc035b5aa763ea6adc1157b Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Wed, 19 Feb 2014 18:26:07 +1300 Subject: [PATCH 383/481] Rename "struct Global" to "struct Global_" to avoid PHP keyword --- Examples/test-suite/nested_scope.i | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Examples/test-suite/nested_scope.i b/Examples/test-suite/nested_scope.i index 08871f182..789478361 100644 --- a/Examples/test-suite/nested_scope.i +++ b/Examples/test-suite/nested_scope.i @@ -6,7 +6,8 @@ %inline %{ namespace ns { - struct Global { + // "global" is a case-insensitive keyword in PHP. + struct Global_ { #ifdef __clang__ struct Outer { struct Nested; From 6d08992945cc5c34698330c7b17659fae2592b12 Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Wed, 19 Feb 2014 18:26:40 +1300 Subject: [PATCH 384/481] Add expected functions which get generated to silence testsuite warning --- Examples/test-suite/php/director_protected_runme.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Examples/test-suite/php/director_protected_runme.php b/Examples/test-suite/php/director_protected_runme.php index 9d47ef658..226f28a0b 100644 --- a/Examples/test-suite/php/director_protected_runme.php +++ b/Examples/test-suite/php/director_protected_runme.php @@ -4,7 +4,7 @@ require "tests.php"; require "director_protected.php"; // No new functions -check::functions(array(foo_pong,foo_s,foo_q,foo_ping,foo_pang,foo_used,bar_create,bar_pong,bar_used,bar_ping,bar_pang,a_draw,b_draw)); +check::functions(array(foo_pong,foo_s,foo_q,foo_ping,foo_pang,foo_used,foo_cheer,bar_create,bar_callping,bar_callcheer,bar_cheer,bar_pong,bar_used,bar_ping,bar_pang,a_draw,b_draw)); // No new classes check::classes(array(Foo,Bar,PrivateFoo,A,B,AA,BB)); // now new vars From 7df6c832c3370ce51c16b8c37e06ee80a961da0d Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Wed, 19 Feb 2014 18:27:14 +1300 Subject: [PATCH 385/481] Remove incorrect comments --- Examples/test-suite/php/director_protected_runme.php | 3 --- 1 file changed, 3 deletions(-) diff --git a/Examples/test-suite/php/director_protected_runme.php b/Examples/test-suite/php/director_protected_runme.php index 226f28a0b..18586ca62 100644 --- a/Examples/test-suite/php/director_protected_runme.php +++ b/Examples/test-suite/php/director_protected_runme.php @@ -3,11 +3,8 @@ require "tests.php"; require "director_protected.php"; -// No new functions check::functions(array(foo_pong,foo_s,foo_q,foo_ping,foo_pang,foo_used,foo_cheer,bar_create,bar_callping,bar_callcheer,bar_cheer,bar_pong,bar_used,bar_ping,bar_pang,a_draw,b_draw)); -// No new classes check::classes(array(Foo,Bar,PrivateFoo,A,B,AA,BB)); -// now new vars check::globals(array(bar_a)); class FooBar extends Bar { From 5b957278a8500e9dfadbb9d1ebc7bf33f5b7c5f5 Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Wed, 19 Feb 2014 22:07:26 +1300 Subject: [PATCH 386/481] -Wallkw now includes keywords for all languages with keyword warnings (previously Go and R were missing). --- CHANGES.current | 4 ++++ Lib/allkw.swg | 6 ++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index 9f6d40689..6595c248e 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,10 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2014-02-19: olly + -Wallkw now includes keywords for all languages with keyword + warnings (previously Go and R were missing). + 2014-02-19: olly [PHP] Update the lists of PHP keywords with new ones from PHP 5.4 and newer (and some missing ones from 5.3). Reserved PHP constants diff --git a/Lib/allkw.swg b/Lib/allkw.swg index b85b64579..99c2969e4 100644 --- a/Lib/allkw.swg +++ b/Lib/allkw.swg @@ -19,14 +19,16 @@ %include %include %include +%include %include +%include +%include %include %include %include -%include +%include %include %include -%include #endif //__Lib_allkw_swg__ From 91461647486b79b055e11b4a15b75e90a0783da1 Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Wed, 19 Feb 2014 22:09:39 +1300 Subject: [PATCH 387/481] Extend php_namewarn_rename to act as a regression test for the warning about built-in function names used in %extend --- Examples/test-suite/php_namewarn_rename.i | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Examples/test-suite/php_namewarn_rename.i b/Examples/test-suite/php_namewarn_rename.i index e3447a9c4..de8a62501 100644 --- a/Examples/test-suite/php_namewarn_rename.i +++ b/Examples/test-suite/php_namewarn_rename.i @@ -7,6 +7,11 @@ %warnfilter(SWIGWARN_PARSE_KEYWORD) Hello::empty(); #endif +%ignore prev::operator++; +%extend prev { + void next() { ++(*self); } +} + %inline %{ int Exception() { return 13; } @@ -26,4 +31,9 @@ void empty() {} }; + struct prev { + prev & operator++() { } + prev operator++(int) { } + }; + %} From 1c5a0f8b9cb3f413df92a87fbb4d65895b954434 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Mon, 28 Oct 2013 13:18:15 +0400 Subject: [PATCH 388/481] Initial implementation - everything compiles but might not work --- Examples/test-suite/nspace.i | 2 +- Lib/lua/luarun.swg | 78 +++- Lib/lua/luaruntime.swg | 23 +- Source/Modules/lang.cxx | 8 + Source/Modules/lua.cxx | 720 ++++++++++++++++++++++++++++------- Source/Modules/swigmod.h | 1 + 6 files changed, 655 insertions(+), 177 deletions(-) diff --git a/Examples/test-suite/nspace.i b/Examples/test-suite/nspace.i index c60a45df5..58c560412 100644 --- a/Examples/test-suite/nspace.i +++ b/Examples/test-suite/nspace.i @@ -2,7 +2,7 @@ %module nspace // nspace feature only supported by these languages -#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGD) +#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGD) || defined(SWIGLUA) #if defined(SWIGJAVA) SWIG_JAVABODY_PROXY(public, public, SWIGTYPE) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index 8485ed499..04d18fdb7 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -129,10 +129,13 @@ typedef struct { swig_type_info **ptype; } swig_lua_const_info; +/* TODO:REMOVE typedef struct { const char *name; lua_CFunction method; } swig_lua_method; +*/ +typedef luaL_Reg swig_lua_method; typedef struct { const char *name; @@ -140,16 +143,20 @@ typedef struct { lua_CFunction setmethod; } swig_lua_attribute; + +struct swig_lua_class; // Can be used to create namespaces. Currently used to // wrap class static methods/variables/constants -typedef struct { +struct swig_lua_namespace { const char *name; swig_lua_method *ns_methods; swig_lua_attribute *ns_attributes; swig_lua_const_info *ns_constants; -} swig_lua_namespace; + swig_lua_class **ns_classes; + swig_lua_namespace **ns_namespaces; +}; -typedef struct swig_lua_class { +struct swig_lua_class { const char *name; swig_type_info **type; lua_CFunction constructor; @@ -159,7 +166,7 @@ typedef struct swig_lua_class { swig_lua_namespace cls_static; struct swig_lua_class **bases; const char **base_names; -} swig_lua_class; +}; /* this is the struct for wrapping all pointers in SwigLua */ @@ -497,28 +504,29 @@ SWIGINTERN int SWIG_Lua_namespace_set(lua_State* L) } SWIGINTERN void SWIG_Lua_InstallConstants(lua_State* L, swig_lua_const_info constants[]); // forward declaration -SWIGINTERN void SWIG_Lua_add_class_variable(lua_State* L,const char* name,lua_CFunction getFn,lua_CFunction setFn); // forward declaration +SWIGINTERN void SWIG_Lua_add_variable(lua_State* L,const char* name,lua_CFunction getFn,lua_CFunction setFn); // forward declaration +SWIGINTERN void SWIG_Lua_class_register(lua_State* L,swig_lua_class* clss); /* helper function - register namespace methods and attributes into namespace */ SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State* L, swig_lua_namespace* ns) { int i = 0; - assert(lua_istable(L,-1)); /* There must be table at the top of the stack */ + assert(lua_istable(L,-1)); SWIG_Lua_InstallConstants(L, ns->ns_constants); lua_getmetatable(L,-1); /* add fns */ for(i=0;ns->ns_attributes[i].name;i++){ - SWIG_Lua_add_class_variable(L,ns->ns_attributes[i].name,ns->ns_attributes[i].getmethod,ns->ns_attributes[i].setmethod); + SWIG_Lua_add_variable(L,ns->ns_attributes[i].name,ns->ns_attributes[i].getmethod,ns->ns_attributes[i].setmethod); } /* add methods to the metatable */ SWIG_Lua_get_table(L,".fn"); /* find the .fn table */ assert(lua_istable(L,-1)); /* just in case */ for(i=0;ns->ns_methods[i].name;i++){ - SWIG_Lua_add_function(L,ns->ns_methods[i].name,ns->ns_methods[i].method); + SWIG_Lua_add_function(L,ns->ns_methods[i].name,ns->ns_methods[i].func); } lua_pop(L,1); @@ -527,12 +535,29 @@ SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State* L, swig_lua_namespace* return 0; } -/* helper function. creates namespace table and add it to module table */ -SWIGINTERN int SWIG_Lua_namespace_register(lua_State* L, swig_lua_namespace* ns) +/* Register all classes in the namespace + */ +SWIGINTERN void SWIG_Lua_add_namespace_classes(lua_State* L, swig_lua_namespace* ns) { - assert(lua_istable(L,-1)); /* just in case. This is supposed to be module table */ + swig_lua_class** classes = ns->ns_classes; + + if( classes != 0 ) { + while((*classes)->name != 0) { + SWIG_Lua_class_register(L, *classes); + classes++; + } + } +} + +/* helper function. creates namespace table and add it to module table + if 'reg' is true, then will register namespace table to parent one (must be on top of the stack + when function is called) + Function always returns newly registered table on top of the stack +*/ +SWIGINTERN int SWIG_Lua_namespace_register(lua_State* L, swig_lua_namespace* ns, bool reg) +{ + assert(lua_istable(L,-1)); /* just in case. This is supposed to be module table or parent namespace table */ lua_checkstack(L,5); - lua_pushstring(L, ns->name); lua_newtable(L); /* namespace itself */ lua_newtable(L); /* metatable for namespace */ @@ -554,8 +579,23 @@ SWIGINTERN int SWIG_Lua_namespace_register(lua_State* L, swig_lua_namespace* ns) SWIG_Lua_add_function(L,"__newindex",SWIG_Lua_namespace_set); lua_setmetatable(L,-2); /* set metatable */ - lua_rawset(L,-3); /* add namespace to module table */ - return 0; + + // Register all functions, variables etc + SWIG_Lua_add_namespace_details(L,ns); + + swig_lua_namespace** sub_namespace = ns->ns_namespaces; + if( sub_namespace != 0) { + while((*sub_namespace)->name != 0) { + SWIG_Lua_namespace_register(L, *sub_namespace, true); + sub_namespace++; + } + } + + if (reg) { + lua_pushstring(L,ns->name); + lua_pushvalue(L,-2); + lua_rawset(L,-4); /* add namespace to module table */ + } } /* ----------------------------------------------------------------------------- * global variable support code: classes @@ -757,7 +797,7 @@ SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State* L,const char* cname) } /* helper add a variable to a registered class */ -SWIGINTERN void SWIG_Lua_add_class_variable(lua_State* L,const char* name,lua_CFunction getFn,lua_CFunction setFn) +SWIGINTERN void SWIG_Lua_add_variable(lua_State* L,const char* name,lua_CFunction getFn,lua_CFunction setFn) { assert(lua_istable(L,-1)); /* just in case */ SWIG_Lua_get_table(L,".get"); /* find the .get table */ @@ -799,13 +839,13 @@ SWIGINTERN void SWIG_Lua_add_class_details(lua_State* L,swig_lua_class* clss) } /* add fns */ for(i=0;clss->attributes[i].name;i++){ - SWIG_Lua_add_class_variable(L,clss->attributes[i].name,clss->attributes[i].getmethod,clss->attributes[i].setmethod); + SWIG_Lua_add_variable(L,clss->attributes[i].name,clss->attributes[i].getmethod,clss->attributes[i].setmethod); } /* add methods to the metatable */ SWIG_Lua_get_table(L,".fn"); /* find the .fn table */ assert(lua_istable(L,-1)); /* just in case */ for(i=0;clss->methods[i].name;i++){ - SWIG_Lua_add_function(L,clss->methods[i].name,clss->methods[i].method); + SWIG_Lua_add_function(L,clss->methods[i].name,clss->methods[i].func); } lua_pop(L,1); /* tidy stack (remove table) */ /* add operator overloads @@ -814,7 +854,7 @@ SWIGINTERN void SWIG_Lua_add_class_details(lua_State* L,swig_lua_class* clss) (this might mess up is someone defines a method __gc (the destructor)*/ for(i=0;clss->methods[i].name;i++){ if (clss->methods[i].name[0]=='_' && clss->methods[i].name[1]=='_'){ - SWIG_Lua_add_function(L,clss->methods[i].name,clss->methods[i].method); + SWIG_Lua_add_function(L,clss->methods[i].name,clss->methods[i].func); } } } @@ -848,7 +888,7 @@ SWIGINTERN void SWIG_Lua_class_register_static(lua_State* L, swig_lua_class* cls assert(lua_istable(L,-1)); /* just in case */ assert(strcmp(clss->name, clss->cls_static.name) == 0); /* in class those 2 must be equal */ - SWIG_Lua_namespace_register(L,&clss->cls_static); + SWIG_Lua_namespace_register(L,&clss->cls_static, false); SWIG_Lua_get_table(L,clss->name); // Get namespace table back assert(lua_istable(L,-1)); /* just in case */ diff --git a/Lib/lua/luaruntime.swg b/Lib/lua/luaruntime.swg index 423c7190b..0011c9d52 100644 --- a/Lib/lua/luaruntime.swg +++ b/Lib/lua/luaruntime.swg @@ -40,16 +40,6 @@ SWIGEXPORT int SWIG_init(lua_State* L) /* default Lua action */ /* add a global fn */ SWIG_Lua_add_function(L,"swig_type",SWIG_Lua_type); SWIG_Lua_add_function(L,"swig_equals",SWIG_Lua_equal); - /* begin the module (its a table with the same name as the module) */ - SWIG_Lua_module_begin(L,SWIG_name); - /* add commands/functions */ - for (i = 0; swig_commands[i].name; i++){ - SWIG_Lua_module_add_function(L,swig_commands[i].name,swig_commands[i].func); - } - /* add variables */ - for (i = 0; swig_variables[i].name; i++){ - SWIG_Lua_module_add_variable(L,swig_variables[i].name,swig_variables[i].get,swig_variables[i].set); - } #endif #if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC) @@ -59,17 +49,16 @@ SWIGEXPORT int SWIG_init(lua_State* L) /* default Lua action */ SWIG_Lua_init_base_class(L,(swig_lua_class*)(swig_types[i]->clientdata)); } } - /* additional registration structs & classes in lua */ - for (i = 0; swig_types[i]; i++){ - if (swig_types[i]->clientdata){ - SWIG_Lua_class_register(L,(swig_lua_class*)(swig_types[i]->clientdata)); - } - } + bool globalRegister = false; +#ifdef SWIG_LUA_MODULE_GLOBAL + globalRegister = true; +#endif + SWIG_Lua_namespace_register(L,&swig___Global, globalRegister); #endif #if ((SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUA) && (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC)) /* constants */ - SWIG_Lua_InstallConstants(L,swig_constants); + /* TODO: REMOVE */ #endif #if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC) diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 3940a3001..97ed295c9 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -3049,6 +3049,7 @@ void Language::main(int argc, char *argv[]) { * ----------------------------------------------------------------------------- */ int Language::addSymbol(const String *s, const Node *n, const_String_or_char_ptr scope) { + //Printf( stdout, "addSymbol: %s %s\n", s, scope ); Hash *symbols = Getattr(symtabs, scope ? scope : ""); if (!symbols) { // New scope which has not been added by the target language - lazily created. @@ -3468,6 +3469,13 @@ String *Language::getNSpace() const { return NSpace; } +/* ----------------------------------------------------------------------------- + * Language::setNSpace() + * ----------------------------------------------------------------------------- */ +void Language::setNSpace(String *nspace) { + NSpace = nspace; +} + /* ----------------------------------------------------------------------------- * Language::getClassName() * ----------------------------------------------------------------------------- */ diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index b76945b95..10d9592cd 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -105,25 +105,27 @@ private: File *f_runtime; File *f_header; File *f_wrappers; + File *f_wrappersForward; // forward declarations for wrappers, TODO: REMOVE File *f_init; File *f_initbeforefunc; - String *s_cmd_tab; // table of command names - String *s_var_tab; // table of global variables - String *s_const_tab; // table of global constants + /* + String *s_ns_methods_tab; // table of namespace methods + String *s_ns_var_tab; // Lua only:table of namespace variables + String *s_ns_dot_get; // eLua only:table of variable 'get' functions + String *s_ns_dot_set; // eLua only:table of variable 'set' functions + String *s_ns_const_tab; // table of namespace constants + */ String *s_methods_tab; // table of class methods String *s_attr_tab; // table of class attributes - String *s_cls_attr_tab; // table of class static attributes - String *s_cls_methods_tab; // table of class static methods - String *s_cls_const_tab; // tables of class constants(including enums) String *s_luacode; // luacode to be called during init - String *s_dot_get; // table of variable 'get' functions - String *s_dot_set; // table of variable 'set' functions - String *s_vars_meta_tab; // metatable for variables + String *module; //name of the module + //String *s_vars_meta_tab; // metatable for variables + Hash* namespaces_hash; int have_constructor; int have_destructor; String *destructor_action; - String *class_name; + String *class_symname; String *constructor_name; enum { @@ -151,26 +153,35 @@ public: f_runtime(0), f_header(0), f_wrappers(0), + f_wrappersForward(0), f_init(0), f_initbeforefunc(0), + /* s_cmd_tab(0), s_var_tab(0), s_const_tab(0), - s_methods_tab(0), - s_attr_tab(0), s_cls_attr_tab(0), s_cls_methods_tab(0), s_cls_const_tab(0), + */ + s_methods_tab(0), + s_attr_tab(0), s_luacode(0), - s_dot_get(0), - s_dot_set(0), - s_vars_meta_tab(0), + module(0), + //s_dot_get(0), + //s_dot_set(0), + //s_vars_meta_tab(0), have_constructor(0), have_destructor(0), destructor_action(0), - class_name(0), + class_symname(0), constructor_name(0), current(NO_CPP) { + namespaces_hash = NewHash(); + } + ~LUA() { + if(namespaces_hash) + Delete(namespaces_hash); } /* NEW LANGUAGE NOTE:*********************************************** @@ -246,7 +257,7 @@ public: virtual int top(Node *n) { /* Get the module name */ - String *module = Getattr(n, "name"); + module = Getattr(n, "name"); /* Get the output file name */ String *outfile = Getattr(n, "outfile"); @@ -260,6 +271,7 @@ public: f_runtime = NewString(""); f_init = NewString(""); f_header = NewString(""); + f_wrappersForward = NewString(""); f_wrappers = NewString(""); f_initbeforefunc = NewString(""); @@ -279,6 +291,8 @@ public: just before it is written to file NEW LANGUAGE NOTE:END ************************************************/ // Initialize some variables for the object interface + // TODO: Replace with call to getNamespaceHash(0) + /* s_cmd_tab = NewString(""); s_var_tab = NewString(""); // s_methods_tab = NewString(""); @@ -287,6 +301,7 @@ public: s_dot_get = NewString(""); s_dot_set = NewString(""); s_vars_meta_tab = NewString(""); + */ s_luacode = NewString(""); Swig_register_filebyname("luacode", s_luacode); @@ -323,28 +338,34 @@ public: Printf(f_header, "#define SWIG_init_user luaopen_%s_user\n\n", module); Printf(f_header, "#define SWIG_LUACODE luaopen_%s_luacode\n", module); + /* if (elua_ltr || eluac_ltr) Printf(f_header, "#define swig_commands %s_map\n\n", module); + */ if (elua_ltr || eluac_ltr) { - Printf(s_cmd_tab, "\n#define MIN_OPT_LEVEL 2\n#include \"lrodefs.h\"\n"); - Printf(s_cmd_tab, "#include \"lrotable.h\"\n"); - Printf(s_cmd_tab, "\nconst LUA_REG_TYPE swig_constants[];\n"); - if (elua_ltr) - Printf(s_cmd_tab, "const LUA_REG_TYPE mt[];\n"); + Printf(f_header, "\n#define MIN_OPT_LEVEL 2\n#include \"lrodefs.h\"\n"); + Printf(f_header, "#include \"lrotable.h\"\n"); + //Printf(s_cmd_tab, "\nconst LUA_REG_TYPE swig_constants[];\n"); + /*if (elua_ltr) + Printf(s_cmd_tab, "const LUA_REG_TYPE mt[];\n");*/ - Printf(s_cmd_tab, "\nconst LUA_REG_TYPE swig_commands[] = {\n"); - Printf(s_const_tab, "\nconst LUA_REG_TYPE swig_constants[] = {\n"); + //Printf(s_cmd_tab, "\nconst LUA_REG_TYPE swig_commands[] = {\n"); + //Printf(s_const_tab, "\nconst LUA_REG_TYPE swig_constants[] = {\n"); Printf(f_wrappers, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n"); - if (elua_ltr) { + Printf(f_wrappersForward, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n"); + /*if (elua_ltr) { Printf(s_dot_get, "\nconst LUA_REG_TYPE dot_get[] = {\n"); Printf(s_dot_set, "\nconst LUA_REG_TYPE dot_set[] = {\n"); - } + }*/ } else { + /* Printf(s_cmd_tab, "\nstatic const struct luaL_Reg swig_commands[] = {\n"); Printf(s_var_tab, "\nstatic swig_lua_var_info swig_variables[] = {\n"); Printf(s_const_tab, "\nstatic swig_lua_const_info swig_constants[] = {\n"); + */ Printf(f_wrappers, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n"); + Printf(f_wrappersForward, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n"); } /* %init code inclusion, effectively in the SWIG_init function */ @@ -354,8 +375,10 @@ public: Printf(f_init, "}\n"); Printf(f_wrappers, "#ifdef __cplusplus\n}\n#endif\n"); + Printf(f_wrappersForward, "#ifdef __cplusplus\n}\n#endif\n"); // Done. Close up the module & write to the wrappers +#if 0 if (elua_ltr || eluac_ltr) { Printv(s_cmd_tab, tab4, "{LSTRKEY(\"const\"), LROVAL(swig_constants)},\n", NIL); if (elua_ltr) @@ -367,7 +390,9 @@ public: Printv(s_var_tab, tab4, "{0,0,0}\n", "};\n", NIL); Printv(s_const_tab, tab4, "{0,0,0,0,0,0}\n", "};\n", NIL); } +#endif +#if 0 if (elua_ltr) { /* Generate the metatable */ Printf(s_vars_meta_tab, "\nconst LUA_REG_TYPE mt[] = {\n"); @@ -380,13 +405,16 @@ public: Printv(s_dot_get, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); Printv(s_dot_set, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); } +#endif if (elua_ltr || eluac_ltr) { /* Final close up of wrappers */ - Printv(f_wrappers, s_cmd_tab, s_dot_get, s_dot_set, s_vars_meta_tab, s_var_tab, s_const_tab, NIL); + //Printv(f_wrappers, s_cmd_tab, s_dot_get, s_dot_set, s_vars_meta_tab, s_var_tab, s_const_tab, NIL); + closeNamespaces(f_wrappers, f_wrappersForward); SwigType_emit_type_table(f_runtime, f_wrappers); } else { - Printv(f_wrappers, s_cmd_tab, s_var_tab, s_const_tab, NIL); + //Printv(f_wrappers, s_cmd_tab, s_var_tab, s_const_tab, NIL); + closeNamespaces(f_wrappers, f_wrappersForward); SwigType_emit_type_table(f_runtime, f_wrappers); } @@ -396,6 +424,7 @@ public: NEW LANGUAGE NOTE:END ************************************************/ Dump(f_runtime, f_begin); Dump(f_header, f_begin); + Dump(f_wrappersForward, f_begin); Dump(f_wrappers, f_begin); Dump(f_initbeforefunc, f_begin); /* for the Lua code it needs to be properly excaped to be added into the C/C++ code */ @@ -404,18 +433,19 @@ public: Wrapper_pretty_print(f_init, f_begin); /* Close all of the files */ Delete(s_luacode); - Delete(s_cmd_tab); - Delete(s_var_tab); - Delete(s_const_tab); + //Delete(s_cmd_tab); + //Delete(s_var_tab); + //Delete(s_const_tab); Delete(f_header); Delete(f_wrappers); + Delete(f_wrappersForward); Delete(f_init); Delete(f_initbeforefunc); Delete(f_runtime); Delete(f_begin); - Delete(s_dot_get); - Delete(s_dot_set); - Delete(s_vars_meta_tab); + //Delete(s_dot_get); + //Delete(s_dot_set); + //Delete(s_vars_meta_tab); /* Done */ return SWIG_OK; @@ -461,7 +491,7 @@ public: if (Getattr(n, "sym:overloaded")) { overname = Getattr(n, "sym:overname"); } else { - if (!addSymbol(iname, n)) { + if (!addSymbol(iname, n, getNSpace())) { Printf(stderr,"addSymbol(%s) failed\n",iname); return SWIG_ERROR; } @@ -479,6 +509,12 @@ public: if (overname) { Append(wname, overname); } + if (current == CONSTRUCTOR) { + if( constructor_name != 0) + Delete(constructor_name); + constructor_name = Copy(wname); + } + //Printf(stdout , "Function wrapper, name %s\n", wname); // TODO:REMOVE /* NEW LANGUAGE NOTE:*********************************************** the format of a lua fn is: @@ -656,7 +692,15 @@ public: } } + // Remember C name of the wrapping function Setattr(n, "wrap:name", wname); + // If it is getter/setter, then write wname under + // wrap:memberset/wrap:memberget accordingly + if( Getattr(n, "memberset") ) + Setattr(n, "memberset:wrap:name", wname); + if( Getattr(n, "memberget") ) + Setattr(n, "memberget:wrap:name", wname); + /* Emit the function call */ String *actioncode = emit_action(n); @@ -746,14 +790,15 @@ public: //REPORT("dispatchFunction", n); // add_method(n, iname, wname, description); if (current==NO_CPP || current==STATIC_FUNC) { // emit normal fns & static fns - String *wrapname = Swig_name_wrapper(iname); + Hash* nspaceHash = getNamespaceHash( getNSpace() ); + String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); if(elua_ltr || eluac_ltr) - Printv(s_cmd_tab, tab4, "{LSTRKEY(\"", iname, "\")", ", LFUNCVAL(", Swig_name_wrapper(iname), ")", "},\n", NIL); + Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", iname, "\")", ", LFUNCVAL(", wname, ")", "},\n", NIL); else - Printv(s_cmd_tab, tab4, "{ \"", iname, "\", ", Swig_name_wrapper(iname), "},\n", NIL); + Printv(s_ns_methods_tab, tab4, "{ \"", iname, "\", ", wname, "},\n", NIL); // Printv(s_cmd_tab, tab4, "{ SWIG_prefix \"", iname, "\", (swig_wrapper_func) ", Swig_name_wrapper(iname), "},\n", NIL); if (getCurrentClass()) { - Setattr(n,"luaclassobj:wrap:name", wrapname); + Setattr(n,"luaclassobj:wrap:name", wname); } } } else { @@ -832,13 +877,24 @@ public: Printv(f->code, "}\n", NIL); Wrapper_print(f, f_wrappers); //add_method(symname,wname,0); - if (current==NO_CPP || current==STATIC_FUNC) // emit normal fns & static fns - Printv(s_cmd_tab, tab4, "{ \"", symname, "\",", wname, "},\n", NIL); + if (current==NO_CPP || current==STATIC_FUNC) { // emit normal fns & static fns + Hash* nspaceHash = getNamespaceHash( getNSpace() ); + String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); + Printv(s_ns_methods_tab, tab4, "{ \"", symname, "\",", wname, "},\n", NIL); + } + if (current == CONSTRUCTOR) { + if( constructor_name != 0 ) + Delete(constructor_name); + constructor_name = Copy(wname); + } - if (getCurrentClass()) - Setattr(n,"luaclassobj:wrap:name", wname); - else - Delete(wname); + Setattr(n, "wrap:name", wname); + // If it is getter/setter, then write wname under + // wrap:memberset/wrap:memberget accordingly + if( Getattr(n, "memberset") ) + Setattr(n, "memberset:wrap:name", wname); + if( Getattr(n, "memberget") ) + Setattr(n, "memberget:wrap:name", wname); DelWrapper(f); Delete(dispatch); @@ -866,7 +922,7 @@ public: current=NO_CPP; // normally SWIG will generate 2 wrappers, a get and a set // but in certain scenarios (immutable, or if its arrays), it will not - String *getName = Swig_name_wrapper(Swig_name_get(NSPACE_TODO, iname)); + String *getName = Swig_name_wrapper(Swig_name_get(getNSpace(), iname)); String *setName = 0; // checking whether it can be set to or not appears to be a very error prone issue // I referred to the Language::variableWrapper() to find this out @@ -878,7 +934,7 @@ public: Delete(tm); if (assignable) { - setName = Swig_name_wrapper(Swig_name_set(NSPACE_TODO, iname)); + setName = Swig_name_wrapper(Swig_name_set(getNSpace(), iname)); } else { // how about calling a 'this is not settable' error message? setName = NewString("SWIG_Lua_set_immutable"); // error message @@ -886,14 +942,19 @@ public: } // register the variable + Hash* nspaceHash = getNamespaceHash( getNSpace() ); + String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); + String* s_ns_var_tab = Getattr(nspaceHash, "attributes"); if (elua_ltr) { - Printf(s_dot_get, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, iname, getName); - Printf(s_dot_set, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, iname, setName); + String* s_ns_dot_get = Getattr(nspaceHash, "get"); + String* s_ns_dot_set = Getattr(nspaceHash, "set"); + Printf(s_ns_dot_get, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, iname, getName); + Printf(s_ns_dot_set, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, iname, setName); } else if (eluac_ltr) { - Printv(s_cmd_tab, tab4, "{LSTRKEY(\"", iname, "_get", "\")", ", LFUNCVAL(", getName, ")", "},\n", NIL); - Printv(s_cmd_tab, tab4, "{LSTRKEY(\"", iname, "_set", "\")", ", LFUNCVAL(", setName, ")", "},\n", NIL); + Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", iname, "_get", "\")", ", LFUNCVAL(", getName, ")", "},\n", NIL); + Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", iname, "_set", "\")", ", LFUNCVAL(", setName, ")", "},\n", NIL); } else { - Printf(s_var_tab, "%s{ \"%s\", %s, %s },\n", tab4, iname, getName, setName); + Printf(s_ns_var_tab, "%s{ \"%s\", %s, %s },\n", tab4, iname, getName, setName); } if (getCurrentClass()) { Setattr(n, "luaclassobj:wrap:get", getName); @@ -918,7 +979,7 @@ public: String *value = rawval ? rawval : Getattr(n, "value"); String *tm; - if (!addSymbol(iname, n)) + if (!addSymbol(iname, n, getNSpace())) return SWIG_ERROR; /* Special hook for member pointer */ @@ -933,6 +994,8 @@ public: Replaceall(tm, "$target", name); Replaceall(tm, "$value", value); Replaceall(tm, "$nsname", nsname); + Hash *nspaceHash = getNamespaceHash( getNSpace() ); + String *s_const_tab = Getattr(nspaceHash, "constants"); Printf(s_const_tab, " %s,\n", tm); } else if ((tm = Swig_typemap_lookup("constcode", n, name, 0))) { Replaceall(tm, "$source", value); @@ -945,6 +1008,7 @@ public: Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value.\n"); return SWIG_NOWRAP; } + /* TODO: Fix if (cparse_cplusplus && getCurrentClass()) { // Additionally add to class constants Swig_require("luaclassobj_constantWrapper", n, "*sym:name", "luaclassobj:symname", NIL); @@ -958,7 +1022,7 @@ public: Printf(s_cls_const_tab, " %s,\n", tm); } Swig_restore(n); - } + }*/ Delete(nsname); return SWIG_OK; } @@ -971,10 +1035,12 @@ public: // REPORT("nativeWrapper", n); String *symname = Getattr(n, "sym:name"); String *wrapname = Getattr(n, "wrap:name"); - if (!addSymbol(wrapname, n)) + if (!addSymbol(wrapname, n, getNSpace())) return SWIG_ERROR; - Printv(s_cmd_tab, tab4, "{ \"", symname, "\",", wrapname, "},\n", NIL); + Hash *nspaceHash = getNamespaceHash( getNSpace() ); + String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); + Printv(s_ns_methods_tab, tab4, "{ \"", symname, "\",", wrapname, "},\n", NIL); // return Language::nativeWrapper(n); // this does nothing... return SWIG_OK; } @@ -1010,20 +1076,28 @@ public: virtual int classHandler(Node *n) { //REPORT("classHandler", n); - String *mangled_classname = 0; - String *real_classname = 0; + String *mangled_full_class_symname = 0; + String *full_class_symname = 0; + String* nspace = getNSpace(); + String* destructor_name = 0; constructor_name = 0; have_constructor = 0; have_destructor = 0; destructor_action = 0; - class_name = Getattr(n, "sym:name"); - if (!addSymbol(class_name, n)) + class_symname = Getattr(n, "sym:name"); + if (!addSymbol(class_symname, n, nspace)) return SWIG_ERROR; - real_classname = Getattr(n, "name"); - mangled_classname = Swig_name_mangle(real_classname); + if (nspace == 0) + full_class_symname = NewStringf("%s", class_symname); + else + full_class_symname = NewStringf("%s.%s", nspace, class_symname); + + assert(full_class_symname != 0); + mangled_full_class_symname = Swig_name_mangle(full_class_symname); + Printf( stdout, "Mangled class symname %s\n", mangled_full_class_symname ); // not sure exactly how this works, // but tcl has a static hashtable of all classes emitted and then only emits code for them once. @@ -1033,50 +1107,88 @@ public: // * consider effect on template_specialization_defarg static Hash *emitted = NewHash(); - if (Getattr(emitted, mangled_classname)) + if (Getattr(emitted, mangled_full_class_symname)) return SWIG_NOWRAP; - Setattr(emitted, mangled_classname, "1"); + Setattr(emitted, mangled_full_class_symname, "1"); - s_attr_tab = NewString(""); - Printf(s_attr_tab, "static swig_lua_attribute swig_"); - Printv(s_attr_tab, mangled_classname, "_attributes[] = {\n", NIL); + // We treat class T as both 'class' and 'namespace'. All static members, attributes + // and constants are considered part of namespace T, all members - part of the 'class' + // Now, here is a trick. Static methods, attributes and non-static methods and attributes + // are described with same structures - swig_lua_attribute/swig_lua_method. Instead of calling + // getNamespaceHash(class name) to initialize things for static methods/attributes and then + // manually doing same initialization for non-static methods, we call getNamespaceHash 2 times: + // 1) With name "class name" + "." + "__Static" to initialize static things + // 2) With "class name" to initialize non-static things + // And we can guarantee that there will not be any name collision because names starting with 2 underscores + // and capital letter are forbiden to use in C++. So, under know circumstances could our class contain + // any member or subclass with name "__Static". Thus, never any name clash. + Hash* non_static_cls = getNamespaceHash(full_class_symname, false); + assert(non_static_cls != 0); + s_attr_tab = Getattr(non_static_cls, "attributes"); + s_methods_tab = Getattr(non_static_cls, "methods"); + String* s_attr_tab_name = Getattr(non_static_cls, "attributes:name"); + String* s_methods_tab_name = Getattr(non_static_cls, "methods:name"); + Setattr(non_static_cls, "lua:no_namespaces", "1"); + Setattr(non_static_cls, "lua:no_classes", "1"); - s_methods_tab = NewString(""); - Printf(s_methods_tab, "static swig_lua_method swig_"); - Printv(s_methods_tab, mangled_classname, "_methods[] = {\n", NIL); + /* There is no use for "constants", "classes" and "namespaces" arrays. + * All constants are considered part of static part of class. + */ - s_cls_methods_tab = NewString(""); - Printf(s_cls_methods_tab, "static swig_lua_method swig_"); - Printv(s_cls_methods_tab, mangled_classname, "_cls_methods[] = {\n", NIL); - - s_cls_attr_tab = NewString(""); - Printf(s_cls_attr_tab, "static swig_lua_attribute swig_"); - Printv(s_cls_attr_tab, mangled_classname, "_cls_attributes[] = {\n", NIL); - - s_cls_const_tab = NewString(""); - Printf(s_cls_const_tab, "static swig_lua_const_info swig_"); - Printv(s_cls_const_tab, mangled_classname, "_cls_constants[] = {\n", NIL); + String *static_cls_key = NewStringf("%s%s__Static", full_class_symname, NSPACE_SEPARATOR); + Hash *static_cls = getNamespaceHash(static_cls_key, false); + if (static_cls == 0) { + return SWIG_ERROR; // This cant be, so it is internal, implementation error + } + Setattr(static_cls, "lua:no_namespaces", "1"); + /* TODO: REMOVE + s_cls_methods_tab = Getattr(static_cls, "methods"); + s_cls_attr_tab = Getattr(static_cls, "attributes"); + s_cls_const_tab = Getattr(static_cls, "constants"); + */ + /* There is no use for "classes" and "namespaces" arrays. Subclasses are not supported + * by SWIG and namespaces couldn't be nested inside classes (C++ Standard) + */ + assert(s_attr_tab != 0); + assert(s_methods_tab != 0); + /* + assert(s_cls_methods_tab != 0); + assert(s_cls_attr_tab != 0); + assert(s_cls_const_tab != 0); + */ + // Replacing namespace with namespace + class in order to static + // member be put inside class static area + setNSpace(static_cls_key); // Generate normal wrappers Language::classHandler(n); + // Restore correct nspace + setNSpace(nspace); SwigType *t = Copy(Getattr(n, "name")); SwigType_add_pointer(t); // Catch all: eg. a class with only static functions and/or variables will not have 'remembered' - String *wrap_class = NewStringf("&_wrap_class_%s", mangled_classname); + String *wrap_class = NewStringf("&_wrap_class_%s", mangled_full_class_symname); SwigType_remember_clientdata(t, wrap_class); String *rt = Copy(getClassType()); SwigType_add_pointer(rt); + // Adding class to apropriate namespace + Hash *nspaceHash = getNamespaceHash(nspace); + String *ns_classes = Getattr(nspaceHash, "classes"); + Printv( ns_classes, wrap_class, ",\n", NIL ); + // Register the class structure with the type checker - // Printf(f_init,"SWIG_TypeClientData(SWIGTYPE%s, (void *) &_wrap_class_%s);\n", SwigType_manglestr(t), mangled_classname); + // Printf(f_init,"SWIG_TypeClientData(SWIGTYPE%s, (void *) &_wrap_class_%s);\n", SwigType_manglestr(t), mangled_full_class_symname); // emit a function to be called to delete the object + // TODO: class_name -> full_class_name || mangled full_class_name if (have_destructor) { - Printv(f_wrappers, "static void swig_delete_", class_name, "(void *obj) {\n", NIL); + destructor_name = NewStringf("swig_delete_%s", mangled_full_class_symname); + Printv(f_wrappers, "static void ", destructor_name, "(void *obj) {\n", NIL); if (destructor_action) { Printv(f_wrappers, SwigType_str(rt, "arg1"), " = (", SwigType_str(rt, 0), ") obj;\n", NIL); Printv(f_wrappers, destructor_action, "\n", NIL); @@ -1090,27 +1202,17 @@ public: Printf(f_wrappers, "}\n"); } - Printf(s_methods_tab, " {0,0}\n};\n"); - Printv(f_wrappers, s_methods_tab, NIL); - - Printf(s_attr_tab, " {0,0,0}\n};\n"); - Printv(f_wrappers, s_attr_tab, NIL); - - Printf(s_cls_attr_tab, " {0,0,0}\n};\n"); - Printv(f_wrappers, s_cls_attr_tab, NIL); - - Printf(s_cls_methods_tab, " {0,0}\n};\n"); - Printv(f_wrappers, s_cls_methods_tab, NIL); - - Printf(s_cls_const_tab, " {0,0,0,0,0,0}\n};\n"); - Printv(f_wrappers, s_cls_const_tab, NIL); + closeNamespaceHash(full_class_symname, f_wrappers); + closeNamespaceHash(static_cls_key, f_wrappers); + /* TODO: REMOVE Delete(s_methods_tab); Delete(s_attr_tab); Delete(s_cls_methods_tab); Delete(s_cls_attr_tab); Delete(s_cls_const_tab); + */ // Handle inheritance // note: with the idea of class hierarchies spread over multiple modules @@ -1135,7 +1237,7 @@ public: b = Next(b); continue; } - // old code: (used the pointer to the base class) + // old code: (used the pointer to the base class) TODO:REMOVE //String *bmangle = Swig_name_mangle(bname); //Printf(base_class, "&_wrap_class_%s", bmangle); //Putc(',', base_class); @@ -1149,24 +1251,30 @@ public: } } - Printv(f_wrappers, "static swig_lua_class *swig_", mangled_classname, "_bases[] = {", base_class, "0};\n", NIL); + Printv(f_wrappers, "static swig_lua_class *swig_", mangled_full_class_symname, "_bases[] = {", base_class, "0};\n", NIL); Delete(base_class); - Printv(f_wrappers, "static const char *swig_", mangled_classname, "_base_names[] = {", base_class_names, "0};\n", NIL); + Printv(f_wrappers, "static const char *swig_", mangled_full_class_symname, "_base_names[] = {", base_class_names, "0};\n", NIL); Delete(base_class_names); - Printv(f_wrappers, "static swig_lua_class _wrap_class_", mangled_classname, " = { \"", class_name, "\", &SWIGTYPE", SwigType_manglestr(t), ",", NIL); + Printv(f_wrappers, "static swig_lua_class _wrap_class_", mangled_full_class_symname, " = { \"", class_symname, "\", &SWIGTYPE", SwigType_manglestr(t), ",", NIL); + // TODO: Replace with constructor_name if (have_constructor) { if (elua_ltr) { - Printf(s_cmd_tab, " {LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", class_name, \ - Swig_name_wrapper(Swig_name_construct(NSPACE_TODO, constructor_name))); - Printf(f_wrappers, "%s", Swig_name_wrapper(Swig_name_construct(NSPACE_TODO, constructor_name))); + String* ns_methods_tab = Getattr(nspaceHash, "methods"); + // TODO: Contructor should be moved to __call method of static part of class + Printf(ns_methods_tab, " {LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", class_symname, \ + Swig_name_wrapper(Swig_name_construct(nspace, constructor_name))); + Printf(f_wrappers, "%s", Swig_name_wrapper(Swig_name_construct(nspace, constructor_name))); } else if (eluac_ltr) { - Printv(s_cmd_tab, tab4, "{LSTRKEY(\"", "new_", class_name, "\")", ", LFUNCVAL(", \ - Swig_name_wrapper(Swig_name_construct(NSPACE_TODO, constructor_name)), ")", "},\n", NIL); - Printf(f_wrappers, "%s", Swig_name_wrapper(Swig_name_construct(NSPACE_TODO, constructor_name))); + String* ns_methods_tab = Getattr(nspaceHash, "methods"); + Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "new_", class_symname, "\")", ", LFUNCVAL(", \ + Swig_name_wrapper(Swig_name_construct(nspace, constructor_name)), ")", "},\n", NIL); + Printf(f_wrappers, "%s", Swig_name_wrapper(Swig_name_construct(nspace, constructor_name))); } else { - Printf(f_wrappers, "%s", Swig_name_wrapper(Swig_name_construct(NSPACE_TODO, constructor_name))); + //Printf( stdout, "Constructor.name %s declaration: %s\n", constructor_name, Swig_name_wrapper(Swig_name_construct(nspace, constructor_name))); + //Printf(f_wrappers, "%s", Swig_name_wrapper(Swig_name_construct(nspace, constructor_name))); + Printv(f_wrappers, constructor_name, NIL); } Delete(constructor_name); constructor_name = 0; @@ -1176,23 +1284,26 @@ public: if (have_destructor) { if (eluac_ltr) { - Printv(s_cmd_tab, tab4, "{LSTRKEY(\"", "free_", class_name, "\")", ", LFUNCVAL(", "swig_delete_", class_name, ")", "},\n", NIL); - Printv(f_wrappers, ", swig_delete_", class_name, NIL); + String* ns_methods_tab = Getattr(nspaceHash, "methods"); + Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "free_", mangled_full_class_symname, "\")", ", LFUNCVAL(", destructor_name, ")", "},\n", NIL); + Printv(f_wrappers, ", ", destructor_name, NIL); } else { - Printv(f_wrappers, ", swig_delete_", class_name, NIL); + Printv(f_wrappers, ", ", destructor_name, NIL); } } else { Printf(f_wrappers, ",0"); } - Printf(f_wrappers, ", swig_%s_methods, swig_%s_attributes, { \"%s\", swig_%s_cls_methods, swig_%s_cls_attributes, swig_%s_cls_constants }, swig_%s_bases, swig_%s_base_names };\n\n", - mangled_classname, mangled_classname, - class_name, mangled_classname, mangled_classname, mangled_classname, - mangled_classname, mangled_classname); + Printf(f_wrappers, ", %s, %s, ", s_methods_tab_name, s_attr_tab_name ); + // TODO: Replace class_symname with class_name + printNamespaceDefinition(static_cls_key, class_symname, f_wrappers); + Printf(f_wrappers, ", swig_%s_bases, swig_%s_base_names };\n\n", + mangled_full_class_symname, mangled_full_class_symname); - // Printv(f_wrappers, ", swig_", mangled_classname, "_methods, swig_", mangled_classname, "_attributes, swig_", mangled_classname, "_bases };\n\n", NIL); - // Printv(s_cmd_tab, tab4, "{ SWIG_prefix \"", class_name, "\", (swig_wrapper_func) SWIG_ObjectConstructor, &_wrap_class_", mangled_classname, "},\n", NIL); + // Printv(f_wrappers, ", swig_", mangled_full_class_symname, "_methods, swig_", mangled_full_class_symname, "_attributes, swig_", mangled_full_class_symname, "_bases };\n\n", NIL); + // Printv(s_cmd_tab, tab4, "{ SWIG_prefix \"", class_name, "\", (swig_wrapper_func) SWIG_ObjectConstructor, &_wrap_class_", mangled_full_class_symname, "},\n", NIL); Delete(t); - Delete(mangled_classname); + Delete(mangled_full_class_symname); + Delete(static_cls_key); return SWIG_OK; } @@ -1221,7 +1332,8 @@ public: current = NO_CPP; realname = iname ? iname : name; - rname = Swig_name_wrapper(Swig_name_member(NSPACE_TODO, class_name, realname)); + rname = Getattr(n, "wrap:name"); + assert(rname != 0); if (!Getattr(n, "sym:nextSibling")) { Printv(s_methods_tab, tab4, "{\"", realname, "\", ", rname, "}, \n", NIL); } @@ -1236,27 +1348,29 @@ public: virtual int membervariableHandler(Node *n) { // REPORT("membervariableHandler",n); String *symname = Getattr(n, "sym:name"); - String *gname, *sname; + String *getter_name, *setter_name; current = MEMBER_VAR; Language::membervariableHandler(n); current = NO_CPP; - gname = Swig_name_wrapper(Swig_name_get(NSPACE_TODO, Swig_name_member(NSPACE_TODO, class_name, symname))); + getter_name = Getattr(n, "memberget:wrap:name"); + assert(getter_name != 0); if (!GetFlag(n, "feature:immutable")) { - sname = Swig_name_wrapper(Swig_name_set(NSPACE_TODO, Swig_name_member(NSPACE_TODO, class_name, symname))); + setter_name = Getattr(n, "memberset:wrap:name"); + assert(setter_name != 0); } else { - //sname = NewString("0"); - sname = NewString("SWIG_Lua_set_immutable"); // error message + //setter_name = NewString("0"); + setter_name = NewString("SWIG_Lua_set_immutable"); // error message } - Printf(s_attr_tab,"%s{ \"%s\", %s, %s},\n",tab4,symname,gname,sname); - if (eluac_ltr) { + Printf(s_attr_tab,"%s{ \"%s\", %s, %s},\n",tab4,symname,getter_name,setter_name); + /*if (eluac_ltr) { TODO: FIX for eluac and uncomments Printv(s_cmd_tab, tab4, "{LSTRKEY(\"", class_name, "_", symname, "_get", "\")", \ - ", LFUNCVAL(", gname, ")", "},\n", NIL); + ", LFUNCVAL(", getter_name, ")", "},\n", NIL); Printv(s_cmd_tab, tab4, "{LSTRKEY(\"", class_name, "_", symname, "_set", "\")", \ - ", LFUNCVAL(", sname, ")", "},\n", NIL); - } - Delete(gname); - Delete(sname); + ", LFUNCVAL(", setter_name, ")", "},\n", NIL); + }*/ + Delete(getter_name); + Delete(setter_name); return SWIG_OK; } @@ -1271,8 +1385,9 @@ public: current = CONSTRUCTOR; Language::constructorHandler(n); current = NO_CPP; - constructor_name = NewString(Getattr(n, "sym:name")); + //constructor_name = NewString(Getattr(n, "sym:name")); have_constructor = 1; + //Printf( stdout, "Constructor %s\n", constructor_name); TODO: REMOVE return SWIG_OK; } @@ -1299,7 +1414,7 @@ public: virtual int staticmemberfunctionHandler(Node *n) { REPORT("staticmemberfunctionHandler", n); current = STATIC_FUNC; - String *symname = Getattr(n, "sym:name"); + //String *symname = Getattr(n, "sym:name"); int result = Language::staticmemberfunctionHandler(n); if (cparse_cplusplus && getCurrentClass()) { @@ -1313,11 +1428,12 @@ public: return SWIG_OK; Swig_require("luaclassobj_staticmemberfunctionHandler", n, "luaclassobj:wrap:name", NIL); - String *name = Getattr(n, "name"); - String *rname, *realname; - realname = symname ? symname : name; - rname = Getattr(n, "luaclassobj:wrap:name"); - Printv(s_cls_methods_tab, tab4, "{\"", realname, "\", ", rname, "}, \n", NIL); + //String *name = Getattr(n, "name"); + //String *rname, *realname; + //realname = symname ? symname : name; + //rname = Getattr(n, "luaclassobj:wrap:name"); + // TODO: Add backward compatibility here: add "ClassName_FuncName" to global table + //Printv(s_cls_methods_tab, tab4, "{\"", realname, "\", ", rname, "}, \n", NIL); Swig_restore(n); return SWIG_OK; @@ -1350,7 +1466,7 @@ public: virtual int staticmembervariableHandler(Node *n) { REPORT("staticmembervariableHandler",n); current = STATIC_VAR; - String *symname = Getattr(n, "sym:name"); + //String *symname = Getattr(n, "sym:name"); int result = Language::staticmembervariableHandler(n); if (result != SWIG_OK) @@ -1360,12 +1476,35 @@ public: if (Getattr(n, "wrappedasconstant")) return SWIG_OK; + /* TODO: Add backward compatibility here: add "ClassName_AttributeName" to class scope Swig_require("luaclassobj_staticmembervariableHandler", n, "luaclassobj:wrap:get", "luaclassobj:wrap:set", NIL); Printf(s_cls_attr_tab,"%s{ \"%s\", %s, %s},\n",tab4,symname,Getattr(n,"luaclassobj:wrap:get"), Getattr(n,"luaclassobj:wrap:set")); Swig_restore(n); + */ return SWIG_OK; } + /* TODO: REMOVE + virtual int namespaceDeclaration(Node *n) { + // Register namespace + String* name = Getattr(n, "sym:name"); + Hash* parent = getNamespaceHash( getNSpace() ); + String *parent_namespaces_tab = Getattr(parent, "namespaces"); + String *mangled_name = Swig_name_mangle(name); + String *full_name = NewString(""); + if (getNSpace() == 0) + Printv(full_name, name); + else + Printv(full_name, getNSpace(), NSPACE_SEPARATOR, name); + Hash *nspace = getNamespaceHash(full_name); + Setattr(nspace, "name", Copy(name)); + Printv(parent_namespaces_tab, mangled_name, ",\n", NIL); + Printf(stdout, "NamespaceDeclaration %s, Parent %s, FQN %s\n", name, getNSpace(), full_name); + Delete(mangled_name); + Delete(full_name); + return Language::namespaceDeclaration(n); + } + */ /* --------------------------------------------------------------------- * external runtime generation * --------------------------------------------------------------------- */ @@ -1428,6 +1567,307 @@ public: Replace(str,"\n","\\n\"\n \"",DOH_REPLACE_ANY); // \n to \n"\n" (ie quoting every line) //Printf(f_runtime,"/* hacked luacode:[[[\n%s\n]]]\n*/\n",str); } + + /* Each namespace can be described with hash that stores C arrays + where members of the namespace should be added. All these hashes are stored + inside namespaces_hash. + nspace could be NULL (NSPACE_TODO), that means functions and variables and classes + that are not in any namespace (this is default for SWIG unless %nspace feature is used) + You can later set some attributes that will affect behaviour of functions that use this hash: + "lua:no_namespaces" will disable "namespaces" array. + "lua:no_classes" will disable "classes" array. + For every component ("attributes", "methods", etc) there are subcomponents: + * XXX:name - name of the C array that stores data for component + * XXX:decl - statement with forward declaration of this array; + */ + Hash* getNamespaceHash(String *nspace, bool reg = true) + { + //Printf( stdout, "Request for %s. register: %d\n", nspace?nspace:"", int(reg)); + Hash* nspace_hash = Getattr(namespaces_hash, nspace?nspace:"" ); + if (nspace_hash != 0) + return nspace_hash; + nspace_hash = NewHash(); + String* mangled_name = 0; + if (nspace == 0 || Len(nspace) == 0) + mangled_name = NewString("__Global"); // C++ names can't start with "__ + capital letter" + else + mangled_name = Swig_name_mangle(nspace); + String* cname = NewStringf("swig_%s", mangled_name); + + if (reg && nspace != 0 && Len(nspace) != 0 && Getattr(nspace_hash, "lua:no_reg") == 0) { + // Split names into components + List* components = Split(nspace, '.', -1); + String *parent_path = NewString(""); + int len = Len(components); + String* name = Copy(Getitem(components, len-1)); + for( int i = 0; i < len-1; i++ ) { + if (i > 0) + Printv(parent_path, NSPACE_SEPARATOR, NIL); + String* item = Getitem(components, i); + Printv(parent_path, item, NIL); + } + Printf(stdout, "Registering %s. User name %s. C-name %s, Parent is %s\n", mangled_name, name, cname, parent_path); + Hash* parent = getNamespaceHash(parent_path, true); + String* namespaces_tab = Getattr(parent, "namespaces"); + Printv(namespaces_tab, "&", cname, ",\n", NIL); + Setattr(nspace_hash, "name", name); + + Delete(components); + Delete(parent_path); + } else if (!reg) // This namespace shouldn't be registered. Lets remember it + Setattr(nspace_hash, "lua:no_reg", "1"); + + + Setattr(nspace_hash, "cname", cname); + + String *attr_tab = NewString(""); + String *attr_tab_name = NewStringf("swig_%s_attributes", mangled_name ); + String *attr_tab_decl = NewString(""); + Printv(attr_tab, "static swig_lua_attribute ", NIL); + Printv(attr_tab, attr_tab_name, "[]", NIL); + Printv(attr_tab_decl, attr_tab, ";\n", NIL); + Printv(attr_tab, " = {\n", NIL); + Setattr(nspace_hash, "attributes", attr_tab); + Setattr(nspace_hash, "attributes:name", attr_tab_name); + Setattr(nspace_hash, "attributes:decl", attr_tab_decl); + + String *methods_tab = NewString(""); + String *methods_tab_name = NewStringf("swig_%s_methods", mangled_name ); + String *methods_tab_decl = NewString(""); + if (elua_ltr || eluac_ltr) // In this case methods array also acts as namespace rotable + Printf(methods_tab, "static LUA_REG_TYPE "); + else + Printf(methods_tab, "static swig_lua_method "); + Printv(methods_tab, methods_tab_name, "[]"); + Printv(methods_tab_decl, methods_tab, ";\n", NIL); + Printv(methods_tab, "= {\n", NIL); + Setattr(nspace_hash, "methods", methods_tab ); + Setattr(nspace_hash, "methods:name", methods_tab_name ); + Setattr(nspace_hash, "methods:decl", methods_tab_decl ); + + String *const_tab = NewString(""); + String *const_tab_name = NewStringf("swig_%s_constants", mangled_name ); + String *const_tab_decl = NewString(""); + if (elua_ltr || eluac_ltr) // In this case const array holds rotable with namespace constants + Printf(const_tab, "static LUA_REG_TYPE "); + else + Printf(const_tab, "static swig_lua_const_info "); + Printv(const_tab, const_tab_name, "[]", NIL); + Printv(const_tab_decl, const_tab, ";", NIL); + Printv(const_tab, "= {\n", NIL); + Setattr(nspace_hash, "constants", const_tab ); + Setattr(nspace_hash, "constants:name", const_tab_name ); + Setattr(nspace_hash, "constants:decl", const_tab_decl ); + + String *classes_tab = NewString(""); + String *classes_tab_name = NewStringf("swig_%s_classes", mangled_name ); + String *classes_tab_decl = NewString(""); + Printf(classes_tab, "static swig_lua_class* "); + Printv(classes_tab, classes_tab_name, "[]"); + Printv(classes_tab_decl, classes_tab, ";", NIL); + Printv(classes_tab, "= {\n", NIL); + Setattr(nspace_hash, "classes", classes_tab ); + Setattr(nspace_hash, "classes:name", classes_tab_name ); + Setattr(nspace_hash, "classes:decl", classes_tab_decl ); + + String* namespaces_tab = NewString(""); + String* namespaces_tab_name = NewStringf("swig_%s_namespaces", mangled_name ); + String* namespaces_tab_decl = NewString(""); + Printf(namespaces_tab, "static swig_lua_namespace* "); + Printv(namespaces_tab, namespaces_tab_name, "[]"); + Printv(namespaces_tab_decl, namespaces_tab, ";", NIL); + Printv(namespaces_tab, " = {\n", NIL); + Setattr(nspace_hash, "namespaces", namespaces_tab ); + Setattr(nspace_hash, "namespaces:name", namespaces_tab_name ); + Setattr(nspace_hash, "namespaces:decl", namespaces_tab_decl ); + + if (elua_ltr) { + // TODO: add xxx:decl here too + String *get_tab = NewString(""); + String *get_tab_name = NewStringf("swig_%s_get", mangled_name); + Printv(get_tab, "const LUA_REG_TYPE ", get_tab_name, "[] = {\n", NIL); + Setattr(nspace_hash, "get", get_tab); + Setattr(nspace_hash, "get:name", get_tab_name); + + String *set_tab = NewString(""); + String *set_tab_name = NewStringf("swig_%s_set", mangled_name); + Printv(set_tab, "const LUA_REG_TYPE ", set_tab_name, "[] = {\n", NIL); + Setattr(nspace_hash, "set", set_tab); + Setattr(nspace_hash, "set:name", set_tab_name); + + if (!eluac_ltr) { + String* metatable_tab = NewString(""); + String* metatable_tab_name = NewStringf("swig_%s_meta", mangled_name); + Printv(metatable_tab, "const LUA_REG_TYPE ", metatable_tab_name, "[] = {\n"); + Setattr(nspace_hash, "metatable", metatable_tab); + Setattr(nspace_hash, "metatable:name", metatable_tab_name); + } + } + String* key = 0; + if (nspace != 0) + key = Copy(nspace); + Setattr(namespaces_hash, key?key:"", nspace_hash); + + Delete(mangled_name); + return nspace_hash; + } + + /* Functions add end markers {0,0,...,0} to all arrays, prints them to + * output and marks hash as closed (lua:closed). Consequent attempts to + * close same hash will result in error + * closeNamespaceHash DOES NOT print structure that describes namespace, it only + * prints array. You can use printNamespaceDefinition to print structure. + * if "lua:no_namespaces" is set, then array for "namespaces" won't be printed + * if "lua:no_classes" is set, then array for "classes" won't be printed + * */ + void closeNamespaceHash(String *nspace, File *output) + { + Hash* nspace_hash = Getattr(namespaces_hash, nspace ); + assert(nspace_hash != 0); + assert(Getattr(nspace_hash, "lua:closed") == 0); + + Setattr(nspace_hash, "lua:closed", "1"); + + String* attr_tab = Getattr(nspace_hash, "attributes"); + Printf(attr_tab, " {0,0,0}\n};\n"); + Printv(output, attr_tab, NIL); + + String* const_tab = Getattr(nspace_hash, "constants"); + String* const_tab_name = Getattr(nspace_hash, "constants:name"); + if (elua_ltr || eluac_ltr) + Printv(const_tab, tab4, "{LNILKEY, LNILVAL}\n", "};\n", NIL); + else + Printf(const_tab, " {0,0,0,0,0,0}\n};\n"); + Printv(output, const_tab, NIL); + + String* methods_tab = Getattr(nspace_hash, "methods"); + String* metatable_tab_name = Getattr(nspace_hash, "metatable:name"); + if (elua_ltr || eluac_ltr) { + Printv(methods_tab, tab4, "{LSTRKEY(\"const\"), LROVAL(", const_tab_name, ")},\n", NIL); + if (elua_ltr) + Printv(methods_tab, tab4, "{LSTRKEY(\"__metatable\"), LROVAL(", metatable_tab_name, ")},\n", NIL); + } else + Printf(methods_tab, " {0,0}\n};\n"); + Printv(output, methods_tab, NIL); + + if (!Getattr(nspace_hash, "lua:no_classes") ) { + String* classes_tab = Getattr(nspace_hash, "classes"); + Printf(classes_tab, " 0\n};\n"); + Printv(output, classes_tab, NIL); + } + + if (!Getattr(nspace_hash, "lua:no_namespaces") ) { + String* namespaces_tab = Getattr(nspace_hash, "namespaces"); + Printf(namespaces_tab, " 0\n};\n"); + Printv(output, namespaces_tab, NIL); + } + if (elua_ltr) { + String *get_tab = Getattr(nspace_hash, "get"); + String *get_tab_name = Getattr(nspace_hash, "get:name"); + String *set_tab = Getattr(nspace_hash, "set"); + String *set_tab_name = Getattr(nspace_hash, "set:name"); + Printv(get_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); + Printv(set_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); + Printv(output, get_tab, NIL); + Printv(output, set_tab, NIL); + + String *metatable_tab = Getattr(nspace_hash, "metatable"); + assert(metatable_tab != 0); + Printv(metatable_tab, tab4, "{LSTRKEY(\"__index\"), LFUNCVAL(SWIG_Lua_module_get)},\n", NIL); + Printv(metatable_tab, tab4, "{LSTRKEY(\"__newindex\"), LFUNCVAL(SWIG_Lua_module_set)},\n", NIL); + Printv(metatable_tab, tab4, "{LSTRKEY(\".get\"), LROVAL(", get_tab_name, ")},\n", NIL); + Printv(metatable_tab, tab4, "{LSTRKEY(\".set\"), LROVAL(", set_tab_name, ")},\n", NIL); + Printv(metatable_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); + Printv(output, metatable_tab, NIL); + } + Printv(output, "\n", NIL); + } + + static int compareByLen( const DOH* f, const DOH* s) { return Len(s) - Len(f); } + // Recursively close all non-closed namespaces. Prints data to dataOutput, + // forward declaration to declOutput + void closeNamespaces(File *dataOutput, File *declOutput) + { + Iterator ki = First(namespaces_hash); + List* to_close = NewList(); + while (ki.key) { + if (Getattr(ki.item, "lua:closed") == 0) + Append(to_close, ki.key); + ki = Next(ki); + } + SortList(to_close, &compareByLen); + int len = Len(to_close); + for( int i = 0; i < len; i++ ) { + String* key = Getitem(to_close,i); + closeNamespaceHash(key, dataOutput); + Hash* nspace = Getattr(namespaces_hash, key); + String* cname = Getattr(nspace, "cname"); // cname - name of the C structure that describes namespace + assert(cname != 0); + Printf( stdout, "Closing namespace %s\n", cname ); + //printNamespaceForwardDeclaration( ki.key, declOutput ); TODO: REMOVE + Printv(dataOutput, "static swig_lua_namespace ", cname, " = ", NIL); + String *name = 0; // name - name of the namespace as it should be visible in Lua + if (DohLen(key) == 0) // This is global module + name = module; + else + name = Getattr(nspace, "name"); + assert(name != 0); + printNamespaceDefinition( key, name, dataOutput ); + Printv(dataOutput, ";\n\n", NIL); + } + Delete(to_close); + } + + // This function prints to output a definition of namespace in + // form of swig_lua_namespace: { attr_array, methods_array, ... , namespaces_array }. + // You can call this function as many times as necessary. + // 'name' is a user-visible name that this namespace will have in Lua. It shouldn't + // be fully qualified name, just it's own name. + void printNamespaceDefinition(String *nspace, String* name, File *output) + { + // TODO: Fix for get_tab/set_tab things (elua_ltr) + Hash *nspace_hash = getNamespaceHash(nspace, false); + String *null_string = NewString("0"); + String *attr_tab_name = Getattr(nspace_hash, "attributes:name"); + String *methods_tab_name = Getattr(nspace_hash, "methods:name"); + String *const_tab_name = Getattr(nspace_hash, "constants:name"); + String *classes_tab_name = Getattr(nspace_hash, "classes:name"); + String *namespaces_tab_name = Getattr(nspace_hash, "namespaces:name"); + bool has_classes = Getattr(nspace_hash, "lua:no_classes") == 0; + bool has_namespaces = Getattr(nspace_hash, "lua:no_namespaces") == 0; + + Printf(output, "{\"%s\", %s, %s, %s, %s, %s}", + name, + methods_tab_name, + attr_tab_name, + const_tab_name, + (has_classes)?classes_tab_name:null_string, + (has_namespaces)?namespaces_tab_name:null_string + ); + } + + // This function prints forward declaration of namespace itself and all its arrays + // TODO: REMOVE + void printNamespaceForwardDeclaration(String* nspace, File* output) + { + Hash *nspace_hash = getNamespaceHash(nspace, false); + String *attr_tab_decl = Getattr(nspace_hash, "attributes:decl"); + String *methods_tab_decl = Getattr(nspace_hash, "methods:decl"); + String *const_tab_decl = Getattr(nspace_hash, "constants:decl"); + String *classes_tab_decl = Getattr(nspace_hash, "classes:decl"); + String *namespaces_tab_decl = Getattr(nspace_hash, "declspaces:decl"); + bool has_classes = Getattr(nspace_hash, "lua:no_classes") == 0; + bool has_namespaces = Getattr(nspace_hash, "lua:no_namespaces") == 0; + Printv( output, attr_tab_decl, "\n", NIL ); + Printv( output, methods_tab_decl, "\n", NIL ); + Printv( output, const_tab_decl, "\n", NIL ); + if( has_classes ) + Printv( output, classes_tab_decl, "\n", NIL ); + if( has_namespaces ) + Printv( output, namespaces_tab_decl, "\n", NIL ); + + Printf( output, "static swig_lua_namespace %s;\n", Getattr(nspace_hash, "cname") ); + } }; /* NEW LANGUAGE NOTE:*********************************************** diff --git a/Source/Modules/swigmod.h b/Source/Modules/swigmod.h index 2929993b3..09fc37c87 100644 --- a/Source/Modules/swigmod.h +++ b/Source/Modules/swigmod.h @@ -278,6 +278,7 @@ protected: /* Return the namespace for the class/enum - the nspace feature */ String *getNSpace() const; + void setNSpace(String *nspace); /* Return the real name of the current class */ String *getClassName() const; From 295788c8a0002fe228d2e884cb370a525fb66a38 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Tue, 29 Oct 2013 21:14:34 +0400 Subject: [PATCH 389/481] nspace.i example is working --- Lib/lua/luarun.swg | 297 +++++++++++++++++++++++++++++-------- Source/Modules/lang.cxx | 10 +- Source/Modules/lua.cxx | 317 ++++++++++++++++++++++++++++------------ 3 files changed, 468 insertions(+), 156 deletions(-) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index 04d18fdb7..ec33ea601 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -157,7 +157,8 @@ struct swig_lua_namespace { }; struct swig_lua_class { - const char *name; + const char *name; // Name that this class has in Lua + const char *fqname; // Fully qualified name - Scope + class name swig_type_info **type; lua_CFunction constructor; void (*destructor)(void *); @@ -511,7 +512,7 @@ SWIGINTERN void SWIG_Lua_class_register(lua_State* L,swig_lua_class* clss); SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State* L, swig_lua_namespace* ns) { int i = 0; - /* There must be table at the top of the stack */ + /* There must be namespace table (not metatable) at the top of the stack */ assert(lua_istable(L,-1)); SWIG_Lua_InstallConstants(L, ns->ns_constants); @@ -539,10 +540,13 @@ SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State* L, swig_lua_namespace* */ SWIGINTERN void SWIG_Lua_add_namespace_classes(lua_State* L, swig_lua_namespace* ns) { + // There must be module/namespace table at the top of the stack + assert(lua_istable(L,-1)); + swig_lua_class** classes = ns->ns_classes; if( classes != 0 ) { - while((*classes)->name != 0) { + while(*classes != 0) { SWIG_Lua_class_register(L, *classes); classes++; } @@ -556,6 +560,7 @@ SWIGINTERN void SWIG_Lua_add_namespace_classes(lua_State* L, swig_lua_namespace* */ SWIGINTERN int SWIG_Lua_namespace_register(lua_State* L, swig_lua_namespace* ns, bool reg) { + int begin = lua_gettop(L); assert(lua_istable(L,-1)); /* just in case. This is supposed to be module table or parent namespace table */ lua_checkstack(L,5); lua_newtable(L); /* namespace itself */ @@ -582,11 +587,14 @@ SWIGINTERN int SWIG_Lua_namespace_register(lua_State* L, swig_lua_namespace* ns, // Register all functions, variables etc SWIG_Lua_add_namespace_details(L,ns); + // Register classes + SWIG_Lua_add_namespace_classes(L,ns); swig_lua_namespace** sub_namespace = ns->ns_namespaces; if( sub_namespace != 0) { - while((*sub_namespace)->name != 0) { + while(*sub_namespace != 0) { SWIG_Lua_namespace_register(L, *sub_namespace, true); + lua_pop(L,1); // removing sub-namespace table sub_namespace++; } } @@ -596,39 +604,45 @@ SWIGINTERN int SWIG_Lua_namespace_register(lua_State* L, swig_lua_namespace* ns, lua_pushvalue(L,-2); lua_rawset(L,-4); /* add namespace to module table */ } + assert(lua_gettop(L) == begin+1); } /* ----------------------------------------------------------------------------- * global variable support code: classes * ----------------------------------------------------------------------------- */ -/* the class.get method, performs the lookup of class attributes */ +/* the class.get method, performs the lookup of class attributes + * Method can be called from Lua directly and recursively from itself. Thats why + * we can't use absolute stack positions + */ SWIGINTERN int SWIG_Lua_class_get(lua_State* L) { /* there should be 2 params passed in (1) userdata (not the meta table) (2) string name of the attribute */ + int base = lua_gettop(L)-2; + lua_checkstack(L,5); assert(lua_isuserdata(L,-2)); /* just in case */ lua_getmetatable(L,-2); /* get the meta table */ assert(lua_istable(L,-1)); /* just in case */ SWIG_Lua_get_table(L,".get"); /* find the .get table */ assert(lua_istable(L,-1)); /* just in case */ /* look for the key in the .get table */ - lua_pushvalue(L,2); /* key */ + lua_pushvalue(L,base+2); /* key */ lua_rawget(L,-2); lua_remove(L,-2); /* stack tidy, remove .get table */ if (lua_iscfunction(L,-1)) { /* found it so call the fn & return its value */ - lua_pushvalue(L,1); /* the userdata */ + lua_pushvalue(L,base+1); /* the userdata */ lua_call(L,1,1); /* 1 value in (userdata),1 out (result) */ lua_remove(L,-2); /* stack tidy, remove metatable */ return 1; } lua_pop(L,1); /* remove whatever was there */ /* ok, so try the .fn table */ - SWIG_Lua_get_table(L,".fn"); /* find the .get table */ + SWIG_Lua_get_table(L,".fn"); /* find the .fn table */ assert(lua_istable(L,-1)); /* just in case */ - lua_pushvalue(L,2); /* key */ + lua_pushvalue(L,base+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 */ @@ -642,60 +656,197 @@ SWIGINTERN int SWIG_Lua_class_get(lua_State* L) SWIG_Lua_get_table(L,"__getitem"); /* find the __getitem fn */ if (lua_iscfunction(L,-1)) /* if its there */ { /* found it so call the fn & return its value */ - lua_pushvalue(L,1); /* the userdata */ - lua_pushvalue(L,2); /* the parameter */ + lua_pushvalue(L,base+1); /* the userdata */ + lua_pushvalue(L,base+2); /* the parameter */ lua_call(L,2,1); /* 2 value in (userdata),1 out (result) */ lua_remove(L,-2); /* stack tidy, remove metatable */ return 1; } + lua_pop(L,1); + // Search in base classes + // TODO: Different for elua_ltr + SWIG_Lua_get_table(L,".bases"); + assert(lua_istable(L,-1)); + int bases_count = lua_rawlen(L,-1); + if(bases_count>0) + { + int original_metatable = lua_absindex(L,-2); + int i; + int ret = 0; // Number of returned values + lua_pushvalue(L,base+1); // push userdata + lua_pushvalue(L,base+2); // Push key again + // Trick: temporaly replacing original metatable + // with metatable for base class and call getter + for(i=0;i0) + break; + } + // Return original metatable back + lua_pushvalue(L,original_metatable); + lua_setmetatable(L,base+1); + if(ret>0) + { + // tidy stack. Stack currently is: + // --base-- + // userdata + // key + // metatable + // .bases table + // userdata + // key : -2 + // return value : -1 + lua_remove(L,-2); // remove key + lua_remove(L,-2); // remove userdata + lua_remove(L,-2); // remove .bases + lua_remove(L,-2); // remove metatable + return 1; + } else { + lua_pop(L,2); // remove key and userdata + } + } + // Tidy stack: + // --base-- + // userdata + // key + // metatable + // .bases table + lua_pop(L,2); + assert(lua_gettop(L)==base+2); return 0; /* sorry not known */ } -/* the class.set method, performs the lookup of class attributes */ -SWIGINTERN int SWIG_Lua_class_set(lua_State* L) +/* helper for the class.set method, performs the lookup of class attributes + * Method can be called from SWIG_Lua_class_set or recursively from itself + */ +SWIGINTERN int SWIG_Lua_class_do_set(lua_State* L) { /* there should be 3 params passed in (1) table (not the meta table) (2) string name of the attribute (3) any for the new value printf("SWIG_Lua_class_set %p(%s) '%s' %p(%s)\n", - lua_topointer(L,1),lua_typename(L,lua_type(L,1)), - lua_tostring(L,2), - lua_topointer(L,3),lua_typename(L,lua_type(L,3)));*/ + lua_topointer(L,-3),lua_typename(L,lua_type(L,-3)), + lua_tostring(L,-2), + lua_topointer(L,-1),lua_typename(L,lua_type(L,-1)));*/ - assert(lua_isuserdata(L,1)); /* just in case */ - lua_getmetatable(L,1); /* get the meta table */ + int base = lua_gettop(L) - 3; + lua_checkstack(L,5); + assert(lua_isuserdata(L,base+1)); /* just in case */ + lua_getmetatable(L,base+1); /* get the meta table */ assert(lua_istable(L,-1)); /* just in case */ SWIG_Lua_get_table(L,".set"); /* find the .set table */ if (lua_istable(L,-1)) { /* look for the key in the .set table */ - lua_pushvalue(L,2); /* key */ + lua_pushvalue(L,base+2); /* key */ lua_rawget(L,-2); + lua_remove(L,-2); /* tidy stack, remove .set table */ if (lua_iscfunction(L,-1)) { /* found it so call the fn & return its value */ - lua_pushvalue(L,1); /* userdata */ - lua_pushvalue(L,3); /* value */ + lua_pushvalue(L,base+1); /* userdata */ + lua_pushvalue(L,base+3); /* value */ lua_call(L,2,0); + lua_remove(L,base+4); /*remove metatable*/ + assert(lua_gettop(L) == base+3); // TODO:REMOVE return 0; } lua_pop(L,1); /* remove the value */ + } else { + lua_pop(L,1); /* remove the answer for .set table request*/ } - lua_pop(L,1); /* remove the value .set table */ + assert(lua_gettop(L) == base + 4); // TODO: REMOVE /* 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 */ { /* found it so call the fn & return its value */ - lua_pushvalue(L,1); /* the userdata */ - lua_pushvalue(L,2); /* the parameter */ - lua_pushvalue(L,3); /* the value */ + lua_pushvalue(L,base+1); /* the userdata */ + lua_pushvalue(L,base+2); /* the parameter */ + lua_pushvalue(L,base+3); /* the value */ lua_call(L,3,0); /* 3 values in ,0 out */ lua_remove(L,-2); /* stack tidy, remove metatable */ - return 1; + return 0; + } + lua_pop(L,1); // remove value + assert(lua_gettop(L) == base + 4); // TODO: REMOVE + + // Search among bases + int original_metatable = base+4; + assert(lua_gettop(L) == original_metatable); // Check that stack is correct + SWIG_Lua_get_table(L,".bases"); + assert(lua_istable(L,-1)); + int bases_count = lua_rawlen(L,-1); + if(bases_count>0) + { + int i = 0; + int ret = 0; + lua_pushvalue(L,base+1); // push userdata + lua_pushvalue(L,base+2); // Push key again + lua_pushvalue(L,base+3); // Push value again + // Trick: temporaly replacing original metatable + // with metatable for base class and call getter + for(i=0;ibases[i];i++) { - SWIG_Lua_add_class_details(L,clss->bases[i]); + SWIG_Lua_get_class_metatable(L,clss->bases[i]->fqname); + // Base class must be already registered + assert(lua_istable(L,-1)); + lua_rawseti(L,-2,i+1); // In lua indexing starts from 1 + bases_count++; } - /* add fns */ + assert(lua_rawlen(L,-1) == bases_count); + lua_pop(L,1); // remove .bases table + /* add attributes */ for(i=0;clss->attributes[i].name;i++){ SWIG_Lua_add_variable(L,clss->attributes[i].name,clss->attributes[i].getmethod,clss->attributes[i].setmethod); } @@ -851,7 +994,7 @@ SWIGINTERN void SWIG_Lua_add_class_details(lua_State* L,swig_lua_class* clss) /* add operator overloads these look ANY method which start with "__" and assume they are operator overloads & add them to the metatable - (this might mess up is someone defines a method __gc (the destructor)*/ + (this might mess up if someone defines a method __gc (the destructor)*/ for(i=0;clss->methods[i].name;i++){ if (clss->methods[i].name[0]=='_' && clss->methods[i].name[1]=='_'){ SWIG_Lua_add_function(L,clss->methods[i].name,clss->methods[i].func); @@ -884,13 +1027,13 @@ SWIGINTERN void SWIG_Lua_init_base_class(lua_State* L,swig_lua_class* clss) /* Register class static methods,attributes etc as well as constructor proxy */ SWIGINTERN void SWIG_Lua_class_register_static(lua_State* L, swig_lua_class* clss) { + int begin = lua_gettop(L); lua_checkstack(L,5); /* just in case */ assert(lua_istable(L,-1)); /* just in case */ assert(strcmp(clss->name, clss->cls_static.name) == 0); /* in class those 2 must be equal */ - SWIG_Lua_namespace_register(L,&clss->cls_static, false); + SWIG_Lua_namespace_register(L,&clss->cls_static, true); - SWIG_Lua_get_table(L,clss->name); // Get namespace table back assert(lua_istable(L,-1)); /* just in case */ /* add its constructor to module with the name of the class @@ -899,10 +1042,9 @@ SWIGINTERN void SWIG_Lua_class_register_static(lua_State* L, swig_lua_class* cls (this overcomes the problem of pure virtual classes without constructors)*/ if (clss->constructor) { - SWIG_Lua_add_function(L,".constructor", clss->constructor); lua_getmetatable(L,-1); assert(lua_istable(L,-1)); /* just in case */ - SWIG_Lua_add_function(L,"__call", SWIG_Lua_constructor_proxy); + SWIG_Lua_add_function(L,"__call", clss->constructor); lua_pop(L,1); } @@ -911,19 +1053,42 @@ SWIGINTERN void SWIG_Lua_class_register_static(lua_State* L, swig_lua_class* cls /* clear stack */ lua_pop(L,1); + assert( lua_gettop(L) == begin ); } -/* performs the entire class registration process */ -SWIGINTERN void SWIG_Lua_class_register(lua_State* L,swig_lua_class* clss) +/* performs the instance(non-static) class registration process. Metatable for class is created + * and added to the class registry. + */ +SWIGINTERN void SWIG_Lua_class_register_instance(lua_State* L,swig_lua_class* clss) { - SWIG_Lua_class_register_static(L,clss); - + int begin = lua_gettop(L); + // if name already there (class is already registered) then do nothing SWIG_Lua_get_class_registry(L); /* get the registry */ - lua_pushstring(L,clss->name); /* get the name */ + lua_pushstring(L,clss->fqname); /* get the name */ + lua_rawget(L,-2); + if(!lua_isnil(L,-1)) { + lua_pop(L,2); + assert(lua_gettop(L)==begin); + return; + } + lua_pop(L,2); // tidy stack + // Recursively initialize all bases + int i = 0; + for(i=0;clss->bases[i];i++) + { + SWIG_Lua_class_register_instance(L,clss->bases[i]); + } + // Again, get registry and push name + SWIG_Lua_get_class_registry(L); /* get the registry */ + lua_pushstring(L,clss->fqname); /* get the name */ lua_newtable(L); /* create the metatable */ /* add string of class name called ".type" */ lua_pushstring(L,".type"); - lua_pushstring(L,clss->name); + lua_pushstring(L,clss->fqname); + lua_rawset(L,-3); + /* add a table called bases */ + lua_pushstring(L,".bases"); + lua_newtable(L); lua_rawset(L,-3); /* add a table called ".get" */ lua_pushstring(L,".get"); @@ -948,10 +1113,18 @@ SWIGINTERN void SWIG_Lua_class_register(lua_State* L,swig_lua_class* clss) /* add it */ lua_rawset(L,-3); /* metatable into registry */ lua_pop(L,1); /* tidy stack (remove registry) */ + assert(lua_gettop(L)==begin); - SWIG_Lua_get_class_metatable(L,clss->name); - SWIG_Lua_add_class_details(L,clss); /* recursive adding of details (atts & ops) */ + SWIG_Lua_get_class_metatable(L,clss->fqname); + SWIG_Lua_add_class_instance_details(L,clss); /* recursive adding of details (atts & ops) */ lua_pop(L,1); /* tidy stack (remove class metatable) */ + assert( lua_gettop(L) == begin ); +} + +SWIGINTERN void SWIG_Lua_class_register(lua_State* L,swig_lua_class* clss) +{ + SWIG_Lua_class_register_instance(L,clss); + SWIG_Lua_class_register_static(L,clss); } /* ----------------------------------------------------------------------------- @@ -963,7 +1136,7 @@ SWIGINTERN void _SWIG_Lua_AddMetatable(lua_State* L,swig_type_info *type) { if (type->clientdata) /* there is clientdata: so add the metatable */ { - SWIG_Lua_get_class_metatable(L,((swig_lua_class*)(type->clientdata))->name); + SWIG_Lua_get_class_metatable(L,((swig_lua_class*)(type->clientdata))->fqname); if (lua_istable(L,-1)) { lua_setmetatable(L,-2); diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 97ed295c9..195da18d6 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -1490,6 +1490,7 @@ int Language::membervariableHandler(Node *n) { Setattr(n, "type", type); Setattr(n, "name", name); Setattr(n, "sym:name", symname); + Delattr(n, "memberset"); /* Delete all attached typemaps and typemap attributes */ Iterator ki; @@ -1507,6 +1508,7 @@ int Language::membervariableHandler(Node *n) { Setattr(n, "sym:name", mrename_get); Setattr(n, "memberget", "1"); functionWrapper(n); + Delattr(n, "memberget"); } Delete(mrename_get); Delete(mrename_set); @@ -2951,11 +2953,14 @@ int Language::constantWrapper(Node *n) { * ---------------------------------------------------------------------- */ int Language::variableWrapper(Node *n) { - Swig_require("variableWrapper", n, "*name", "*sym:name", "*type", "?parms", NIL); + Swig_require("variableWrapper", n, "*name", "*sym:name", "*type", "?parms", "?varset", "?varget", NIL); String *symname = Getattr(n, "sym:name"); SwigType *type = Getattr(n, "type"); String *name = Getattr(n, "name"); + Delattr(n,"varset"); + Delattr(n,"varget"); + /* If no way to set variables. We simply create functions */ int assignable = is_assignable(n); int flags = use_naturalvar_mode(n); @@ -2986,12 +2991,14 @@ int Language::variableWrapper(Node *n) { Delete(pname0); } if (make_set_wrapper) { + Setattr(n, "varset", "1"); functionWrapper(n); } /* Restore parameters */ Setattr(n, "sym:name", symname); Setattr(n, "type", type); Setattr(n, "name", name); + Delattr(n, "varset"); /* Delete all attached typemaps and typemap attributes */ Iterator ki; @@ -3005,6 +3012,7 @@ int Language::variableWrapper(Node *n) { String *gname = Swig_name_get(NSpace, symname); Setattr(n, "sym:name", gname); Delete(gname); + Setattr(n, "varget", "1"); functionWrapper(n); Swig_restore(n); return SWIG_OK; diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 10d9592cd..7a4f3229c 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -122,13 +122,20 @@ private: //String *s_vars_meta_tab; // metatable for variables Hash* namespaces_hash; + // Parameters for current class. NIL if not parsing class int have_constructor; int have_destructor; String *destructor_action; String *class_symname; + String *class_fq_symname; // Fully qualified symname - NSpace + '.' + class_symname + String *class_static_nspace; String *constructor_name; - enum { + // Many wrappers forward calls to each other, for example staticmembervariableHandler + // forwards call to variableHandler, which, in turn, makes to call to functionWrapper. + // In order to access information about whether it is static member of class or just + // plain old variable an array current is kept and used as 'log' of call stack. + enum TState { NO_CPP, VARIABLE, MEMBER_FUNC, @@ -137,8 +144,12 @@ private: MEMBER_VAR, CLASS_CONST, STATIC_FUNC, - STATIC_VAR - }current; + STATIC_VAR, + STATIC_CONST, // enums and things like static const int x = 5; + + STATES_COUNT + }; + bool current[STATES_COUNT]; public: @@ -175,10 +186,14 @@ public: have_destructor(0), destructor_action(0), class_symname(0), - constructor_name(0), - current(NO_CPP) { + class_fq_symname(0), + class_static_nspace(0), + constructor_name(0) { namespaces_hash = NewHash(); + for(int i = 0; i < STATES_COUNT; i++ ) + current[i] = false; } + ~LUA() { if(namespaces_hash) Delete(namespaces_hash); @@ -306,7 +321,9 @@ public: s_luacode = NewString(""); Swig_register_filebyname("luacode", s_luacode); - current=NO_CPP; + current[NO_CPP] = true; + // Registering names schemes + Swig_name_register("member", "%m"); /* Standard stuff for the SWIG runtime section */ Swig_banner(f_begin); @@ -473,6 +490,21 @@ public: * Create a function declaration and register it with the interpreter. * --------------------------------------------------------------------- */ + // Helper function. Remembers wrap name + void rememberWrapName(Node *n, String *wrapname) { + Setattr(n, "wrap:name", wrapname); + // If it is getter/setter, then write wrapname under + // wrap:memberset/wrap:memberget accordingly + if( Getattr(n, "memberset") ) + Setattr(n, "memberset:wrap:name", wrapname); + if( Getattr(n, "varset") ) + Setattr(n, "varset:wrap:name", wrapname); + if( Getattr(n, "memberget") ) + Setattr(n, "memberget:wrap:name", wrapname); + if( Getattr(n, "varget") ) + Setattr(n, "varget:wrap:name", wrapname); + } + virtual int functionWrapper(Node *n) { REPORT("functionWrapper",n); @@ -491,7 +523,7 @@ public: if (Getattr(n, "sym:overloaded")) { overname = Getattr(n, "sym:overname"); } else { - if (!addSymbol(iname, n, getNSpace())) { + if (!luaAddSymbol(iname, n)) { Printf(stderr,"addSymbol(%s) failed\n",iname); return SWIG_ERROR; } @@ -505,11 +537,13 @@ public: Wrapper_add_local(f, "SWIG_arg", "int SWIG_arg = 0"); - String *wname = Swig_name_wrapper(iname); + String* fqname = fully_qualified_name(iname); + String *wname = Swig_name_wrapper(fqname); + Delete(fqname); if (overname) { Append(wname, overname); } - if (current == CONSTRUCTOR) { + if (current[CONSTRUCTOR]) { if( constructor_name != 0) Delete(constructor_name); constructor_name = Copy(wname); @@ -552,12 +586,6 @@ public: } - /* 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; - /* NEW LANGUAGE NOTE:*********************************************** from here on in, it gets rather hairy this is the code to convert from the scripting language to C/C++ @@ -693,14 +721,7 @@ public: } // Remember C name of the wrapping function - Setattr(n, "wrap:name", wname); - // If it is getter/setter, then write wname under - // wrap:memberset/wrap:memberget accordingly - if( Getattr(n, "memberset") ) - Setattr(n, "memberset:wrap:name", wname); - if( Getattr(n, "memberget") ) - Setattr(n, "memberget:wrap:name", wname); - + rememberWrapName(n, wname); /* Emit the function call */ String *actioncode = emit_action(n); @@ -777,7 +798,7 @@ public: Therefore we go though the whole function, but do not write the code into the wrapper */ - if(current!=DESTRUCTOR) { + if(!current[DESTRUCTOR]) { Wrapper_print(f, f_wrappers); } @@ -789,7 +810,7 @@ public: if (!Getattr(n, "sym:overloaded")) { //REPORT("dispatchFunction", n); // add_method(n, iname, wname, description); - if (current==NO_CPP || current==STATIC_FUNC) { // emit normal fns & static fns + if (current[NO_CPP] || current[STATIC_FUNC]) { // emit normal fns & static fns Hash* nspaceHash = getNamespaceHash( getNSpace() ); String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); if(elua_ltr || eluac_ltr) @@ -877,24 +898,19 @@ public: Printv(f->code, "}\n", NIL); Wrapper_print(f, f_wrappers); //add_method(symname,wname,0); - if (current==NO_CPP || current==STATIC_FUNC) { // emit normal fns & static fns + if (current[NO_CPP] || current[STATIC_FUNC]) { // emit normal fns & static fns Hash* nspaceHash = getNamespaceHash( getNSpace() ); String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); Printv(s_ns_methods_tab, tab4, "{ \"", symname, "\",", wname, "},\n", NIL); } - if (current == CONSTRUCTOR) { + if (current[CONSTRUCTOR]) { if( constructor_name != 0 ) Delete(constructor_name); constructor_name = Copy(wname); } - Setattr(n, "wrap:name", wname); - // If it is getter/setter, then write wname under - // wrap:memberset/wrap:memberget accordingly - if( Getattr(n, "memberset") ) - Setattr(n, "memberset:wrap:name", wname); - if( Getattr(n, "memberget") ) - Setattr(n, "memberget:wrap:name", wname); + // Remember C name of the wrapping function + rememberWrapName(n, wname); DelWrapper(f); Delete(dispatch); @@ -916,13 +932,14 @@ public: NEW LANGUAGE NOTE:END ************************************************/ // REPORT("variableWrapper", n); String *iname = Getattr(n, "sym:name"); - current=VARIABLE; + String *unassignable = NewString("SWIG_Lua_set_immutable"); + current[VARIABLE] = true; // let SWIG generate the wrappers int result = Language::variableWrapper(n); - current=NO_CPP; + current[VARIABLE] = false; // normally SWIG will generate 2 wrappers, a get and a set // but in certain scenarios (immutable, or if its arrays), it will not - String *getName = Swig_name_wrapper(Swig_name_get(getNSpace(), iname)); + String *getName = Getattr(n,"varget:wrap:name"); String *setName = 0; // checking whether it can be set to or not appears to be a very error prone issue // I referred to the Language::variableWrapper() to find this out @@ -934,14 +951,15 @@ public: Delete(tm); if (assignable) { - setName = Swig_name_wrapper(Swig_name_set(getNSpace(), iname)); + setName = Getattr(n,"varset:wrap:name"); } else { // how about calling a 'this is not settable' error message? - setName = NewString("SWIG_Lua_set_immutable"); // error message - //setName = NewString("0"); + setName = unassignable;// error message } // register the variable + assert(setName != 0); + assert(getName != 0); Hash* nspaceHash = getNamespaceHash( getNSpace() ); String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); String* s_ns_var_tab = Getattr(nspaceHash, "attributes"); @@ -956,12 +974,11 @@ public: } else { Printf(s_ns_var_tab, "%s{ \"%s\", %s, %s },\n", tab4, iname, getName, setName); } - if (getCurrentClass()) { + if (getCurrentClass()) { // TODO: REMOVE Setattr(n, "luaclassobj:wrap:get", getName); Setattr(n, "luaclassobj:wrap:set", setName); } else { - Delete(getName); - Delete(setName); + Delete(unassignable); } return result; } @@ -978,8 +995,9 @@ public: String *rawval = Getattr(n, "rawval"); String *value = rawval ? rawval : Getattr(n, "value"); String *tm; + //Printf( stdout, "Add constant %s, ns %s\n", iname, getNSpace() );// TODO: REMOVE - if (!addSymbol(iname, n, getNSpace())) + if (!luaAddSymbol(iname, n)) return SWIG_ERROR; /* Special hook for member pointer */ @@ -1035,7 +1053,7 @@ public: // REPORT("nativeWrapper", n); String *symname = Getattr(n, "sym:name"); String *wrapname = Getattr(n, "wrap:name"); - if (!addSymbol(wrapname, n, getNSpace())) + if (!luaAddSymbol(wrapname, n)) return SWIG_ERROR; Hash *nspaceHash = getNamespaceHash( getNSpace() ); @@ -1050,7 +1068,23 @@ public: * ------------------------------------------------------------ */ virtual int enumDeclaration(Node *n) { - return Language::enumDeclaration(n); + // enumDeclaration supplied by Language is messing with NSpace. + // So this is the exact copy of function from Language with + // correct handling of namespaces + String *oldNSpace = getNSpace(); + if( getCurrentClass() == 0 ) { + setNSpace(Getattr(n, "sym:nspace")); + } + + if (!ImportMode) { + current[STATIC_CONST] = true; + emit_children(n); + current[STATIC_CONST] = false; + } + + setNSpace(oldNSpace); + + return SWIG_OK; } /* ------------------------------------------------------------ @@ -1058,7 +1092,27 @@ public: * ------------------------------------------------------------ */ virtual int enumvalueDeclaration(Node *n) { - return Language::enumvalueDeclaration(n); + if (getCurrentClass() && (cplus_mode != PUBLIC)) + return SWIG_NOWRAP; + + Swig_require("enumvalueDeclaration", n, "*name", "?value", NIL); + String *value = Getattr(n, "value"); + String *name = Getattr(n, "name"); + String *tmpValue; + + if (value) + tmpValue = NewString(value); + else + tmpValue = NewString(name); + Setattr(n, "value", tmpValue); + + Setattr(n, "name", tmpValue); /* for wrapping of enums in a namespace when emit_action is used */ + constantWrapper(n); + + Delete(tmpValue); + Swig_restore(n); + // TODO: Backward compatibility: add ClassName_ConstantName member + return SWIG_OK; } /* ------------------------------------------------------------ @@ -1076,8 +1130,7 @@ public: virtual int classHandler(Node *n) { //REPORT("classHandler", n); - String *mangled_full_class_symname = 0; - String *full_class_symname = 0; + String *mangled_class_fq_symname = 0; String* nspace = getNSpace(); String* destructor_name = 0; @@ -1085,19 +1138,27 @@ public: have_constructor = 0; have_destructor = 0; destructor_action = 0; + assert(class_static_nspace == 0); + assert(class_fq_symname == 0); + assert(class_symname == 0); + + current[NO_CPP] = false; class_symname = Getattr(n, "sym:name"); - if (!addSymbol(class_symname, n, nspace)) + // We have to enforce nspace here, because technically we are already + // inside class parsing (getCurrentClass != 0), but we should register + // class in the it's parent namespace + if (!luaAddSymbol(class_symname, n, nspace)) return SWIG_ERROR; if (nspace == 0) - full_class_symname = NewStringf("%s", class_symname); + class_fq_symname = NewStringf("%s", class_symname); else - full_class_symname = NewStringf("%s.%s", nspace, class_symname); + class_fq_symname = NewStringf("%s.%s", nspace, class_symname); - assert(full_class_symname != 0); - mangled_full_class_symname = Swig_name_mangle(full_class_symname); - Printf( stdout, "Mangled class symname %s\n", mangled_full_class_symname ); + assert(class_fq_symname != 0); + mangled_class_fq_symname = Swig_name_mangle(class_fq_symname); + Printf( stdout, "Mangled class symname %s\n", mangled_class_fq_symname ); // not sure exactly how this works, // but tcl has a static hashtable of all classes emitted and then only emits code for them once. @@ -1107,9 +1168,9 @@ public: // * consider effect on template_specialization_defarg static Hash *emitted = NewHash(); - if (Getattr(emitted, mangled_full_class_symname)) + if (Getattr(emitted, mangled_class_fq_symname)) return SWIG_NOWRAP; - Setattr(emitted, mangled_full_class_symname, "1"); + Setattr(emitted, mangled_class_fq_symname, "1"); // We treat class T as both 'class' and 'namespace'. All static members, attributes // and constants are considered part of namespace T, all members - part of the 'class' @@ -1122,7 +1183,7 @@ public: // And we can guarantee that there will not be any name collision because names starting with 2 underscores // and capital letter are forbiden to use in C++. So, under know circumstances could our class contain // any member or subclass with name "__Static". Thus, never any name clash. - Hash* non_static_cls = getNamespaceHash(full_class_symname, false); + Hash* non_static_cls = getNamespaceHash(class_fq_symname, false); assert(non_static_cls != 0); s_attr_tab = Getattr(non_static_cls, "attributes"); s_methods_tab = Getattr(non_static_cls, "methods"); @@ -1135,11 +1196,9 @@ public: * All constants are considered part of static part of class. */ - String *static_cls_key = NewStringf("%s%s__Static", full_class_symname, NSPACE_SEPARATOR); - Hash *static_cls = getNamespaceHash(static_cls_key, false); - if (static_cls == 0) { - return SWIG_ERROR; // This cant be, so it is internal, implementation error - } + class_static_nspace = NewStringf("%s%s__Static", class_fq_symname, NSPACE_SEPARATOR); + Hash *static_cls = getNamespaceHash(class_static_nspace, false); + assert(static_cls != 0); Setattr(static_cls, "lua:no_namespaces", "1"); /* TODO: REMOVE s_cls_methods_tab = Getattr(static_cls, "methods"); @@ -1160,17 +1219,18 @@ public: // Replacing namespace with namespace + class in order to static // member be put inside class static area - setNSpace(static_cls_key); + setNSpace(class_static_nspace); // Generate normal wrappers Language::classHandler(n); // Restore correct nspace setNSpace(nspace); + //Printf( stdout, "Class finished\n" ); TODO:REMOVE SwigType *t = Copy(Getattr(n, "name")); SwigType_add_pointer(t); // Catch all: eg. a class with only static functions and/or variables will not have 'remembered' - String *wrap_class = NewStringf("&_wrap_class_%s", mangled_full_class_symname); + String *wrap_class = NewStringf("&_wrap_class_%s", mangled_class_fq_symname); SwigType_remember_clientdata(t, wrap_class); String *rt = Copy(getClassType()); @@ -1182,12 +1242,12 @@ public: Printv( ns_classes, wrap_class, ",\n", NIL ); // Register the class structure with the type checker - // Printf(f_init,"SWIG_TypeClientData(SWIGTYPE%s, (void *) &_wrap_class_%s);\n", SwigType_manglestr(t), mangled_full_class_symname); + // Printf(f_init,"SWIG_TypeClientData(SWIGTYPE%s, (void *) &_wrap_class_%s);\n", SwigType_manglestr(t), mangled_class_fq_symname); // emit a function to be called to delete the object // TODO: class_name -> full_class_name || mangled full_class_name if (have_destructor) { - destructor_name = NewStringf("swig_delete_%s", mangled_full_class_symname); + destructor_name = NewStringf("swig_delete_%s", mangled_class_fq_symname); Printv(f_wrappers, "static void ", destructor_name, "(void *obj) {\n", NIL); if (destructor_action) { Printv(f_wrappers, SwigType_str(rt, "arg1"), " = (", SwigType_str(rt, 0), ") obj;\n", NIL); @@ -1201,9 +1261,26 @@ public: } Printf(f_wrappers, "}\n"); } + // Wrap constructor wrapper into one more proxy function. It will be used as class namespace __call method, thus + // allowing both + // Module.ClassName.StaticMethod to access static method/variable/constant + // Module.ClassName() to create new object + if (have_constructor) { + String* constructor_proxy_name = NewStringf("_proxy_%s", constructor_name); + Printv(f_wrappers, "static int ", constructor_proxy_name, "(lua_State *L) {\n", NIL); + Printv(f_wrappers, + tab4, "assert(lua_istable(L,1));\n", + tab4, "lua_pushcfunction(L,", constructor_name, ");\n", + tab4, "assert(!lua_isnil(L,-1));\n", + tab4, "lua_replace(L,1); /* replace our table with real constructor */\n", + tab4, "lua_call(L,lua_gettop(L)-1,1);\n", + tab4, "return 1;\n}\n", NIL); + Delete(constructor_name); + constructor_name = constructor_proxy_name; + } - closeNamespaceHash(full_class_symname, f_wrappers); - closeNamespaceHash(static_cls_key, f_wrappers); + closeNamespaceHash(class_fq_symname, f_wrappers); + closeNamespaceHash(class_static_nspace, f_wrappers); /* TODO: REMOVE @@ -1251,12 +1328,12 @@ public: } } - Printv(f_wrappers, "static swig_lua_class *swig_", mangled_full_class_symname, "_bases[] = {", base_class, "0};\n", NIL); + Printv(f_wrappers, "static swig_lua_class *swig_", mangled_class_fq_symname, "_bases[] = {", base_class, "0};\n", NIL); Delete(base_class); - Printv(f_wrappers, "static const char *swig_", mangled_full_class_symname, "_base_names[] = {", base_class_names, "0};\n", NIL); + Printv(f_wrappers, "static const char *swig_", mangled_class_fq_symname, "_base_names[] = {", base_class_names, "0};\n", NIL); Delete(base_class_names); - Printv(f_wrappers, "static swig_lua_class _wrap_class_", mangled_full_class_symname, " = { \"", class_symname, "\", &SWIGTYPE", SwigType_manglestr(t), ",", NIL); + Printv(f_wrappers, "static swig_lua_class _wrap_class_", mangled_class_fq_symname, " = { \"", class_symname, "\", \"", class_fq_symname,"\", &SWIGTYPE", SwigType_manglestr(t), ",", NIL); // TODO: Replace with constructor_name if (have_constructor) { @@ -1285,7 +1362,7 @@ public: if (have_destructor) { if (eluac_ltr) { String* ns_methods_tab = Getattr(nspaceHash, "methods"); - Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "free_", mangled_full_class_symname, "\")", ", LFUNCVAL(", destructor_name, ")", "},\n", NIL); + Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "free_", mangled_class_fq_symname, "\")", ", LFUNCVAL(", destructor_name, ")", "},\n", NIL); Printv(f_wrappers, ", ", destructor_name, NIL); } else { Printv(f_wrappers, ", ", destructor_name, NIL); @@ -1295,15 +1372,21 @@ public: } Printf(f_wrappers, ", %s, %s, ", s_methods_tab_name, s_attr_tab_name ); // TODO: Replace class_symname with class_name - printNamespaceDefinition(static_cls_key, class_symname, f_wrappers); + printNamespaceDefinition(class_static_nspace, class_symname, f_wrappers); Printf(f_wrappers, ", swig_%s_bases, swig_%s_base_names };\n\n", - mangled_full_class_symname, mangled_full_class_symname); + mangled_class_fq_symname, mangled_class_fq_symname); - // Printv(f_wrappers, ", swig_", mangled_full_class_symname, "_methods, swig_", mangled_full_class_symname, "_attributes, swig_", mangled_full_class_symname, "_bases };\n\n", NIL); - // Printv(s_cmd_tab, tab4, "{ SWIG_prefix \"", class_name, "\", (swig_wrapper_func) SWIG_ObjectConstructor, &_wrap_class_", mangled_full_class_symname, "},\n", NIL); + // Printv(f_wrappers, ", swig_", mangled_class_fq_symname, "_methods, swig_", mangled_class_fq_symname, "_attributes, swig_", mangled_class_fq_symname, "_bases };\n\n", NIL); + // Printv(s_cmd_tab, tab4, "{ SWIG_prefix \"", class_name, "\", (swig_wrapper_func) SWIG_ObjectConstructor, &_wrap_class_", mangled_class_fq_symname, "},\n", NIL); + + current[NO_CPP] = true; Delete(t); - Delete(mangled_full_class_symname); - Delete(static_cls_key); + Delete(mangled_class_fq_symname); + Delete(class_static_nspace); + class_static_nspace = 0; + Delete(class_fq_symname); + class_fq_symname = 0; + class_symname = 0; return SWIG_OK; } @@ -1327,9 +1410,9 @@ public: String *realname, *rname; - current = MEMBER_FUNC; + current[MEMBER_FUNC] = true; Language::memberfunctionHandler(n); - current = NO_CPP; + current[MEMBER_FUNC] = false; realname = iname ? iname : name; rname = Getattr(n, "wrap:name"); @@ -1350,9 +1433,9 @@ public: String *symname = Getattr(n, "sym:name"); String *getter_name, *setter_name; - current = MEMBER_VAR; + current[MEMBER_VAR] = true; Language::membervariableHandler(n); - current = NO_CPP; + current[MEMBER_VAR] = false; getter_name = Getattr(n, "memberget:wrap:name"); assert(getter_name != 0); if (!GetFlag(n, "feature:immutable")) { @@ -1382,9 +1465,9 @@ public: virtual int constructorHandler(Node *n) { // REPORT("constructorHandler", n); - current = CONSTRUCTOR; + current[CONSTRUCTOR] = true; Language::constructorHandler(n); - current = NO_CPP; + current[CONSTRUCTOR] = false; //constructor_name = NewString(Getattr(n, "sym:name")); have_constructor = 1; //Printf( stdout, "Constructor %s\n", constructor_name); TODO: REMOVE @@ -1397,9 +1480,9 @@ public: virtual int destructorHandler(Node *n) { REPORT("destructorHandler", n); - current = DESTRUCTOR; + current[DESTRUCTOR] = true; Language::destructorHandler(n); - current = NO_CPP; + current[DESTRUCTOR] = false; have_destructor = 1; destructor_action = Getattr(n, "wrap:action"); return SWIG_OK; @@ -1413,28 +1496,28 @@ public: virtual int staticmemberfunctionHandler(Node *n) { REPORT("staticmemberfunctionHandler", n); - current = STATIC_FUNC; + current[STATIC_FUNC] = true; //String *symname = Getattr(n, "sym:name"); int result = Language::staticmemberfunctionHandler(n); if (cparse_cplusplus && getCurrentClass()) { Swig_restore(n); } - current = NO_CPP; + current[STATIC_FUNC] = false;; if (result != SWIG_OK) return result; if (Getattr(n, "sym:nextSibling")) return SWIG_OK; - Swig_require("luaclassobj_staticmemberfunctionHandler", n, "luaclassobj:wrap:name", NIL); + //Swig_require("luaclassobj_staticmemberfunctionHandler", n, "luaclassobj:wrap:name", NIL); //String *name = Getattr(n, "name"); //String *rname, *realname; //realname = symname ? symname : name; //rname = Getattr(n, "luaclassobj:wrap:name"); // TODO: Add backward compatibility here: add "ClassName_FuncName" to global table //Printv(s_cls_methods_tab, tab4, "{\"", realname, "\", ", rname, "}, \n", NIL); - Swig_restore(n); + //Swig_restore(n); return SWIG_OK; } @@ -1454,7 +1537,7 @@ public: } int result = Language::memberconstantHandler(n); if (cparse_cplusplus && getCurrentClass()) - Swig_restore(n); + Swig_restore(n); // TODO: WTF ? return result; } @@ -1465,9 +1548,10 @@ public: virtual int staticmembervariableHandler(Node *n) { REPORT("staticmembervariableHandler",n); - current = STATIC_VAR; + current[STATIC_VAR] = true; //String *symname = Getattr(n, "sym:name"); int result = Language::staticmembervariableHandler(n); + current[STATIC_VAR] = false; if (result != SWIG_OK) return result; @@ -1868,6 +1952,53 @@ public: Printf( output, "static swig_lua_namespace %s;\n", Getattr(nspace_hash, "cname") ); } + + // Our implementation of addSymbol. Determines scope correctly, then calls Language::addSymbol + int luaAddSymbol(const String *s, const Node *n) { + String* scope = 0; + // If ouside class, than NSpace is used. + if( !getCurrentClass()) + scope = getNSpace(); + else { + // If inside class, then either class static namespace or class fully qualified name is used + assert(!current[NO_CPP]); + if(current[STATIC_FUNC] || current[STATIC_VAR] || current[STATIC_CONST] ) { + scope = class_static_nspace; + } else if(current[MEMBER_VAR] || current[CLASS_CONST] || current[CONSTRUCTOR] || current[DESTRUCTOR] + || current[MEMBER_FUNC] ) { + scope = class_fq_symname; + } else { + assert(0); // Can't be. Implementation error + } + assert(scope != 0); + } + return Language::addSymbol(s,n,scope); + } + + // Overload. Enforces given scope. Actually, it simply forwards call to Language::addSymbol + int luaAddSymbol(const String*s, const Node*n, const_String_or_char_ptr scope) { + return Language::addSymbol(s,n,scope); + } + + // Function creates fully qualified name of given symbol. Current NSpace and current class + // are used + String* fully_qualified_name(const_String_or_char_ptr name) + { + assert(name != 0); + String* scope= 0; + if( getCurrentClass() ) + scope = class_fq_symname; + else + scope = getNSpace(); + + String *fqname = 0; + if( scope ) + fqname = NewStringf("%s::%s",scope,name); + else + fqname = Copy(name); + + return fqname; + } }; /* NEW LANGUAGE NOTE:*********************************************** From 602cf3a797fcc405b84fc1f462cc5cb1d864226d Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Thu, 31 Oct 2013 18:03:06 +0400 Subject: [PATCH 390/481] Bugfixes --- Source/Modules/lua.cxx | 316 ++++++++++++++++++++++++++++-------- Source/Modules/overload.cxx | 2 + Source/Swig/typesys.c | 2 +- 3 files changed, 253 insertions(+), 67 deletions(-) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 7a4f3229c..72d8fe8d1 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -73,7 +73,55 @@ void display_mapping(DOH *d) { } } +// Holds the pointer. Call's Delete in destructor, assignment etc +// TODO: REVIEW +template // T is ignored because everything is DOH* +class DohPointer { + public: + /* + DohPointer( DOH* _ptr ): + p_ptr(_ptr) + { + assert( p_ptr != 0 ); + } + */ + DohPointer(): + p_ptr(0) {} + DohPointer( const DohPointer& rhs ) { + AttachExisting( rhs.p_ptr ); + } + + const DohPointer& operator=( const DohPointer& rhs ) { + AttachExisting(rhs.p_ptr); + } + + DOH* ptr() { return p_ptr; } + const DOH* ptr() const { return p_ptr; } + operator DOH* () { return p_ptr; } + operator DOH* () const { return p_ptr; } + + // Attaches existing pointer. Refcount will be increased + void AttachExisting( DOH* obj ) { + AttachNew(obj); + if( p_ptr != 0 ) + DohIncref(p_ptr); + } + + // Attaches new pointer. As refcount is set to 1 at the creation, it won't be + // increased + void AttachNew( DOH *obj ) { + DOH* old_ptr = p_ptr; + p_ptr = obj; + if( old_ptr != 0 ) + Delete(old_ptr); + } + + private: + DOH* p_ptr; +}; + +#define Pointer DohPointer /* NEW LANGUAGE NOTE:*********************************************** most of the default options are handled by SWIG @@ -91,6 +139,7 @@ Lua Options (available with -lua)\n\ static int nomoduleglobal = 0; static int elua_ltr = 0; static int eluac_ltr = 0; +static int v2_compatibility = 1; /* NEW LANGUAGE NOTE:*********************************************** To add a new language, you need to derive your class from @@ -129,6 +178,7 @@ private: String *class_symname; String *class_fq_symname; // Fully qualified symname - NSpace + '.' + class_symname String *class_static_nspace; + String *class_parent_nspace; String *constructor_name; // Many wrappers forward calls to each other, for example staticmembervariableHandler @@ -322,8 +372,9 @@ public: Swig_register_filebyname("luacode", s_luacode); current[NO_CPP] = true; - // Registering names schemes - Swig_name_register("member", "%m"); + // Registering names schemes: TODO: REMOVE + //Swig_name_register("member", "%m"); + //Swig_name_register("construct", "new_%c"); /* Standard stuff for the SWIG runtime section */ Swig_banner(f_begin); @@ -476,6 +527,27 @@ public: return Language::importDirective(n); } + virtual int cDeclaration(Node *n) { + // Language is messing with symname in a really heavy way. + // Although documentation states that sym:name is a name in + // the target language space, it is not true. sym:name and + // it's derivatives are used in various places, including + // behind-the-scene C code generation. The best way is not to + // touch it at all. + // But we need to know what was the name of function/variable + // etc that user desired, that's why we store correct symname + // as lua:name + Setattr(n, "lua:name", Getattr(n, "sym:name") ); + return Language::cDeclaration(n); + } + virtual int constructorDeclaration(Node *n) { + Setattr(n, "lua:name", Getattr(n, "sym:name") ); + return Language::constructorDeclaration(n); + } + virtual int destructorDeclaration(Node *n) { + Setattr(n, "lua:name", Getattr(n, "sym:name") ); + return Language::destructorDeclaration(n); + } /* NEW LANGUAGE NOTE:*********************************************** This is it! you get this one right, and most of your work is done @@ -510,6 +582,8 @@ public: String *name = Getattr(n, "name"); String *iname = Getattr(n, "sym:name"); + String *target_name = Getattr(n, "lua:name"); + assert(target_name != 0); SwigType *d = Getattr(n, "type"); ParmList *l = Getattr(n, "parms"); //Printf(stdout,"functionWrapper %s %s\n",name,iname); @@ -523,8 +597,8 @@ public: if (Getattr(n, "sym:overloaded")) { overname = Getattr(n, "sym:overname"); } else { - if (!luaAddSymbol(iname, n)) { - Printf(stderr,"addSymbol(%s) failed\n",iname); + if (!luaAddSymbol(target_name, n)) { + Printf(stderr,"addSymbol(%s) failed\n",target_name); return SWIG_ERROR; } } @@ -537,9 +611,7 @@ public: Wrapper_add_local(f, "SWIG_arg", "int SWIG_arg = 0"); - String* fqname = fully_qualified_name(iname); - String *wname = Swig_name_wrapper(fqname); - Delete(fqname); + String *wname = symname_wrapper(iname); if (overname) { Append(wname, overname); } @@ -548,7 +620,7 @@ public: Delete(constructor_name); constructor_name = Copy(wname); } - //Printf(stdout , "Function wrapper, name %s\n", wname); // TODO:REMOVE + //Printf(stdout , "Function wrapper, name %s wrapname %s\n", iname, wname); // TODO:REMOVE /* NEW LANGUAGE NOTE:*********************************************** the format of a lua fn is: @@ -807,20 +879,10 @@ public: different language mappings seem to use different ideas NEW LANGUAGE NOTE:END ************************************************/ /* Now register the function with the interpreter. */ + //TODO: iname -> lua:name if (!Getattr(n, "sym:overloaded")) { - //REPORT("dispatchFunction", n); - // add_method(n, iname, wname, description); if (current[NO_CPP] || current[STATIC_FUNC]) { // emit normal fns & static fns - Hash* nspaceHash = getNamespaceHash( getNSpace() ); - String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); - if(elua_ltr || eluac_ltr) - Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", iname, "\")", ", LFUNCVAL(", wname, ")", "},\n", NIL); - else - Printv(s_ns_methods_tab, tab4, "{ \"", iname, "\", ", wname, "},\n", NIL); - // Printv(s_cmd_tab, tab4, "{ SWIG_prefix \"", iname, "\", (swig_wrapper_func) ", Swig_name_wrapper(iname), "},\n", NIL); - if (getCurrentClass()) { - Setattr(n,"luaclassobj:wrap:name", wname); - } + registerMethod(getNSpace(), n); } } else { if (!Getattr(n, "sym:nextSibling")) { @@ -834,7 +896,7 @@ public: Delete(cleanup); Delete(outarg); // Delete(description); - Delete(wname); + //Delete(wname); // TODO: Reference count seems not working DelWrapper(f); return SWIG_OK; @@ -856,6 +918,7 @@ public: //REPORT("dispatchFunction", n); /* Last node in overloaded chain */ + //Printf(stdout , "Dispatch, wrapname %s\n", Getattr(n,"wrap:name")); // TODO:REMOVE int maxargs; String *tmp = NewString(""); String *dispatch = Swig_overload_dispatch(n, "return %s(L);", &maxargs); @@ -864,7 +927,9 @@ public: Wrapper *f = NewWrapper(); String *symname = Getattr(n, "sym:name"); - String *wname = Swig_name_wrapper(symname); + String *target_name = Getattr(n, "lua:name"); + assert(target_name != 0); + String *wname = symname_wrapper(symname); //Printf(stdout,"Swig_overload_dispatch %s %s '%s' %d\n",symname,wname,dispatch,maxargs); @@ -897,11 +962,11 @@ public: Printf(f->code, "lua_error(L);return 0;\n"); Printv(f->code, "}\n", NIL); Wrapper_print(f, f_wrappers); - //add_method(symname,wname,0); if (current[NO_CPP] || current[STATIC_FUNC]) { // emit normal fns & static fns + // TODO: elua_ltr ? Hash* nspaceHash = getNamespaceHash( getNSpace() ); String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); - Printv(s_ns_methods_tab, tab4, "{ \"", symname, "\",", wname, "},\n", NIL); + Printv(s_ns_methods_tab, tab4, "{ \"", target_name, "\",", wname, "},\n", NIL); } if (current[CONSTRUCTOR]) { if( constructor_name != 0 ) @@ -932,17 +997,20 @@ public: NEW LANGUAGE NOTE:END ************************************************/ // REPORT("variableWrapper", n); String *iname = Getattr(n, "sym:name"); - String *unassignable = NewString("SWIG_Lua_set_immutable"); + String *target_name = Getattr(n, "lua:name"); + assert(target_name != 0); current[VARIABLE] = true; // let SWIG generate the wrappers int result = Language::variableWrapper(n); current[VARIABLE] = false; // normally SWIG will generate 2 wrappers, a get and a set // but in certain scenarios (immutable, or if its arrays), it will not - String *getName = Getattr(n,"varget:wrap:name"); - String *setName = 0; + //String *getName = Getattr(n,"varget:wrap:name"); + //String *setName = 0; // checking whether it can be set to or not appears to be a very error prone issue // I referred to the Language::variableWrapper() to find this out + // TODO: REMOVE? + /* bool assignable=is_assignable(n) ? true : false; SwigType *type = Getattr(n, "type"); String *tm = Swig_typemap_lookup("globalin", n, iname, 0); @@ -955,31 +1023,20 @@ public: } else { // how about calling a 'this is not settable' error message? setName = unassignable;// error message - } + }*/ // register the variable - assert(setName != 0); - assert(getName != 0); - Hash* nspaceHash = getNamespaceHash( getNSpace() ); - String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); - String* s_ns_var_tab = Getattr(nspaceHash, "attributes"); - if (elua_ltr) { - String* s_ns_dot_get = Getattr(nspaceHash, "get"); - String* s_ns_dot_set = Getattr(nspaceHash, "set"); - Printf(s_ns_dot_get, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, iname, getName); - Printf(s_ns_dot_set, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, iname, setName); - } else if (eluac_ltr) { - Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", iname, "_get", "\")", ", LFUNCVAL(", getName, ")", "},\n", NIL); - Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", iname, "_set", "\")", ", LFUNCVAL(", setName, ")", "},\n", NIL); - } else { - Printf(s_ns_var_tab, "%s{ \"%s\", %s, %s },\n", tab4, iname, getName, setName); - } - if (getCurrentClass()) { // TODO: REMOVE + //assert(setName != 0); + //assert(getName != 0); + // TODO: CHeck. It seems to register everything in namespaces + // What about class variables ? + registerVariable( getNSpace(), n, "varget:wrap:name", "varset:wrap:name" ); + /*if (getCurrentClass()) { // TODO: REMOVE Setattr(n, "luaclassobj:wrap:get", getName); Setattr(n, "luaclassobj:wrap:set", setName); } else { Delete(unassignable); - } + }*/ return result; } @@ -990,6 +1047,9 @@ public: REPORT("constantWrapper", n); String *name = Getattr(n, "name"); String *iname = Getattr(n, "sym:name"); + String *target_name = Getattr(n, "lua:name"); + if(target_name == 0) + target_name = iname; String *nsname = Copy(iname); SwigType *type = Getattr(n, "type"); String *rawval = Getattr(n, "rawval"); @@ -997,12 +1057,14 @@ public: String *tm; //Printf( stdout, "Add constant %s, ns %s\n", iname, getNSpace() );// TODO: REMOVE - if (!luaAddSymbol(iname, n)) + if (!luaAddSymbol(target_name, n)) return SWIG_ERROR; + Swig_save("lua_constantMember", n, "sym:name", NIL); + Setattr(n, "sym:name", target_name); /* Special hook for member pointer */ if (SwigType_type(type) == T_MPOINTER) { - String *wname = Swig_name_wrapper(iname); + String *wname = symname_wrapper(iname); Printf(f_wrappers, "static %s = %s;\n", SwigType_str(type, wname), value); value = Char(wname); } @@ -1024,8 +1086,37 @@ public: } else { Delete(nsname); Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value.\n"); + Swig_restore(n); return SWIG_NOWRAP; } + /* TODO: Review + if( v2_compatibility && getCurrentClass() ) { + if (!luaAddSymbol(iname, n, class_parent_nspace)) + return SWIG_ERROR; + + Setattr(n, "sym:name", iname); + 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); + Hash *nspaceHash = getNamespaceHash( class_parent_nspace ); + String *s_const_tab = Getattr(nspaceHash, "constants"); + Printf(s_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); + } else { + Delete(nsname); + Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value.\n"); + Swig_restore(n); + return SWIG_NOWRAP; + } + } + */ /* TODO: Fix if (cparse_cplusplus && getCurrentClass()) { // Additionally add to class constants @@ -1041,6 +1132,7 @@ public: } Swig_restore(n); }*/ + Swig_restore(n); Delete(nsname); return SWIG_OK; } @@ -1053,6 +1145,7 @@ public: // REPORT("nativeWrapper", n); String *symname = Getattr(n, "sym:name"); String *wrapname = Getattr(n, "wrap:name"); + //String *target_name = Getattr(n, "lua:name"); TODO: REMOVE if (!luaAddSymbol(wrapname, n)) return SWIG_ERROR; @@ -1158,8 +1251,15 @@ public: assert(class_fq_symname != 0); mangled_class_fq_symname = Swig_name_mangle(class_fq_symname); - Printf( stdout, "Mangled class symname %s\n", mangled_class_fq_symname ); + SwigType *t = Copy(Getattr(n, "name")); + SwigType *fr_t = SwigType_typedef_resolve_all(t); /* Create fully resolved type */ + SwigType *t_tmp = SwigType_typedef_qualified(fr_t); // Temporal variable + Delete(fr_t); + fr_t = SwigType_strip_qualifiers(t_tmp); + Delete(t_tmp); + String *mangled_fr_t = SwigType_manglestr(fr_t); + //Printf( stdout, "Mangled class symname %s fr type%s\n", mangled_class_fq_symname, mangled_fr_t ); // TODO: REMOVE // not sure exactly how this works, // but tcl has a static hashtable of all classes emitted and then only emits code for them once. // this fixes issues in test suites: template_default2 & template_specialization @@ -1168,9 +1268,13 @@ public: // * consider effect on template_specialization_defarg static Hash *emitted = NewHash(); - if (Getattr(emitted, mangled_class_fq_symname)) + if (Getattr(emitted, mangled_fr_t)) { + class_fq_symname = 0; + class_symname = 0; + // TODO: Memory leak here return SWIG_NOWRAP; - Setattr(emitted, mangled_class_fq_symname, "1"); + } + Setattr(emitted, mangled_fr_t, "1"); // We treat class T as both 'class' and 'namespace'. All static members, attributes // and constants are considered part of namespace T, all members - part of the 'class' @@ -1219,14 +1323,15 @@ public: // Replacing namespace with namespace + class in order to static // member be put inside class static area + class_parent_nspace = getNSpace(); setNSpace(class_static_nspace); // Generate normal wrappers Language::classHandler(n); // Restore correct nspace setNSpace(nspace); + class_parent_nspace = 0; //Printf( stdout, "Class finished\n" ); TODO:REMOVE - SwigType *t = Copy(Getattr(n, "name")); SwigType_add_pointer(t); // Catch all: eg. a class with only static functions and/or variables will not have 'remembered' @@ -1341,16 +1446,16 @@ public: String* ns_methods_tab = Getattr(nspaceHash, "methods"); // TODO: Contructor should be moved to __call method of static part of class Printf(ns_methods_tab, " {LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", class_symname, \ - Swig_name_wrapper(Swig_name_construct(nspace, constructor_name))); - Printf(f_wrappers, "%s", Swig_name_wrapper(Swig_name_construct(nspace, constructor_name))); + symname_wrapper(Swig_name_construct(nspace, constructor_name))); + Printf(f_wrappers, "%s", symname_wrapper(Swig_name_construct(nspace, constructor_name))); } else if (eluac_ltr) { String* ns_methods_tab = Getattr(nspaceHash, "methods"); Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "new_", class_symname, "\")", ", LFUNCVAL(", \ - Swig_name_wrapper(Swig_name_construct(nspace, constructor_name)), ")", "},\n", NIL); - Printf(f_wrappers, "%s", Swig_name_wrapper(Swig_name_construct(nspace, constructor_name))); + symname_wrapper(Swig_name_construct(nspace, constructor_name)), ")", "},\n", NIL); + Printf(f_wrappers, "%s", symname_wrapper(Swig_name_construct(nspace, constructor_name))); } else { - //Printf( stdout, "Constructor.name %s declaration: %s\n", constructor_name, Swig_name_wrapper(Swig_name_construct(nspace, constructor_name))); - //Printf(f_wrappers, "%s", Swig_name_wrapper(Swig_name_construct(nspace, constructor_name))); + //Printf( stdout, "Constructor.name %s declaration: %s\n", constructor_name, symname_wrapper(Swig_name_construct(nspace, constructor_name))); + //Printf(f_wrappers, "%s", symname_wrapper(Swig_name_construct(nspace, constructor_name))); Printv(f_wrappers, constructor_name, NIL); } Delete(constructor_name); @@ -1501,12 +1606,16 @@ public: int result = Language::staticmemberfunctionHandler(n); if (cparse_cplusplus && getCurrentClass()) { - Swig_restore(n); + Swig_restore(n); // TODO: WTF ? } current[STATIC_FUNC] = false;; if (result != SWIG_OK) return result; + if(v2_compatibility) { + registerMethod( class_parent_nspace, n ); + } + if (Getattr(n, "sym:nextSibling")) return SWIG_OK; @@ -1531,13 +1640,16 @@ public: virtual int memberconstantHandler(Node *n) { REPORT("memberconstantHandler",n); String *symname = Getattr(n, "sym:name"); + /* TODO:REMOVE if (cparse_cplusplus && getCurrentClass()) { Swig_save("luaclassobj_memberconstantHandler", n, "luaclassobj:symname", NIL); Setattr(n, "luaclassobj:symname", symname); - } + }*/ int result = Language::memberconstantHandler(n); + /* TODO:REMOVE if (cparse_cplusplus && getCurrentClass()) Swig_restore(n); // TODO: WTF ? + */ return result; } @@ -1556,9 +1668,25 @@ public: if (result != SWIG_OK) return result; - - if (Getattr(n, "wrappedasconstant")) - return SWIG_OK; + // This will add static member variable to the class namespace with name ClassName_VarName + if(v2_compatibility) { + Swig_save("lua_staticmembervariableHandler",n,"lua:name"); + String *target_name = Getattr(n, "lua:name"); + String *v2_name = Swig_name_member(NIL, class_symname, target_name); + //Printf( stdout, "Name %s, class %s, compt. name %s\n", target_name, class_symname, v2_name ); // TODO: REMOVE + if( !GetFlag(n,"wrappedasconstant") ) { + Setattr(n, "lua:name", v2_name); + registerVariable( class_parent_nspace, n, "varget:wrap:name", "varset:wrap:name"); + } else { + Setattr(n, "lua:name", v2_name); + String* oldNSpace = getNSpace(); + setNSpace(class_parent_nspace); + constantWrapper(n); + setNSpace(oldNSpace); + } + Delete(v2_name); + Swig_restore(n); + } /* TODO: Add backward compatibility here: add "ClassName_AttributeName" to class scope Swig_require("luaclassobj_staticmembervariableHandler", n, "luaclassobj:wrap:get", "luaclassobj:wrap:set", NIL); @@ -1887,7 +2015,7 @@ public: Hash* nspace = Getattr(namespaces_hash, key); String* cname = Getattr(nspace, "cname"); // cname - name of the C structure that describes namespace assert(cname != 0); - Printf( stdout, "Closing namespace %s\n", cname ); + //Printf( stdout, "Closing namespace %s\n", cname ); TODO: REMOVE //printNamespaceForwardDeclaration( ki.key, declOutput ); TODO: REMOVE Printv(dataOutput, "static swig_lua_namespace ", cname, " = ", NIL); String *name = 0; // name - name of the namespace as it should be visible in Lua @@ -1930,6 +2058,50 @@ public: ); } + // Add method to the "methods" C array of given namespace/class + void registerMethod(String *nspace_or_class_name, Node* n) { + Hash* nspaceHash = getNamespaceHash( nspace_or_class_name ); + String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); + String *wname = Getattr(n, "wrap:name"); + String *iname = Getattr(n, "sym:name"); + String *target_name = Getattr(n, "lua:name"); + if(elua_ltr || eluac_ltr) + Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", iname, "\")", ", LFUNCVAL(", wname, ")", "},\n", NIL); + else + Printv(s_ns_methods_tab, tab4, "{ \"", target_name, "\", ", wname, "},\n", NIL); + // Printv(s_cmd_tab, tab4, "{ SWIG_prefix \"", iname, "\", (swig_wrapper_func) ", symname_wrapper(iname), "},\n", NIL); + if (getCurrentClass()) { + Setattr(n,"luaclassobj:wrap:name", wname); // TODO: REMOVE + } + } + + // Add variable to the "attributes" (or "get"/"set" in + // case of elua_ltr) C arrays of given namespace or class + void registerVariable(String *nspace_or_class_name, Node* n, const char *getAttrName, const char *setAttrName) { + String *unassignable = NewString("SWIG_Lua_set_immutable"); + String *getName = Getattr(n,getAttrName); + String *setName = Getattr(n,setAttrName); + if(setName == 0) { + setName = unassignable; + } + Hash* nspaceHash = getNamespaceHash( nspace_or_class_name ); + String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); + String* s_ns_var_tab = Getattr(nspaceHash, "attributes"); + String *target_name = Getattr(n, "lua:name"); + if (elua_ltr) { + String* s_ns_dot_get = Getattr(nspaceHash, "get"); + String* s_ns_dot_set = Getattr(nspaceHash, "set"); + Printf(s_ns_dot_get, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, target_name, getName); + Printf(s_ns_dot_set, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, target_name, setName); + } else if (eluac_ltr) { + Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", target_name, "_get", "\")", ", LFUNCVAL(", getName, ")", "},\n", NIL); + Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", target_name, "_set", "\")", ", LFUNCVAL(", setName, ")", "},\n", NIL); + } else { + Printf(s_ns_var_tab, "%s{ \"%s\", %s, %s },\n", tab4, target_name, getName, setName); + } + } + + // This function prints forward declaration of namespace itself and all its arrays // TODO: REMOVE void printNamespaceForwardDeclaration(String* nspace, File* output) @@ -1955,6 +2127,7 @@ public: // Our implementation of addSymbol. Determines scope correctly, then calls Language::addSymbol int luaAddSymbol(const String *s, const Node *n) { + //Printf(stdout, "addSymbol: %s", s); // TODO:REMOVE String* scope = 0; // If ouside class, than NSpace is used. if( !getCurrentClass()) @@ -1967,11 +2140,12 @@ public: } else if(current[MEMBER_VAR] || current[CLASS_CONST] || current[CONSTRUCTOR] || current[DESTRUCTOR] || current[MEMBER_FUNC] ) { scope = class_fq_symname; - } else { - assert(0); // Can't be. Implementation error + } else { // Friend functions are handled this way + scope = class_static_nspace; } assert(scope != 0); } + //Printf( stdout, " scope: %s\n", scope ); // TODO:REMOVE return Language::addSymbol(s,n,scope); } @@ -1999,6 +2173,16 @@ public: return fqname; } + + // Input: symname + // Output - wrapper around fully qualified form of symname + String* symname_wrapper( String *symname) + { + String *fqname = fully_qualified_name(symname); + String* wname = Swig_name_wrapper(fqname); + Delete(fqname); + return wname; + } }; /* NEW LANGUAGE NOTE:*********************************************** diff --git a/Source/Modules/overload.cxx b/Source/Modules/overload.cxx index e95ef557f..4c0d06702 100644 --- a/Source/Modules/overload.cxx +++ b/Source/Modules/overload.cxx @@ -765,6 +765,7 @@ String *Swig_overload_dispatch(Node *n, const_String_or_char_ptr fmt, int *maxar for (i = 0; i < nfunc; i++) { Node *ni = Getitem(dispatch, i); Parm *pi = Getattr(ni, "wrap:parms"); + //Printf(stdout , "Dispatch, wrapname %s\n", Getattr(ni,"wrap:name")); // TODO:REMOVE bool implicitconvtypecheckoff = GetFlag(ni, "implicitconvtypecheckoff") != 0; int num_required = emit_num_required(pi); int num_arguments = emit_num_arguments(pi); @@ -818,6 +819,7 @@ String *Swig_overload_dispatch(Node *n, const_String_or_char_ptr fmt, int *maxar j++; } String *lfmt = ReplaceFormat(fmt, num_arguments); + //Printf(stdout , "Dispatch, wrapname %s\n", Getattr(ni,"wrap:name")); // TODO:REMOVE Printf(f, Char(lfmt), Getattr(ni, "wrap:name")); Delete(lfmt); /* close braces */ diff --git a/Source/Swig/typesys.c b/Source/Swig/typesys.c index e11fc781a..a7060ca54 100644 --- a/Source/Swig/typesys.c +++ b/Source/Swig/typesys.c @@ -1594,7 +1594,7 @@ void SwigType_remember_clientdata(const SwigType *t, const_String_or_char_ptr cl Delete(qr); /*Printf(stdout,"t = '%s'\n", t); - Printf(stdout,"fr= '%s'\n\n", fr); */ + Printf(stdout,"fr= '%s'\n\n", fr); TODO: COmment back*/ if (t) { char *ct = Char(t); From aec439128429d594090d6872e710ded4fdb386ed Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Thu, 31 Oct 2013 20:48:38 +0400 Subject: [PATCH 391/481] Add runtime test --- Examples/test-suite/lua/nspace_runme.lua | 67 ++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Examples/test-suite/lua/nspace_runme.lua diff --git a/Examples/test-suite/lua/nspace_runme.lua b/Examples/test-suite/lua/nspace_runme.lua new file mode 100644 index 000000000..4eb0ffaf6 --- /dev/null +++ b/Examples/test-suite/lua/nspace_runme.lua @@ -0,0 +1,67 @@ +require("import") -- the import fn +import("nspace") -- import lib + +-- catch "undefined" global variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +ns = nspace + +-- Inheritance +blue1 = ns.Outer.Inner3.Blue() +debug.debug() +-- blue1:blueInstanceMethod() +blue1:colorInstanceMethod(60.0) +blue1.instanceMemberVariable = 4 +assert( blue1.instanceMemberVariable == 4 ) + +-- Constructors +color1 = ns.Outer.Inner1.Color() +color2 = ns.Outer.Inner1.Color.create() +color = ns.Outer.Inner1.Color(color1) +color3 = ns.Outer.Inner2.Color.create() +color4 = ns.Outer.Inner2.Color.create() +color5 = ns.Outer.Inner2.Color.create() +mwp2 = ns.Outer.MyWorldPart2() +gc = ns.GlobalClass() + +nnsp = ns.NoNSpacePlease() + +-- Class methods +color:colorInstanceMethod(20.0) +ns.Outer.Inner1.Color.colorStaticMethod(30.0) +color3:colorInstanceMethod(40.0) +ns.Outer.Inner2.Color.colorStaticMethod(50.0) +color3:colors(color1, color2, color3, color4, color5) + +gc:gmethod() + +-- Class variables +color.instanceMemberVariable = 5 +color1.instanceMemberVariable = 7 +assert( color.instanceMemberVariable == 5 ) +assert( color1.instanceMemberVariable == 7 ) +assert(ns.Outer.Inner1.Color.staticMemberVariable == 0 ) +assert(ns.Outer.Inner2.Color.staticMemberVariable == 0 ) +ns.Outer.Inner1.Color.staticMemberVariable = 9 +ns.Outer.Inner2.Color.staticMemberVariable = 11 +assert(ns.Outer.Inner1.Color.staticMemberVariable == 9) +assert(ns.Outer.Inner2.Color.staticMemberVariable == 11) + +-- Class constants +assert( ns.Outer.Inner1.Color.Specular == 0x20 ) +assert( ns.Outer.Inner2.Color.Specular == 0x40 ) +assert( ns.Outer.Inner1.Color.staticConstMemberVariable == 222 ) +assert( ns.Outer.Inner2.Color.staticConstMemberVariable == 333 ) +assert( ns.Outer.Inner1.Color.staticConstEnumMemberVariable ~= ns.Outer.Inner2.Color.staticConstEnumMemberVariable ) + + +-- Aggregation +sc = ns.Outer.SomeClass() +assert( sc:GetInner1ColorChannel() ~= sc:GetInner2Channel() ) +assert( sc:GetInner1Channel() ~= sc:GetInner2Channel() ) + + + + From ad375d9526e6b99c93394771339cdcb4e52c0896 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Fri, 1 Nov 2013 17:47:12 +0400 Subject: [PATCH 392/481] Add pointer guard --- Source/Modules/lua.cxx | 106 +++++++++++++++++++++++++++++++++-------- 1 file changed, 86 insertions(+), 20 deletions(-) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 72d8fe8d1..0a7dd1041 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -75,6 +75,7 @@ void display_mapping(DOH *d) { // Holds the pointer. Call's Delete in destructor, assignment etc // TODO: REVIEW +// Class won't work, TODO: REMOVE template // T is ignored because everything is DOH* class DohPointer { public: @@ -123,6 +124,74 @@ class DohPointer { #define Pointer DohPointer +template // T is ignored because everything is DOH* +class DohPtrGuard { + public: + DohPtrGuard( DOH* _ptr ): + p_ptr(_ptr) + { + assert( p_ptr != 0 ); + } + DohPtrGuard(): + p_ptr(0) {} + + ~DohPtrGuard() { + release(); + } + + // Guard is empty, ptr - any: assigns new value for guard + // Guard is holding pointer, ptr == 0 - releases value that guard holds + // Any other combination - assert + void operator=( DOH* ptr ) { + attach(ptr); + } + + DOH* ptr() { return p_ptr; } + const DOH* ptr() const { return p_ptr; } + operator DOH* () { return p_ptr; } + operator DOH* () const { return p_ptr; } + + private: + DOH* p_ptr; // pointer to actual object + + void attach(DOH* ptr) { + if( p_ptr != 0 ) { // If some object already attached, then we can't attach another one + assert(ptr == 0); + if( ptr == 0 ) { + release(); + } + } else { + p_ptr = ptr; + } + } + + void release() { + if( p_ptr != 0 ) { + Delete(p_ptr); + p_ptr = 0; + } + } + // Copying is forbiden + DohPtrGuard( const DohPtrGuard& rhs ); + void operator=( const DohPtrGuard& rhs ); + +}; + +// Overloading DohDelete for DohPtrGuard. You might not call DohDelete on DohPtrGuard instances, +// as it is supposed to manage underlying pointer by itself + +void DohDelete(const DohPtrGuard& guard) { + Printf( stderr, "ERROR: Attempt to delete guarded pointer without deleting it's guardian\n" ); + assert(false); +} +void DohDelete(DohPtrGuard& guard) { + Printf( stderr, "ERROR: Attempt to delete guarded pointer without deleting it's guardian\n" ); + assert(false); +} + + +#define PtrGuard DohPtrGuard + /* NEW LANGUAGE NOTE:*********************************************** most of the default options are handled by SWIG you can add new ones here @@ -1223,9 +1292,9 @@ public: virtual int classHandler(Node *n) { //REPORT("classHandler", n); - String *mangled_class_fq_symname = 0; + PtrGuard mangled_class_fq_symname; + PtrGuard destructor_name; String* nspace = getNSpace(); - String* destructor_name = 0; constructor_name = 0; have_constructor = 0; @@ -1252,13 +1321,12 @@ public: assert(class_fq_symname != 0); mangled_class_fq_symname = Swig_name_mangle(class_fq_symname); - SwigType *t = Copy(Getattr(n, "name")); - SwigType *fr_t = SwigType_typedef_resolve_all(t); /* Create fully resolved type */ - SwigType *t_tmp = SwigType_typedef_qualified(fr_t); // Temporal variable - Delete(fr_t); + PtrGuard t = Copy(Getattr(n, "name")); + PtrGuard fr_t = SwigType_typedef_resolve_all(t); /* Create fully resolved type */ + PtrGuard t_tmp = SwigType_typedef_qualified(fr_t); // Temporal variable + fr_t = 0; fr_t = SwigType_strip_qualifiers(t_tmp); - Delete(t_tmp); - String *mangled_fr_t = SwigType_manglestr(fr_t); + PtrGuard mangled_fr_t = SwigType_manglestr(fr_t); //Printf( stdout, "Mangled class symname %s fr type%s\n", mangled_class_fq_symname, mangled_fr_t ); // TODO: REMOVE // not sure exactly how this works, // but tcl has a static hashtable of all classes emitted and then only emits code for them once. @@ -1335,7 +1403,7 @@ public: SwigType_add_pointer(t); // Catch all: eg. a class with only static functions and/or variables will not have 'remembered' - String *wrap_class = NewStringf("&_wrap_class_%s", mangled_class_fq_symname); + String *wrap_class = NewStringf("&_wrap_class_%s", mangled_class_fq_symname.ptr()); SwigType_remember_clientdata(t, wrap_class); String *rt = Copy(getClassType()); @@ -1352,8 +1420,8 @@ public: // emit a function to be called to delete the object // TODO: class_name -> full_class_name || mangled full_class_name if (have_destructor) { - destructor_name = NewStringf("swig_delete_%s", mangled_class_fq_symname); - Printv(f_wrappers, "static void ", destructor_name, "(void *obj) {\n", NIL); + destructor_name = NewStringf("swig_delete_%s", mangled_class_fq_symname.ptr()); + Printv(f_wrappers, "static void ", destructor_name.ptr(), "(void *obj) {\n", NIL); if (destructor_action) { Printv(f_wrappers, SwigType_str(rt, "arg1"), " = (", SwigType_str(rt, 0), ") obj;\n", NIL); Printv(f_wrappers, destructor_action, "\n", NIL); @@ -1433,12 +1501,12 @@ public: } } - Printv(f_wrappers, "static swig_lua_class *swig_", mangled_class_fq_symname, "_bases[] = {", base_class, "0};\n", NIL); + Printv(f_wrappers, "static swig_lua_class *swig_", mangled_class_fq_symname.ptr(), "_bases[] = {", base_class, "0};\n", NIL); Delete(base_class); - Printv(f_wrappers, "static const char *swig_", mangled_class_fq_symname, "_base_names[] = {", base_class_names, "0};\n", NIL); + Printv(f_wrappers, "static const char *swig_", mangled_class_fq_symname.ptr(), "_base_names[] = {", base_class_names, "0};\n", NIL); Delete(base_class_names); - Printv(f_wrappers, "static swig_lua_class _wrap_class_", mangled_class_fq_symname, " = { \"", class_symname, "\", \"", class_fq_symname,"\", &SWIGTYPE", SwigType_manglestr(t), ",", NIL); + Printv(f_wrappers, "static swig_lua_class _wrap_class_", mangled_class_fq_symname.ptr(), " = { \"", class_symname, "\", \"", class_fq_symname,"\", &SWIGTYPE", SwigType_manglestr(t), ",", NIL); // TODO: SwigType_manglestr(t) - memory leak // TODO: Replace with constructor_name if (have_constructor) { @@ -1467,10 +1535,10 @@ public: if (have_destructor) { if (eluac_ltr) { String* ns_methods_tab = Getattr(nspaceHash, "methods"); - Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "free_", mangled_class_fq_symname, "\")", ", LFUNCVAL(", destructor_name, ")", "},\n", NIL); - Printv(f_wrappers, ", ", destructor_name, NIL); + Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "free_", mangled_class_fq_symname.ptr(), "\")", ", LFUNCVAL(", destructor_name.ptr(), ")", "},\n", NIL); + Printv(f_wrappers, ", ", destructor_name.ptr(), NIL); } else { - Printv(f_wrappers, ", ", destructor_name, NIL); + Printv(f_wrappers, ", ", destructor_name.ptr(), NIL); } } else { Printf(f_wrappers, ",0"); @@ -1479,14 +1547,12 @@ public: // TODO: Replace class_symname with class_name printNamespaceDefinition(class_static_nspace, class_symname, f_wrappers); Printf(f_wrappers, ", swig_%s_bases, swig_%s_base_names };\n\n", - mangled_class_fq_symname, mangled_class_fq_symname); + mangled_class_fq_symname.ptr(), mangled_class_fq_symname.ptr()); // Printv(f_wrappers, ", swig_", mangled_class_fq_symname, "_methods, swig_", mangled_class_fq_symname, "_attributes, swig_", mangled_class_fq_symname, "_bases };\n\n", NIL); // Printv(s_cmd_tab, tab4, "{ SWIG_prefix \"", class_name, "\", (swig_wrapper_func) SWIG_ObjectConstructor, &_wrap_class_", mangled_class_fq_symname, "},\n", NIL); current[NO_CPP] = true; - Delete(t); - Delete(mangled_class_fq_symname); Delete(class_static_nspace); class_static_nspace = 0; Delete(class_fq_symname); From 577f20c9904c5e25a1be57ec38fbe9163d7a314d Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Fri, 1 Nov 2013 19:57:47 +0400 Subject: [PATCH 393/481] Fixing issuse with v2-compatible static function names --- Source/Modules/lua.cxx | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 0a7dd1041..413c30b32 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -1321,12 +1321,14 @@ public: assert(class_fq_symname != 0); mangled_class_fq_symname = Swig_name_mangle(class_fq_symname); - PtrGuard t = Copy(Getattr(n, "name")); - PtrGuard fr_t = SwigType_typedef_resolve_all(t); /* Create fully resolved type */ - PtrGuard t_tmp = SwigType_typedef_qualified(fr_t); // Temporal variable + PtrGuard t( Copy(Getattr(n, "name")) ); + PtrGuard fr_t( SwigType_typedef_resolve_all(t) ); /* Create fully resolved type */ + PtrGuard t_tmp; + t_tmp = SwigType_typedef_qualified(fr_t); // Temporal variable fr_t = 0; fr_t = SwigType_strip_qualifiers(t_tmp); - PtrGuard mangled_fr_t = SwigType_manglestr(fr_t); + PtrGuard mangled_fr_t; + mangled_fr_t = SwigType_manglestr(fr_t); //Printf( stdout, "Mangled class symname %s fr type%s\n", mangled_class_fq_symname, mangled_fr_t ); // TODO: REMOVE // not sure exactly how this works, // but tcl has a static hashtable of all classes emitted and then only emits code for them once. @@ -1671,15 +1673,18 @@ public: //String *symname = Getattr(n, "sym:name"); int result = Language::staticmemberfunctionHandler(n); - if (cparse_cplusplus && getCurrentClass()) { - Swig_restore(n); // TODO: WTF ? - } current[STATIC_FUNC] = false;; if (result != SWIG_OK) return result; if(v2_compatibility) { + Swig_require("lua_staticmemberfunctionHandler", n, "*lua:name", NIL); + String *target_name = Getattr(n, "lua:name"); + PtrGuard compat_name; + compat_name = Swig_name_member(0, class_symname, target_name); + Setattr(n, "lua:name", compat_name); registerMethod( class_parent_nspace, n ); + Swig_restore(n); } if (Getattr(n, "sym:nextSibling")) From 63a26c6dbe0f1ae722219fb6f035ce305bf34075 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Tue, 5 Nov 2013 16:37:58 +0400 Subject: [PATCH 394/481] More changes. Mostly to the would-be class library --- Lib/lua/luarun.swg | 180 +++++++++++++++- Lib/lua/luaruntime.swg | 2 + Source/Modules/lua.cxx | 463 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 641 insertions(+), 4 deletions(-) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index ec33ea601..c398c7925 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -879,13 +879,13 @@ SWIGINTERN int SWIG_Lua_class_tostring(lua_State* L) unsigned long userData = (unsigned long)lua_touserdata(L,1); /* get the userdata address for later */ lua_getmetatable(L,1); /* get the meta table */ assert(lua_istable(L,-1)); /* just in case */ - + lua_getfield(L, -1, ".type"); const char* className = lua_tostring(L, -1); - + char output[256]; - sprintf(output, "<%s userdata: %lX>", className, userData); - + snprintf(output, 255, "<%s userdata: %lX>", className, userData); + lua_pushstring(L, (const char*)output); return 1; } @@ -1123,8 +1123,37 @@ SWIGINTERN void SWIG_Lua_class_register_instance(lua_State* L,swig_lua_class* c SWIGINTERN void SWIG_Lua_class_register(lua_State* L,swig_lua_class* clss) { + assert(lua_istable(L,-1)); /* This is table(module or namespace) where class will be added */ SWIG_Lua_class_register_instance(L,clss); SWIG_Lua_class_register_static(L,clss); + + /* Add links from static part to instance part and vice versa */ + /* [SWIG registry] [Module] + * "MyClass" ----> [MyClass metatable] <===== "MyClass" -+> [static part] + * ".get" ----> ... | | getmetatable()----| + * ".set" ----> ... | | | + * ".static" --------------)----------------/ [static part metatable] + * | ".get" --> ... + * | ".set" --> .... + * |=============================== ".instance" + */ + int begin = lua_gettop(L); + lua_pushstring(L,clss->cls_static.name); + lua_rawget(L,-2); /* get class static table */ + assert(lua_istable(L,-1)); + lua_getmetatable(L,-1); + assert(lua_istable(L,-1)); /* get class static metatable */ + lua_pushstring(L,".instance"); /* prepare key */ + + SWIG_Lua_get_class_metatable(L,clss->fqname); /* get class metatable */ + assert(lua_istable(L,-1)); + lua_pushstring(L,".static"); /* prepare key */ + lua_pushvalue(L, -4); /* push static class TABLE */ + assert(lua_istable(L,-1)); + lua_rawset(L,-3); /* assign static class table(!NOT metatable) as ".static" member of class metatable */ + lua_rawset(L,-3); /* assign class metatable as ".instance" member of class static METATABLE */ + lua_pop(L,2); + assert(lua_gettop(L) == begin); } /* ----------------------------------------------------------------------------- @@ -1351,4 +1380,147 @@ SWIG_Lua_dostring(lua_State *L, const char* str) { } #endif +/* ----------------------------------------------------------------------------- + * runtime class manipulation + * ----------------------------------------------------------------------------- */ + +#if ((SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUA) && (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC)) +/* Set of functions that allow manipulating class bindings from C/C++ and from lua + */ + +SWIGINTERN bool +SWIG_Lua_metaclass_add_table(lua_State *L, int metatable_index, const char *class_name, const char *metatable_name, + const char *metaclass_name) +{ + /* Table to add new field must be on to of the stack */ + assert(lua_istable(L,-1)); + lua_pushstring(L,metaclass_name); + lua_pushvalue(L,metatable_index); + lua_pushstring(L,metatable_name); + lua_rawget(L,-2); + if(!lua_istable(L,-1)) { + SWIG_Lua_pushferrstring(L,"Class %s metatable is corrupt. Table %s is missing or not a table", class_name, metatable_name); + return false; + } + lua_rawset(L,-2); + return true; +} + +SWIGRUNTIME int +SWIG_Lua_get_class_metaclass(lua_State *L) +{ + /* One argument: + * - SWIG name of class as string + * - or instance of class + * - or class entry point in module + * metaclass( "MyClass" ) + * metaclass( myvar_of_type_MyClass_int_double ) + * metaclass( module.MyClass_int_double ) + */ + const char *class_name = 0; + int metatable_index = 0; + int static_metatable_index = 0; + int static_table_index = 0; + int answer_index = 0; + SWIG_check_num_args("SWIG_Lua_metaclass", 1, 1); + lua_checkstack(L,15); + if(lua_type(L,1) == LUA_TSTRING) { // class name is given + class_name = lua_tostring(L,1); + SWIG_Lua_get_class_registry(L); /* get the registry */ + assert(lua_istable(L,-1)); + lua_pushvalue(L,1); + lua_rawget(L,-2); /* get class metatable */ + if(!lua_istable(L,-1)) { + SWIG_Lua_pushferrstring(L,"There is no registered class with name %s", class_name ); + SWIG_fail + } + metatable_index = lua_gettop(L); + } else if(lua_isuserdata(L,1)) { // class instance is given + /* We don't check that class is registered in SWIG because it can be user-created-in-lua class */ + lua_getmetatable(L,1); + if(!lua_istable(L,-1)) { + SWIG_Lua_pushferrstring(L,"Userdata is passed, but it is not SWIG-wrapped class. There is no metatable."); + SWIG_fail; + } + metatable_index = lua_gettop(L); + lua_getfield(L,-1,".type"); + if(lua_type(L,-1) != LUA_TSTRING) { + SWIG_Lua_pushferrstring(L,"Userdata is passed, but it is not SWIG-wrapped class. Metatable has different structure."); + SWIG_fail; + } + class_name = lua_tostring(L,-1); + } else { // class entry is given. Well, it is supposed to be a class entry :) + lua_getmetatable(L,1); /* get metatable */ + if(!lua_istable(L,-1)) { + SWIG_Lua_pushferrstring(L, "Table is passed but it is not SWIG class entry point. There is no metatable"); + SWIG_fail; + } + lua_getfield(L,-1, ".instance"); /* get class metatable */ + if(lua_isnil(L,-1)) { + SWIG_Lua_pushferrstring(L, "Table is passed but it is not SWIG class entry point. Metatable has different structure."); + SWIG_fail; + } + metatable_index = lua_gettop(L); + lua_getfield(L,-1,".type"); + if(lua_type(L,-1) != LUA_TSTRING) { + SWIG_Lua_pushferrstring(L,"Userdata is passed, but it is not SWIG-wrapped class. Metatable has different structure."); + SWIG_fail; + } + class_name = lua_tostring(L,-1); + } + + /* Get static table */ + lua_getfield(L,metatable_index,".static"); + assert(!lua_isnil(L,-1)); + static_table_index = lua_gettop(L); + /* Get static metatable */ + lua_getmetatable(L,-1); + assert(!lua_isnil(L,-1)); + static_metatable_index = lua_gettop(L); + /* This will be our answer */ + lua_newtable(L); + answer_index = lua_gettop(L); + /* Adding instance member manipulators + * .bases can't be edited + */ + if(!SWIG_Lua_metaclass_add_table(L,metatable_index,class_name, ".fn", "methods") ) + SWIG_fail; + if(!SWIG_Lua_metaclass_add_table(L,metatable_index,class_name, ".get", "getters") ) + SWIG_fail; + if(!SWIG_Lua_metaclass_add_table(L,metatable_index,class_name, ".set", "setters") ) + SWIG_fail; + /* Adding static members manipulators */ + if(!SWIG_Lua_metaclass_add_table(L,static_metatable_index,class_name, ".get", "static_getters") ) + SWIG_fail; + if(!SWIG_Lua_metaclass_add_table(L,static_metatable_index,class_name, ".set", "static_setters") ) + SWIG_fail; + lua_pushstring(L, "static_methods"); + lua_pushvalue(L, static_table_index); + lua_rawset(L,-3); + + lua_pushstring(L, "static_constants"); + lua_pushvalue(L, static_table_index); + lua_rawset(L,-3); + + assert(lua_gettop(L) == answer_index); + return 1; + +fail: + lua_error(L); + return 0; +} + +/* Creates new class in lua. Must inherit existing SWIG class */ +SWIGRUNTIME int +SWIG_Lua_new_class(lua_State *L) { + SWIG_check_num_args("SWIG_Lua_new_class", 1, 1); + return 0; + +fail: + lua_error(L); + return 0; + +} +#endif + /* ------------------------------ end luarun.swg ------------------------------ */ diff --git a/Lib/lua/luaruntime.swg b/Lib/lua/luaruntime.swg index 0011c9d52..f510a0832 100644 --- a/Lib/lua/luaruntime.swg +++ b/Lib/lua/luaruntime.swg @@ -40,6 +40,8 @@ SWIGEXPORT int SWIG_init(lua_State* L) /* default Lua action */ /* add a global fn */ SWIG_Lua_add_function(L,"swig_type",SWIG_Lua_type); SWIG_Lua_add_function(L,"swig_equals",SWIG_Lua_equal); + SWIG_Lua_add_function(L,"swig_new_class",SWIG_Lua_new_class); + SWIG_Lua_add_function(L,"swig_metaclass",SWIG_Lua_get_class_metaclass); #endif #if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 413c30b32..3e976c373 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -393,6 +393,8 @@ public: /* Get the module name */ module = Getattr(n, "name"); + /* Some global settings */ + director_language = 1; /* Get the output file name */ String *outfile = Getattr(n, "outfile"); @@ -1767,6 +1769,467 @@ public: return SWIG_OK; } +#if 0 + virtual int classDirectorMethod(Node *n, Node *parent, String *super) { + int is_void = 0; + int is_pointer = 0; + String *decl = Getattr(n, "decl"); + String *name = Getattr(n, "name"); + String *classname = Getattr(parent, "sym:name"); + String *c_classname = Getattr(parent, "name"); + String *symname = Getattr(n, "sym:name"); + String *declaration = NewString(""); + ParmList *l = Getattr(n, "parms"); + Wrapper *w = NewWrapper(); + String *tm; + String *wrap_args = NewString(""); + String *returntype = Getattr(n, "type"); + String *value = Getattr(n, "value"); + String *storage = Getattr(n, "storage"); + bool pure_virtual = false; + int status = SWIG_OK; + int idx; + bool ignored_method = GetFlag(n, "feature:ignore") ? true : false; + + if (Cmp(storage, "virtual") == 0) { + if (Cmp(value, "0") == 0) { + pure_virtual = true; + } + } + + /* determine if the method returns a pointer */ + is_pointer = SwigType_ispointer_return(decl); + is_void = (!Cmp(returntype, "void") && !is_pointer); + + /* virtual method definition */ + String *target; + String *pclassname = NewStringf("SwigDirector_%s", classname); + String *qualified_name = NewStringf("%s::%s", pclassname, name); + SwigType *rtype = Getattr(n, "conversion_operator") ? 0 : Getattr(n, "classDirectorMethods:type"); + target = Swig_method_decl(rtype, decl, qualified_name, l, 0, 0); + Printf(w->def, "%s", target); + Delete(qualified_name); + Delete(target); + /* header declaration */ + target = Swig_method_decl(rtype, decl, name, l, 0, 1); + Printf(declaration, " virtual %s", target); + Delete(target); + + // Get any exception classes in the throws typemap + ParmList *throw_parm_list = 0; + + if ((throw_parm_list = Getattr(n, "throws")) || Getattr(n, "throw")) { + Parm *p; + int gencomma = 0; + + Append(w->def, " throw("); + Append(declaration, " throw("); + + if (throw_parm_list) + Swig_typemap_attach_parms("throws", throw_parm_list, 0); + for (p = throw_parm_list; p; p = nextSibling(p)) { + if (Getattr(p, "tmap:throws")) { + if (gencomma++) { + Append(w->def, ", "); + Append(declaration, ", "); + } + String *str = SwigType_str(Getattr(p, "type"), 0); + Append(w->def, str); + Append(declaration, str); + Delete(str); + } + } + + Append(w->def, ")"); + Append(declaration, ")"); + } + + Append(w->def, " {"); + Append(declaration, ";\n"); + + /* 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). + */ + if (!is_void) { + if (!(ignored_method && !pure_virtual)) { + String *cres = SwigType_lstr(returntype, "c_result"); + Printf(w->code, "%s;\n", cres); + Delete(cres); + } + } + + if (builtin) { + Printv(w->code, "PyObject *self = NULL;\n", NIL); + Printv(w->code, "(void)self;\n", NIL); + } + + if (ignored_method) { + if (!pure_virtual) { + if (!is_void) + Printf(w->code, "return "); + String *super_call = Swig_method_call(super, l); + Printf(w->code, "%s;\n", super_call); + 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)); + } + } else { + /* attach typemaps to arguments (C/C++ -> Python) */ + String *arglist = NewString(""); + String *parse_args = NewString(""); + + Swig_director_parms_fixup(l); + + /* remove the wrapper 'w' since it was producing spurious temps */ + Swig_typemap_attach_parms("in", l, 0); + Swig_typemap_attach_parms("directorin", l, 0); + Swig_typemap_attach_parms("directorargout", l, w); + + Parm *p; + char source[256]; + + int outputs = 0; + if (!is_void) + outputs++; + + /* build argument list and type conversion string */ + idx = 0; + p = l; + int use_parse = 0; + while (p) { + if (checkAttribute(p, "tmap:in:numinputs", "0")) { + p = Getattr(p, "tmap:in:next"); + continue; + } + + /* old style? caused segfaults without the p!=0 check + in the for() condition, and seems dangerous in the + while loop as well. + while (Getattr(p, "tmap:ignore")) { + p = Getattr(p, "tmap:ignore:next"); + } + */ + + if (Getattr(p, "tmap:directorargout") != 0) + outputs++; + + String *pname = Getattr(p, "name"); + String *ptype = Getattr(p, "type"); + + Putc(',', arglist); + if ((tm = Getattr(p, "tmap:directorin")) != 0) { + String *parse = Getattr(p, "tmap:directorin:parse"); + if (!parse) { + sprintf(source, "obj%d", idx++); + String *input = NewString(source); + Setattr(p, "emit:directorinput", input); + Replaceall(tm, "$input", input); + Delete(input); + Replaceall(tm, "$owner", "0"); + /* Wrapper_add_localv(w, source, "swig::SwigVar_PyObject", source, "= 0", NIL); */ + Printv(wrap_args, "swig::SwigVar_PyObject ", source, ";\n", NIL); + + Printv(wrap_args, tm, "\n", NIL); + Printv(arglist, "(PyObject *)", source, NIL); + Putc('O', parse_args); + } else { + use_parse = 1; + Append(parse_args, parse); + Setattr(p, "emit:directorinput", pname); + Replaceall(tm, "$input", pname); + Replaceall(tm, "$owner", "0"); + if (Len(tm) == 0) + Append(tm, pname); + Append(arglist, tm); + } + p = Getattr(p, "tmap:directorin:next"); + continue; + } else if (Cmp(ptype, "void")) { + /* special handling for pointers to other C++ director classes. + * ideally this would be left to a typemap, but there is currently no + * way to selectively apply the dynamic_cast<> to classes that have + * directors. in other words, the type "SwigDirector_$1_lname" only exists + * for classes with directors. we avoid the problem here by checking + * module.wrap::directormap, but it's not clear how to get a typemap to + * do something similar. perhaps a new default typemap (in addition + * to SWIGTYPE) called DIRECTORTYPE? + */ + if (SwigType_ispointer(ptype) || SwigType_isreference(ptype)) { + Node *module = Getattr(parent, "module"); + Node *target = Swig_directormap(module, ptype); + sprintf(source, "obj%d", idx++); + String *nonconst = 0; + /* strip pointer/reference --- should move to Swig/stype.c */ + String *nptype = NewString(Char(ptype) + 2); + /* name as pointer */ + String *ppname = Copy(pname); + if (SwigType_isreference(ptype)) { + Insert(ppname, 0, "&"); + } + /* if necessary, cast away const since Python doesn't support it! */ + if (SwigType_isconst(nptype)) { + nonconst = NewStringf("nc_tmp_%s", pname); + String *nonconst_i = NewStringf("= const_cast< %s >(%s)", SwigType_lstr(ptype, 0), ppname); + Wrapper_add_localv(w, nonconst, SwigType_lstr(ptype, 0), nonconst, nonconst_i, NIL); + Delete(nonconst_i); + Swig_warning(WARN_LANG_DISCARD_CONST, input_file, line_number, + "Target language argument '%s' discards const in director method %s::%s.\n", + SwigType_str(ptype, pname), SwigType_namestr(c_classname), SwigType_namestr(name)); + } else { + nonconst = Copy(ppname); + } + Delete(nptype); + Delete(ppname); + String *mangle = SwigType_manglestr(ptype); + if (target) { + String *director = NewStringf("director_%s", mangle); + Wrapper_add_localv(w, director, "Swig::Director *", director, "= 0", NIL); + Wrapper_add_localv(w, source, "swig::SwigVar_PyObject", source, "= 0", NIL); + Printf(wrap_args, "%s = SWIG_DIRECTOR_CAST(%s);\n", director, nonconst); + Printf(wrap_args, "if (!%s) {\n", director); + Printf(wrap_args, "%s = SWIG_InternalNewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle); + Append(wrap_args, "} else {\n"); + Printf(wrap_args, "%s = %s->swig_get_self();\n", source, director); + Printf(wrap_args, "Py_INCREF((PyObject *)%s);\n", source); + Append(wrap_args, "}\n"); + Delete(director); + Printv(arglist, source, NIL); + } else { + Wrapper_add_localv(w, source, "swig::SwigVar_PyObject", source, "= 0", NIL); + Printf(wrap_args, "%s = SWIG_InternalNewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle); + //Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE_p_%s, 0);\n", + // source, nonconst, base); + Printv(arglist, source, NIL); + } + Putc('O', parse_args); + Delete(mangle); + Delete(nonconst); + } else { + Swig_warning(WARN_TYPEMAP_DIRECTORIN_UNDEF, input_file, line_number, + "Unable to use type %s as a function argument in director method %s::%s (skipping method).\n", SwigType_str(ptype, 0), + SwigType_namestr(c_classname), SwigType_namestr(name)); + status = SWIG_NOWRAP; + break; + } + } + p = nextSibling(p); + } + + /* add the method name as a PyString */ + String *pyname = Getattr(n, "sym:name"); + + int allow_thread = threads_enable(n); + + if (allow_thread) { + thread_begin_block(n, w->code); + Append(w->code, "{\n"); + } + + /* wrap complex arguments to PyObjects */ + Printv(w->code, wrap_args, NIL); + + /* pass the method call on to the Python object */ + if (dirprot_mode() && !is_public(n)) { + Printf(w->code, "swig_set_inner(\"%s\", true);\n", name); + } + + + Append(w->code, "if (!swig_get_self()) {\n"); + Printf(w->code, " Swig::DirectorException::raise(\"'self' uninitialized, maybe you forgot to call %s.__init__.\");\n", classname); + Append(w->code, "}\n"); + Append(w->code, "#if defined(SWIG_PYTHON_DIRECTOR_VTABLE)\n"); + Printf(w->code, "const size_t swig_method_index = %d;\n", director_method_index++); + Printf(w->code, "const char * const swig_method_name = \"%s\";\n", pyname); + + Append(w->code, "PyObject* method = swig_get_method(swig_method_index, swig_method_name);\n"); + if (Len(parse_args) > 0) { + if (use_parse || !modernargs) { + Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_CallFunction(method, (char *)\"(%s)\" %s);\n", Swig_cresult_name(), parse_args, arglist); + } else { + Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_CallFunctionObjArgs(method %s, NULL);\n", Swig_cresult_name(), arglist); + } + } else { + if (modernargs) { + Append(w->code, "swig::SwigVar_PyObject args = PyTuple_New(0);\n"); + Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_Call(method, (PyObject*) args, NULL);\n", Swig_cresult_name()); + } else { + Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_CallFunction(method, NULL, NULL);\n", Swig_cresult_name()); + } + } + Append(w->code, "#else\n"); + if (Len(parse_args) > 0) { + if (use_parse || !modernargs) { + Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_CallMethod(swig_get_self(), (char *)\"%s\", (char *)\"(%s)\" %s);\n", Swig_cresult_name(), pyname, parse_args, arglist); + } else { + Printf(w->code, "swig::SwigVar_PyObject swig_method_name = SWIG_Python_str_FromChar((char *)\"%s\");\n", pyname); + Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_CallMethodObjArgs(swig_get_self(), (PyObject *) swig_method_name %s, NULL);\n", Swig_cresult_name(), arglist); + } + } else { + if (!modernargs) { + Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_CallMethod(swig_get_self(), (char *) \"%s\", NULL);\n", Swig_cresult_name(), pyname); + } else { + Printf(w->code, "swig::SwigVar_PyObject swig_method_name = SWIG_Python_str_FromChar((char *)\"%s\");\n", pyname); + Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_CallMethodObjArgs(swig_get_self(), (PyObject *) swig_method_name, NULL);\n", Swig_cresult_name()); + } + } + Append(w->code, "#endif\n"); + + if (dirprot_mode() && !is_public(n)) + Printf(w->code, "swig_set_inner(\"%s\", false);\n", name); + + /* 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); + } + Printf(w->code, "if (!%s) {\n", Swig_cresult_name()); + Append(w->code, " PyObject *error = PyErr_Occurred();\n"); + if ((tm) && Len(tm) && (Strcmp(tm, "1") != 0)) { + Replaceall(tm, "$error", "error"); + Printv(w->code, Str(tm), "\n", NIL); + } else { + Append(w->code, " if (error) {\n"); + Printf(w->code, " Swig::DirectorMethodException::raise(\"Error detected when calling '%s.%s'\");\n", classname, pyname); + Append(w->code, " }\n"); + } + Append(w->code, "}\n"); + Delete(tm); + + /* + * Python method may return a simple object, or a tuple. + * for in/out aruments, we have to extract the appropriate PyObjects from the tuple, + * then marshal everything back to C/C++ (return value and output arguments). + * + */ + + /* marshal return value and other outputs (if any) from PyObject to C/C++ type */ + + String *cleanup = NewString(""); + String *outarg = NewString(""); + + if (outputs > 1) { + Wrapper_add_local(w, "output", "PyObject *output"); + Printf(w->code, "if (!PyTuple_Check(%s)) {\n", Swig_cresult_name()); + Printf(w->code, " Swig::DirectorTypeMismatchException::raise(\"Python method %s.%sfailed to return a tuple.\");\n", classname, pyname); + Append(w->code, "}\n"); + } + + idx = 0; + + /* marshal return value */ + if (!is_void) { + tm = Swig_typemap_lookup("directorout", n, Swig_cresult_name(), w); + if (tm != 0) { + if (outputs > 1) { + Printf(w->code, "output = PyTuple_GetItem(%s, %d);\n", Swig_cresult_name(), idx++); + Replaceall(tm, "$input", "output"); + } else { + Replaceall(tm, "$input", Swig_cresult_name()); + } + char temp[24]; + sprintf(temp, "%d", idx); + Replaceall(tm, "$argnum", temp); + + /* TODO check this */ + if (Getattr(n, "wrap:disown")) { + Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); + } else { + Replaceall(tm, "$disown", "0"); + } + if (Getattr(n, "tmap:directorout:implicitconv")) { + Replaceall(tm, "$implicitconv", get_implicitconv_flag(n)); + } + Replaceall(tm, "$result", "c_result"); + Printv(w->code, tm, "\n", NIL); + 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)); + status = SWIG_ERROR; + } + } + + /* marshal outputs */ + for (p = l; p;) { + if ((tm = Getattr(p, "tmap:directorargout")) != 0) { + if (outputs > 1) { + Printf(w->code, "output = PyTuple_GetItem(%s, %d);\n", Swig_cresult_name(), idx++); + Replaceall(tm, "$result", "output"); + } else { + Replaceall(tm, "$result", Swig_cresult_name()); + } + Replaceall(tm, "$input", Getattr(p, "emit:directorinput")); + Printv(w->code, tm, "\n", NIL); + p = Getattr(p, "tmap:directorargout:next"); + } else { + p = nextSibling(p); + } + } + + /* any existing helper functions to handle this? */ + if (allow_thread) { + Append(w->code, "}\n"); + thread_end_block(n, w->code); + } + + Delete(parse_args); + Delete(arglist); + Delete(cleanup); + Delete(outarg); + } + + if (!is_void) { + if (!(ignored_method && !pure_virtual)) { + String *rettype = SwigType_str(returntype, 0); + if (!SwigType_isreference(returntype)) { + Printf(w->code, "return (%s) c_result;\n", rettype); + } else { + Printf(w->code, "return (%s) *c_result;\n", rettype); + } + Delete(rettype); + } + } + + Append(w->code, "}\n"); + + // We expose protected methods via an extra public inline method which makes a straight call to the wrapped class' method + String *inline_extra_method = NewString(""); + if (dirprot_mode() && !is_public(n) && !pure_virtual) { + Printv(inline_extra_method, declaration, NIL); + String *extra_method_name = NewStringf("%sSwigPublic", name); + Replaceall(inline_extra_method, name, extra_method_name); + Replaceall(inline_extra_method, ";\n", " {\n "); + if (!is_void) + Printf(inline_extra_method, "return "); + String *methodcall = Swig_method_call(super, l); + Printv(inline_extra_method, methodcall, ";\n }\n", NIL); + Delete(methodcall); + Delete(extra_method_name); + } + + /* emit the director method */ + if (status == SWIG_OK) { + if (!Getattr(n, "defaultargs")) { + Replaceall(w->code, "$symname", symname); + Wrapper_print(w, f_directors); + Printv(f_directors_h, declaration, NIL); + Printv(f_directors_h, inline_extra_method, NIL); + } + } + + /* clean up */ + Delete(wrap_args); + Delete(pclassname); + DelWrapper(w); + return status; + } +#endif + /* TODO: REMOVE virtual int namespaceDeclaration(Node *n) { // Register namespace From aa1b8298cac25867995e97d8d7d5116d63ba0d62 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Thu, 7 Nov 2013 18:56:34 +0400 Subject: [PATCH 395/481] Preparations before pull request - part 1 --- Lib/lua/luarun.swg | 320 +-------------- Lib/lua/luaruntime.swg | 2 - Source/Modules/lua.cxx | 901 ++++------------------------------------- 3 files changed, 79 insertions(+), 1144 deletions(-) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index c398c7925..764ec5fe4 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -129,12 +129,6 @@ typedef struct { swig_type_info **ptype; } swig_lua_const_info; -/* TODO:REMOVE -typedef struct { - const char *name; - lua_CFunction method; -} swig_lua_method; -*/ typedef luaL_Reg swig_lua_method; typedef struct { @@ -164,7 +158,7 @@ struct swig_lua_class { void (*destructor)(void *); swig_lua_method *methods; swig_lua_attribute *attributes; - swig_lua_namespace cls_static; + swig_lua_namespace *cls_static; struct swig_lua_class **bases; const char **base_names; }; @@ -274,167 +268,8 @@ SWIGINTERN int SWIG_Lua_set_immutable(lua_State* L) return 0; /* should not return anything */ } -/* the module.get method used for getting linked data */ -SWIGINTERN int SWIG_Lua_module_get(lua_State* L) -{ -/* there should be 2 params passed in - (1) table (not the meta table) - (2) string name of the attribute - printf("SWIG_Lua_module_get %p(%s) '%s'\n", - lua_topointer(L,1),lua_typename(L,lua_type(L,1)), - lua_tostring(L,2)); -*/ - /* get the metatable */ -#if ((SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC)) - assert(lua_isrotable(L,1)); /* just in case */ -#else - assert(lua_istable(L,1)); /* default Lua action */ -#endif - lua_getmetatable(L,1); /* get the metatable */ -#if ((SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC)) - assert(lua_isrotable(L,-1)); /* just in case */ -#else - assert(lua_istable(L,-1)); -#endif - SWIG_Lua_get_table(L,".get"); /* get the .get table */ - lua_remove(L,3); /* remove metatable */ -#if ((SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC)) - if (lua_isrotable(L,-1)) -#else - if (lua_istable(L,-1)) -#endif - { - /* look for the key in the .get table */ - lua_pushvalue(L,2); /* key */ - lua_rawget(L,-2); - lua_remove(L,3); /* remove .get */ - if (lua_iscfunction(L,-1)) - { /* found it so call the fn & return its value */ - lua_call(L,0,1); - return 1; - } - lua_pop(L,1); /* remove the top */ - } - lua_pop(L,1); /* remove the .get */ - lua_pushnil(L); /* return a nil */ - return 1; -} - -/* the module.set method used for setting linked data */ -SWIGINTERN int SWIG_Lua_module_set(lua_State* L) -{ -/* there should be 3 params passed in - (1) table (not the meta table) - (2) string name of the attribute - (3) any for the new value -*/ - /* get the metatable */ -#if ((SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC)) - assert(lua_isrotable(L,1)); /* just in case */ -#else - assert(lua_istable(L,1)); /* default Lua action */ -#endif - lua_getmetatable(L,1); /* get the metatable */ -#if ((SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC)) - assert(lua_isrotable(L,-1)); /* just in case */ -#else - assert(lua_istable(L,-1)); -#endif - SWIG_Lua_get_table(L,".set"); /* get the .set table */ - lua_remove(L,4); /* remove metatable */ -#if ((SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC)) - if (lua_isrotable(L,-1)) -#else - if (lua_istable(L,-1)) -#endif - { - /* look for the key in the .set table */ - lua_pushvalue(L,2); /* key */ - lua_rawget(L,-2); - lua_remove(L,4); /* remove .set */ - if (lua_iscfunction(L,-1)) - { /* found it so call the fn & return its value */ - lua_pushvalue(L,3); /* value */ - lua_call(L,1,0); - return 0; - } -#if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) - else { - return 0; // Exits stoically if an invalid key is initialized. - } -#endif - } - lua_settop(L,3); /* reset back to start */ - /* we now have the table, key & new value, so just set directly */ - lua_rawset(L,1); /* add direct */ - return 0; -} - -#if ((SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUA) && (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC)) -/* registering a module in lua. Pushes the module table on the stack. */ -SWIGINTERN void SWIG_Lua_module_begin(lua_State* L,const char* name) -{ - assert(lua_istable(L,-1)); /* just in case */ - lua_pushstring(L,name); - lua_newtable(L); /* the table */ - /* add meta table */ - lua_newtable(L); /* the meta table */ - SWIG_Lua_add_function(L,"__index",SWIG_Lua_module_get); - SWIG_Lua_add_function(L,"__newindex",SWIG_Lua_module_set); - lua_pushstring(L,".get"); - lua_newtable(L); /* the .get table */ - lua_rawset(L,-3); /* add .get into metatable */ - lua_pushstring(L,".set"); - lua_newtable(L); /* the .set table */ - lua_rawset(L,-3); /* add .set into metatable */ - lua_setmetatable(L,-2); /* sets meta table in module */ -#ifdef SWIG_LUA_MODULE_GLOBAL - /* If requested, install the module directly into the global namespace. */ - lua_rawset(L,-3); /* add module into parent */ - SWIG_Lua_get_table(L,name); /* get the table back out */ -#else - /* Do not install the module table as global name. The stack top has - the module table with the name below. We pop the top and replace - the name with it. */ - lua_replace(L,-2); -#endif -} - -/* ending the register */ -SWIGINTERN void SWIG_Lua_module_end(lua_State* L) -{ - lua_pop(L,1); /* tidy stack (remove module) */ -} - -/* adding a linked variable to the module */ -SWIGINTERN void SWIG_Lua_module_add_variable(lua_State* L,const char* name,lua_CFunction getFn,lua_CFunction setFn) -{ - assert(lua_istable(L,-1)); /* just in case */ - lua_getmetatable(L,-1); /* get the metatable */ - assert(lua_istable(L,-1)); /* just in case */ - SWIG_Lua_get_table(L,".get"); /* find the .get table */ - assert(lua_istable(L,-1)); /* should be a table: */ - SWIG_Lua_add_function(L,name,getFn); - lua_pop(L,1); /* tidy stack (remove table) */ - if (setFn) /* if there is a set fn */ - { - SWIG_Lua_get_table(L,".set"); /* find the .set table */ - assert(lua_istable(L,-1)); /* should be a table: */ - SWIG_Lua_add_function(L,name,setFn); - lua_pop(L,1); /* tidy stack (remove table) */ - } - lua_pop(L,1); /* tidy stack (remove meta) */ -} -#endif - -/* adding a function module */ -SWIGINTERN void SWIG_Lua_module_add_function(lua_State* L,const char* name,lua_CFunction fn) -{ - SWIG_Lua_add_function(L,name,fn); -} - /* ----------------------------------------------------------------------------- - * global variable support code: namespaces + * global variable support code: namespaces and modules (which are the same thing) * ----------------------------------------------------------------------------- */ SWIGINTERN int SWIG_Lua_namespace_get(lua_State* L) @@ -959,7 +794,7 @@ SWIGINTERN void SWIG_Lua_add_class_static_details(lua_State* L, swig_lua_class* SWIG_Lua_add_class_static_details(L,clss->bases[i]); } - SWIG_Lua_add_namespace_details(L, &clss->cls_static); + SWIG_Lua_add_namespace_details(L, clss->cls_static); } /* helper to recursively add class details (attributes & operations) */ @@ -1030,9 +865,9 @@ SWIGINTERN void SWIG_Lua_class_register_static(lua_State* L, swig_lua_class* cls int begin = lua_gettop(L); lua_checkstack(L,5); /* just in case */ assert(lua_istable(L,-1)); /* just in case */ - assert(strcmp(clss->name, clss->cls_static.name) == 0); /* in class those 2 must be equal */ + assert(strcmp(clss->name, clss->cls_static->name) == 0); /* in class those 2 must be equal */ - SWIG_Lua_namespace_register(L,&clss->cls_static, true); + SWIG_Lua_namespace_register(L,clss->cls_static, true); assert(lua_istable(L,-1)); /* just in case */ @@ -1138,7 +973,7 @@ SWIGINTERN void SWIG_Lua_class_register(lua_State* L,swig_lua_class* clss) * |=============================== ".instance" */ int begin = lua_gettop(L); - lua_pushstring(L,clss->cls_static.name); + lua_pushstring(L,clss->cls_static->name); lua_rawget(L,-2); /* get class static table */ assert(lua_istable(L,-1)); lua_getmetatable(L,-1); @@ -1380,147 +1215,4 @@ SWIG_Lua_dostring(lua_State *L, const char* str) { } #endif -/* ----------------------------------------------------------------------------- - * runtime class manipulation - * ----------------------------------------------------------------------------- */ - -#if ((SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUA) && (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC)) -/* Set of functions that allow manipulating class bindings from C/C++ and from lua - */ - -SWIGINTERN bool -SWIG_Lua_metaclass_add_table(lua_State *L, int metatable_index, const char *class_name, const char *metatable_name, - const char *metaclass_name) -{ - /* Table to add new field must be on to of the stack */ - assert(lua_istable(L,-1)); - lua_pushstring(L,metaclass_name); - lua_pushvalue(L,metatable_index); - lua_pushstring(L,metatable_name); - lua_rawget(L,-2); - if(!lua_istable(L,-1)) { - SWIG_Lua_pushferrstring(L,"Class %s metatable is corrupt. Table %s is missing or not a table", class_name, metatable_name); - return false; - } - lua_rawset(L,-2); - return true; -} - -SWIGRUNTIME int -SWIG_Lua_get_class_metaclass(lua_State *L) -{ - /* One argument: - * - SWIG name of class as string - * - or instance of class - * - or class entry point in module - * metaclass( "MyClass" ) - * metaclass( myvar_of_type_MyClass_int_double ) - * metaclass( module.MyClass_int_double ) - */ - const char *class_name = 0; - int metatable_index = 0; - int static_metatable_index = 0; - int static_table_index = 0; - int answer_index = 0; - SWIG_check_num_args("SWIG_Lua_metaclass", 1, 1); - lua_checkstack(L,15); - if(lua_type(L,1) == LUA_TSTRING) { // class name is given - class_name = lua_tostring(L,1); - SWIG_Lua_get_class_registry(L); /* get the registry */ - assert(lua_istable(L,-1)); - lua_pushvalue(L,1); - lua_rawget(L,-2); /* get class metatable */ - if(!lua_istable(L,-1)) { - SWIG_Lua_pushferrstring(L,"There is no registered class with name %s", class_name ); - SWIG_fail - } - metatable_index = lua_gettop(L); - } else if(lua_isuserdata(L,1)) { // class instance is given - /* We don't check that class is registered in SWIG because it can be user-created-in-lua class */ - lua_getmetatable(L,1); - if(!lua_istable(L,-1)) { - SWIG_Lua_pushferrstring(L,"Userdata is passed, but it is not SWIG-wrapped class. There is no metatable."); - SWIG_fail; - } - metatable_index = lua_gettop(L); - lua_getfield(L,-1,".type"); - if(lua_type(L,-1) != LUA_TSTRING) { - SWIG_Lua_pushferrstring(L,"Userdata is passed, but it is not SWIG-wrapped class. Metatable has different structure."); - SWIG_fail; - } - class_name = lua_tostring(L,-1); - } else { // class entry is given. Well, it is supposed to be a class entry :) - lua_getmetatable(L,1); /* get metatable */ - if(!lua_istable(L,-1)) { - SWIG_Lua_pushferrstring(L, "Table is passed but it is not SWIG class entry point. There is no metatable"); - SWIG_fail; - } - lua_getfield(L,-1, ".instance"); /* get class metatable */ - if(lua_isnil(L,-1)) { - SWIG_Lua_pushferrstring(L, "Table is passed but it is not SWIG class entry point. Metatable has different structure."); - SWIG_fail; - } - metatable_index = lua_gettop(L); - lua_getfield(L,-1,".type"); - if(lua_type(L,-1) != LUA_TSTRING) { - SWIG_Lua_pushferrstring(L,"Userdata is passed, but it is not SWIG-wrapped class. Metatable has different structure."); - SWIG_fail; - } - class_name = lua_tostring(L,-1); - } - - /* Get static table */ - lua_getfield(L,metatable_index,".static"); - assert(!lua_isnil(L,-1)); - static_table_index = lua_gettop(L); - /* Get static metatable */ - lua_getmetatable(L,-1); - assert(!lua_isnil(L,-1)); - static_metatable_index = lua_gettop(L); - /* This will be our answer */ - lua_newtable(L); - answer_index = lua_gettop(L); - /* Adding instance member manipulators - * .bases can't be edited - */ - if(!SWIG_Lua_metaclass_add_table(L,metatable_index,class_name, ".fn", "methods") ) - SWIG_fail; - if(!SWIG_Lua_metaclass_add_table(L,metatable_index,class_name, ".get", "getters") ) - SWIG_fail; - if(!SWIG_Lua_metaclass_add_table(L,metatable_index,class_name, ".set", "setters") ) - SWIG_fail; - /* Adding static members manipulators */ - if(!SWIG_Lua_metaclass_add_table(L,static_metatable_index,class_name, ".get", "static_getters") ) - SWIG_fail; - if(!SWIG_Lua_metaclass_add_table(L,static_metatable_index,class_name, ".set", "static_setters") ) - SWIG_fail; - lua_pushstring(L, "static_methods"); - lua_pushvalue(L, static_table_index); - lua_rawset(L,-3); - - lua_pushstring(L, "static_constants"); - lua_pushvalue(L, static_table_index); - lua_rawset(L,-3); - - assert(lua_gettop(L) == answer_index); - return 1; - -fail: - lua_error(L); - return 0; -} - -/* Creates new class in lua. Must inherit existing SWIG class */ -SWIGRUNTIME int -SWIG_Lua_new_class(lua_State *L) { - SWIG_check_num_args("SWIG_Lua_new_class", 1, 1); - return 0; - -fail: - lua_error(L); - return 0; - -} -#endif - /* ------------------------------ end luarun.swg ------------------------------ */ diff --git a/Lib/lua/luaruntime.swg b/Lib/lua/luaruntime.swg index f510a0832..0011c9d52 100644 --- a/Lib/lua/luaruntime.swg +++ b/Lib/lua/luaruntime.swg @@ -40,8 +40,6 @@ SWIGEXPORT int SWIG_init(lua_State* L) /* default Lua action */ /* add a global fn */ SWIG_Lua_add_function(L,"swig_type",SWIG_Lua_type); SWIG_Lua_add_function(L,"swig_equals",SWIG_Lua_equal); - SWIG_Lua_add_function(L,"swig_new_class",SWIG_Lua_new_class); - SWIG_Lua_add_function(L,"swig_metaclass",SWIG_Lua_get_class_metaclass); #endif #if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 3e976c373..c719bad66 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -73,57 +73,6 @@ void display_mapping(DOH *d) { } } -// Holds the pointer. Call's Delete in destructor, assignment etc -// TODO: REVIEW -// Class won't work, TODO: REMOVE -template // T is ignored because everything is DOH* -class DohPointer { - public: - /* - DohPointer( DOH* _ptr ): - p_ptr(_ptr) - { - assert( p_ptr != 0 ); - } - */ - DohPointer(): - p_ptr(0) {} - - DohPointer( const DohPointer& rhs ) { - AttachExisting( rhs.p_ptr ); - } - - const DohPointer& operator=( const DohPointer& rhs ) { - AttachExisting(rhs.p_ptr); - } - - DOH* ptr() { return p_ptr; } - const DOH* ptr() const { return p_ptr; } - operator DOH* () { return p_ptr; } - operator DOH* () const { return p_ptr; } - - // Attaches existing pointer. Refcount will be increased - void AttachExisting( DOH* obj ) { - AttachNew(obj); - if( p_ptr != 0 ) - DohIncref(p_ptr); - } - - // Attaches new pointer. As refcount is set to 1 at the creation, it won't be - // increased - void AttachNew( DOH *obj ) { - DOH* old_ptr = p_ptr; - p_ptr = obj; - if( old_ptr != 0 ) - Delete(old_ptr); - } - - private: - DOH* p_ptr; -}; - -#define Pointer DohPointer - template // T is ignored because everything is DOH* class DohPtrGuard { public: @@ -223,21 +172,12 @@ private: File *f_runtime; File *f_header; File *f_wrappers; - File *f_wrappersForward; // forward declarations for wrappers, TODO: REMOVE File *f_init; File *f_initbeforefunc; - /* - String *s_ns_methods_tab; // table of namespace methods - String *s_ns_var_tab; // Lua only:table of namespace variables - String *s_ns_dot_get; // eLua only:table of variable 'get' functions - String *s_ns_dot_set; // eLua only:table of variable 'set' functions - String *s_ns_const_tab; // table of namespace constants - */ String *s_methods_tab; // table of class methods String *s_attr_tab; // table of class attributes String *s_luacode; // luacode to be called during init String *module; //name of the module - //String *s_vars_meta_tab; // metatable for variables Hash* namespaces_hash; // Parameters for current class. NIL if not parsing class @@ -261,7 +201,7 @@ private: CONSTRUCTOR, DESTRUCTOR, MEMBER_VAR, - CLASS_CONST, + CLASS_CONST, // TODO: What is this ? STATIC_FUNC, STATIC_VAR, STATIC_CONST, // enums and things like static const int x = 5; @@ -283,24 +223,12 @@ public: f_runtime(0), f_header(0), f_wrappers(0), - f_wrappersForward(0), f_init(0), f_initbeforefunc(0), - /* - s_cmd_tab(0), - s_var_tab(0), - s_const_tab(0), - s_cls_attr_tab(0), - s_cls_methods_tab(0), - s_cls_const_tab(0), - */ s_methods_tab(0), s_attr_tab(0), s_luacode(0), module(0), - //s_dot_get(0), - //s_dot_set(0), - //s_vars_meta_tab(0), have_constructor(0), have_destructor(0), destructor_action(0), @@ -407,7 +335,6 @@ public: f_runtime = NewString(""); f_init = NewString(""); f_header = NewString(""); - f_wrappersForward = NewString(""); f_wrappers = NewString(""); f_initbeforefunc = NewString(""); @@ -419,33 +346,11 @@ public: Swig_register_filebyname("init", f_init); Swig_register_filebyname("initbeforefunc", f_initbeforefunc); - /* NEW LANGUAGE NOTE:*********************************************** - s_cmd_tab,s_var_tab & s_const_tab hold the names of the fns for - registering with SWIG. - These will be filled in when the functions/variables are wrapped & - then added to the end of the wrappering code - just before it is written to file - NEW LANGUAGE NOTE:END ************************************************/ - // Initialize some variables for the object interface - // TODO: Replace with call to getNamespaceHash(0) - /* - s_cmd_tab = NewString(""); - s_var_tab = NewString(""); - // s_methods_tab = NewString(""); - s_const_tab = NewString(""); - - s_dot_get = NewString(""); - s_dot_set = NewString(""); - s_vars_meta_tab = NewString(""); - */ s_luacode = NewString(""); Swig_register_filebyname("luacode", s_luacode); current[NO_CPP] = true; - // Registering names schemes: TODO: REMOVE - //Swig_name_register("member", "%m"); - //Swig_name_register("construct", "new_%c"); /* Standard stuff for the SWIG runtime section */ Swig_banner(f_begin); @@ -477,34 +382,12 @@ public: Printf(f_header, "#define SWIG_init_user luaopen_%s_user\n\n", module); Printf(f_header, "#define SWIG_LUACODE luaopen_%s_luacode\n", module); - /* - if (elua_ltr || eluac_ltr) - Printf(f_header, "#define swig_commands %s_map\n\n", module); - */ - if (elua_ltr || eluac_ltr) { Printf(f_header, "\n#define MIN_OPT_LEVEL 2\n#include \"lrodefs.h\"\n"); Printf(f_header, "#include \"lrotable.h\"\n"); - //Printf(s_cmd_tab, "\nconst LUA_REG_TYPE swig_constants[];\n"); - /*if (elua_ltr) - Printf(s_cmd_tab, "const LUA_REG_TYPE mt[];\n");*/ - - //Printf(s_cmd_tab, "\nconst LUA_REG_TYPE swig_commands[] = {\n"); - //Printf(s_const_tab, "\nconst LUA_REG_TYPE swig_constants[] = {\n"); Printf(f_wrappers, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n"); - Printf(f_wrappersForward, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n"); - /*if (elua_ltr) { - Printf(s_dot_get, "\nconst LUA_REG_TYPE dot_get[] = {\n"); - Printf(s_dot_set, "\nconst LUA_REG_TYPE dot_set[] = {\n"); - }*/ } else { - /* - Printf(s_cmd_tab, "\nstatic const struct luaL_Reg swig_commands[] = {\n"); - Printf(s_var_tab, "\nstatic swig_lua_var_info swig_variables[] = {\n"); - Printf(s_const_tab, "\nstatic swig_lua_const_info swig_constants[] = {\n"); - */ Printf(f_wrappers, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n"); - Printf(f_wrappersForward, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n"); } /* %init code inclusion, effectively in the SWIG_init function */ @@ -514,46 +397,16 @@ public: Printf(f_init, "}\n"); Printf(f_wrappers, "#ifdef __cplusplus\n}\n#endif\n"); - Printf(f_wrappersForward, "#ifdef __cplusplus\n}\n#endif\n"); // Done. Close up the module & write to the wrappers -#if 0 - if (elua_ltr || eluac_ltr) { - Printv(s_cmd_tab, tab4, "{LSTRKEY(\"const\"), LROVAL(swig_constants)},\n", NIL); - if (elua_ltr) - Printv(s_cmd_tab, tab4, "{LSTRKEY(\"__metatable\"), LROVAL(mt)},\n", NIL); - Printv(s_cmd_tab, tab4, "{LNILKEY, LNILVAL}\n", "};\n", NIL); - Printv(s_const_tab, tab4, "{LNILKEY, LNILVAL}\n", "};\n", NIL); - } else { - Printv(s_cmd_tab, tab4, "{0,0}\n", "};\n", NIL); - Printv(s_var_tab, tab4, "{0,0,0}\n", "};\n", NIL); - Printv(s_const_tab, tab4, "{0,0,0,0,0,0}\n", "};\n", NIL); - } -#endif - -#if 0 - if (elua_ltr) { - /* Generate the metatable */ - Printf(s_vars_meta_tab, "\nconst LUA_REG_TYPE mt[] = {\n"); - Printv(s_vars_meta_tab, tab4, "{LSTRKEY(\"__index\"), LFUNCVAL(SWIG_Lua_module_get)},\n", NIL); - Printv(s_vars_meta_tab, tab4, "{LSTRKEY(\"__newindex\"), LFUNCVAL(SWIG_Lua_module_set)},\n", NIL); - Printv(s_vars_meta_tab, tab4, "{LSTRKEY(\".get\"), LROVAL(dot_get)},\n", NIL); - Printv(s_vars_meta_tab, tab4, "{LSTRKEY(\".set\"), LROVAL(dot_set)},\n", NIL); - Printv(s_vars_meta_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); - - Printv(s_dot_get, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); - Printv(s_dot_set, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); - } -#endif if (elua_ltr || eluac_ltr) { /* Final close up of wrappers */ - //Printv(f_wrappers, s_cmd_tab, s_dot_get, s_dot_set, s_vars_meta_tab, s_var_tab, s_const_tab, NIL); - closeNamespaces(f_wrappers, f_wrappersForward); + closeNamespaces(f_wrappers, 0); // TODO: Remove last parameter SwigType_emit_type_table(f_runtime, f_wrappers); } else { //Printv(f_wrappers, s_cmd_tab, s_var_tab, s_const_tab, NIL); - closeNamespaces(f_wrappers, f_wrappersForward); + closeNamespaces(f_wrappers, 0); SwigType_emit_type_table(f_runtime, f_wrappers); } @@ -563,7 +416,6 @@ public: NEW LANGUAGE NOTE:END ************************************************/ Dump(f_runtime, f_begin); Dump(f_header, f_begin); - Dump(f_wrappersForward, f_begin); Dump(f_wrappers, f_begin); Dump(f_initbeforefunc, f_begin); /* for the Lua code it needs to be properly excaped to be added into the C/C++ code */ @@ -572,19 +424,12 @@ public: Wrapper_pretty_print(f_init, f_begin); /* Close all of the files */ Delete(s_luacode); - //Delete(s_cmd_tab); - //Delete(s_var_tab); - //Delete(s_const_tab); Delete(f_header); Delete(f_wrappers); - Delete(f_wrappersForward); Delete(f_init); Delete(f_initbeforefunc); Delete(f_runtime); Delete(f_begin); - //Delete(s_dot_get); - //Delete(s_dot_set); - //Delete(s_vars_meta_tab); /* Done */ return SWIG_OK; @@ -599,7 +444,7 @@ public: } virtual int cDeclaration(Node *n) { - // Language is messing with symname in a really heavy way. + // class 'Language' is messing with symname in a really heavy way. // Although documentation states that sym:name is a name in // the target language space, it is not true. sym:name and // it's derivatives are used in various places, including @@ -657,12 +502,10 @@ public: assert(target_name != 0); SwigType *d = Getattr(n, "type"); ParmList *l = Getattr(n, "parms"); - //Printf(stdout,"functionWrapper %s %s\n",name,iname); Parm *p; String *tm; int i; //Printf(stdout,"functionWrapper %s %s %d\n",name,iname,current); - // int returnval=0; // number of arguments returned String *overname = 0; if (Getattr(n, "sym:overloaded")) { @@ -691,7 +534,6 @@ public: Delete(constructor_name); constructor_name = Copy(wname); } - //Printf(stdout , "Function wrapper, name %s wrapname %s\n", iname, wname); // TODO:REMOVE /* NEW LANGUAGE NOTE:*********************************************** the format of a lua fn is: @@ -950,7 +792,6 @@ public: different language mappings seem to use different ideas NEW LANGUAGE NOTE:END ************************************************/ /* Now register the function with the interpreter. */ - //TODO: iname -> lua:name if (!Getattr(n, "sym:overloaded")) { if (current[NO_CPP] || current[STATIC_FUNC]) { // emit normal fns & static fns registerMethod(getNSpace(), n); @@ -967,7 +808,6 @@ public: Delete(cleanup); Delete(outarg); // Delete(description); - //Delete(wname); // TODO: Reference count seems not working DelWrapper(f); return SWIG_OK; @@ -989,7 +829,6 @@ public: //REPORT("dispatchFunction", n); /* Last node in overloaded chain */ - //Printf(stdout , "Dispatch, wrapname %s\n", Getattr(n,"wrap:name")); // TODO:REMOVE int maxargs; String *tmp = NewString(""); String *dispatch = Swig_overload_dispatch(n, "return %s(L);", &maxargs); @@ -1034,10 +873,7 @@ public: Printv(f->code, "}\n", NIL); Wrapper_print(f, f_wrappers); if (current[NO_CPP] || current[STATIC_FUNC]) { // emit normal fns & static fns - // TODO: elua_ltr ? - Hash* nspaceHash = getNamespaceHash( getNSpace() ); - String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); - Printv(s_ns_methods_tab, tab4, "{ \"", target_name, "\",", wname, "},\n", NIL); + registerMethod(getNSpace(), n); } if (current[CONSTRUCTOR]) { if( constructor_name != 0 ) @@ -1067,47 +903,13 @@ public: only WRT this variable will look into this later. NEW LANGUAGE NOTE:END ************************************************/ // REPORT("variableWrapper", n); - String *iname = Getattr(n, "sym:name"); String *target_name = Getattr(n, "lua:name"); assert(target_name != 0); current[VARIABLE] = true; // let SWIG generate the wrappers int result = Language::variableWrapper(n); current[VARIABLE] = false; - // normally SWIG will generate 2 wrappers, a get and a set - // but in certain scenarios (immutable, or if its arrays), it will not - //String *getName = Getattr(n,"varget:wrap:name"); - //String *setName = 0; - // checking whether it can be set to or not appears to be a very error prone issue - // I referred to the Language::variableWrapper() to find this out - // TODO: REMOVE? - /* - bool assignable=is_assignable(n) ? true : false; - SwigType *type = Getattr(n, "type"); - String *tm = Swig_typemap_lookup("globalin", n, iname, 0); - if (!tm && SwigType_isarray(type)) - assignable=false; - Delete(tm); - - if (assignable) { - setName = Getattr(n,"varset:wrap:name"); - } else { - // how about calling a 'this is not settable' error message? - setName = unassignable;// error message - }*/ - - // register the variable - //assert(setName != 0); - //assert(getName != 0); - // TODO: CHeck. It seems to register everything in namespaces - // What about class variables ? registerVariable( getNSpace(), n, "varget:wrap:name", "varset:wrap:name" ); - /*if (getCurrentClass()) { // TODO: REMOVE - Setattr(n, "luaclassobj:wrap:get", getName); - Setattr(n, "luaclassobj:wrap:set", setName); - } else { - Delete(unassignable); - }*/ return result; } @@ -1126,7 +928,6 @@ public: String *rawval = Getattr(n, "rawval"); String *value = rawval ? rawval : Getattr(n, "value"); String *tm; - //Printf( stdout, "Add constant %s, ns %s\n", iname, getNSpace() );// TODO: REMOVE if (!luaAddSymbol(target_name, n)) return SWIG_ERROR; @@ -1188,21 +989,6 @@ public: } } */ - /* TODO: Fix - if (cparse_cplusplus && getCurrentClass()) { - // Additionally add to class constants - Swig_require("luaclassobj_constantWrapper", n, "*sym:name", "luaclassobj:symname", NIL); - Setattr(n, "sym:name", Getattr(n, "luaclassobj:symname")); - String *cls_nsname = Getattr(n, "sym:name"); - if ((tm = Swig_typemap_lookup("consttab", n, name, 0))) { - Replaceall(tm, "$source", value); - Replaceall(tm, "$target", name); - Replaceall(tm, "$value", value); - Replaceall(tm, "$nsname", cls_nsname); - Printf(s_cls_const_tab, " %s,\n", tm); - } - Swig_restore(n); - }*/ Swig_restore(n); Delete(nsname); return SWIG_OK; @@ -1216,7 +1002,6 @@ public: // REPORT("nativeWrapper", n); String *symname = Getattr(n, "sym:name"); String *wrapname = Getattr(n, "wrap:name"); - //String *target_name = Getattr(n, "lua:name"); TODO: REMOVE if (!luaAddSymbol(wrapname, n)) return SWIG_ERROR; @@ -1331,7 +1116,6 @@ public: fr_t = SwigType_strip_qualifiers(t_tmp); PtrGuard mangled_fr_t; mangled_fr_t = SwigType_manglestr(fr_t); - //Printf( stdout, "Mangled class symname %s fr type%s\n", mangled_class_fq_symname, mangled_fr_t ); // TODO: REMOVE // not sure exactly how this works, // but tcl has a static hashtable of all classes emitted and then only emits code for them once. // this fixes issues in test suites: template_default2 & template_specialization @@ -1343,7 +1127,6 @@ public: if (Getattr(emitted, mangled_fr_t)) { class_fq_symname = 0; class_symname = 0; - // TODO: Memory leak here return SWIG_NOWRAP; } Setattr(emitted, mangled_fr_t, "1"); @@ -1359,14 +1142,15 @@ public: // And we can guarantee that there will not be any name collision because names starting with 2 underscores // and capital letter are forbiden to use in C++. So, under know circumstances could our class contain // any member or subclass with name "__Static". Thus, never any name clash. - Hash* non_static_cls = getNamespaceHash(class_fq_symname, false); - assert(non_static_cls != 0); - s_attr_tab = Getattr(non_static_cls, "attributes"); - s_methods_tab = Getattr(non_static_cls, "methods"); - String* s_attr_tab_name = Getattr(non_static_cls, "attributes:name"); - String* s_methods_tab_name = Getattr(non_static_cls, "methods:name"); - Setattr(non_static_cls, "lua:no_namespaces", "1"); - Setattr(non_static_cls, "lua:no_classes", "1"); + Hash* instance_cls = getNamespaceHash(class_fq_symname, false); + assert(instance_cls != 0); + s_attr_tab = Getattr(instance_cls, "attributes"); + s_methods_tab = Getattr(instance_cls, "methods"); + String* s_attr_tab_name = Getattr(instance_cls, "attributes:name"); + String* s_methods_tab_name = Getattr(instance_cls, "methods:name"); + Setattr(instance_cls, "lua:no_namespaces", "1"); + Setattr(instance_cls, "lua:no_classes", "1"); + Setattr(instance_cls, "lua:class_instance", "1"); /* There is no use for "constants", "classes" and "namespaces" arrays. * All constants are considered part of static part of class. @@ -1376,22 +1160,17 @@ public: Hash *static_cls = getNamespaceHash(class_static_nspace, false); assert(static_cls != 0); Setattr(static_cls, "lua:no_namespaces", "1"); - /* TODO: REMOVE - s_cls_methods_tab = Getattr(static_cls, "methods"); - s_cls_attr_tab = Getattr(static_cls, "attributes"); - s_cls_const_tab = Getattr(static_cls, "constants"); - */ + Setattr(static_cls, "lua:class_static", "1"); + + // Notifying instance_cls and static_cls hashes about each other + Setattr(instance_cls, "lua:class_instance:static_hash", static_cls); + Setattr(static_cls, "lua:class_static:instance_hash", instance_cls); /* There is no use for "classes" and "namespaces" arrays. Subclasses are not supported * by SWIG and namespaces couldn't be nested inside classes (C++ Standard) */ assert(s_attr_tab != 0); assert(s_methods_tab != 0); - /* - assert(s_cls_methods_tab != 0); - assert(s_cls_attr_tab != 0); - assert(s_cls_const_tab != 0); - */ // Replacing namespace with namespace + class in order to static // member be put inside class static area @@ -1402,7 +1181,6 @@ public: // Restore correct nspace setNSpace(nspace); class_parent_nspace = 0; - //Printf( stdout, "Class finished\n" ); TODO:REMOVE SwigType_add_pointer(t); @@ -1422,7 +1200,6 @@ public: // Printf(f_init,"SWIG_TypeClientData(SWIGTYPE%s, (void *) &_wrap_class_%s);\n", SwigType_manglestr(t), mangled_class_fq_symname); // emit a function to be called to delete the object - // TODO: class_name -> full_class_name || mangled full_class_name if (have_destructor) { destructor_name = NewStringf("swig_delete_%s", mangled_class_fq_symname.ptr()); Printv(f_wrappers, "static void ", destructor_name.ptr(), "(void *obj) {\n", NIL); @@ -1454,20 +1231,26 @@ public: tab4, "return 1;\n}\n", NIL); Delete(constructor_name); constructor_name = constructor_proxy_name; + if (elua_ltr) { + String* static_cls_metatable_tab = Getattr(static_cls, "metatable"); + Printf(static_cls_metatable_tab, " {LSTRKEY(\"__call\"), LFUNCVAL(%s)},\n", constructor_name); + } else if (eluac_ltr) { + String* ns_methods_tab = Getattr(nspaceHash, "methods"); + Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "new_", class_symname, "\")", ", LFUNCVAL(", \ + constructor_name, ")", "},\n", NIL); + } + } + if (have_destructor) { + if (eluac_ltr) { + String* ns_methods_tab = Getattr(nspaceHash, "methods"); + Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "free_", mangled_class_fq_symname.ptr(), "\")", ", LFUNCVAL(", destructor_name.ptr(), ")", "},\n", NIL); + } } closeNamespaceHash(class_fq_symname, f_wrappers); closeNamespaceHash(class_static_nspace, f_wrappers); - /* TODO: REMOVE - Delete(s_methods_tab); - Delete(s_attr_tab); - Delete(s_cls_methods_tab); - Delete(s_cls_attr_tab); - Delete(s_cls_const_tab); - */ - // Handle inheritance // note: with the idea of class hierarchies spread over multiple modules // cf test-suite: imports.i @@ -1491,12 +1274,7 @@ public: b = Next(b); continue; } - // old code: (used the pointer to the base class) TODO:REMOVE - //String *bmangle = Swig_name_mangle(bname); - //Printf(base_class, "&_wrap_class_%s", bmangle); - //Putc(',', base_class); - //Delete(bmangle); - // new code: stores a null pointer & the name + // stores a null pointer & the name Printf(base_class, "0,"); Printf(base_class_names, "\"%s *\",", SwigType_namestr(bname)); @@ -1505,31 +1283,19 @@ public: } } + // First, print class static part + printNamespaceDefinition(class_static_nspace, class_symname, f_wrappers); + + // Then print class isntance part Printv(f_wrappers, "static swig_lua_class *swig_", mangled_class_fq_symname.ptr(), "_bases[] = {", base_class, "0};\n", NIL); Delete(base_class); Printv(f_wrappers, "static const char *swig_", mangled_class_fq_symname.ptr(), "_base_names[] = {", base_class_names, "0};\n", NIL); Delete(base_class_names); - Printv(f_wrappers, "static swig_lua_class _wrap_class_", mangled_class_fq_symname.ptr(), " = { \"", class_symname, "\", \"", class_fq_symname,"\", &SWIGTYPE", SwigType_manglestr(t), ",", NIL); // TODO: SwigType_manglestr(t) - memory leak + Printv(f_wrappers, "static swig_lua_class _wrap_class_", mangled_class_fq_symname.ptr(), " = { \"", class_symname, "\", \"", class_fq_symname,"\", &SWIGTYPE", SwigType_manglestr(t), ",", NIL); - // TODO: Replace with constructor_name if (have_constructor) { - if (elua_ltr) { - String* ns_methods_tab = Getattr(nspaceHash, "methods"); - // TODO: Contructor should be moved to __call method of static part of class - Printf(ns_methods_tab, " {LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", class_symname, \ - symname_wrapper(Swig_name_construct(nspace, constructor_name))); - Printf(f_wrappers, "%s", symname_wrapper(Swig_name_construct(nspace, constructor_name))); - } else if (eluac_ltr) { - String* ns_methods_tab = Getattr(nspaceHash, "methods"); - Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "new_", class_symname, "\")", ", LFUNCVAL(", \ - symname_wrapper(Swig_name_construct(nspace, constructor_name)), ")", "},\n", NIL); - Printf(f_wrappers, "%s", symname_wrapper(Swig_name_construct(nspace, constructor_name))); - } else { - //Printf( stdout, "Constructor.name %s declaration: %s\n", constructor_name, symname_wrapper(Swig_name_construct(nspace, constructor_name))); - //Printf(f_wrappers, "%s", symname_wrapper(Swig_name_construct(nspace, constructor_name))); - Printv(f_wrappers, constructor_name, NIL); - } + Printv(f_wrappers, constructor_name, NIL); Delete(constructor_name); constructor_name = 0; } else { @@ -1537,25 +1303,14 @@ public: } if (have_destructor) { - if (eluac_ltr) { - String* ns_methods_tab = Getattr(nspaceHash, "methods"); - Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "free_", mangled_class_fq_symname.ptr(), "\")", ", LFUNCVAL(", destructor_name.ptr(), ")", "},\n", NIL); - Printv(f_wrappers, ", ", destructor_name.ptr(), NIL); - } else { - Printv(f_wrappers, ", ", destructor_name.ptr(), NIL); - } + Printv(f_wrappers, ", ", destructor_name.ptr(), NIL); } else { Printf(f_wrappers, ",0"); } - Printf(f_wrappers, ", %s, %s, ", s_methods_tab_name, s_attr_tab_name ); - // TODO: Replace class_symname with class_name - printNamespaceDefinition(class_static_nspace, class_symname, f_wrappers); + Printf(f_wrappers, ", %s, %s, &%s", s_methods_tab_name, s_attr_tab_name, Getattr(static_cls, "cname") ); Printf(f_wrappers, ", swig_%s_bases, swig_%s_base_names };\n\n", mangled_class_fq_symname.ptr(), mangled_class_fq_symname.ptr()); - // Printv(f_wrappers, ", swig_", mangled_class_fq_symname, "_methods, swig_", mangled_class_fq_symname, "_attributes, swig_", mangled_class_fq_symname, "_bases };\n\n", NIL); - // Printv(s_cmd_tab, tab4, "{ SWIG_prefix \"", class_name, "\", (swig_wrapper_func) SWIG_ObjectConstructor, &_wrap_class_", mangled_class_fq_symname, "},\n", NIL); - current[NO_CPP] = true; Delete(class_static_nspace); class_static_nspace = 0; @@ -1712,17 +1467,7 @@ public: virtual int memberconstantHandler(Node *n) { REPORT("memberconstantHandler",n); - String *symname = Getattr(n, "sym:name"); - /* TODO:REMOVE - if (cparse_cplusplus && getCurrentClass()) { - Swig_save("luaclassobj_memberconstantHandler", n, "luaclassobj:symname", NIL); - Setattr(n, "luaclassobj:symname", symname); - }*/ int result = Language::memberconstantHandler(n); - /* TODO:REMOVE - if (cparse_cplusplus && getCurrentClass()) - Swig_restore(n); // TODO: WTF ? - */ return result; } @@ -1761,496 +1506,10 @@ public: Swig_restore(n); } - /* TODO: Add backward compatibility here: add "ClassName_AttributeName" to class scope - Swig_require("luaclassobj_staticmembervariableHandler", n, "luaclassobj:wrap:get", "luaclassobj:wrap:set", NIL); - Printf(s_cls_attr_tab,"%s{ \"%s\", %s, %s},\n",tab4,symname,Getattr(n,"luaclassobj:wrap:get"), Getattr(n,"luaclassobj:wrap:set")); - Swig_restore(n); - */ return SWIG_OK; } -#if 0 - virtual int classDirectorMethod(Node *n, Node *parent, String *super) { - int is_void = 0; - int is_pointer = 0; - String *decl = Getattr(n, "decl"); - String *name = Getattr(n, "name"); - String *classname = Getattr(parent, "sym:name"); - String *c_classname = Getattr(parent, "name"); - String *symname = Getattr(n, "sym:name"); - String *declaration = NewString(""); - ParmList *l = Getattr(n, "parms"); - Wrapper *w = NewWrapper(); - String *tm; - String *wrap_args = NewString(""); - String *returntype = Getattr(n, "type"); - String *value = Getattr(n, "value"); - String *storage = Getattr(n, "storage"); - bool pure_virtual = false; - int status = SWIG_OK; - int idx; - bool ignored_method = GetFlag(n, "feature:ignore") ? true : false; - if (Cmp(storage, "virtual") == 0) { - if (Cmp(value, "0") == 0) { - pure_virtual = true; - } - } - - /* determine if the method returns a pointer */ - is_pointer = SwigType_ispointer_return(decl); - is_void = (!Cmp(returntype, "void") && !is_pointer); - - /* virtual method definition */ - String *target; - String *pclassname = NewStringf("SwigDirector_%s", classname); - String *qualified_name = NewStringf("%s::%s", pclassname, name); - SwigType *rtype = Getattr(n, "conversion_operator") ? 0 : Getattr(n, "classDirectorMethods:type"); - target = Swig_method_decl(rtype, decl, qualified_name, l, 0, 0); - Printf(w->def, "%s", target); - Delete(qualified_name); - Delete(target); - /* header declaration */ - target = Swig_method_decl(rtype, decl, name, l, 0, 1); - Printf(declaration, " virtual %s", target); - Delete(target); - - // Get any exception classes in the throws typemap - ParmList *throw_parm_list = 0; - - if ((throw_parm_list = Getattr(n, "throws")) || Getattr(n, "throw")) { - Parm *p; - int gencomma = 0; - - Append(w->def, " throw("); - Append(declaration, " throw("); - - if (throw_parm_list) - Swig_typemap_attach_parms("throws", throw_parm_list, 0); - for (p = throw_parm_list; p; p = nextSibling(p)) { - if (Getattr(p, "tmap:throws")) { - if (gencomma++) { - Append(w->def, ", "); - Append(declaration, ", "); - } - String *str = SwigType_str(Getattr(p, "type"), 0); - Append(w->def, str); - Append(declaration, str); - Delete(str); - } - } - - Append(w->def, ")"); - Append(declaration, ")"); - } - - Append(w->def, " {"); - Append(declaration, ";\n"); - - /* 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). - */ - if (!is_void) { - if (!(ignored_method && !pure_virtual)) { - String *cres = SwigType_lstr(returntype, "c_result"); - Printf(w->code, "%s;\n", cres); - Delete(cres); - } - } - - if (builtin) { - Printv(w->code, "PyObject *self = NULL;\n", NIL); - Printv(w->code, "(void)self;\n", NIL); - } - - if (ignored_method) { - if (!pure_virtual) { - if (!is_void) - Printf(w->code, "return "); - String *super_call = Swig_method_call(super, l); - Printf(w->code, "%s;\n", super_call); - 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)); - } - } else { - /* attach typemaps to arguments (C/C++ -> Python) */ - String *arglist = NewString(""); - String *parse_args = NewString(""); - - Swig_director_parms_fixup(l); - - /* remove the wrapper 'w' since it was producing spurious temps */ - Swig_typemap_attach_parms("in", l, 0); - Swig_typemap_attach_parms("directorin", l, 0); - Swig_typemap_attach_parms("directorargout", l, w); - - Parm *p; - char source[256]; - - int outputs = 0; - if (!is_void) - outputs++; - - /* build argument list and type conversion string */ - idx = 0; - p = l; - int use_parse = 0; - while (p) { - if (checkAttribute(p, "tmap:in:numinputs", "0")) { - p = Getattr(p, "tmap:in:next"); - continue; - } - - /* old style? caused segfaults without the p!=0 check - in the for() condition, and seems dangerous in the - while loop as well. - while (Getattr(p, "tmap:ignore")) { - p = Getattr(p, "tmap:ignore:next"); - } - */ - - if (Getattr(p, "tmap:directorargout") != 0) - outputs++; - - String *pname = Getattr(p, "name"); - String *ptype = Getattr(p, "type"); - - Putc(',', arglist); - if ((tm = Getattr(p, "tmap:directorin")) != 0) { - String *parse = Getattr(p, "tmap:directorin:parse"); - if (!parse) { - sprintf(source, "obj%d", idx++); - String *input = NewString(source); - Setattr(p, "emit:directorinput", input); - Replaceall(tm, "$input", input); - Delete(input); - Replaceall(tm, "$owner", "0"); - /* Wrapper_add_localv(w, source, "swig::SwigVar_PyObject", source, "= 0", NIL); */ - Printv(wrap_args, "swig::SwigVar_PyObject ", source, ";\n", NIL); - - Printv(wrap_args, tm, "\n", NIL); - Printv(arglist, "(PyObject *)", source, NIL); - Putc('O', parse_args); - } else { - use_parse = 1; - Append(parse_args, parse); - Setattr(p, "emit:directorinput", pname); - Replaceall(tm, "$input", pname); - Replaceall(tm, "$owner", "0"); - if (Len(tm) == 0) - Append(tm, pname); - Append(arglist, tm); - } - p = Getattr(p, "tmap:directorin:next"); - continue; - } else if (Cmp(ptype, "void")) { - /* special handling for pointers to other C++ director classes. - * ideally this would be left to a typemap, but there is currently no - * way to selectively apply the dynamic_cast<> to classes that have - * directors. in other words, the type "SwigDirector_$1_lname" only exists - * for classes with directors. we avoid the problem here by checking - * module.wrap::directormap, but it's not clear how to get a typemap to - * do something similar. perhaps a new default typemap (in addition - * to SWIGTYPE) called DIRECTORTYPE? - */ - if (SwigType_ispointer(ptype) || SwigType_isreference(ptype)) { - Node *module = Getattr(parent, "module"); - Node *target = Swig_directormap(module, ptype); - sprintf(source, "obj%d", idx++); - String *nonconst = 0; - /* strip pointer/reference --- should move to Swig/stype.c */ - String *nptype = NewString(Char(ptype) + 2); - /* name as pointer */ - String *ppname = Copy(pname); - if (SwigType_isreference(ptype)) { - Insert(ppname, 0, "&"); - } - /* if necessary, cast away const since Python doesn't support it! */ - if (SwigType_isconst(nptype)) { - nonconst = NewStringf("nc_tmp_%s", pname); - String *nonconst_i = NewStringf("= const_cast< %s >(%s)", SwigType_lstr(ptype, 0), ppname); - Wrapper_add_localv(w, nonconst, SwigType_lstr(ptype, 0), nonconst, nonconst_i, NIL); - Delete(nonconst_i); - Swig_warning(WARN_LANG_DISCARD_CONST, input_file, line_number, - "Target language argument '%s' discards const in director method %s::%s.\n", - SwigType_str(ptype, pname), SwigType_namestr(c_classname), SwigType_namestr(name)); - } else { - nonconst = Copy(ppname); - } - Delete(nptype); - Delete(ppname); - String *mangle = SwigType_manglestr(ptype); - if (target) { - String *director = NewStringf("director_%s", mangle); - Wrapper_add_localv(w, director, "Swig::Director *", director, "= 0", NIL); - Wrapper_add_localv(w, source, "swig::SwigVar_PyObject", source, "= 0", NIL); - Printf(wrap_args, "%s = SWIG_DIRECTOR_CAST(%s);\n", director, nonconst); - Printf(wrap_args, "if (!%s) {\n", director); - Printf(wrap_args, "%s = SWIG_InternalNewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle); - Append(wrap_args, "} else {\n"); - Printf(wrap_args, "%s = %s->swig_get_self();\n", source, director); - Printf(wrap_args, "Py_INCREF((PyObject *)%s);\n", source); - Append(wrap_args, "}\n"); - Delete(director); - Printv(arglist, source, NIL); - } else { - Wrapper_add_localv(w, source, "swig::SwigVar_PyObject", source, "= 0", NIL); - Printf(wrap_args, "%s = SWIG_InternalNewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle); - //Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE_p_%s, 0);\n", - // source, nonconst, base); - Printv(arglist, source, NIL); - } - Putc('O', parse_args); - Delete(mangle); - Delete(nonconst); - } else { - Swig_warning(WARN_TYPEMAP_DIRECTORIN_UNDEF, input_file, line_number, - "Unable to use type %s as a function argument in director method %s::%s (skipping method).\n", SwigType_str(ptype, 0), - SwigType_namestr(c_classname), SwigType_namestr(name)); - status = SWIG_NOWRAP; - break; - } - } - p = nextSibling(p); - } - - /* add the method name as a PyString */ - String *pyname = Getattr(n, "sym:name"); - - int allow_thread = threads_enable(n); - - if (allow_thread) { - thread_begin_block(n, w->code); - Append(w->code, "{\n"); - } - - /* wrap complex arguments to PyObjects */ - Printv(w->code, wrap_args, NIL); - - /* pass the method call on to the Python object */ - if (dirprot_mode() && !is_public(n)) { - Printf(w->code, "swig_set_inner(\"%s\", true);\n", name); - } - - - Append(w->code, "if (!swig_get_self()) {\n"); - Printf(w->code, " Swig::DirectorException::raise(\"'self' uninitialized, maybe you forgot to call %s.__init__.\");\n", classname); - Append(w->code, "}\n"); - Append(w->code, "#if defined(SWIG_PYTHON_DIRECTOR_VTABLE)\n"); - Printf(w->code, "const size_t swig_method_index = %d;\n", director_method_index++); - Printf(w->code, "const char * const swig_method_name = \"%s\";\n", pyname); - - Append(w->code, "PyObject* method = swig_get_method(swig_method_index, swig_method_name);\n"); - if (Len(parse_args) > 0) { - if (use_parse || !modernargs) { - Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_CallFunction(method, (char *)\"(%s)\" %s);\n", Swig_cresult_name(), parse_args, arglist); - } else { - Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_CallFunctionObjArgs(method %s, NULL);\n", Swig_cresult_name(), arglist); - } - } else { - if (modernargs) { - Append(w->code, "swig::SwigVar_PyObject args = PyTuple_New(0);\n"); - Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_Call(method, (PyObject*) args, NULL);\n", Swig_cresult_name()); - } else { - Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_CallFunction(method, NULL, NULL);\n", Swig_cresult_name()); - } - } - Append(w->code, "#else\n"); - if (Len(parse_args) > 0) { - if (use_parse || !modernargs) { - Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_CallMethod(swig_get_self(), (char *)\"%s\", (char *)\"(%s)\" %s);\n", Swig_cresult_name(), pyname, parse_args, arglist); - } else { - Printf(w->code, "swig::SwigVar_PyObject swig_method_name = SWIG_Python_str_FromChar((char *)\"%s\");\n", pyname); - Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_CallMethodObjArgs(swig_get_self(), (PyObject *) swig_method_name %s, NULL);\n", Swig_cresult_name(), arglist); - } - } else { - if (!modernargs) { - Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_CallMethod(swig_get_self(), (char *) \"%s\", NULL);\n", Swig_cresult_name(), pyname); - } else { - Printf(w->code, "swig::SwigVar_PyObject swig_method_name = SWIG_Python_str_FromChar((char *)\"%s\");\n", pyname); - Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_CallMethodObjArgs(swig_get_self(), (PyObject *) swig_method_name, NULL);\n", Swig_cresult_name()); - } - } - Append(w->code, "#endif\n"); - - if (dirprot_mode() && !is_public(n)) - Printf(w->code, "swig_set_inner(\"%s\", false);\n", name); - - /* 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); - } - Printf(w->code, "if (!%s) {\n", Swig_cresult_name()); - Append(w->code, " PyObject *error = PyErr_Occurred();\n"); - if ((tm) && Len(tm) && (Strcmp(tm, "1") != 0)) { - Replaceall(tm, "$error", "error"); - Printv(w->code, Str(tm), "\n", NIL); - } else { - Append(w->code, " if (error) {\n"); - Printf(w->code, " Swig::DirectorMethodException::raise(\"Error detected when calling '%s.%s'\");\n", classname, pyname); - Append(w->code, " }\n"); - } - Append(w->code, "}\n"); - Delete(tm); - - /* - * Python method may return a simple object, or a tuple. - * for in/out aruments, we have to extract the appropriate PyObjects from the tuple, - * then marshal everything back to C/C++ (return value and output arguments). - * - */ - - /* marshal return value and other outputs (if any) from PyObject to C/C++ type */ - - String *cleanup = NewString(""); - String *outarg = NewString(""); - - if (outputs > 1) { - Wrapper_add_local(w, "output", "PyObject *output"); - Printf(w->code, "if (!PyTuple_Check(%s)) {\n", Swig_cresult_name()); - Printf(w->code, " Swig::DirectorTypeMismatchException::raise(\"Python method %s.%sfailed to return a tuple.\");\n", classname, pyname); - Append(w->code, "}\n"); - } - - idx = 0; - - /* marshal return value */ - if (!is_void) { - tm = Swig_typemap_lookup("directorout", n, Swig_cresult_name(), w); - if (tm != 0) { - if (outputs > 1) { - Printf(w->code, "output = PyTuple_GetItem(%s, %d);\n", Swig_cresult_name(), idx++); - Replaceall(tm, "$input", "output"); - } else { - Replaceall(tm, "$input", Swig_cresult_name()); - } - char temp[24]; - sprintf(temp, "%d", idx); - Replaceall(tm, "$argnum", temp); - - /* TODO check this */ - if (Getattr(n, "wrap:disown")) { - Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); - } else { - Replaceall(tm, "$disown", "0"); - } - if (Getattr(n, "tmap:directorout:implicitconv")) { - Replaceall(tm, "$implicitconv", get_implicitconv_flag(n)); - } - Replaceall(tm, "$result", "c_result"); - Printv(w->code, tm, "\n", NIL); - 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)); - status = SWIG_ERROR; - } - } - - /* marshal outputs */ - for (p = l; p;) { - if ((tm = Getattr(p, "tmap:directorargout")) != 0) { - if (outputs > 1) { - Printf(w->code, "output = PyTuple_GetItem(%s, %d);\n", Swig_cresult_name(), idx++); - Replaceall(tm, "$result", "output"); - } else { - Replaceall(tm, "$result", Swig_cresult_name()); - } - Replaceall(tm, "$input", Getattr(p, "emit:directorinput")); - Printv(w->code, tm, "\n", NIL); - p = Getattr(p, "tmap:directorargout:next"); - } else { - p = nextSibling(p); - } - } - - /* any existing helper functions to handle this? */ - if (allow_thread) { - Append(w->code, "}\n"); - thread_end_block(n, w->code); - } - - Delete(parse_args); - Delete(arglist); - Delete(cleanup); - Delete(outarg); - } - - if (!is_void) { - if (!(ignored_method && !pure_virtual)) { - String *rettype = SwigType_str(returntype, 0); - if (!SwigType_isreference(returntype)) { - Printf(w->code, "return (%s) c_result;\n", rettype); - } else { - Printf(w->code, "return (%s) *c_result;\n", rettype); - } - Delete(rettype); - } - } - - Append(w->code, "}\n"); - - // We expose protected methods via an extra public inline method which makes a straight call to the wrapped class' method - String *inline_extra_method = NewString(""); - if (dirprot_mode() && !is_public(n) && !pure_virtual) { - Printv(inline_extra_method, declaration, NIL); - String *extra_method_name = NewStringf("%sSwigPublic", name); - Replaceall(inline_extra_method, name, extra_method_name); - Replaceall(inline_extra_method, ";\n", " {\n "); - if (!is_void) - Printf(inline_extra_method, "return "); - String *methodcall = Swig_method_call(super, l); - Printv(inline_extra_method, methodcall, ";\n }\n", NIL); - Delete(methodcall); - Delete(extra_method_name); - } - - /* emit the director method */ - if (status == SWIG_OK) { - if (!Getattr(n, "defaultargs")) { - Replaceall(w->code, "$symname", symname); - Wrapper_print(w, f_directors); - Printv(f_directors_h, declaration, NIL); - Printv(f_directors_h, inline_extra_method, NIL); - } - } - - /* clean up */ - Delete(wrap_args); - Delete(pclassname); - DelWrapper(w); - return status; - } -#endif - - /* TODO: REMOVE - virtual int namespaceDeclaration(Node *n) { - // Register namespace - String* name = Getattr(n, "sym:name"); - Hash* parent = getNamespaceHash( getNSpace() ); - String *parent_namespaces_tab = Getattr(parent, "namespaces"); - String *mangled_name = Swig_name_mangle(name); - String *full_name = NewString(""); - if (getNSpace() == 0) - Printv(full_name, name); - else - Printv(full_name, getNSpace(), NSPACE_SEPARATOR, name); - Hash *nspace = getNamespaceHash(full_name); - Setattr(nspace, "name", Copy(name)); - Printv(parent_namespaces_tab, mangled_name, ",\n", NIL); - Printf(stdout, "NamespaceDeclaration %s, Parent %s, FQN %s\n", name, getNSpace(), full_name); - Delete(mangled_name); - Delete(full_name); - return Language::namespaceDeclaration(n); - } - */ /* --------------------------------------------------------------------- * external runtime generation * --------------------------------------------------------------------- */ @@ -2328,7 +1587,6 @@ public: */ Hash* getNamespaceHash(String *nspace, bool reg = true) { - //Printf( stdout, "Request for %s. register: %d\n", nspace?nspace:"", int(reg)); Hash* nspace_hash = Getattr(namespaces_hash, nspace?nspace:"" ); if (nspace_hash != 0) return nspace_hash; @@ -2352,7 +1610,7 @@ public: String* item = Getitem(components, i); Printv(parent_path, item, NIL); } - Printf(stdout, "Registering %s. User name %s. C-name %s, Parent is %s\n", mangled_name, name, cname, parent_path); + //Printf(stdout, "Registering %s. User name %s. C-name %s, Parent is %s\n", mangled_name, name, cname, parent_path); Hash* parent = getNamespaceHash(parent_path, true); String* namespaces_tab = Getattr(parent, "namespaces"); Printv(namespaces_tab, "&", cname, ",\n", NIL); @@ -2523,6 +1781,20 @@ public: Printv(metatable_tab, tab4, "{LSTRKEY(\"__newindex\"), LFUNCVAL(SWIG_Lua_module_set)},\n", NIL); Printv(metatable_tab, tab4, "{LSTRKEY(\".get\"), LROVAL(", get_tab_name, ")},\n", NIL); Printv(metatable_tab, tab4, "{LSTRKEY(\".set\"), LROVAL(", set_tab_name, ")},\n", NIL); + if (Getattr(nspace_hash, "lua:class")) { + String *static_cls = Getattr(nspace_hash, "lua:class_instance:static_hash"); + assert(static_cls != 0); + String *static_cls_cname = Getattr(static_cls, "cname"); + assert(static_cls_cname != 0); + Printv(metatable_tab, tab4, "LSTRKEY(\".static\"), LROVAL(", static_cls_cname, ")},\n"); + } else if (Getattr(nspace_hash, "lua:class_static") ) { + Hash *instance_cls = Getattr(nspace_hash, "lua:class_static:instance_hash"); + assert(instance_cls != 0); + String *instance_cls_metatable_name = Getattr(instance_cls, "metatable:name"); + assert(instance_cls_metatable_name != 0); + Printv(metatable_tab, tab4, "LSTRKEY(\".static\"), LROVAL(", instance_cls_metatable_name, ")},\n"); + } + Printv(metatable_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); Printv(output, metatable_tab, NIL); } @@ -2547,11 +1819,6 @@ public: String* key = Getitem(to_close,i); closeNamespaceHash(key, dataOutput); Hash* nspace = Getattr(namespaces_hash, key); - String* cname = Getattr(nspace, "cname"); // cname - name of the C structure that describes namespace - assert(cname != 0); - //Printf( stdout, "Closing namespace %s\n", cname ); TODO: REMOVE - //printNamespaceForwardDeclaration( ki.key, declOutput ); TODO: REMOVE - Printv(dataOutput, "static swig_lua_namespace ", cname, " = ", NIL); String *name = 0; // name - name of the namespace as it should be visible in Lua if (DohLen(key) == 0) // This is global module name = module; @@ -2559,7 +1826,6 @@ public: name = Getattr(nspace, "name"); assert(name != 0); printNamespaceDefinition( key, name, dataOutput ); - Printv(dataOutput, ";\n\n", NIL); } Delete(to_close); } @@ -2573,7 +1839,13 @@ public: { // TODO: Fix for get_tab/set_tab things (elua_ltr) Hash *nspace_hash = getNamespaceHash(nspace, false); - String *null_string = NewString("0"); + + String* cname = Getattr(nspace_hash, "cname"); // cname - name of the C structure that describes namespace + assert(cname != 0); + Printv(output, "static swig_lua_namespace ", cname, " = ", NIL); + + PtrGuard null_string; + null_string = NewString("0"); String *attr_tab_name = Getattr(nspace_hash, "attributes:name"); String *methods_tab_name = Getattr(nspace_hash, "methods:name"); String *const_tab_name = Getattr(nspace_hash, "constants:name"); @@ -2582,13 +1854,14 @@ public: bool has_classes = Getattr(nspace_hash, "lua:no_classes") == 0; bool has_namespaces = Getattr(nspace_hash, "lua:no_namespaces") == 0; - Printf(output, "{\"%s\", %s, %s, %s, %s, %s}", - name, - methods_tab_name, - attr_tab_name, - const_tab_name, - (has_classes)?classes_tab_name:null_string, - (has_namespaces)?namespaces_tab_name:null_string + Printv(output, "{\n", + tab4, "\"", name, "\",\n", + tab4, methods_tab_name, ",\n", + tab4, attr_tab_name, ",\n", + tab4, const_tab_name, ",\n", + tab4, (has_classes)?classes_tab_name:null_string.ptr(), ",\n", + tab4, (has_namespaces)?namespaces_tab_name:null_string.ptr(), "};\n", + NIL ); } @@ -2603,10 +1876,6 @@ public: Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", iname, "\")", ", LFUNCVAL(", wname, ")", "},\n", NIL); else Printv(s_ns_methods_tab, tab4, "{ \"", target_name, "\", ", wname, "},\n", NIL); - // Printv(s_cmd_tab, tab4, "{ SWIG_prefix \"", iname, "\", (swig_wrapper_func) ", symname_wrapper(iname), "},\n", NIL); - if (getCurrentClass()) { - Setattr(n,"luaclassobj:wrap:name", wname); // TODO: REMOVE - } } // Add variable to the "attributes" (or "get"/"set" in @@ -2636,32 +1905,8 @@ public: } - // This function prints forward declaration of namespace itself and all its arrays - // TODO: REMOVE - void printNamespaceForwardDeclaration(String* nspace, File* output) - { - Hash *nspace_hash = getNamespaceHash(nspace, false); - String *attr_tab_decl = Getattr(nspace_hash, "attributes:decl"); - String *methods_tab_decl = Getattr(nspace_hash, "methods:decl"); - String *const_tab_decl = Getattr(nspace_hash, "constants:decl"); - String *classes_tab_decl = Getattr(nspace_hash, "classes:decl"); - String *namespaces_tab_decl = Getattr(nspace_hash, "declspaces:decl"); - bool has_classes = Getattr(nspace_hash, "lua:no_classes") == 0; - bool has_namespaces = Getattr(nspace_hash, "lua:no_namespaces") == 0; - Printv( output, attr_tab_decl, "\n", NIL ); - Printv( output, methods_tab_decl, "\n", NIL ); - Printv( output, const_tab_decl, "\n", NIL ); - if( has_classes ) - Printv( output, classes_tab_decl, "\n", NIL ); - if( has_namespaces ) - Printv( output, namespaces_tab_decl, "\n", NIL ); - - Printf( output, "static swig_lua_namespace %s;\n", Getattr(nspace_hash, "cname") ); - } - // Our implementation of addSymbol. Determines scope correctly, then calls Language::addSymbol int luaAddSymbol(const String *s, const Node *n) { - //Printf(stdout, "addSymbol: %s", s); // TODO:REMOVE String* scope = 0; // If ouside class, than NSpace is used. if( !getCurrentClass()) @@ -2679,7 +1924,7 @@ public: } assert(scope != 0); } - //Printf( stdout, " scope: %s\n", scope ); // TODO:REMOVE + //Printf(stdout, "addSymbol: %s scope: %s'n", s, scope); return Language::addSymbol(s,n,scope); } From 7e052c18736eba09f70dec8b9191e3d8d98b9f81 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Thu, 7 Nov 2013 19:59:38 +0400 Subject: [PATCH 396/481] Bugfixes --- Source/Modules/lua.cxx | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index c719bad66..0c5821326 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -321,8 +321,6 @@ public: /* Get the module name */ module = Getattr(n, "name"); - /* Some global settings */ - director_language = 1; /* Get the output file name */ String *outfile = Getattr(n, "outfile"); @@ -402,11 +400,11 @@ public: if (elua_ltr || eluac_ltr) { /* Final close up of wrappers */ - closeNamespaces(f_wrappers, 0); // TODO: Remove last parameter + closeNamespaces(f_wrappers); // TODO: Remove last parameter SwigType_emit_type_table(f_runtime, f_wrappers); } else { //Printv(f_wrappers, s_cmd_tab, s_var_tab, s_const_tab, NIL); - closeNamespaces(f_wrappers, 0); + closeNamespaces(f_wrappers); SwigType_emit_type_table(f_runtime, f_wrappers); } @@ -1233,9 +1231,11 @@ public: constructor_name = constructor_proxy_name; if (elua_ltr) { String* static_cls_metatable_tab = Getattr(static_cls, "metatable"); + assert(static_cls_metatable_tab != 0); Printf(static_cls_metatable_tab, " {LSTRKEY(\"__call\"), LFUNCVAL(%s)},\n", constructor_name); } else if (eluac_ltr) { String* ns_methods_tab = Getattr(nspaceHash, "methods"); + assert(ns_methods_tab != 0); Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "new_", class_symname, "\")", ", LFUNCVAL(", \ constructor_name, ")", "},\n", NIL); } @@ -1243,6 +1243,7 @@ public: if (have_destructor) { if (eluac_ltr) { String* ns_methods_tab = Getattr(nspaceHash, "methods"); + assert(ns_methods_tab != 0); Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "free_", mangled_class_fq_symname.ptr(), "\")", ", LFUNCVAL(", destructor_name.ptr(), ")", "},\n", NIL); } } @@ -1400,7 +1401,6 @@ public: current[CONSTRUCTOR] = false; //constructor_name = NewString(Getattr(n, "sym:name")); have_constructor = 1; - //Printf( stdout, "Constructor %s\n", constructor_name); TODO: REMOVE return SWIG_OK; } @@ -1781,18 +1781,18 @@ public: Printv(metatable_tab, tab4, "{LSTRKEY(\"__newindex\"), LFUNCVAL(SWIG_Lua_module_set)},\n", NIL); Printv(metatable_tab, tab4, "{LSTRKEY(\".get\"), LROVAL(", get_tab_name, ")},\n", NIL); Printv(metatable_tab, tab4, "{LSTRKEY(\".set\"), LROVAL(", set_tab_name, ")},\n", NIL); - if (Getattr(nspace_hash, "lua:class")) { + if (Getattr(nspace_hash, "lua:class_instance")) { String *static_cls = Getattr(nspace_hash, "lua:class_instance:static_hash"); assert(static_cls != 0); String *static_cls_cname = Getattr(static_cls, "cname"); assert(static_cls_cname != 0); - Printv(metatable_tab, tab4, "LSTRKEY(\".static\"), LROVAL(", static_cls_cname, ")},\n"); + Printv(metatable_tab, tab4, "LSTRKEY(\".static\"), LROVAL(", static_cls_cname, ")},\n", NIL); } else if (Getattr(nspace_hash, "lua:class_static") ) { Hash *instance_cls = Getattr(nspace_hash, "lua:class_static:instance_hash"); assert(instance_cls != 0); String *instance_cls_metatable_name = Getattr(instance_cls, "metatable:name"); assert(instance_cls_metatable_name != 0); - Printv(metatable_tab, tab4, "LSTRKEY(\".static\"), LROVAL(", instance_cls_metatable_name, ")},\n"); + Printv(metatable_tab, tab4, "LSTRKEY(\".static\"), LROVAL(", instance_cls_metatable_name, ")},\n", NIL); } Printv(metatable_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); @@ -1803,8 +1803,7 @@ public: static int compareByLen( const DOH* f, const DOH* s) { return Len(s) - Len(f); } // Recursively close all non-closed namespaces. Prints data to dataOutput, - // forward declaration to declOutput - void closeNamespaces(File *dataOutput, File *declOutput) + void closeNamespaces(File *dataOutput) { Iterator ki = First(namespaces_hash); List* to_close = NewList(); @@ -1867,15 +1866,16 @@ public: // Add method to the "methods" C array of given namespace/class void registerMethod(String *nspace_or_class_name, Node* n) { - Hash* nspaceHash = getNamespaceHash( nspace_or_class_name ); - String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); - String *wname = Getattr(n, "wrap:name"); - String *iname = Getattr(n, "sym:name"); - String *target_name = Getattr(n, "lua:name"); - if(elua_ltr || eluac_ltr) - Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", iname, "\")", ", LFUNCVAL(", wname, ")", "},\n", NIL); - else - Printv(s_ns_methods_tab, tab4, "{ \"", target_name, "\", ", wname, "},\n", NIL); + assert(n != 0); + Hash* nspaceHash = getNamespaceHash( nspace_or_class_name ); + String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); + String *wname = Getattr(n, "wrap:name"); + String *iname = Getattr(n, "sym:name"); + String *target_name = Getattr(n, "lua:name"); + if(elua_ltr || eluac_ltr) + Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", iname, "\")", ", LFUNCVAL(", wname, ")", "},\n", NIL); + else + Printv(s_ns_methods_tab, tab4, "{ \"", target_name, "\", ", wname, "},\n", NIL); } // Add variable to the "attributes" (or "get"/"set" in @@ -1924,7 +1924,7 @@ public: } assert(scope != 0); } - //Printf(stdout, "addSymbol: %s scope: %s'n", s, scope); + //Printf(stdout, "addSymbol: %s scope: %s\n", s, scope); return Language::addSymbol(s,n,scope); } From da0510376c4d29bcf5f08ce734b0dcfbd3264849 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Fri, 8 Nov 2013 12:28:45 +0400 Subject: [PATCH 397/481] Bugfixes. CMD args handling. Code cleanup --- Examples/test-suite/lua/li_carrays_runme.lua | 20 +- .../test-suite/lua/member_pointer_runme.lua | 39 +-- Lib/lua/luarun.swg | 29 ++- Lib/lua/luaruntime.swg | 4 +- Source/Modules/lua.cxx | 246 ++++++++++++------ 5 files changed, 220 insertions(+), 118 deletions(-) diff --git a/Examples/test-suite/lua/li_carrays_runme.lua b/Examples/test-suite/lua/li_carrays_runme.lua index 285d7b32a..d007fae36 100644 --- a/Examples/test-suite/lua/li_carrays_runme.lua +++ b/Examples/test-suite/lua/li_carrays_runme.lua @@ -1,8 +1,6 @@ require("import") -- the import fn import("li_carrays") -- import code - --- moving to global -for k,v in pairs(li_carrays) do _G[k]=v end +lc = li_carrays -- catch "undefined" global variables local env = _ENV -- Lua 5.2 @@ -10,22 +8,22 @@ if not env then env = getfenv () end -- Lua 5.1 setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) -- Testing for %array_functions(int,intArray) -ary = new_intArray(2) -intArray_setitem(ary, 0, 0) -intArray_setitem(ary, 1, 1) -assert(intArray_getitem(ary, 0)==0) -assert(intArray_getitem(ary, 1)==1) -delete_intArray(ary) +ary = lc.new_intArray(2) +lc.intArray_setitem(ary, 0, 0) +lc.intArray_setitem(ary, 1, 1) +assert(lc.intArray_getitem(ary, 0)==0) +assert(lc.intArray_getitem(ary, 1)==1) +lc.delete_intArray(ary) -- Testing for %array_class(double, doubleArray) -d = doubleArray(10) +d = lc.doubleArray(10) d[0] = 7 d[5] = d[0] + 3 assert(d[5] + d[0] == 17) --print(d[5] + d[0]) ptr = d:cast() -- to ptr -d2 = doubleArray_frompointer(ptr) -- and back to array +d2 = lc.doubleArray_frompointer(ptr) -- and back to array assert(d2[5] + d2[0] == 17) --print(d2[5] + d2[0]) diff --git a/Examples/test-suite/lua/member_pointer_runme.lua b/Examples/test-suite/lua/member_pointer_runme.lua index 8dddab295..1240d92a0 100644 --- a/Examples/test-suite/lua/member_pointer_runme.lua +++ b/Examples/test-suite/lua/member_pointer_runme.lua @@ -1,43 +1,46 @@ --Example using pointers to member functions - require("import") -- the import fn import("member_pointer") -- import code +mp = member_pointer -for k,v in pairs(member_pointer) do _G[k]=v end +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) function check(what, expected, actual) assert(expected == actual,"Failed: "..what.." Expected: "..expected.." Actual: "..actual) end -- Get the pointers -area_pt = areapt() -perim_pt = perimeterpt() +area_pt = mp.areapt() +perim_pt = mp.perimeterpt() -- Create some objects -s = Square(10) +s = mp.Square(10) -- Do some calculations -check ("Square area ", 100.0, do_op(s,area_pt)) -check ("Square perim", 40.0, do_op(s,perim_pt)) +check ("Square area ", 100.0, mp.do_op(s,area_pt)) +check ("Square perim", 40.0, mp.do_op(s,perim_pt)) -- Try the variables -- these have to still be part of the 'member_pointer' table -memberPtr = member_pointer.areavar -memberPtr = member_pointer.perimetervar +memberPtr = mp.areavar +memberPtr = mp.perimetervar -check ("Square area ", 100.0, do_op(s,member_pointer.areavar)) -check ("Square perim", 40.0, do_op(s,member_pointer.perimetervar)) +check ("Square area ", 100.0, mp.do_op(s,mp.areavar)) +check ("Square perim", 40.0, mp.do_op(s,mp.perimetervar)) -- Modify one of the variables -member_pointer.areavar = perim_pt +mp.areavar = perim_pt -check ("Square perimeter", 40.0, do_op(s,member_pointer.areavar)) +check ("Square perimeter", 40.0, mp.do_op(s,mp.areavar)) -- Try the constants -memberPtr = AREAPT -memberPtr = PERIMPT -memberPtr = NULLPT +memberPtr = mp.AREAPT +memberPtr = mp.PERIMPT +memberPtr = mp.NULLPT -check ("Square area ", 100.0, do_op(s,AREAPT)) -check ("Square perim", 40.0, do_op(s,PERIMPT)) +check ("Square area ", 100.0, mp.do_op(s,mp.AREAPT)) +check ("Square perim", 40.0, mp.do_op(s,mp.PERIMPT)) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index 764ec5fe4..4ed260774 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -138,19 +138,19 @@ typedef struct { } swig_lua_attribute; -struct swig_lua_class; +struct _swig_lua_class; // Can be used to create namespaces. Currently used to // wrap class static methods/variables/constants -struct swig_lua_namespace { +typedef struct _swig_lua_namespace { const char *name; swig_lua_method *ns_methods; swig_lua_attribute *ns_attributes; swig_lua_const_info *ns_constants; - swig_lua_class **ns_classes; - swig_lua_namespace **ns_namespaces; -}; + struct _swig_lua_class **ns_classes; + struct _swig_lua_namespace **ns_namespaces; +} swig_lua_namespace; -struct swig_lua_class { +typedef struct _swig_lua_class { const char *name; // Name that this class has in Lua const char *fqname; // Fully qualified name - Scope + class name swig_type_info **type; @@ -159,9 +159,9 @@ struct swig_lua_class { swig_lua_method *methods; swig_lua_attribute *attributes; swig_lua_namespace *cls_static; - struct swig_lua_class **bases; + struct _swig_lua_class **bases; const char **base_names; -}; +} swig_lua_class; /* this is the struct for wrapping all pointers in SwigLua */ @@ -351,6 +351,10 @@ SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State* L, swig_lua_namespace* assert(lua_istable(L,-1)); SWIG_Lua_InstallConstants(L, ns->ns_constants); + /* add methods to the namespace/module table */ + for(i=0;ns->ns_methods[i].name;i++){ + SWIG_Lua_add_function(L,ns->ns_methods[i].name,ns->ns_methods[i].func); + } lua_getmetatable(L,-1); /* add fns */ @@ -358,6 +362,8 @@ SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State* L, swig_lua_namespace* SWIG_Lua_add_variable(L,ns->ns_attributes[i].name,ns->ns_attributes[i].getmethod,ns->ns_attributes[i].setmethod); } +#if 0 + // TODO: REMOVE. .fn table is unused /* add methods to the metatable */ SWIG_Lua_get_table(L,".fn"); /* find the .fn table */ assert(lua_istable(L,-1)); /* just in case */ @@ -365,6 +371,7 @@ SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State* L, swig_lua_namespace* SWIG_Lua_add_function(L,ns->ns_methods[i].name,ns->ns_methods[i].func); } lua_pop(L,1); +#endif /* clear stack - remove metatble */ lua_pop(L,1); @@ -393,7 +400,7 @@ SWIGINTERN void SWIG_Lua_add_namespace_classes(lua_State* L, swig_lua_namespace* when function is called) Function always returns newly registered table on top of the stack */ -SWIGINTERN int SWIG_Lua_namespace_register(lua_State* L, swig_lua_namespace* ns, bool reg) +SWIGINTERN int SWIG_Lua_namespace_register(lua_State* L, swig_lua_namespace* ns, int reg) { int begin = lua_gettop(L); assert(lua_istable(L,-1)); /* just in case. This is supposed to be module table or parent namespace table */ @@ -428,7 +435,7 @@ SWIGINTERN int SWIG_Lua_namespace_register(lua_State* L, swig_lua_namespace* ns, swig_lua_namespace** sub_namespace = ns->ns_namespaces; if( sub_namespace != 0) { while(*sub_namespace != 0) { - SWIG_Lua_namespace_register(L, *sub_namespace, true); + SWIG_Lua_namespace_register(L, *sub_namespace, 1); lua_pop(L,1); // removing sub-namespace table sub_namespace++; } @@ -867,7 +874,7 @@ SWIGINTERN void SWIG_Lua_class_register_static(lua_State* L, swig_lua_class* cls assert(lua_istable(L,-1)); /* just in case */ assert(strcmp(clss->name, clss->cls_static->name) == 0); /* in class those 2 must be equal */ - SWIG_Lua_namespace_register(L,clss->cls_static, true); + SWIG_Lua_namespace_register(L,clss->cls_static, 1); assert(lua_istable(L,-1)); /* just in case */ diff --git a/Lib/lua/luaruntime.swg b/Lib/lua/luaruntime.swg index 0011c9d52..5e4ba9fd9 100644 --- a/Lib/lua/luaruntime.swg +++ b/Lib/lua/luaruntime.swg @@ -49,9 +49,9 @@ SWIGEXPORT int SWIG_init(lua_State* L) /* default Lua action */ SWIG_Lua_init_base_class(L,(swig_lua_class*)(swig_types[i]->clientdata)); } } - bool globalRegister = false; + int globalRegister = 0; #ifdef SWIG_LUA_MODULE_GLOBAL - globalRegister = true; + globalRegister = 1; #endif SWIG_Lua_namespace_register(L,&swig___Global, globalRegister); #endif diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 0c5821326..824590b3a 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -91,14 +91,16 @@ class DohPtrGuard { // Guard is empty, ptr - any: assigns new value for guard // Guard is holding pointer, ptr == 0 - releases value that guard holds // Any other combination - assert - void operator=( DOH* ptr ) { + DOH* operator=( DOH* ptr ) { attach(ptr); + return ptr; } DOH* ptr() { return p_ptr; } const DOH* ptr() const { return p_ptr; } operator DOH* () { return p_ptr; } operator DOH* () const { return p_ptr; } + operator bool() const { return ptr != 0; } private: DOH* p_ptr; // pointer to actual object @@ -129,11 +131,11 @@ class DohPtrGuard { // Overloading DohDelete for DohPtrGuard. You might not call DohDelete on DohPtrGuard instances, // as it is supposed to manage underlying pointer by itself -void DohDelete(const DohPtrGuard& guard) { +void DohDelete(const DohPtrGuard& /*guard*/) { Printf( stderr, "ERROR: Attempt to delete guarded pointer without deleting it's guardian\n" ); assert(false); } -void DohDelete(DohPtrGuard& guard) { +void DohDelete(DohPtrGuard& /*guard*/) { Printf( stderr, "ERROR: Attempt to delete guarded pointer without deleting it's guardian\n" ); assert(false); } @@ -152,12 +154,23 @@ Lua Options (available with -lua)\n\ -eluac - LTR compatible wrappers in \"crass compress\" mode for elua\n\ -nomoduleglobal - Do not register the module name as a global variable \n\ but return the module table from calls to require.\n\ + -api-lvl-from NUM\n\ + - Force support for old-style bindings. All old-style bindings\n\ + from NUM to current new-style bindings will be supported. For example,\n\ + if current lua bindings API version is 10 and NUM==7 then SWIG will\n\ + generate bindings compatible with lua bindings versions 7,8,9 and,\n\ + of course current version of bindings, 10.\n\ + API levels:\n\ + 2 - SWIG 2.*\n\ + 3 - SWIG 3.*\n\ + Default NUM is 2.\n\ \n"; static int nomoduleglobal = 0; static int elua_ltr = 0; static int eluac_ltr = 0; -static int v2_compatibility = 1; +static int v2_compatibility = 0; +static const int default_api_level = 2; /* NEW LANGUAGE NOTE:*********************************************** To add a new language, you need to derive your class from @@ -260,6 +273,7 @@ public: virtual void main(int argc, char *argv[]) { + int api_level = default_api_level; // Default api level /* Set location of SWIG library */ SWIG_library_directory("lua"); @@ -277,10 +291,30 @@ public: } else if(strcmp(argv[i], "-eluac") == 0) { eluac_ltr = 1; Swig_mark_arg(i); + } else if(strcmp(argv[i], "-api-lvl-from") == 0) { + if(argv[i+1]) { + api_level = atoi(argv[i+1]); + if(api_level == 0) + Swig_arg_error(); + Swig_mark_arg(i+1); + i++; + } else { + Swig_arg_error(); + } } } } + // Set API-compatibility options + if(api_level <= 2) // Must be compatible with SWIG 2.* + v2_compatibility = 1; + // template for further API breaks + //if(api_level <= 3) + // v3_compatibility = 1; + //if(api_level <= 4) + // v4_compatibility = 1; + + /* NEW LANGUAGE NOTE:*********************************************** This is the boilerplate code, setting a few #defines and which lib directory to use @@ -400,7 +434,7 @@ public: if (elua_ltr || eluac_ltr) { /* Final close up of wrappers */ - closeNamespaces(f_wrappers); // TODO: Remove last parameter + closeNamespaces(f_wrappers); SwigType_emit_type_table(f_runtime, f_wrappers); } else { //Printv(f_wrappers, s_cmd_tab, s_var_tab, s_const_tab, NIL); @@ -491,6 +525,16 @@ public: Setattr(n, "varget:wrap:name", wrapname); } + // Helper for functionWrapper - determines whether we should + // register method in the appropriate class/namespace/module + // table or not. + // (not => it is variable wrapper or something similar) + bool functionWrapperRegisterNow() const { + if (current[VARIABLE]) + return false; + return (current[NO_CPP] || current[STATIC_FUNC]); + } + virtual int functionWrapper(Node *n) { REPORT("functionWrapper",n); @@ -503,14 +547,13 @@ public: Parm *p; String *tm; int i; - //Printf(stdout,"functionWrapper %s %s %d\n",name,iname,current); + //Printf(stdout,"functionWrapper %s %s %d\n",name,iname,current); // TODO: COMMENT BACK String *overname = 0; if (Getattr(n, "sym:overloaded")) { overname = Getattr(n, "sym:overname"); } else { if (!luaAddSymbol(target_name, n)) { - Printf(stderr,"addSymbol(%s) failed\n",target_name); return SWIG_ERROR; } } @@ -790,13 +833,14 @@ public: different language mappings seem to use different ideas NEW LANGUAGE NOTE:END ************************************************/ /* Now register the function with the interpreter. */ + int result = SWIG_OK; if (!Getattr(n, "sym:overloaded")) { - if (current[NO_CPP] || current[STATIC_FUNC]) { // emit normal fns & static fns - registerMethod(getNSpace(), n); + if (functionWrapperRegisterNow()) { // emit normal fns & static fns + registerMethod(luaCurrentSymbolNSpace(), n); } } else { if (!Getattr(n, "sym:nextSibling")) { - dispatchFunction(n); + result = dispatchFunction(n); } } @@ -808,7 +852,7 @@ public: // Delete(description); DelWrapper(f); - return SWIG_OK; + return result; } /* ------------------------------------------------------------ @@ -823,7 +867,7 @@ public: nost of the real work in again typemaps: look for %typecheck(SWIG_TYPECHECK_*) in the .swg file NEW LANGUAGE NOTE:END ************************************************/ - void dispatchFunction(Node *n) { + int dispatchFunction(Node *n) { //REPORT("dispatchFunction", n); /* Last node in overloaded chain */ @@ -841,6 +885,10 @@ public: //Printf(stdout,"Swig_overload_dispatch %s %s '%s' %d\n",symname,wname,dispatch,maxargs); + if (!luaAddSymbol(target_name, n)) { + return SWIG_ERROR; + } + Printv(f->def, "static int ", wname, "(lua_State* L) {", NIL); Wrapper_add_local(f, "argc", "int argc"); Printf(tmp, "int argv[%d]={1", maxargs + 1); @@ -870,8 +918,12 @@ public: Printf(f->code, "lua_error(L);return 0;\n"); Printv(f->code, "}\n", NIL); Wrapper_print(f, f_wrappers); - if (current[NO_CPP] || current[STATIC_FUNC]) { // emit normal fns & static fns - registerMethod(getNSpace(), n); + + // Remember C name of the wrapping function + rememberWrapName(n, wname); + + if (functionWrapperRegisterNow()) { // emit normal fns & static fns + registerMethod(luaCurrentSymbolNSpace(), n); } if (current[CONSTRUCTOR]) { if( constructor_name != 0 ) @@ -879,12 +931,11 @@ public: constructor_name = Copy(wname); } - // Remember C name of the wrapping function - rememberWrapName(n, wname); - DelWrapper(f); Delete(dispatch); Delete(tmp); + + return SWIG_OK; } @@ -906,8 +957,8 @@ public: current[VARIABLE] = true; // let SWIG generate the wrappers int result = Language::variableWrapper(n); + registerVariable( luaCurrentSymbolNSpace(), n, "varget:wrap:name", "varset:wrap:name" ); current[VARIABLE] = false; - registerVariable( getNSpace(), n, "varget:wrap:name", "varset:wrap:name" ); return result; } @@ -926,10 +977,26 @@ public: String *rawval = Getattr(n, "rawval"); String *value = rawval ? rawval : Getattr(n, "value"); String *tm; + PtrGuard target_name_v2; + PtrGuard tm_v2; + PtrGuard iname_v2; + PtrGuard n_v2; if (!luaAddSymbol(target_name, n)) return SWIG_ERROR; + bool make_v2_compatible = v2_compatibility && getCurrentClass() != 0; + //Printf( stdout, "V2 compatible: %d\n", int(make_v2_compatible) ); // TODO: REMOVE + if( make_v2_compatible ) { + target_name_v2 = Swig_name_member(0, class_symname, target_name); + iname_v2 = Swig_name_member(0, class_symname, iname); + n_v2 = Copy(n); + //Printf( stdout, "target name v2: %s, symname v2 %s\n", target_name_v2.ptr(), iname_v2.ptr());// TODO:REMOVE + if (!luaAddSymbol(iname_v2, n, class_parent_nspace)) { + return SWIG_ERROR; + } + } + Swig_save("lua_constantMember", n, "sym:name", NIL); Setattr(n, "sym:name", target_name); /* Special hook for member pointer */ @@ -940,16 +1007,17 @@ public: } if ((tm = Swig_typemap_lookup("consttab", n, name, 0))) { + //Printf(stdout, "tm v1: %s\n", tm); // TODO:REMOVE Replaceall(tm, "$source", value); - Replaceall(tm, "$target", name); + Replaceall(tm, "$target", target_name); Replaceall(tm, "$value", value); Replaceall(tm, "$nsname", nsname); - Hash *nspaceHash = getNamespaceHash( getNSpace() ); + Hash *nspaceHash = getNamespaceHash( luaCurrentSymbolNSpace() ); String *s_const_tab = Getattr(nspaceHash, "constants"); Printf(s_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, "$target", target_name); Replaceall(tm, "$value", value); Replaceall(tm, "$nsname", nsname); Printf(f_init, "%s\n", tm); @@ -959,34 +1027,35 @@ public: Swig_restore(n); return SWIG_NOWRAP; } - /* TODO: Review - if( v2_compatibility && getCurrentClass() ) { - if (!luaAddSymbol(iname, n, class_parent_nspace)) - return SWIG_ERROR; - Setattr(n, "sym:name", iname); - 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); + if( make_v2_compatible ) { + Setattr(n_v2, "sym:name", target_name_v2); + tm_v2 = Swig_typemap_lookup("consttab", n_v2, name, 0); + if (tm_v2) { + //Printf(stdout, "tm v2: %s\n", tm_v2.ptr()); // TODO:REMOVE + Replaceall(tm_v2, "$source", value); + Replaceall(tm_v2, "$target", target_name_v2); + Replaceall(tm_v2, "$value", value); + Replaceall(tm_v2, "$nsname", nsname); Hash *nspaceHash = getNamespaceHash( class_parent_nspace ); String *s_const_tab = Getattr(nspaceHash, "constants"); - Printf(s_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); + Printf(s_const_tab, " %s,\n", tm_v2.ptr()); } else { - Delete(nsname); - Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value.\n"); - Swig_restore(n); - return SWIG_NOWRAP; + tm_v2 = Swig_typemap_lookup("constcode", n_v2, name, 0); + if( !tm_v2) { + // This can't be. + assert(false); + Swig_restore(n); + return SWIG_ERROR; + } + Replaceall(tm_v2, "$source", value); + Replaceall(tm_v2, "$target", target_name_v2); + Replaceall(tm_v2, "$value", value); + Replaceall(tm_v2, "$nsname", nsname); + Printf(f_init, "%s\n", tm_v2.ptr()); } } - */ + Swig_restore(n); Delete(nsname); return SWIG_OK; @@ -1019,9 +1088,11 @@ public: // So this is the exact copy of function from Language with // correct handling of namespaces String *oldNSpace = getNSpace(); + /* TODO: REVIEW/REMOVE_and_replace_with_Language::enumDeclaration if( getCurrentClass() == 0 ) { setNSpace(Getattr(n, "sym:nspace")); - } + }*/ + setNSpace(Getattr(n, "sym:nspace")); if (!ImportMode) { current[STATIC_CONST] = true; @@ -1054,12 +1125,11 @@ public: Setattr(n, "value", tmpValue); Setattr(n, "name", tmpValue); /* for wrapping of enums in a namespace when emit_action is used */ - constantWrapper(n); + int result = constantWrapper(n); Delete(tmpValue); Swig_restore(n); - // TODO: Backward compatibility: add ClassName_ConstantName member - return SWIG_OK; + return result; } /* ------------------------------------------------------------ @@ -1173,11 +1243,11 @@ public: // Replacing namespace with namespace + class in order to static // member be put inside class static area class_parent_nspace = getNSpace(); - setNSpace(class_static_nspace); + //setNSpace(class_static_nspace); TODO: REMOVE // Generate normal wrappers Language::classHandler(n); // Restore correct nspace - setNSpace(nspace); + //setNSpace(nspace); // TODO: REMOVE if remove above class_parent_nspace = 0; SwigType_add_pointer(t); @@ -1418,6 +1488,22 @@ public: return SWIG_OK; } + /* ---------------------------------------------------------------------- + * globalfunctionHandler() + * It can be called: + * 1. Usual C/C++ global function. + * 2. During class parsing for functions declared/defined as friend + * 3. During class parsing from staticmemberfunctionHandler + * ---------------------------------------------------------------------- */ + int globalfunctionHandler(Node *n) { + bool oldVal = current[NO_CPP]; + if(!current[STATIC_FUNC]) // If static funct, don't switch to NO_CPP + current[NO_CPP] = true; + int result = Language::globalfunctionHandler(n); + current[NO_CPP] = oldVal; + return result; + } + /* ----------------------------------------------------------------------- * staticmemberfunctionHandler() * @@ -1427,7 +1513,6 @@ public: virtual int staticmemberfunctionHandler(Node *n) { REPORT("staticmemberfunctionHandler", n); current[STATIC_FUNC] = true; - //String *symname = Getattr(n, "sym:name"); int result = Language::staticmemberfunctionHandler(n); current[STATIC_FUNC] = false;; @@ -1444,18 +1529,6 @@ public: Swig_restore(n); } - if (Getattr(n, "sym:nextSibling")) - return SWIG_OK; - - //Swig_require("luaclassobj_staticmemberfunctionHandler", n, "luaclassobj:wrap:name", NIL); - //String *name = Getattr(n, "name"); - //String *rname, *realname; - //realname = symname ? symname : name; - //rname = Getattr(n, "luaclassobj:wrap:name"); - // TODO: Add backward compatibility here: add "ClassName_FuncName" to global table - //Printv(s_cls_methods_tab, tab4, "{\"", realname, "\", ", rname, "}, \n", NIL); - //Swig_restore(n); - return SWIG_OK; } @@ -1495,13 +1568,10 @@ public: if( !GetFlag(n,"wrappedasconstant") ) { Setattr(n, "lua:name", v2_name); registerVariable( class_parent_nspace, n, "varget:wrap:name", "varset:wrap:name"); - } else { - Setattr(n, "lua:name", v2_name); - String* oldNSpace = getNSpace(); - setNSpace(class_parent_nspace); - constantWrapper(n); - setNSpace(oldNSpace); } + // If static member variable was wrapped as constant, then + // constant wrapper has already performed all actions + // necessary for v2_compatibility Delete(v2_name); Swig_restore(n); } @@ -1805,6 +1875,12 @@ public: // Recursively close all non-closed namespaces. Prints data to dataOutput, void closeNamespaces(File *dataOutput) { + // Special handling for empty module. + if( Getattr(namespaces_hash, "") == 0 ) { + // Module is empty. Create hash for global scope in order to have swig__Global + // variable in resulting file + getNamespaceHash(0); + } Iterator ki = First(namespaces_hash); List* to_close = NewList(); while (ki.key) { @@ -1904,14 +1980,19 @@ public: } } - - // Our implementation of addSymbol. Determines scope correctly, then calls Language::addSymbol - int luaAddSymbol(const String *s, const Node *n) { + // This function determines actual namespace/scope where any symbol at the + // current moment should be placed. It looks at the 'current' array + // and depending on where are we - static class member/function, + // instance class member/function or just global functions decides + // where symbol should be put. + // The namespace/scope doesn't depend from symbol, only from 'current' + String* luaCurrentSymbolNSpace() { String* scope = 0; // If ouside class, than NSpace is used. - if( !getCurrentClass()) + // If inside class, but current[NO_CPP], then this is friend function. It belongs to NSpace + if( !getCurrentClass() || current[NO_CPP]) { scope = getNSpace(); - else { + } else { // If inside class, then either class static namespace or class fully qualified name is used assert(!current[NO_CPP]); if(current[STATIC_FUNC] || current[STATIC_VAR] || current[STATIC_CONST] ) { @@ -1924,13 +2005,26 @@ public: } assert(scope != 0); } - //Printf(stdout, "addSymbol: %s scope: %s\n", s, scope); - return Language::addSymbol(s,n,scope); + return scope; + } + + // Our implementation of addSymbol. Determines scope correctly, then calls Language::addSymbol + int luaAddSymbol(const String *s, const Node *n) { + String *scope = luaCurrentSymbolNSpace(); + //Printf(stdout, "luaAddSymbol: %s scope: %s\n", s, scope); + int result = Language::addSymbol(s,n,scope); + if( !result ) + Printf(stderr,"addSymbol(%s to scope %s) failed\n",s, scope); + return result; } // Overload. Enforces given scope. Actually, it simply forwards call to Language::addSymbol int luaAddSymbol(const String*s, const Node*n, const_String_or_char_ptr scope) { - return Language::addSymbol(s,n,scope); + //Printf(stdout, "luaAddSymbol: %s scope: %s\n", s, scope); + int result = Language::addSymbol(s,n,scope); + if( !result ) + Printf(stderr,"addSymbol(%s to scope %s) failed\n",s, scope); + return result; } // Function creates fully qualified name of given symbol. Current NSpace and current class From 9d6cd75c7324397f866e0704deb6ed93ffdcf032 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Fri, 8 Nov 2013 13:20:20 +0400 Subject: [PATCH 398/481] Bugfixes --- Examples/test-suite/director_nspace.i | 2 +- .../test-suite/director_nspace_director_name_collision.i | 2 +- Examples/test-suite/lua/nspace_runme.lua | 2 +- Examples/test-suite/nspace_extend.i | 2 +- Lib/lua/luarun.swg | 4 ++++ Source/Modules/lua.cxx | 8 ++++---- 6 files changed, 12 insertions(+), 8 deletions(-) diff --git a/Examples/test-suite/director_nspace.i b/Examples/test-suite/director_nspace.i index 512077e8b..fdea75e2f 100644 --- a/Examples/test-suite/director_nspace.i +++ b/Examples/test-suite/director_nspace.i @@ -40,7 +40,7 @@ namespace TopLevel %include // nspace feature only supported by these languages -#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGD) +#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGD) || defined(SWIGLUA) %nspace TopLevel::Bar::Foo; %nspace TopLevel::Bar::FooBar; #else diff --git a/Examples/test-suite/director_nspace_director_name_collision.i b/Examples/test-suite/director_nspace_director_name_collision.i index c6f13b451..8fd27c968 100644 --- a/Examples/test-suite/director_nspace_director_name_collision.i +++ b/Examples/test-suite/director_nspace_director_name_collision.i @@ -34,7 +34,7 @@ namespace TopLevel %include // nspace feature only supported by these languages -#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGD) +#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGD) || defined(SWIGLUA) %nspace TopLevel::A::Foo; %nspace TopLevel::B::Foo; #else diff --git a/Examples/test-suite/lua/nspace_runme.lua b/Examples/test-suite/lua/nspace_runme.lua index 4eb0ffaf6..2ed8a86b7 100644 --- a/Examples/test-suite/lua/nspace_runme.lua +++ b/Examples/test-suite/lua/nspace_runme.lua @@ -10,7 +10,7 @@ ns = nspace -- Inheritance blue1 = ns.Outer.Inner3.Blue() -debug.debug() + -- blue1:blueInstanceMethod() blue1:colorInstanceMethod(60.0) blue1.instanceMemberVariable = 4 diff --git a/Examples/test-suite/nspace_extend.i b/Examples/test-suite/nspace_extend.i index 782ce90ca..e92ff8c1d 100644 --- a/Examples/test-suite/nspace_extend.i +++ b/Examples/test-suite/nspace_extend.i @@ -2,7 +2,7 @@ %module nspace_extend // nspace feature only supported by these languages -#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGD) +#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGD) || defined(SWIGLUA) #if defined(SWIGJAVA) SWIG_JAVABODY_PROXY(public, public, SWIGTYPE) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index 4ed260774..da8b8d3a7 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -70,6 +70,10 @@ extern "C" { # define lua_pushglobaltable(L) lua_pushvalue(L, LUA_GLOBALSINDEX) #endif +/* lua_absindex was introduced in Lua 5.2 */ +#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502 +# define lua_absindex(L,i) ((i)>0 || (i) <= LUA_REGISTRYINDEX ? (i) : lua_gettop(L) + (i) + 1) +#endif /* -------------------------------------------------------------------------- * Helper functions for error handling diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 824590b3a..4cfaca6ed 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -1712,7 +1712,7 @@ public: Printf(methods_tab, "static LUA_REG_TYPE "); else Printf(methods_tab, "static swig_lua_method "); - Printv(methods_tab, methods_tab_name, "[]"); + Printv(methods_tab, methods_tab_name, "[]", NIL); Printv(methods_tab_decl, methods_tab, ";\n", NIL); Printv(methods_tab, "= {\n", NIL); Setattr(nspace_hash, "methods", methods_tab ); @@ -1737,7 +1737,7 @@ public: String *classes_tab_name = NewStringf("swig_%s_classes", mangled_name ); String *classes_tab_decl = NewString(""); Printf(classes_tab, "static swig_lua_class* "); - Printv(classes_tab, classes_tab_name, "[]"); + Printv(classes_tab, classes_tab_name, "[]", NIL); Printv(classes_tab_decl, classes_tab, ";", NIL); Printv(classes_tab, "= {\n", NIL); Setattr(nspace_hash, "classes", classes_tab ); @@ -1748,7 +1748,7 @@ public: String* namespaces_tab_name = NewStringf("swig_%s_namespaces", mangled_name ); String* namespaces_tab_decl = NewString(""); Printf(namespaces_tab, "static swig_lua_namespace* "); - Printv(namespaces_tab, namespaces_tab_name, "[]"); + Printv(namespaces_tab, namespaces_tab_name, "[]", NIL); Printv(namespaces_tab_decl, namespaces_tab, ";", NIL); Printv(namespaces_tab, " = {\n", NIL); Setattr(nspace_hash, "namespaces", namespaces_tab ); @@ -1772,7 +1772,7 @@ public: if (!eluac_ltr) { String* metatable_tab = NewString(""); String* metatable_tab_name = NewStringf("swig_%s_meta", mangled_name); - Printv(metatable_tab, "const LUA_REG_TYPE ", metatable_tab_name, "[] = {\n"); + Printv(metatable_tab, "const LUA_REG_TYPE ", metatable_tab_name, "[] = {\n", NIL); Setattr(nspace_hash, "metatable", metatable_tab); Setattr(nspace_hash, "metatable:name", metatable_tab_name); } From c775e660480d76a7d067e04e5c620f142896e0e7 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Sat, 9 Nov 2013 22:38:03 +0400 Subject: [PATCH 399/481] Fixes for elua --- Lib/lua/lua.swg | 8 +- Lib/lua/luarun.swg | 80 +++++++------ Lib/lua/luaruntime.swg | 5 + Source/Modules/lua.cxx | 247 ++++++++++++++++++++++++----------------- 4 files changed, 198 insertions(+), 142 deletions(-) diff --git a/Lib/lua/lua.swg b/Lib/lua/lua.swg index 80c4c04c1..c470d9298 100644 --- a/Lib/lua/lua.swg +++ b/Lib/lua/lua.swg @@ -40,12 +40,14 @@ %typemap(consttab) long long, unsigned long long {SWIG_LUA_CONSTTAB_STRING("$symname", "$value")} -%typemap(consttab) SWIGTYPE *, SWIGTYPE *const, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] - { SWIG_LUA_POINTER, (char *)"$symname", 0, 0, (void *)$value, &$1_descriptor} +%typemap(consttab) SWIGTYPE *, SWIGTYPE *const, SWIGTYPE &, SWIGTYPE [] + { SWIG_LUA_CONSTTAB_POINTER("$symname",$value, $1_descriptor) } + //{ SWIG_LUA_POINTER, (char *)"$symname", 0, 0, (void *)$value, &$1_descriptor}// TODO: REMOVE // member function pointers %typemap(consttab) SWIGTYPE (CLASS::*) - { SWIG_LUA_BINARY, (char *)"$symname", sizeof($type), 0, (void *)&$value, &$1_descriptor} + { SWIG_LUA_CONSTTAB_BINARY("$symname", sizeof($type),&$value, $1_descriptor) } + //{ SWIG_LUA_BINARY, (char *)"$symname", sizeof($type), 0, (void *)&$value, &$1_descriptor}// TODO:REMOVE /* ----------------------------------------------------------------------------- diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index da8b8d3a7..04d4e93c3 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -32,11 +32,18 @@ extern "C" { # define SWIG_LUA_CONSTTAB_FLOAT(B, C) LSTRKEY(B), LNUMVAL(C) # define SWIG_LUA_CONSTTAB_STRING(B, C) LSTRKEY(B), LSTRVAL(C) # define SWIG_LUA_CONSTTAB_CHAR(B, C) LSTRKEY(B), LNUMVAL(C) + // Those two types of constants are not supported in elua +# define SWIG_LUA_CONSTTAB_POINTER(B,C,D) LSTRKEY(B), LNILVAL +# define SWIG_LUA_CONSTTAB_BINARY(B, S, C, D) LSTRKEY(B), LNILVAL #else /* SWIG_LUA_FLAVOR_LUA */ # define SWIG_LUA_CONSTTAB_INT(B, C) SWIG_LUA_INT, (char *)B, (long)C, 0, 0, 0 # define SWIG_LUA_CONSTTAB_FLOAT(B, C) SWIG_LUA_FLOAT, (char *)B, 0, (double)C, 0, 0 # define SWIG_LUA_CONSTTAB_STRING(B, C) SWIG_LUA_STRING, (char *)B, 0, 0, (void *)C, 0 # define SWIG_LUA_CONSTTAB_CHAR(B, C) SWIG_LUA_CHAR, (char *)B, (long)C, 0, 0, 0 +# define SWIG_LUA_CONSTTAB_POINTER(B,C,D)\ + SWIG_LUA_POINTER, (char *)B, 0, 0, (void *)C, &D +# define SWIG_LUA_CONSTTAB_BINARY(B, S, C, D)\ + SWIG_LUA_BINARY, (char *)B, S, 0, (void *)C, &D #endif #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC) @@ -44,6 +51,10 @@ extern "C" { # define LSTRVAL LRO_STRVAL #endif +#if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC) +#include "lrodefs.h" +#include "lrotable.h" +#endif /* ----------------------------------------------------------------------------- * compatibility defines * ----------------------------------------------------------------------------- */ @@ -123,6 +134,12 @@ typedef struct { lua_CFunction set; } swig_lua_var_info; +#if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC) +typedef const LUA_REG_TYPE swig_lua_method; +typedef const LUA_REG_TYPE swig_lua_const_info; +#else // Normal lua +typedef luaL_Reg swig_lua_method; + /* Constant information structure */ typedef struct { int type; @@ -133,7 +150,7 @@ typedef struct { swig_type_info **ptype; } swig_lua_const_info; -typedef luaL_Reg swig_lua_method; +#endif typedef struct { const char *name; @@ -343,6 +360,7 @@ SWIGINTERN int SWIG_Lua_namespace_set(lua_State* L) return 0; } +#if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) // In elua this is useless SWIGINTERN void SWIG_Lua_InstallConstants(lua_State* L, swig_lua_const_info constants[]); // forward declaration SWIGINTERN void SWIG_Lua_add_variable(lua_State* L,const char* name,lua_CFunction getFn,lua_CFunction setFn); // forward declaration SWIGINTERN void SWIG_Lua_class_register(lua_State* L,swig_lua_class* clss); @@ -366,17 +384,6 @@ SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State* L, swig_lua_namespace* SWIG_Lua_add_variable(L,ns->ns_attributes[i].name,ns->ns_attributes[i].getmethod,ns->ns_attributes[i].setmethod); } -#if 0 - // TODO: REMOVE. .fn table is unused - /* add methods to the metatable */ - SWIG_Lua_get_table(L,".fn"); /* find the .fn table */ - assert(lua_istable(L,-1)); /* just in case */ - for(i=0;ns->ns_methods[i].name;i++){ - SWIG_Lua_add_function(L,ns->ns_methods[i].name,ns->ns_methods[i].func); - } - lua_pop(L,1); -#endif - /* clear stack - remove metatble */ lua_pop(L,1); return 0; @@ -452,6 +459,7 @@ SWIGINTERN int SWIG_Lua_namespace_register(lua_State* L, swig_lua_namespace* ns, } assert(lua_gettop(L) == begin+1); } +#endif // SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA /* ----------------------------------------------------------------------------- * global variable support code: classes * ----------------------------------------------------------------------------- */ @@ -601,7 +609,6 @@ printf("SWIG_Lua_class_set %p(%s) '%s' %p(%s)\n", lua_pushvalue(L,base+3); /* value */ lua_call(L,2,0); lua_remove(L,base+4); /*remove metatable*/ - assert(lua_gettop(L) == base+3); // TODO:REMOVE return 0; } lua_pop(L,1); /* remove the value */ @@ -776,6 +783,29 @@ SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State* L,const char* cname) lua_remove(L,-2); /* tidy up (remove registry) */ } +/* set up the base classes pointers. +Each class structure has a list of pointers to the base class structures. +This function fills them. +It cannot be done at compile time, as this will not work with hireachies +spread over more than one swig file. +Therefore it must be done at runtime, querying the SWIG type system. +*/ +SWIGINTERN void SWIG_Lua_init_base_class(lua_State* L,swig_lua_class* clss) +{ + int i=0; + swig_module_info* module=SWIG_GetModule(L); + for(i=0;clss->base_names[i];i++) + { + if (clss->bases[i]==0) /* not found yet */ + { + /* lookup and cache the base class */ + swig_type_info *info = SWIG_TypeQueryModule(module,module,clss->base_names[i]); + if (info) clss->bases[i] = (swig_lua_class *) info->clientdata; + } + } +} + +#if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) // In elua this is useless /* helper add a variable to a registered class */ SWIGINTERN void SWIG_Lua_add_variable(lua_State* L,const char* name,lua_CFunction getFn,lua_CFunction setFn) { @@ -848,28 +878,6 @@ SWIGINTERN void SWIG_Lua_add_class_instance_details(lua_State* L,swig_lua_class } } -/* set up the base classes pointers. -Each class structure has a list of pointers to the base class structures. -This function fills them. -It cannot be done at compile time, as this will not work with hireachies -spread over more than one swig file. -Therefore it must be done at runtime, querying the SWIG type system. -*/ -SWIGINTERN void SWIG_Lua_init_base_class(lua_State* L,swig_lua_class* clss) -{ - int i=0; - swig_module_info* module=SWIG_GetModule(L); - for(i=0;clss->base_names[i];i++) - { - if (clss->bases[i]==0) /* not found yet */ - { - /* lookup and cache the base class */ - swig_type_info *info = SWIG_TypeQueryModule(module,module,clss->base_names[i]); - if (info) clss->bases[i] = (swig_lua_class *) info->clientdata; - } - } -} - /* Register class static methods,attributes etc as well as constructor proxy */ SWIGINTERN void SWIG_Lua_class_register_static(lua_State* L, swig_lua_class* clss) { @@ -1001,7 +1009,7 @@ SWIGINTERN void SWIG_Lua_class_register(lua_State* L,swig_lua_class* clss) lua_pop(L,2); assert(lua_gettop(L) == begin); } - +#endif // SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA /* ----------------------------------------------------------------------------- * Class/structure conversion fns * ----------------------------------------------------------------------------- */ diff --git a/Lib/lua/luaruntime.swg b/Lib/lua/luaruntime.swg index 5e4ba9fd9..758544185 100644 --- a/Lib/lua/luaruntime.swg +++ b/Lib/lua/luaruntime.swg @@ -53,9 +53,14 @@ SWIGEXPORT int SWIG_init(lua_State* L) /* default Lua action */ #ifdef SWIG_LUA_MODULE_GLOBAL globalRegister = 1; #endif + + +#if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) SWIG_Lua_namespace_register(L,&swig___Global, globalRegister); #endif +#endif + #if ((SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUA) && (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC)) /* constants */ /* TODO: REMOVE */ diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 4cfaca6ed..3a8822ccd 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -150,8 +150,10 @@ void DohDelete(DohPtrGuard& /*guard*/) { NEW LANGUAGE NOTE:END ************************************************/ static const char *usage = (char *) "\ Lua Options (available with -lua)\n\ - -elua - Generates LTR compatible wrappers for smaller devices running elua\n\ - -eluac - LTR compatible wrappers in \"crass compress\" mode for elua\n\ + -elua [NUM] - Generates LTR compatible wrappers for smaller devices running elua\n\ + Optional NUM is default value for MIN_OPT_LEVEL\n\ + -eluac [NUM] - LTR compatible wrappers in \"crass compress\" mode for elua\n\ + Optional NUM is default value for MIN_OPT_LEVEL\n\ -nomoduleglobal - Do not register the module name as a global variable \n\ but return the module table from calls to require.\n\ -api-lvl-from NUM\n\ @@ -168,6 +170,7 @@ Lua Options (available with -lua)\n\ static int nomoduleglobal = 0; static int elua_ltr = 0; +static int elua_opt_lvl = 2; static int eluac_ltr = 0; static int v2_compatibility = 0; static const int default_api_level = 2; @@ -187,8 +190,6 @@ private: File *f_wrappers; File *f_init; File *f_initbeforefunc; - String *s_methods_tab; // table of class methods - String *s_attr_tab; // table of class attributes String *s_luacode; // luacode to be called during init String *module; //name of the module Hash* namespaces_hash; @@ -238,8 +239,6 @@ public: f_wrappers(0), f_init(0), f_initbeforefunc(0), - s_methods_tab(0), - s_attr_tab(0), s_luacode(0), module(0), have_constructor(0), @@ -265,6 +264,17 @@ public: which depends upon what args your code supports NEW LANGUAGE NOTE:END ************************************************/ + bool strToInt(const char* string, int& value) { + long int tmp; + char *p_end = 0; + if(string == 0) + return false; + tmp = strtol(string,&p_end,10); + if( p_end == 0 || *p_end != 0 ) + return false; + value = tmp; + return true; + } /* --------------------------------------------------------------------- * main() * @@ -288,13 +298,20 @@ public: } else if(strcmp(argv[i], "-elua") == 0) { elua_ltr = 1; Swig_mark_arg(i); + if(strToInt(argv[i+1],elua_opt_lvl)) { + Swig_mark_arg(i+1); + i++; + } } else if(strcmp(argv[i], "-eluac") == 0) { eluac_ltr = 1; Swig_mark_arg(i); + if(strToInt(argv[i+1],elua_opt_lvl)) { + Swig_mark_arg(i+1); + i++; + } } else if(strcmp(argv[i], "-api-lvl-from") == 0) { if(argv[i+1]) { - api_level = atoi(argv[i+1]); - if(api_level == 0) + if(!strToInt(argv[i+1], api_level)) Swig_arg_error(); Swig_mark_arg(i+1); i++; @@ -392,6 +409,12 @@ public: emitLuaFlavor(f_runtime); + if (elua_ltr || eluac_ltr) + Printf(f_runtime, + "#ifndef MIN_OPT_LEVEL\n"\ + "#define MIN_OPT_LEVEL %d\n"\ + "#endif\n", elua_opt_lvl); + if (nomoduleglobal) { Printf(f_runtime, "#define SWIG_LUA_NO_MODULE_GLOBAL\n"); } else { @@ -415,8 +438,14 @@ public: Printf(f_header, "#define SWIG_LUACODE luaopen_%s_luacode\n", module); if (elua_ltr || eluac_ltr) { - Printf(f_header, "\n#define MIN_OPT_LEVEL 2\n#include \"lrodefs.h\"\n"); + /* TODO: REMOVE + Printf(f_header, + "#ifndef MIN_OPT_LEVEL\n"\ + "#define MIN_OPT_LEVEL %d\n"\ + "#endif\n", elua_opt_lvl); + Printf(f_header, "#include \"lrodefs.h\"\n"); Printf(f_header, "#include \"lrotable.h\"\n"); + */ Printf(f_wrappers, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n"); } else { Printf(f_wrappers, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n"); @@ -525,6 +554,20 @@ public: Setattr(n, "varget:wrap:name", wrapname); } + // Add method to the "methods" C array of given namespace/class + void registerMethod(String *nspace_or_class_name, Node* n) { + assert(n != 0); + Hash* nspaceHash = getNamespaceHash( nspace_or_class_name ); + String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); + String *wname = Getattr(n, "wrap:name"); + String *iname = Getattr(n, "sym:name"); + String *target_name = Getattr(n, "lua:name"); + if(elua_ltr || eluac_ltr) + Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", iname, "\")", ", LFUNCVAL(", wname, ")", "},\n", NIL); + else + Printv(s_ns_methods_tab, tab4, "{ \"", target_name, "\", ", wname, "},\n", NIL); + } + // Helper for functionWrapper - determines whether we should // register method in the appropriate class/namespace/module // table or not. @@ -943,6 +986,32 @@ public: * variableWrapper() * ------------------------------------------------------------ */ + // Add variable to the "attributes" (or "get"/"set" in + // case of elua_ltr) C arrays of given namespace or class + void registerVariable(String *nspace_or_class_name, Node* n, const char *getAttrName, const char *setAttrName) { + String *unassignable = NewString("SWIG_Lua_set_immutable"); + String *getName = Getattr(n,getAttrName); + String *setName = Getattr(n,setAttrName); + if(setName == 0 || GetFlag(n, "feature:immutable")) { + setName = unassignable; + } + Hash* nspaceHash = getNamespaceHash( nspace_or_class_name ); + String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); + String* s_ns_var_tab = Getattr(nspaceHash, "attributes"); + String *target_name = Getattr(n, "lua:name"); + if (elua_ltr) { + String* s_ns_dot_get = Getattr(nspaceHash, "get"); + String* s_ns_dot_set = Getattr(nspaceHash, "set"); + Printf(s_ns_dot_get, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, target_name, getName); + Printf(s_ns_dot_set, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, target_name, setName); + } else if (eluac_ltr) { + Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", target_name, "_get", "\")", ", LFUNCVAL(", getName, ")", "},\n", NIL); + Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", target_name, "_set", "\")", ", LFUNCVAL(", setName, ")", "},\n", NIL); + } else { + Printf(s_ns_var_tab, "%s{ \"%s\", %s, %s },\n", tab4, target_name, getName, setName); + } + } + virtual int variableWrapper(Node *n) { /* NEW LANGUAGE NOTE:*********************************************** Language::variableWrapper(n) will generate two wrapper fns @@ -962,9 +1031,34 @@ public: return result; } + /* ------------------------------------------------------------ * constantWrapper() * ------------------------------------------------------------ */ + + /* Add constant to appropriate C array. constantRecord is an array record. + * Actually, in current implementation it is resolved consttab typemap + */ + void registerConstant( String *nspace, String *constantRecord ) { + Hash *nspaceHash = getNamespaceHash( nspace ); + String *s_const_tab = 0; + if( eluac_ltr || elua_ltr ) + // In elua everything goes to "methods" tab + s_const_tab = Getattr(nspaceHash, "methods"); + else + s_const_tab = Getattr(nspaceHash, "constants"); + + assert(s_const_tab != 0); + Printf(s_const_tab, " %s,\n", constantRecord); + + if( ( eluac_ltr || elua_ltr ) && v2_compatibility ) { + s_const_tab = Getattr(nspaceHash, "constants"); + assert(s_const_tab != 0); + Printf(s_const_tab, " %s,\n", constantRecord); + } + + } + virtual int constantWrapper(Node *n) { REPORT("constantWrapper", n); String *name = Getattr(n, "name"); @@ -1012,9 +1106,7 @@ public: Replaceall(tm, "$target", target_name); Replaceall(tm, "$value", value); Replaceall(tm, "$nsname", nsname); - Hash *nspaceHash = getNamespaceHash( luaCurrentSymbolNSpace() ); - String *s_const_tab = Getattr(nspaceHash, "constants"); - Printf(s_const_tab, " %s,\n", tm); + registerConstant( luaCurrentSymbolNSpace(), tm); } else if ((tm = Swig_typemap_lookup("constcode", n, name, 0))) { Replaceall(tm, "$source", value); Replaceall(tm, "$target", target_name); @@ -1037,9 +1129,7 @@ public: Replaceall(tm_v2, "$target", target_name_v2); Replaceall(tm_v2, "$value", value); Replaceall(tm_v2, "$nsname", nsname); - Hash *nspaceHash = getNamespaceHash( class_parent_nspace ); - String *s_const_tab = Getattr(nspaceHash, "constants"); - Printf(s_const_tab, " %s,\n", tm_v2.ptr()); + registerConstant( class_parent_nspace, tm); } else { tm_v2 = Swig_typemap_lookup("constcode", n_v2, name, 0); if( !tm_v2) { @@ -1212,8 +1302,6 @@ public: // any member or subclass with name "__Static". Thus, never any name clash. Hash* instance_cls = getNamespaceHash(class_fq_symname, false); assert(instance_cls != 0); - s_attr_tab = Getattr(instance_cls, "attributes"); - s_methods_tab = Getattr(instance_cls, "methods"); String* s_attr_tab_name = Getattr(instance_cls, "attributes:name"); String* s_methods_tab_name = Getattr(instance_cls, "methods:name"); Setattr(instance_cls, "lua:no_namespaces", "1"); @@ -1237,9 +1325,6 @@ public: /* There is no use for "classes" and "namespaces" arrays. Subclasses are not supported * by SWIG and namespaces couldn't be nested inside classes (C++ Standard) */ - assert(s_attr_tab != 0); - assert(s_methods_tab != 0); - // Replacing namespace with namespace + class in order to static // member be put inside class static area class_parent_nspace = getNSpace(); @@ -1396,32 +1481,25 @@ public: * ------------------------------------------------------------ */ virtual int memberfunctionHandler(Node *n) { - String *name = Getattr(n, "name"); - String *iname = GetChar(n, "sym:name"); + String *symname = GetChar(n, "sym:name"); //Printf(stdout,"memberfunctionHandler %s %s\n",name,iname); // Special case unary minus: LUA passes two parameters for the // wrapper function while we want only one. Tell our // functionWrapper to ignore a parameter. - if (Cmp(Getattr(n, "sym:name"), "__unm") == 0) { + if (Cmp(symname, "__unm") == 0) { //Printf(stdout, "unary minus: ignore one argument\n"); SetInt(n, "lua:ignore_args", 1); } - String *realname, *rname; - current[MEMBER_FUNC] = true; Language::memberfunctionHandler(n); current[MEMBER_FUNC] = false; - realname = iname ? iname : name; - rname = Getattr(n, "wrap:name"); - assert(rname != 0); if (!Getattr(n, "sym:nextSibling")) { - Printv(s_methods_tab, tab4, "{\"", realname, "\", ", rname, "}, \n", NIL); + registerMethod( luaCurrentSymbolNSpace(), n); } - Delete(rname); return SWIG_OK; } @@ -1431,30 +1509,10 @@ public: virtual int membervariableHandler(Node *n) { // REPORT("membervariableHandler",n); - String *symname = Getattr(n, "sym:name"); - String *getter_name, *setter_name; - current[MEMBER_VAR] = true; Language::membervariableHandler(n); current[MEMBER_VAR] = false; - getter_name = Getattr(n, "memberget:wrap:name"); - assert(getter_name != 0); - if (!GetFlag(n, "feature:immutable")) { - setter_name = Getattr(n, "memberset:wrap:name"); - assert(setter_name != 0); - } else { - //setter_name = NewString("0"); - setter_name = NewString("SWIG_Lua_set_immutable"); // error message - } - Printf(s_attr_tab,"%s{ \"%s\", %s, %s},\n",tab4,symname,getter_name,setter_name); - /*if (eluac_ltr) { TODO: FIX for eluac and uncomments - Printv(s_cmd_tab, tab4, "{LSTRKEY(\"", class_name, "_", symname, "_get", "\")", \ - ", LFUNCVAL(", getter_name, ")", "},\n", NIL); - Printv(s_cmd_tab, tab4, "{LSTRKEY(\"", class_name, "_", symname, "_set", "\")", \ - ", LFUNCVAL(", setter_name, ")", "},\n", NIL); - }*/ - Delete(getter_name); - Delete(setter_name); + registerVariable( luaCurrentSymbolNSpace(), n, "memberget:wrap:name", "memberset:wrap:name" ); return SWIG_OK; } @@ -1709,7 +1767,7 @@ public: String *methods_tab_name = NewStringf("swig_%s_methods", mangled_name ); String *methods_tab_decl = NewString(""); if (elua_ltr || eluac_ltr) // In this case methods array also acts as namespace rotable - Printf(methods_tab, "static LUA_REG_TYPE "); + Printf(methods_tab, "const LUA_REG_TYPE "); else Printf(methods_tab, "static swig_lua_method "); Printv(methods_tab, methods_tab_name, "[]", NIL); @@ -1723,7 +1781,7 @@ public: String *const_tab_name = NewStringf("swig_%s_constants", mangled_name ); String *const_tab_decl = NewString(""); if (elua_ltr || eluac_ltr) // In this case const array holds rotable with namespace constants - Printf(const_tab, "static LUA_REG_TYPE "); + Printf(const_tab, "const LUA_REG_TYPE "); else Printf(const_tab, "static swig_lua_const_info "); Printv(const_tab, const_tab_name, "[]", NIL); @@ -1759,22 +1817,34 @@ public: // TODO: add xxx:decl here too String *get_tab = NewString(""); String *get_tab_name = NewStringf("swig_%s_get", mangled_name); - Printv(get_tab, "const LUA_REG_TYPE ", get_tab_name, "[] = {\n", NIL); + String *get_tab_decl = NewString(""); + Printv(get_tab, "const LUA_REG_TYPE ", get_tab_name, "[]", NIL); + Printv(get_tab_decl, get_tab, ";", NIL); + Printv(get_tab, " = {\n", NIL); Setattr(nspace_hash, "get", get_tab); Setattr(nspace_hash, "get:name", get_tab_name); + Setattr(nspace_hash, "get:decl", get_tab_decl); String *set_tab = NewString(""); String *set_tab_name = NewStringf("swig_%s_set", mangled_name); - Printv(set_tab, "const LUA_REG_TYPE ", set_tab_name, "[] = {\n", NIL); + String *set_tab_decl = NewString(""); + Printv(set_tab, "const LUA_REG_TYPE ", set_tab_name, "[]", NIL); + Printv(set_tab_decl, set_tab, ";", NIL); + Printv(set_tab, " = {\n", NIL); Setattr(nspace_hash, "set", set_tab); Setattr(nspace_hash, "set:name", set_tab_name); + Setattr(nspace_hash, "set:decl", set_tab_decl); if (!eluac_ltr) { String* metatable_tab = NewString(""); String* metatable_tab_name = NewStringf("swig_%s_meta", mangled_name); - Printv(metatable_tab, "const LUA_REG_TYPE ", metatable_tab_name, "[] = {\n", NIL); + String *metatable_tab_decl = NewString(""); + Printv(metatable_tab, "const LUA_REG_TYPE ", metatable_tab_name, "[]", NIL); + Printv(metatable_tab_decl, metatable_tab, ";", NIL); + Printv(metatable_tab, " = {\n", NIL); Setattr(nspace_hash, "metatable", metatable_tab); Setattr(nspace_hash, "metatable:name", metatable_tab_name); + Setattr(nspace_hash, "metatable:decl", metatable_tab_decl); } } String* key = 0; @@ -1814,12 +1884,19 @@ public: Printf(const_tab, " {0,0,0,0,0,0}\n};\n"); Printv(output, const_tab, NIL); + if (elua_ltr) { + // Put forward declaration of metatable array + Printv(output, "extern ", Getattr(nspace_hash, "metatable:decl"), "\n", NIL); + } String* methods_tab = Getattr(nspace_hash, "methods"); String* metatable_tab_name = Getattr(nspace_hash, "metatable:name"); if (elua_ltr || eluac_ltr) { - Printv(methods_tab, tab4, "{LSTRKEY(\"const\"), LROVAL(", const_tab_name, ")},\n", NIL); + if( v2_compatibility ) + Printv(methods_tab, tab4, "{LSTRKEY(\"const\"), LROVAL(", const_tab_name, ")},\n", NIL); if (elua_ltr) Printv(methods_tab, tab4, "{LSTRKEY(\"__metatable\"), LROVAL(", metatable_tab_name, ")},\n", NIL); + + Printv(methods_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); } else Printf(methods_tab, " {0,0}\n};\n"); Printv(output, methods_tab, NIL); @@ -1847,22 +1924,26 @@ public: String *metatable_tab = Getattr(nspace_hash, "metatable"); assert(metatable_tab != 0); - Printv(metatable_tab, tab4, "{LSTRKEY(\"__index\"), LFUNCVAL(SWIG_Lua_module_get)},\n", NIL); - Printv(metatable_tab, tab4, "{LSTRKEY(\"__newindex\"), LFUNCVAL(SWIG_Lua_module_set)},\n", NIL); + Printv(metatable_tab, tab4, "{LSTRKEY(\"__index\"), LFUNCVAL(SWIG_Lua_namespace_get)},\n", NIL); + Printv(metatable_tab, tab4, "{LSTRKEY(\"__newindex\"), LFUNCVAL(SWIG_Lua_namespace_set)},\n", NIL); Printv(metatable_tab, tab4, "{LSTRKEY(\".get\"), LROVAL(", get_tab_name, ")},\n", NIL); Printv(metatable_tab, tab4, "{LSTRKEY(\".set\"), LROVAL(", set_tab_name, ")},\n", NIL); if (Getattr(nspace_hash, "lua:class_instance")) { String *static_cls = Getattr(nspace_hash, "lua:class_instance:static_hash"); assert(static_cls != 0); - String *static_cls_cname = Getattr(static_cls, "cname"); + // static_cls is swig_lua_namespace. This structure can't be use with eLua(LTR) + // Instead structure describing its methods isused + String *static_cls_cname = Getattr(static_cls, "methods:name"); assert(static_cls_cname != 0); - Printv(metatable_tab, tab4, "LSTRKEY(\".static\"), LROVAL(", static_cls_cname, ")},\n", NIL); + Printv(metatable_tab, tab4, "{LSTRKEY(\".static\"), LROVAL(", static_cls_cname, ")},\n", NIL); + // Put forward declaration of this array + Printv(output, "extern ", Getattr(static_cls, "methods:decl"), "\n", NIL); } else if (Getattr(nspace_hash, "lua:class_static") ) { Hash *instance_cls = Getattr(nspace_hash, "lua:class_static:instance_hash"); assert(instance_cls != 0); String *instance_cls_metatable_name = Getattr(instance_cls, "metatable:name"); assert(instance_cls_metatable_name != 0); - Printv(metatable_tab, tab4, "LSTRKEY(\".static\"), LROVAL(", instance_cls_metatable_name, ")},\n", NIL); + Printv(metatable_tab, tab4, "{LSTRKEY(\".instance\"), LROVAL(", instance_cls_metatable_name, ")},\n", NIL); } Printv(metatable_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); @@ -1935,51 +2016,11 @@ public: tab4, attr_tab_name, ",\n", tab4, const_tab_name, ",\n", tab4, (has_classes)?classes_tab_name:null_string.ptr(), ",\n", - tab4, (has_namespaces)?namespaces_tab_name:null_string.ptr(), "};\n", + tab4, (has_namespaces)?namespaces_tab_name:null_string.ptr(), "\n};\n", NIL ); } - // Add method to the "methods" C array of given namespace/class - void registerMethod(String *nspace_or_class_name, Node* n) { - assert(n != 0); - Hash* nspaceHash = getNamespaceHash( nspace_or_class_name ); - String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); - String *wname = Getattr(n, "wrap:name"); - String *iname = Getattr(n, "sym:name"); - String *target_name = Getattr(n, "lua:name"); - if(elua_ltr || eluac_ltr) - Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", iname, "\")", ", LFUNCVAL(", wname, ")", "},\n", NIL); - else - Printv(s_ns_methods_tab, tab4, "{ \"", target_name, "\", ", wname, "},\n", NIL); - } - - // Add variable to the "attributes" (or "get"/"set" in - // case of elua_ltr) C arrays of given namespace or class - void registerVariable(String *nspace_or_class_name, Node* n, const char *getAttrName, const char *setAttrName) { - String *unassignable = NewString("SWIG_Lua_set_immutable"); - String *getName = Getattr(n,getAttrName); - String *setName = Getattr(n,setAttrName); - if(setName == 0) { - setName = unassignable; - } - Hash* nspaceHash = getNamespaceHash( nspace_or_class_name ); - String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); - String* s_ns_var_tab = Getattr(nspaceHash, "attributes"); - String *target_name = Getattr(n, "lua:name"); - if (elua_ltr) { - String* s_ns_dot_get = Getattr(nspaceHash, "get"); - String* s_ns_dot_set = Getattr(nspaceHash, "set"); - Printf(s_ns_dot_get, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, target_name, getName); - Printf(s_ns_dot_set, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, target_name, setName); - } else if (eluac_ltr) { - Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", target_name, "_get", "\")", ", LFUNCVAL(", getName, ")", "},\n", NIL); - Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", target_name, "_set", "\")", ", LFUNCVAL(", setName, ")", "},\n", NIL); - } else { - Printf(s_ns_var_tab, "%s{ \"%s\", %s, %s },\n", tab4, target_name, getName, setName); - } - } - // This function determines actual namespace/scope where any symbol at the // current moment should be placed. It looks at the 'current' array // and depending on where are we - static class member/function, From afd269f9b619eeecd6d8557d3f3ef19cd20069bb Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Mon, 11 Nov 2013 00:11:13 +0400 Subject: [PATCH 400/481] Some class bases iteration improvements --- Lib/lua/luarun.swg | 311 ++++++++++++++++++++++++--------------------- 1 file changed, 166 insertions(+), 145 deletions(-) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index 04d4e93c3..632dbd512 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -464,17 +464,108 @@ SWIGINTERN int SWIG_Lua_namespace_register(lua_State* L, swig_lua_namespace* ns, * global variable support code: classes * ----------------------------------------------------------------------------- */ -/* the class.get method, performs the lookup of class attributes - * Method can be called from Lua directly and recursively from itself. Thats why - * we can't use absolute stack positions +SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State* L,const char* cname); + +/* Macroses for iteration among class bases */ +#if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) +#define SWIG_LUA_INIT_BASE_SEARCH(bases_count)\ + SWIG_Lua_get_table(L,".bases");\ + assert(lua_istable(L,-1));\ + bases_count = lua_rawlen(L,-1);\ + int bases_table = lua_gettop(L); +#define SWIG_LUA_GET_BASE_METATABLE(i,base_swig_type, valid)\ + lua_rawgeti(L,bases_table,i+1);\ + base_swig_type = 0;\ + if(lua_isnil(L,-1)) {\ + valid = false;\ + lua_pop(L,1);\ + } else\ + valid = true; + +#else // en elua .bases table doesn't exist. Use table from swig_lua_class + +#define SWIG_LUA_INIT_BASE_SEARCH(bases_count)\ + swig_module_info* module=SWIG_GetModule(L);\ + swig_lua_class **bases= ((swig_lua_class*)(swig_type->clientdata))->bases;\ + const char **base_names= ((swig_lua_class*)(swig_type->clientdata))->base_names;\ + bases_count = 0;\ + for(;base_names[bases_count];bases_count++);// get length of bases + +#define SWIG_LUA_GET_BASE_METATABLE(i,base_swig_type, valid)\ + swig_lua_class *base_class = bases[i];\ + if(!base_class)\ + valid = false;\ + else {\ + valid = true;\ + SWIG_Lua_get_class_metatable(L,base_class->fqname);\ + base_swig_type = SWIG_TypeQueryModule(module,module,base_class->fqname);\ + } + +#endif + +typedef int (*swig_lua_base_iterator_func)(lua_State*,swig_type_info*, int, int& ret); + +int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info* swig_type, int first_arg, swig_lua_base_iterator_func func, int& ret) +{ + // first_arg - position of the object in stack. Everything that is above are arguments + // and is passed to every evocation of the func + int last_argument = lua_gettop(L);// position of last argument + lua_getmetatable(L,first_arg); + int original_metatable = last_argument + 1; + int bases_count; + SWIG_LUA_INIT_BASE_SEARCH(bases_count); + int result = SWIG_OK; + ret = 0; + if(bases_count>0) + { + int i; + int j; + int subcall_start = lua_gettop(L) + 1;// Here a copy of first_arg and arguments begin + bool valid = true; + for(j=first_arg;j<=last_argument;j++) + lua_pushvalue(L,j); + int subcall_end = lua_gettop(L); + swig_type_info *base_swig_type = 0; + + // Trick: temporaly replacing original metatable + // with metatable for base class and call getter + for(i=0;i0) - { - int original_metatable = lua_absindex(L,-2); - int i; - int ret = 0; // Number of returned values - lua_pushvalue(L,base+1); // push userdata - lua_pushvalue(L,base+2); // Push key again - // Trick: temporaly replacing original metatable - // with metatable for base class and call getter - for(i=0;i0) - break; - } - // Return original metatable back - lua_pushvalue(L,original_metatable); - lua_setmetatable(L,base+1); - if(ret>0) - { - // tidy stack. Stack currently is: - // --base-- - // userdata - // key - // metatable - // .bases table - // userdata - // key : -2 - // return value : -1 - lua_remove(L,-2); // remove key - lua_remove(L,-2); // remove userdata - lua_remove(L,-2); // remove .bases - lua_remove(L,-2); // remove metatable - return 1; - } else { - lua_pop(L,2); // remove key and userdata - } - } - // Tidy stack: - // --base-- - // userdata - // key - // metatable - // .bases table - lua_pop(L,2); - assert(lua_gettop(L)==base+2); - return 0; /* sorry not known */ + int bases_search_result = SWIG_Lua_iterate_bases(L,type,substack_start+1,SWIG_Lua_class_do_get,ret); + return bases_search_result; /* sorry not known */ +} + +/* the class.get method, performs the lookup of class attributes + */ +SWIGINTERN int SWIG_Lua_class_get(lua_State* L) +{ +/* there should be 2 params passed in + (1) userdata (not the meta table) + (2) string name of the attribute +*/ + assert(lua_isuserdata(L,1)); + swig_lua_userdata *usr=(swig_lua_userdata*)lua_touserdata(L,1); /* get data */ + swig_type_info *type = usr->type; + int ret = 0; + int result = SWIG_Lua_class_do_get(L,type,1,ret); + if(result == SWIG_OK) + return ret; + + return 0; } /* helper for the class.set method, performs the lookup of class attributes - * Method can be called from SWIG_Lua_class_set or recursively from itself + * It returns error code. Number of function return values is passed inside 'ret' */ -SWIGINTERN int SWIG_Lua_class_do_set(lua_State* L) +SWIGINTERN int SWIG_Lua_class_do_set(lua_State* L, swig_type_info *type, int first_arg, int& ret) { /* there should be 3 params passed in (1) table (not the meta table) (2) string name of the attribute (3) any for the new value -printf("SWIG_Lua_class_set %p(%s) '%s' %p(%s)\n", - lua_topointer(L,-3),lua_typename(L,lua_type(L,-3)), - lua_tostring(L,-2), - lua_topointer(L,-1),lua_typename(L,lua_type(L,-1)));*/ + */ - int base = lua_gettop(L) - 3; + int substack_start = lua_gettop(L) - 3; lua_checkstack(L,5); - assert(lua_isuserdata(L,base+1)); /* just in case */ - lua_getmetatable(L,base+1); /* get the meta table */ + assert(lua_isuserdata(L,substack_start+1)); /* just in case */ + lua_getmetatable(L,substack_start+1); /* get the meta table */ assert(lua_istable(L,-1)); /* just in case */ + ret = 0; // it is setter - number of return values is always 0 SWIG_Lua_get_table(L,".set"); /* find the .set table */ if (lua_istable(L,-1)) { /* look for the key in the .set table */ - lua_pushvalue(L,base+2); /* key */ + lua_pushvalue(L,substack_start+2); /* key */ lua_rawget(L,-2); lua_remove(L,-2); /* tidy stack, remove .set table */ if (lua_iscfunction(L,-1)) { /* found it so call the fn & return its value */ - lua_pushvalue(L,base+1); /* userdata */ - lua_pushvalue(L,base+3); /* value */ + lua_pushvalue(L,substack_start+1); /* userdata */ + lua_pushvalue(L,substack_start+3); /* value */ lua_call(L,2,0); - lua_remove(L,base+4); /*remove metatable*/ - return 0; + lua_remove(L,substack_start+4); /*remove metatable*/ + return SWIG_OK; } lua_pop(L,1); /* remove the value */ } else { lua_pop(L,1); /* remove the answer for .set table request*/ } - assert(lua_gettop(L) == base + 4); // TODO: REMOVE + assert(lua_gettop(L) == substack_start + 4); // TODO: REMOVE /* 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 */ { /* found it so call the fn & return its value */ - lua_pushvalue(L,base+1); /* the userdata */ - lua_pushvalue(L,base+2); /* the parameter */ - lua_pushvalue(L,base+3); /* the value */ + lua_pushvalue(L,substack_start+1); /* the userdata */ + lua_pushvalue(L,substack_start+2); /* the parameter */ + lua_pushvalue(L,substack_start+3); /* the value */ lua_call(L,3,0); /* 3 values in ,0 out */ lua_remove(L,-2); /* stack tidy, remove metatable */ - return 0; + return SWIG_OK; } lua_pop(L,1); // remove value - assert(lua_gettop(L) == base + 4); // TODO: REMOVE - - // Search among bases - int original_metatable = base+4; - assert(lua_gettop(L) == original_metatable); // Check that stack is correct - SWIG_Lua_get_table(L,".bases"); - assert(lua_istable(L,-1)); - int bases_count = lua_rawlen(L,-1); - if(bases_count>0) - { - int i = 0; - int ret = 0; - lua_pushvalue(L,base+1); // push userdata - lua_pushvalue(L,base+2); // Push key again - lua_pushvalue(L,base+3); // Push value again - // Trick: temporaly replacing original metatable - // with metatable for base class and call getter - for(i=0;itype; + int ret = 0; + int result = SWIG_Lua_class_do_set(L,type,1,ret); + if(result != SWIG_OK) { SWIG_Lua_pushferrstring(L,"Assignment not possible. No setter/member with this name. For custom assignments implement __setitem method"); lua_error(L); } else { - assert(0); // Internal implementation error + assert(ret==0); return 0; } } From dcbcac42b762ee5f07197a75435684822bf00ef1 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Mon, 11 Nov 2013 11:33:27 +0400 Subject: [PATCH 401/481] A few bugfixes --- Lib/lua/luarun.swg | 48 +++++++++++++++++++++++++++++------------- Source/Modules/lua.cxx | 46 ++++++++++++++++++++-------------------- 2 files changed, 56 insertions(+), 38 deletions(-) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index 632dbd512..9f669cae6 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -509,22 +509,22 @@ int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info* swig_type, int first_ar { // first_arg - position of the object in stack. Everything that is above are arguments // and is passed to every evocation of the func - int last_argument = lua_gettop(L);// position of last argument + int last_arg = lua_gettop(L);// position of last argument lua_getmetatable(L,first_arg); - int original_metatable = last_argument + 1; + int original_metatable = last_arg + 1; int bases_count; SWIG_LUA_INIT_BASE_SEARCH(bases_count); - int result = SWIG_OK; + int result = SWIG_ERROR; ret = 0; if(bases_count>0) { int i; int j; - int subcall_start = lua_gettop(L) + 1;// Here a copy of first_arg and arguments begin + int subcall_first_arg = lua_gettop(L) + 1;// Here a copy of first_arg and arguments begin bool valid = true; - for(j=first_arg;j<=last_argument;j++) + for(j=first_arg;j<=last_arg;j++) lua_pushvalue(L,j); - int subcall_end = lua_gettop(L); + int subcall_last_arg = lua_gettop(L); swig_type_info *base_swig_type = 0; // Trick: temporaly replacing original metatable @@ -533,11 +533,12 @@ int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info* swig_type, int first_ar SWIG_LUA_GET_BASE_METATABLE(i,base_swig_type,valid); if(!valid) continue; + assert(lua_isuserdata(L, subcall_first_arg)); assert(lua_istable(L,-1)); - assert(lua_isuserdata(L, subcall_start)); - lua_setmetatable(L,subcall_start); // Set new metatable - result = func(L, base_swig_type,subcall_start, ret); // Forward call - assert(lua_gettop(L) == subcall_end + ret); // + lua_setmetatable(L,subcall_first_arg); // Set new metatable + assert(lua_gettop(L) == subcall_last_arg); + result = func(L, base_swig_type,subcall_first_arg, ret); // Forward call + assert(lua_gettop(L) == subcall_last_arg + ret); // TODO: REMOVE if(result != SWIG_ERROR) { break; } @@ -545,12 +546,16 @@ int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info* swig_type, int first_ar // Return original metatable back lua_pushvalue(L,original_metatable); lua_setmetatable(L,first_arg); - // Clear - remove everything between last_argument and subcall_end including - const int to_remove = subcall_end - last_argument - 1; + // Clear - remove everything between last_arg and subcall_last_arg including + const int to_remove = subcall_last_arg - last_arg; for(j=0;j Date: Mon, 11 Nov 2013 15:23:50 +0400 Subject: [PATCH 402/481] Bugfixes --- .../lua/template_default_arg_runme.lua | 1 + Lib/lua/luarun.swg | 46 +++++++++---------- Source/Modules/lua.cxx | 2 +- 3 files changed, 25 insertions(+), 24 deletions(-) diff --git a/Examples/test-suite/lua/template_default_arg_runme.lua b/Examples/test-suite/lua/template_default_arg_runme.lua index ebb22ed63..853f57882 100644 --- a/Examples/test-suite/lua/template_default_arg_runme.lua +++ b/Examples/test-suite/lua/template_default_arg_runme.lua @@ -3,6 +3,7 @@ import("template_default_arg") -- import code --for k,v in pairs(template_default_arg) do _G[k]=v end -- move to global helloInt = template_default_arg.Hello_int() +assert(template_default_arg.Hello_int_hi ~= nil) helloInt:foo(template_default_arg.Hello_int_hi) x = template_default_arg.X_int() diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index 9f669cae6..fb8b0c89f 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -477,10 +477,10 @@ SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State* L,const char* cname); lua_rawgeti(L,bases_table,i+1);\ base_swig_type = 0;\ if(lua_isnil(L,-1)) {\ - valid = false;\ + valid = 0;\ lua_pop(L,1);\ } else\ - valid = true; + valid = 1; #else // en elua .bases table doesn't exist. Use table from swig_lua_class @@ -494,18 +494,18 @@ SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State* L,const char* cname); #define SWIG_LUA_GET_BASE_METATABLE(i,base_swig_type, valid)\ swig_lua_class *base_class = bases[i];\ if(!base_class)\ - valid = false;\ + valid = 0;\ else {\ - valid = true;\ + valid = 1;\ SWIG_Lua_get_class_metatable(L,base_class->fqname);\ base_swig_type = SWIG_TypeQueryModule(module,module,base_class->fqname);\ } #endif -typedef int (*swig_lua_base_iterator_func)(lua_State*,swig_type_info*, int, int& ret); +typedef int (*swig_lua_base_iterator_func)(lua_State*,swig_type_info*, int, int *ret); -int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info* swig_type, int first_arg, swig_lua_base_iterator_func func, int& ret) +int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info* swig_type, int first_arg, swig_lua_base_iterator_func func, int * const ret) { // first_arg - position of the object in stack. Everything that is above are arguments // and is passed to every evocation of the func @@ -515,13 +515,13 @@ int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info* swig_type, int first_ar int bases_count; SWIG_LUA_INIT_BASE_SEARCH(bases_count); int result = SWIG_ERROR; - ret = 0; + if(ret) *ret = 0; if(bases_count>0) { int i; int j; int subcall_first_arg = lua_gettop(L) + 1;// Here a copy of first_arg and arguments begin - bool valid = true; + int valid = 1; for(j=first_arg;j<=last_arg;j++) lua_pushvalue(L,j); int subcall_last_arg = lua_gettop(L); @@ -538,7 +538,7 @@ int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info* swig_type, int first_ar lua_setmetatable(L,subcall_first_arg); // Set new metatable assert(lua_gettop(L) == subcall_last_arg); result = func(L, base_swig_type,subcall_first_arg, ret); // Forward call - assert(lua_gettop(L) == subcall_last_arg + ret); // TODO: REMOVE + if(ret) assert(lua_gettop(L) == subcall_last_arg + *ret); // TODO: REMOVE if(result != SWIG_ERROR) { break; } @@ -550,12 +550,12 @@ int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info* swig_type, int first_ar const int to_remove = subcall_last_arg - last_arg; for(j=0;jtype; int ret = 0; - int result = SWIG_Lua_class_do_get(L,type,1,ret); + int result = SWIG_Lua_class_do_get(L,type,1,&ret); if(result == SWIG_OK) return ret; @@ -658,7 +658,7 @@ SWIGINTERN int SWIG_Lua_class_get(lua_State* L) /* helper for the class.set method, performs the lookup of class attributes * It returns error code. Number of function return values is passed inside 'ret' */ -SWIGINTERN int SWIG_Lua_class_do_set(lua_State* L, swig_type_info *type, int first_arg, int& ret) +SWIGINTERN int SWIG_Lua_class_do_set(lua_State* L, swig_type_info *type, int first_arg, int *ret) { /* there should be 3 params passed in (1) table (not the meta table) @@ -671,7 +671,7 @@ SWIGINTERN int SWIG_Lua_class_do_set(lua_State* L, swig_type_info *type, int fi assert(lua_isuserdata(L,substack_start+1)); /* just in case */ lua_getmetatable(L,substack_start+1); /* get the meta table */ assert(lua_istable(L,-1)); /* just in case */ - ret = 0; // it is setter - number of return values is always 0 + if(ret) *ret = 0; // it is setter - number of return values is always 0 SWIG_Lua_get_table(L,".set"); /* find the .set table */ if (lua_istable(L,-1)) @@ -712,7 +712,7 @@ SWIGINTERN int SWIG_Lua_class_do_set(lua_State* L, swig_type_info *type, int fi // Search among bases assert(lua_gettop(L) == first_arg+2); // TODO: REMOVE int bases_search_result = SWIG_Lua_iterate_bases(L,type,first_arg,SWIG_Lua_class_do_set,ret); - assert(ret == 0); + if(ret) assert(*ret == 0); assert(lua_gettop(L) == substack_start + 3); return bases_search_result; } @@ -731,7 +731,7 @@ SWIGINTERN int SWIG_Lua_class_set(lua_State* L) swig_lua_userdata *usr=(swig_lua_userdata*)lua_touserdata(L,1); /* get data */ swig_type_info *type = usr->type; int ret = 0; - int result = SWIG_Lua_class_do_set(L,type,1,ret); + int result = SWIG_Lua_class_do_set(L,type,1,&ret); if(result != SWIG_OK) { SWIG_Lua_pushferrstring(L,"Assignment not possible. No setter/member with this name. For custom assignments implement __setitem method"); lua_error(L); diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 2683cb88a..b741bce7a 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -1129,7 +1129,7 @@ public: Replaceall(tm_v2, "$target", target_name_v2); Replaceall(tm_v2, "$value", value); Replaceall(tm_v2, "$nsname", nsname); - registerConstant( class_parent_nspace, tm); + registerConstant( class_parent_nspace, tm_v2.ptr()); } else { tm_v2 = Swig_typemap_lookup("constcode", n_v2, name, 0); if( !tm_v2) { From a3515ca450644189661839f1ba2f3b444fba324d Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Mon, 11 Nov 2013 17:30:40 +0400 Subject: [PATCH 403/481] Removing obsolete debug code --- Source/Modules/lang.cxx | 8 +- Source/Modules/lua.cxx | 210 +++++++++--------------------------- Source/Modules/overload.cxx | 2 - Source/Swig/typesys.c | 2 +- 4 files changed, 54 insertions(+), 168 deletions(-) diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 195da18d6..6e0e88507 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -3014,6 +3014,7 @@ int Language::variableWrapper(Node *n) { Delete(gname); Setattr(n, "varget", "1"); functionWrapper(n); + Delattr(n, "varget"); Swig_restore(n); return SWIG_OK; } @@ -3477,13 +3478,6 @@ String *Language::getNSpace() const { return NSpace; } -/* ----------------------------------------------------------------------------- - * Language::setNSpace() - * ----------------------------------------------------------------------------- */ -void Language::setNSpace(String *nspace) { - NSpace = nspace; -} - /* ----------------------------------------------------------------------------- * Language::getClassName() * ----------------------------------------------------------------------------- */ diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index b741bce7a..91f6aeb8d 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -73,76 +73,6 @@ void display_mapping(DOH *d) { } } -template // T is ignored because everything is DOH* -class DohPtrGuard { - public: - DohPtrGuard( DOH* _ptr ): - p_ptr(_ptr) - { - assert( p_ptr != 0 ); - } - DohPtrGuard(): - p_ptr(0) {} - - ~DohPtrGuard() { - release(); - } - - // Guard is empty, ptr - any: assigns new value for guard - // Guard is holding pointer, ptr == 0 - releases value that guard holds - // Any other combination - assert - DOH* operator=( DOH* ptr ) { - attach(ptr); - return ptr; - } - - DOH* ptr() { return p_ptr; } - const DOH* ptr() const { return p_ptr; } - operator DOH* () { return p_ptr; } - operator DOH* () const { return p_ptr; } - operator bool() const { return ptr != 0; } - - private: - DOH* p_ptr; // pointer to actual object - - void attach(DOH* ptr) { - if( p_ptr != 0 ) { // If some object already attached, then we can't attach another one - assert(ptr == 0); - if( ptr == 0 ) { - release(); - } - } else { - p_ptr = ptr; - } - } - - void release() { - if( p_ptr != 0 ) { - Delete(p_ptr); - p_ptr = 0; - } - } - // Copying is forbiden - DohPtrGuard( const DohPtrGuard& rhs ); - void operator=( const DohPtrGuard& rhs ); - -}; - -// Overloading DohDelete for DohPtrGuard. You might not call DohDelete on DohPtrGuard instances, -// as it is supposed to manage underlying pointer by itself - -void DohDelete(const DohPtrGuard& /*guard*/) { - Printf( stderr, "ERROR: Attempt to delete guarded pointer without deleting it's guardian\n" ); - assert(false); -} -void DohDelete(DohPtrGuard& /*guard*/) { - Printf( stderr, "ERROR: Attempt to delete guarded pointer without deleting it's guardian\n" ); - assert(false); -} - - -#define PtrGuard DohPtrGuard - /* NEW LANGUAGE NOTE:*********************************************** most of the default options are handled by SWIG you can add new ones here @@ -215,7 +145,6 @@ private: CONSTRUCTOR, DESTRUCTOR, MEMBER_VAR, - CLASS_CONST, // TODO: What is this ? STATIC_FUNC, STATIC_VAR, STATIC_CONST, // enums and things like static const int x = 5; @@ -437,19 +366,7 @@ public: Printf(f_header, "#define SWIG_init_user luaopen_%s_user\n\n", module); Printf(f_header, "#define SWIG_LUACODE luaopen_%s_luacode\n", module); - if (elua_ltr || eluac_ltr) { - /* TODO: REMOVE - Printf(f_header, - "#ifndef MIN_OPT_LEVEL\n"\ - "#define MIN_OPT_LEVEL %d\n"\ - "#endif\n", elua_opt_lvl); - Printf(f_header, "#include \"lrodefs.h\"\n"); - Printf(f_header, "#include \"lrotable.h\"\n"); - */ - Printf(f_wrappers, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n"); - } else { - Printf(f_wrappers, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n"); - } + Printf(f_wrappers, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n"); /* %init code inclusion, effectively in the SWIG_init function */ Printf(f_init, "void SWIG_init_user(lua_State* L)\n{\n"); @@ -461,15 +378,9 @@ public: // Done. Close up the module & write to the wrappers - if (elua_ltr || eluac_ltr) { - /* Final close up of wrappers */ - closeNamespaces(f_wrappers); - SwigType_emit_type_table(f_runtime, f_wrappers); - } else { - //Printv(f_wrappers, s_cmd_tab, s_var_tab, s_const_tab, NIL); - closeNamespaces(f_wrappers); - SwigType_emit_type_table(f_runtime, f_wrappers); - } + //Printv(f_wrappers, s_cmd_tab, s_var_tab, s_const_tab, NIL); + closeNamespaces(f_wrappers); + SwigType_emit_type_table(f_runtime, f_wrappers); /* NEW LANGUAGE NOTE:*********************************************** this basically combines several of the strings together @@ -590,7 +501,7 @@ public: Parm *p; String *tm; int i; - //Printf(stdout,"functionWrapper %s %s %d\n",name,iname,current); // TODO: COMMENT BACK + //Printf(stdout,"functionWrapper %s %s %d\n",name,iname,current); String *overname = 0; if (Getattr(n, "sym:overloaded")) { @@ -1071,26 +982,14 @@ public: String *rawval = Getattr(n, "rawval"); String *value = rawval ? rawval : Getattr(n, "value"); String *tm; - PtrGuard target_name_v2; - PtrGuard tm_v2; - PtrGuard iname_v2; - PtrGuard n_v2; + String *target_name_v2 = 0; + String *tm_v2 = 0; + String *iname_v2 = 0; + Node *n_v2 = 0; if (!luaAddSymbol(target_name, n)) return SWIG_ERROR; - bool make_v2_compatible = v2_compatibility && getCurrentClass() != 0; - //Printf( stdout, "V2 compatible: %d\n", int(make_v2_compatible) ); // TODO: REMOVE - if( make_v2_compatible ) { - target_name_v2 = Swig_name_member(0, class_symname, target_name); - iname_v2 = Swig_name_member(0, class_symname, iname); - n_v2 = Copy(n); - //Printf( stdout, "target name v2: %s, symname v2 %s\n", target_name_v2.ptr(), iname_v2.ptr());// TODO:REMOVE - if (!luaAddSymbol(iname_v2, n, class_parent_nspace)) { - return SWIG_ERROR; - } - } - Swig_save("lua_constantMember", n, "sym:name", NIL); Setattr(n, "sym:name", target_name); /* Special hook for member pointer */ @@ -1120,7 +1019,17 @@ public: return SWIG_NOWRAP; } + bool make_v2_compatible = v2_compatibility && getCurrentClass() != 0; + if( make_v2_compatible ) { + target_name_v2 = Swig_name_member(0, class_symname, target_name); + iname_v2 = Swig_name_member(0, class_symname, iname); + n_v2 = Copy(n); + //Printf( stdout, "target name v2: %s, symname v2 %s\n", target_name_v2.ptr(), iname_v2.ptr());// TODO:REMOVE + if (!luaAddSymbol(iname_v2, n, class_parent_nspace)) { + return SWIG_ERROR; + } + Setattr(n_v2, "sym:name", target_name_v2); tm_v2 = Swig_typemap_lookup("consttab", n_v2, name, 0); if (tm_v2) { @@ -1129,7 +1038,7 @@ public: Replaceall(tm_v2, "$target", target_name_v2); Replaceall(tm_v2, "$value", value); Replaceall(tm_v2, "$nsname", nsname); - registerConstant( class_parent_nspace, tm_v2.ptr()); + registerConstant( class_parent_nspace, tm_v2); } else { tm_v2 = Swig_typemap_lookup("constcode", n_v2, name, 0); if( !tm_v2) { @@ -1142,8 +1051,9 @@ public: Replaceall(tm_v2, "$target", target_name_v2); Replaceall(tm_v2, "$value", value); Replaceall(tm_v2, "$nsname", nsname); - Printf(f_init, "%s\n", tm_v2.ptr()); + Printf(f_init, "%s\n", tm_v2); } + Delete(n_v2); } Swig_restore(n); @@ -1174,25 +1084,10 @@ public: * ------------------------------------------------------------ */ virtual int enumDeclaration(Node *n) { - // enumDeclaration supplied by Language is messing with NSpace. - // So this is the exact copy of function from Language with - // correct handling of namespaces - String *oldNSpace = getNSpace(); - /* TODO: REVIEW/REMOVE_and_replace_with_Language::enumDeclaration - if( getCurrentClass() == 0 ) { - setNSpace(Getattr(n, "sym:nspace")); - }*/ - setNSpace(Getattr(n, "sym:nspace")); - - if (!ImportMode) { - current[STATIC_CONST] = true; - emit_children(n); - current[STATIC_CONST] = false; - } - - setNSpace(oldNSpace); - - return SWIG_OK; + current[STATIC_CONST] = true; + int result = Language::enumDeclaration(n); + current[STATIC_CONST] = false; + return result; } /* ------------------------------------------------------------ @@ -1237,8 +1132,8 @@ public: virtual int classHandler(Node *n) { //REPORT("classHandler", n); - PtrGuard mangled_class_fq_symname; - PtrGuard destructor_name; + String *mangled_class_fq_symname; + String *destructor_name; String* nspace = getNSpace(); constructor_name = 0; @@ -1266,13 +1161,13 @@ public: assert(class_fq_symname != 0); mangled_class_fq_symname = Swig_name_mangle(class_fq_symname); - PtrGuard t( Copy(Getattr(n, "name")) ); - PtrGuard fr_t( SwigType_typedef_resolve_all(t) ); /* Create fully resolved type */ - PtrGuard t_tmp; + SwigType *t( Copy(Getattr(n, "name")) ); + SwigType *fr_t( SwigType_typedef_resolve_all(t) ); /* Create fully resolved type */ + SwigType *t_tmp = 0; t_tmp = SwigType_typedef_qualified(fr_t); // Temporal variable - fr_t = 0; + Delete(fr_t); fr_t = SwigType_strip_qualifiers(t_tmp); - PtrGuard mangled_fr_t; + String *mangled_fr_t = 0; mangled_fr_t = SwigType_manglestr(fr_t); // not sure exactly how this works, // but tcl has a static hashtable of all classes emitted and then only emits code for them once. @@ -1328,17 +1223,15 @@ public: // Replacing namespace with namespace + class in order to static // member be put inside class static area class_parent_nspace = getNSpace(); - //setNSpace(class_static_nspace); TODO: REMOVE // Generate normal wrappers Language::classHandler(n); // Restore correct nspace - //setNSpace(nspace); // TODO: REMOVE if remove above class_parent_nspace = 0; SwigType_add_pointer(t); // Catch all: eg. a class with only static functions and/or variables will not have 'remembered' - String *wrap_class = NewStringf("&_wrap_class_%s", mangled_class_fq_symname.ptr()); + String *wrap_class = NewStringf("&_wrap_class_%s", mangled_class_fq_symname); SwigType_remember_clientdata(t, wrap_class); String *rt = Copy(getClassType()); @@ -1354,8 +1247,8 @@ public: // emit a function to be called to delete the object if (have_destructor) { - destructor_name = NewStringf("swig_delete_%s", mangled_class_fq_symname.ptr()); - Printv(f_wrappers, "static void ", destructor_name.ptr(), "(void *obj) {\n", NIL); + destructor_name = NewStringf("swig_delete_%s", mangled_class_fq_symname); + Printv(f_wrappers, "static void ", destructor_name, "(void *obj) {\n", NIL); if (destructor_action) { Printv(f_wrappers, SwigType_str(rt, "arg1"), " = (", SwigType_str(rt, 0), ") obj;\n", NIL); Printv(f_wrappers, destructor_action, "\n", NIL); @@ -1399,7 +1292,7 @@ public: if (eluac_ltr) { String* ns_methods_tab = Getattr(nspaceHash, "methods"); assert(ns_methods_tab != 0); - Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "free_", mangled_class_fq_symname.ptr(), "\")", ", LFUNCVAL(", destructor_name.ptr(), ")", "},\n", NIL); + Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "free_", mangled_class_fq_symname, "\")", ", LFUNCVAL(", destructor_name, ")", "},\n", NIL); } } @@ -1443,12 +1336,12 @@ public: printNamespaceDefinition(class_static_nspace, class_symname, f_wrappers); // Then print class isntance part - Printv(f_wrappers, "static swig_lua_class *swig_", mangled_class_fq_symname.ptr(), "_bases[] = {", base_class, "0};\n", NIL); + Printv(f_wrappers, "static swig_lua_class *swig_", mangled_class_fq_symname, "_bases[] = {", base_class, "0};\n", NIL); Delete(base_class); - Printv(f_wrappers, "static const char *swig_", mangled_class_fq_symname.ptr(), "_base_names[] = {", base_class_names, "0};\n", NIL); + Printv(f_wrappers, "static const char *swig_", mangled_class_fq_symname, "_base_names[] = {", base_class_names, "0};\n", NIL); Delete(base_class_names); - Printv(f_wrappers, "static swig_lua_class _wrap_class_", mangled_class_fq_symname.ptr(), " = { \"", class_symname, "\", \"", class_fq_symname,"\", &SWIGTYPE", SwigType_manglestr(t), ",", NIL); + Printv(f_wrappers, "static swig_lua_class _wrap_class_", mangled_class_fq_symname, " = { \"", class_symname, "\", \"", class_fq_symname,"\", &SWIGTYPE", SwigType_manglestr(t), ",", NIL); if (have_constructor) { Printv(f_wrappers, constructor_name, NIL); @@ -1459,16 +1352,18 @@ public: } if (have_destructor) { - Printv(f_wrappers, ", ", destructor_name.ptr(), NIL); + Printv(f_wrappers, ", ", destructor_name, NIL); } else { Printf(f_wrappers, ",0"); } Printf(f_wrappers, ", %s, %s, &%s", s_methods_tab_name, s_attr_tab_name, Getattr(static_cls, "cname") ); Printf(f_wrappers, ", swig_%s_bases, swig_%s_base_names };\n\n", - mangled_class_fq_symname.ptr(), mangled_class_fq_symname.ptr()); + mangled_class_fq_symname, mangled_class_fq_symname); current[NO_CPP] = true; Delete(class_static_nspace); + Delete(mangled_class_fq_symname); + Delete(destructor_name); class_static_nspace = 0; Delete(class_fq_symname); class_fq_symname = 0; @@ -1581,10 +1476,10 @@ public: if(v2_compatibility) { Swig_require("lua_staticmemberfunctionHandler", n, "*lua:name", NIL); String *target_name = Getattr(n, "lua:name"); - PtrGuard compat_name; - compat_name = Swig_name_member(0, class_symname, target_name); + String *compat_name = Swig_name_member(0, class_symname, target_name); Setattr(n, "lua:name", compat_name); registerMethod( class_parent_nspace, n ); + Delete(compat_name); Swig_restore(n); } @@ -1738,7 +1633,7 @@ public: String* item = Getitem(components, i); Printv(parent_path, item, NIL); } - //Printf(stdout, "Registering %s. User name %s. C-name %s, Parent is %s\n", mangled_name, name, cname, parent_path); + //Printf(stdout, "Registering %s. User name %s. C-name %s, Parent is %s\n", mangled_name, name, cname, parent_path); // TODO: REMOVE Hash* parent = getNamespaceHash(parent_path, true); String* namespaces_tab = Getattr(parent, "namespaces"); Printv(namespaces_tab, "&", cname, ",\n", NIL); @@ -1814,7 +1709,6 @@ public: Setattr(nspace_hash, "namespaces:decl", namespaces_tab_decl ); if (elua_ltr) { - // TODO: add xxx:decl here too String *get_tab = NewString(""); String *get_tab_name = NewStringf("swig_%s_get", mangled_name); String *get_tab_decl = NewString(""); @@ -1993,14 +1887,13 @@ public: // be fully qualified name, just it's own name. void printNamespaceDefinition(String *nspace, String* name, File *output) { - // TODO: Fix for get_tab/set_tab things (elua_ltr) Hash *nspace_hash = getNamespaceHash(nspace, false); String* cname = Getattr(nspace_hash, "cname"); // cname - name of the C structure that describes namespace assert(cname != 0); Printv(output, "static swig_lua_namespace ", cname, " = ", NIL); - PtrGuard null_string; + String *null_string; null_string = NewString("0"); String *attr_tab_name = Getattr(nspace_hash, "attributes:name"); String *methods_tab_name = Getattr(nspace_hash, "methods:name"); @@ -2015,10 +1908,11 @@ public: tab4, methods_tab_name, ",\n", tab4, attr_tab_name, ",\n", tab4, const_tab_name, ",\n", - tab4, (has_classes)?classes_tab_name:null_string.ptr(), ",\n", - tab4, (has_namespaces)?namespaces_tab_name:null_string.ptr(), "\n};\n", + tab4, (has_classes)?classes_tab_name:null_string, ",\n", + tab4, (has_namespaces)?namespaces_tab_name:null_string, "\n};\n", NIL ); + Delete(null_string); } // This function determines actual namespace/scope where any symbol at the @@ -2038,7 +1932,7 @@ public: assert(!current[NO_CPP]); if(current[STATIC_FUNC] || current[STATIC_VAR] || current[STATIC_CONST] ) { scope = class_static_nspace; - } else if(current[MEMBER_VAR] || current[CLASS_CONST] || current[CONSTRUCTOR] || current[DESTRUCTOR] + } else if(current[MEMBER_VAR] || current[CONSTRUCTOR] || current[DESTRUCTOR] || current[MEMBER_FUNC] ) { scope = class_fq_symname; } else { // Friend functions are handled this way diff --git a/Source/Modules/overload.cxx b/Source/Modules/overload.cxx index 4c0d06702..e95ef557f 100644 --- a/Source/Modules/overload.cxx +++ b/Source/Modules/overload.cxx @@ -765,7 +765,6 @@ String *Swig_overload_dispatch(Node *n, const_String_or_char_ptr fmt, int *maxar for (i = 0; i < nfunc; i++) { Node *ni = Getitem(dispatch, i); Parm *pi = Getattr(ni, "wrap:parms"); - //Printf(stdout , "Dispatch, wrapname %s\n", Getattr(ni,"wrap:name")); // TODO:REMOVE bool implicitconvtypecheckoff = GetFlag(ni, "implicitconvtypecheckoff") != 0; int num_required = emit_num_required(pi); int num_arguments = emit_num_arguments(pi); @@ -819,7 +818,6 @@ String *Swig_overload_dispatch(Node *n, const_String_or_char_ptr fmt, int *maxar j++; } String *lfmt = ReplaceFormat(fmt, num_arguments); - //Printf(stdout , "Dispatch, wrapname %s\n", Getattr(ni,"wrap:name")); // TODO:REMOVE Printf(f, Char(lfmt), Getattr(ni, "wrap:name")); Delete(lfmt); /* close braces */ diff --git a/Source/Swig/typesys.c b/Source/Swig/typesys.c index a7060ca54..c5ddb56f6 100644 --- a/Source/Swig/typesys.c +++ b/Source/Swig/typesys.c @@ -1594,7 +1594,7 @@ void SwigType_remember_clientdata(const SwigType *t, const_String_or_char_ptr cl Delete(qr); /*Printf(stdout,"t = '%s'\n", t); - Printf(stdout,"fr= '%s'\n\n", fr); TODO: COmment back*/ + Printf(stdout,"fr= '%s'\n\n", fr);*/ if (t) { char *ct = Char(t); From 9bd39fe4fa80307167fbc26290aaa188d57f5485 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Mon, 11 Nov 2013 17:37:39 +0400 Subject: [PATCH 404/481] Valuewrapper test --- Examples/test-suite/lua/valuewrapper_runme.lua | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Examples/test-suite/lua/valuewrapper_runme.lua diff --git a/Examples/test-suite/lua/valuewrapper_runme.lua b/Examples/test-suite/lua/valuewrapper_runme.lua new file mode 100644 index 000000000..94d49c7cc --- /dev/null +++ b/Examples/test-suite/lua/valuewrapper_runme.lua @@ -0,0 +1,17 @@ +require("import") -- the import fn +import("valuewrapper") -- import code +v=valuewrapper -- renaming import + +-- catch "undefined" global variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +assert(v.Xi ~= nil) +assert(v.YXi ~= nil) + +x1 = v.Xi(5) + +y1 =v.YXi() +assert(y1:spam(x1) == 0) +assert(y1:spam() == 0) From 1e282e39817880e6e94dbcaeaf71c2c25ce812ee Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Mon, 11 Nov 2013 18:02:27 +0400 Subject: [PATCH 405/481] Code beautifier --- Source/Modules/lua.cxx | 1041 ++++++++++++++++++++-------------------- 1 file changed, 511 insertions(+), 530 deletions(-) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 91f6aeb8d..f1803e068 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -54,7 +54,7 @@ */ #define REPORT(T,D) // no info: //#define REPORT(T,D) {Printf(stdout,T"\n");} // only title -//#define REPORT(T,D) {Printf(stdout,T" %p\n",n);} // title & pointer +//#define REPORT(T,D) {Printf(stdout,T" %p\n",n);} // title & pointer //#define REPORT(T,D) {Printf(stdout,T"\n");display_mapping(D);} // the works //#define REPORT(T,D) {Printf(stdout,T"\n");if(D)Swig_print_node(D);} // the works @@ -122,14 +122,14 @@ private: File *f_initbeforefunc; String *s_luacode; // luacode to be called during init String *module; //name of the module - Hash* namespaces_hash; + Hash *namespaces_hash; // Parameters for current class. NIL if not parsing class int have_constructor; int have_destructor; String *destructor_action; String *class_symname; - String *class_fq_symname; // Fully qualified symname - NSpace + '.' + class_symname + String *class_fq_symname; // Fully qualified symname - NSpace + '.' + class_symname String *class_static_nspace; String *class_parent_nspace; String *constructor_name; @@ -147,7 +147,7 @@ private: MEMBER_VAR, STATIC_FUNC, STATIC_VAR, - STATIC_CONST, // enums and things like static const int x = 5; + STATIC_CONST, // enums and things like static const int x = 5; STATES_COUNT }; @@ -161,29 +161,22 @@ public: * Initialize member data * --------------------------------------------------------------------- */ - LUA() : - f_begin(0), - f_runtime(0), - f_header(0), - f_wrappers(0), - f_init(0), - f_initbeforefunc(0), - s_luacode(0), - module(0), - have_constructor(0), - have_destructor(0), - destructor_action(0), - class_symname(0), - class_fq_symname(0), - class_static_nspace(0), - constructor_name(0) { - namespaces_hash = NewHash(); - for(int i = 0; i < STATES_COUNT; i++ ) - current[i] = false; + LUA(): + f_begin(0), + f_runtime(0), + f_header(0), + f_wrappers(0), + f_init(0), + f_initbeforefunc(0), + s_luacode(0), + module(0), + have_constructor(0), have_destructor(0), destructor_action(0), class_symname(0), class_fq_symname(0), class_static_nspace(0), constructor_name(0) { + namespaces_hash = NewHash(); + for (int i = 0; i < STATES_COUNT; i++) + current[i] = false; } - ~LUA() { - if(namespaces_hash) + if (namespaces_hash) Delete(namespaces_hash); } @@ -191,82 +184,82 @@ public: This is called to initalise the system & read any command line args most of this is boilerplate code, except the command line args which depends upon what args your code supports - NEW LANGUAGE NOTE:END ************************************************/ + NEW LANGUAGE NOTE:END *********************************************** */ - bool strToInt(const char* string, int& value) { - long int tmp; - char *p_end = 0; - if(string == 0) - return false; - tmp = strtol(string,&p_end,10); - if( p_end == 0 || *p_end != 0 ) - return false; - value = tmp; - return true; + bool strToInt(const char *string, int &value) { + long int tmp; + char *p_end = 0; + if (string == 0) + return false; + tmp = strtol(string, &p_end, 10); + if (p_end == 0 || *p_end != 0) + return false; + value = tmp; + return true; } /* --------------------------------------------------------------------- - * main() - * - * Parse command line options and initializes variables. - * --------------------------------------------------------------------- */ + * main() + * + * Parse command line options and initializes variables. + * --------------------------------------------------------------------- */ virtual void main(int argc, char *argv[]) { - int api_level = default_api_level; // Default api level + int api_level = default_api_level; // Default api level /* Set location of SWIG library */ SWIG_library_directory("lua"); /* Look for certain command line options */ for (int i = 1; i < argc; i++) { if (argv[i]) { - if (strcmp(argv[i], "-help") == 0) { // usage flags - fputs(usage, stdout); - } else if (strcmp(argv[i], "-nomoduleglobal") == 0) { - nomoduleglobal = 1; - Swig_mark_arg(i); - } else if(strcmp(argv[i], "-elua") == 0) { - elua_ltr = 1; - Swig_mark_arg(i); - if(strToInt(argv[i+1],elua_opt_lvl)) { - Swig_mark_arg(i+1); - i++; - } - } else if(strcmp(argv[i], "-eluac") == 0) { - eluac_ltr = 1; - Swig_mark_arg(i); - if(strToInt(argv[i+1],elua_opt_lvl)) { - Swig_mark_arg(i+1); - i++; - } - } else if(strcmp(argv[i], "-api-lvl-from") == 0) { - if(argv[i+1]) { - if(!strToInt(argv[i+1], api_level)) - Swig_arg_error(); - Swig_mark_arg(i+1); - i++; - } else { - Swig_arg_error(); - } - } + if (strcmp(argv[i], "-help") == 0) { // usage flags + fputs(usage, stdout); + } else if (strcmp(argv[i], "-nomoduleglobal") == 0) { + nomoduleglobal = 1; + Swig_mark_arg(i); + } else if (strcmp(argv[i], "-elua") == 0) { + elua_ltr = 1; + Swig_mark_arg(i); + if (strToInt(argv[i + 1], elua_opt_lvl)) { + Swig_mark_arg(i + 1); + i++; + } + } else if (strcmp(argv[i], "-eluac") == 0) { + eluac_ltr = 1; + Swig_mark_arg(i); + if (strToInt(argv[i + 1], elua_opt_lvl)) { + Swig_mark_arg(i + 1); + i++; + } + } else if (strcmp(argv[i], "-api-lvl-from") == 0) { + if (argv[i + 1]) { + if (!strToInt(argv[i + 1], api_level)) + Swig_arg_error(); + Swig_mark_arg(i + 1); + i++; + } else { + Swig_arg_error(); + } + } } } // Set API-compatibility options - if(api_level <= 2) // Must be compatible with SWIG 2.* + if (api_level <= 2) // Must be compatible with SWIG 2.* v2_compatibility = 1; - // template for further API breaks - //if(api_level <= 3) - // v3_compatibility = 1; - //if(api_level <= 4) - // v4_compatibility = 1; - + // template for further API breaks + //if(api_level <= 3) + // v3_compatibility = 1; + //if(api_level <= 4) + // v4_compatibility = 1; + /* NEW LANGUAGE NOTE:*********************************************** - This is the boilerplate code, setting a few #defines - and which lib directory to use - the SWIG_library_directory() is also boilerplate code - but it always seems to be the first line of code - NEW LANGUAGE NOTE:END ************************************************/ + This is the boilerplate code, setting a few #defines + and which lib directory to use + the SWIG_library_directory() is also boilerplate code + but it always seems to be the first line of code + NEW LANGUAGE NOTE:END *********************************************** */ /* Add a symbol to the parser for conditional compilation */ Preprocessor_define("SWIGLUA 1", 0); @@ -284,15 +277,15 @@ public: /* NEW LANGUAGE NOTE:*********************************************** - After calling main, SWIG parses the code to wrap (I believe) - then calls top() - in this is more boilerplate code to set everything up - and a call to Language::top() - which begins the code generations by calling the member fns - after all that is more boilerplate code to close all down - (overall there is virtually nothing here that needs to be edited - just use as is) - NEW LANGUAGE NOTE:END ************************************************/ + After calling main, SWIG parses the code to wrap (I believe) + then calls top() + in this is more boilerplate code to set everything up + and a call to Language::top() + which begins the code generations by calling the member fns + after all that is more boilerplate code to close all down + (overall there is virtually nothing here that needs to be edited + just use as is) + NEW LANGUAGE NOTE:END *********************************************** */ /* --------------------------------------------------------------------- * top() * --------------------------------------------------------------------- */ @@ -324,10 +317,10 @@ public: Swig_register_filebyname("init", f_init); Swig_register_filebyname("initbeforefunc", f_initbeforefunc); - + s_luacode = NewString(""); Swig_register_filebyname("luacode", s_luacode); - + current[NO_CPP] = true; /* Standard stuff for the SWIG runtime section */ @@ -339,11 +332,8 @@ public: emitLuaFlavor(f_runtime); if (elua_ltr || eluac_ltr) - Printf(f_runtime, - "#ifndef MIN_OPT_LEVEL\n"\ - "#define MIN_OPT_LEVEL %d\n"\ - "#endif\n", elua_opt_lvl); - + Printf(f_runtime, "#ifndef MIN_OPT_LEVEL\n" "#define MIN_OPT_LEVEL %d\n" "#endif\n", elua_opt_lvl); + if (nomoduleglobal) { Printf(f_runtime, "#define SWIG_LUA_NO_MODULE_GLOBAL\n"); } else { @@ -371,7 +361,7 @@ public: /* %init code inclusion, effectively in the SWIG_init function */ Printf(f_init, "void SWIG_init_user(lua_State* L)\n{\n"); Language::top(n); - Printf(f_init,"/* exec Lua code if applicable */\nSWIG_Lua_dostring(L,SWIG_LUACODE);\n"); + Printf(f_init, "/* exec Lua code if applicable */\nSWIG_Lua_dostring(L,SWIG_LUACODE);\n"); Printf(f_init, "}\n"); Printf(f_wrappers, "#ifdef __cplusplus\n}\n#endif\n"); @@ -383,16 +373,16 @@ public: SwigType_emit_type_table(f_runtime, f_wrappers); /* NEW LANGUAGE NOTE:*********************************************** - this basically combines several of the strings together - and then writes it all to a file - NEW LANGUAGE NOTE:END ************************************************/ + this basically combines several of the strings together + and then writes it all to a file + NEW LANGUAGE NOTE:END *********************************************** */ Dump(f_runtime, f_begin); Dump(f_header, f_begin); Dump(f_wrappers, f_begin); Dump(f_initbeforefunc, f_begin); /* for the Lua code it needs to be properly excaped to be added into the C/C++ code */ EscapeCode(s_luacode); - Printf(f_begin, "const char* SWIG_LUACODE=\n \"%s\";\n\n",s_luacode); + Printf(f_begin, "const char* SWIG_LUACODE=\n \"%s\";\n\n", s_luacode); Wrapper_pretty_print(f_init, f_begin); /* Close all of the files */ Delete(s_luacode); @@ -425,25 +415,25 @@ public: // But we need to know what was the name of function/variable // etc that user desired, that's why we store correct symname // as lua:name - Setattr(n, "lua:name", Getattr(n, "sym:name") ); + Setattr(n, "lua:name", Getattr(n, "sym:name")); return Language::cDeclaration(n); } virtual int constructorDeclaration(Node *n) { - Setattr(n, "lua:name", Getattr(n, "sym:name") ); + Setattr(n, "lua:name", Getattr(n, "sym:name")); return Language::constructorDeclaration(n); } virtual int destructorDeclaration(Node *n) { - Setattr(n, "lua:name", Getattr(n, "sym:name") ); + Setattr(n, "lua:name", Getattr(n, "sym:name")); return Language::destructorDeclaration(n); } /* NEW LANGUAGE NOTE:*********************************************** - This is it! - you get this one right, and most of your work is done - but its going to take soem file to get it working right - quite a bit of this is generally boilerplate code - (or stuff I dont understand) - that which matters will have extra added comments - NEW LANGUAGE NOTE:END ************************************************/ + This is it! + you get this one right, and most of your work is done + but its going to take soem file to get it working right + quite a bit of this is generally boilerplate code + (or stuff I dont understand) + that which matters will have extra added comments + NEW LANGUAGE NOTE:END *********************************************** */ /* --------------------------------------------------------------------- * functionWrapper() * @@ -455,25 +445,25 @@ public: Setattr(n, "wrap:name", wrapname); // If it is getter/setter, then write wrapname under // wrap:memberset/wrap:memberget accordingly - if( Getattr(n, "memberset") ) + if (Getattr(n, "memberset")) Setattr(n, "memberset:wrap:name", wrapname); - if( Getattr(n, "varset") ) + if (Getattr(n, "varset")) Setattr(n, "varset:wrap:name", wrapname); - if( Getattr(n, "memberget") ) + if (Getattr(n, "memberget")) Setattr(n, "memberget:wrap:name", wrapname); - if( Getattr(n, "varget") ) + if (Getattr(n, "varget")) Setattr(n, "varget:wrap:name", wrapname); } // Add method to the "methods" C array of given namespace/class - void registerMethod(String *nspace_or_class_name, Node* n) { + void registerMethod(String *nspace_or_class_name, Node *n) { assert(n != 0); - Hash* nspaceHash = getNamespaceHash( nspace_or_class_name ); - String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); + Hash *nspaceHash = getNamespaceHash(nspace_or_class_name); + String *s_ns_methods_tab = Getattr(nspaceHash, "methods"); String *wname = Getattr(n, "wrap:name"); String *iname = Getattr(n, "sym:name"); String *target_name = Getattr(n, "lua:name"); - if(elua_ltr || eluac_ltr) + if (elua_ltr || eluac_ltr) Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", iname, "\")", ", LFUNCVAL(", wname, ")", "},\n", NIL); else Printv(s_ns_methods_tab, tab4, "{ \"", target_name, "\", ", wname, "},\n", NIL); @@ -487,10 +477,10 @@ public: if (current[VARIABLE]) return false; return (current[NO_CPP] || current[STATIC_FUNC]); - } - + } + virtual int functionWrapper(Node *n) { - REPORT("functionWrapper",n); + REPORT("functionWrapper", n); String *name = Getattr(n, "name"); String *iname = Getattr(n, "sym:name"); @@ -508,14 +498,14 @@ public: overname = Getattr(n, "sym:overname"); } else { if (!luaAddSymbol(target_name, n)) { - return SWIG_ERROR; + return SWIG_ERROR; } } /* NEW LANGUAGE NOTE:*********************************************** the wrapper object holds all the wrappering code - we need to add a couple of local variables - NEW LANGUAGE NOTE:END ************************************************/ + we need to add a couple of local variables + NEW LANGUAGE NOTE:END *********************************************** */ Wrapper *f = NewWrapper(); Wrapper_add_local(f, "SWIG_arg", "int SWIG_arg = 0"); @@ -525,25 +515,25 @@ public: Append(wname, overname); } if (current[CONSTRUCTOR]) { - if( constructor_name != 0) - Delete(constructor_name); + if (constructor_name != 0) + Delete(constructor_name); constructor_name = Copy(wname); } /* NEW LANGUAGE NOTE:*********************************************** the format of a lua fn is: - static int wrap_XXX(lua_State* L){...} + static int wrap_XXX(lua_State* L){...} this line adds this into the wrappering code - NEW LANGUAGE NOTE:END ************************************************/ + NEW LANGUAGE NOTE:END *********************************************** */ Printv(f->def, "static int ", wname, "(lua_State* L) {", NIL); /* NEW LANGUAGE NOTE:*********************************************** this prints the list of args, eg for a C fn int gcd(int x,int y); it will print - int arg1; - int arg2; - NEW LANGUAGE NOTE:END ************************************************/ + int arg1; + int arg2; + NEW LANGUAGE NOTE:END *********************************************** */ /* Write code to extract function parameters. */ emit_parameter_variables(l, f); @@ -572,24 +562,24 @@ public: some of the stuff will refer to the typemaps code written in your swig file (lua.swg), and some is done in the code here I suppose you could do all the conversion on C, but it would be a nightmare to do - NEW LANGUAGE NOTE:END ************************************************/ + NEW LANGUAGE NOTE:END *********************************************** */ /* Generate code for argument marshalling */ // String *description = NewString(""); /* NEW LANGUAGE NOTE:*********************************************** argument_check is a new feature I added to check types of arguments: eg for int gcd(int,int) I want to check that arg1 & arg2 really are integers - NEW LANGUAGE NOTE:END ************************************************/ + NEW LANGUAGE NOTE:END *********************************************** */ String *argument_check = NewString(""); String *argument_parse = NewString(""); String *checkfn = NULL; char source[64]; - Printf(argument_check, "SWIG_check_num_args(\"%s\",%d,%d)\n",Swig_name_str(n),num_required+args_to_ignore,num_arguments+args_to_ignore); + Printf(argument_check, "SWIG_check_num_args(\"%s\",%d,%d)\n", Swig_name_str(n), num_required + args_to_ignore, num_arguments + args_to_ignore); for (i = 0, p = l; i < num_arguments; i++) { while (checkAttribute(p, "tmap:in:numinputs", "0")) { - p = Getattr(p, "tmap:in:next"); + p = Getattr(p, "tmap:in:next"); } SwigType *pt = Getattr(p, "type"); @@ -598,49 +588,49 @@ public: /* 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"))) { - Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); - } else { - Replaceall(tm, "$disown", "0"); - } - /* NEW LANGUAGE NOTE:*********************************************** - look for a 'checkfn' typemap - this an additional parameter added to the in typemap - if found the type will be tested for - this will result in code either in the - argument_check or argument_parse string - NEW LANGUAGE NOTE:END ************************************************/ - if ((checkfn = Getattr(p, "tmap:in:checkfn"))) { - if (i < num_required) { - Printf(argument_check, "if(!%s(L,%s))", checkfn, source); - } else { - Printf(argument_check, "if(lua_gettop(L)>=%s && !%s(L,%s))", source, checkfn, source); - } - Printf(argument_check, " SWIG_fail_arg(\"%s\",%s,\"%s\");\n", Swig_name_str(n), source, SwigType_str(pt, 0)); - } - /* NEW LANGUAGE NOTE:*********************************************** - lua states the number of arguments passed to a function using the fn - lua_gettop() - we can use this to deal with default arguments - NEW LANGUAGE NOTE:END ************************************************/ - if (i < num_required) { - Printf(argument_parse, "%s\n", tm); - } else { - Printf(argument_parse, "if(lua_gettop(L)>=%s){%s}\n", source, tm); - } - p = Getattr(p, "tmap:in:next"); - continue; + 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"))) { + Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); + } else { + Replaceall(tm, "$disown", "0"); + } + /* NEW LANGUAGE NOTE:*********************************************** + look for a 'checkfn' typemap + this an additional parameter added to the in typemap + if found the type will be tested for + this will result in code either in the + argument_check or argument_parse string + NEW LANGUAGE NOTE:END *********************************************** */ + if ((checkfn = Getattr(p, "tmap:in:checkfn"))) { + if (i < num_required) { + Printf(argument_check, "if(!%s(L,%s))", checkfn, source); + } else { + Printf(argument_check, "if(lua_gettop(L)>=%s && !%s(L,%s))", source, checkfn, source); + } + Printf(argument_check, " SWIG_fail_arg(\"%s\",%s,\"%s\");\n", Swig_name_str(n), source, SwigType_str(pt, 0)); + } + /* NEW LANGUAGE NOTE:*********************************************** + lua states the number of arguments passed to a function using the fn + lua_gettop() + we can use this to deal with default arguments + NEW LANGUAGE NOTE:END *********************************************** */ + if (i < num_required) { + Printf(argument_parse, "%s\n", tm); + } else { + Printf(argument_parse, "if(lua_gettop(L)>=%s){%s}\n", source, tm); + } + p = Getattr(p, "tmap:in:next"); + continue; } else { - /* NEW LANGUAGE NOTE:*********************************************** - // why is this code not called when I dont have a typemap? - // instead of giving a warning, no code is generated - NEW LANGUAGE NOTE:END ************************************************/ - 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; + /* NEW LANGUAGE NOTE:*********************************************** + // why is this code not called when I dont have a typemap? + // instead of giving a warning, no code is generated + NEW LANGUAGE NOTE:END *********************************************** */ + 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; } } @@ -650,19 +640,19 @@ public: /* Check for trailing varargs */ if (varargs) { if (p && (tm = Getattr(p, "tmap:in"))) { - Replaceall(tm, "$input", "varargs"); - Printv(f->code, tm, "\n", NIL); + 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"); + Replaceall(tm, "$target", Getattr(p, "lname")); + Printv(f->code, tm, "\n", NIL); + p = Getattr(p, "tmap:check:next"); } else { - p = nextSibling(p); + p = nextSibling(p); } } @@ -670,11 +660,11 @@ 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"); + Replaceall(tm, "$source", Getattr(p, "lname")); + Printv(cleanup, tm, "\n", NIL); + p = Getattr(p, "tmap:freearg:next"); } else { - p = nextSibling(p); + p = nextSibling(p); } } @@ -682,21 +672,21 @@ public: String *outarg = NewString(""); for (p = l; p;) { if ((tm = Getattr(p, "tmap:argout"))) { - // // managing the number of returning variables - // if (numoutputs=Getattr(p,"tmap:argout:numoutputs")){ - // int i=GetInt(p,"tmap:argout:numoutputs"); - // printf("got argout:numoutputs of %d\n",i); - // 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); - p = Getattr(p, "tmap:argout:next"); + // // managing the number of returning variables + // if (numoutputs=Getattr(p,"tmap:argout:numoutputs")){ + // int i=GetInt(p,"tmap:argout:numoutputs"); + // printf("got argout:numoutputs of %d\n",i); + // 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); + p = Getattr(p, "tmap:argout:next"); } else { - p = nextSibling(p); + p = nextSibling(p); } } @@ -707,10 +697,10 @@ public: String *actioncode = emit_action(n); /* NEW LANGUAGE NOTE:*********************************************** - FIXME: - returns 1 if there is a void return type - this is because there is a typemap for void - NEW LANGUAGE NOTE:END ************************************************/ + FIXME: + returns 1 if there is a void return type + this is because there is a typemap for void + NEW LANGUAGE NOTE:END *********************************************** */ // Return value if necessary if ((tm = Swig_typemap_lookup_out("out", n, Swig_cresult_name(), f, actioncode))) { // managing the number of returning variables @@ -722,9 +712,9 @@ public: // else returnval++; Replaceall(tm, "$source", Swig_cresult_name()); if (GetFlag(n, "feature:new")) { - Replaceall(tm, "$owner", "1"); + Replaceall(tm, "$owner", "1"); } else { - Replaceall(tm, "$owner", "0"); + Replaceall(tm, "$owner", "0"); } Printf(f->code, "%s\n", tm); // returnval++; @@ -742,8 +732,8 @@ 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); + Replaceall(tm, "$source", Swig_cresult_name()); + Printf(f->code, "%s\n", tm); } } @@ -772,29 +762,29 @@ public: /* Dump the function out */ /* in Lua we will not emit the destructor as a wrappered function, - Lua will automatically call the destructor when the object is free'd - However: you cannot just skip this function as it will not emit - any custom destructor (using %extend), as you need to call emit_action() - Therefore we go though the whole function, - but do not write the code into the wrapper - */ - if(!current[DESTRUCTOR]) { - Wrapper_print(f, f_wrappers); + Lua will automatically call the destructor when the object is free'd + However: you cannot just skip this function as it will not emit + any custom destructor (using %extend), as you need to call emit_action() + Therefore we go though the whole function, + but do not write the code into the wrapper + */ + if (!current[DESTRUCTOR]) { + Wrapper_print(f, f_wrappers); } - + /* NEW LANGUAGE NOTE:*********************************************** - register the function in SWIG - different language mappings seem to use different ideas - NEW LANGUAGE NOTE:END ************************************************/ + register the function in SWIG + different language mappings seem to use different ideas + NEW LANGUAGE NOTE:END *********************************************** */ /* Now register the function with the interpreter. */ int result = SWIG_OK; if (!Getattr(n, "sym:overloaded")) { - if (functionWrapperRegisterNow()) { // emit normal fns & static fns - registerMethod(luaCurrentSymbolNSpace(), n); + if (functionWrapperRegisterNow()) { // emit normal fns & static fns + registerMethod(luaCurrentSymbolNSpace(), n); } } else { if (!Getattr(n, "sym:nextSibling")) { - result = dispatchFunction(n); + result = dispatchFunction(n); } } @@ -816,11 +806,11 @@ public: * ------------------------------------------------------------ */ /* NEW LANGUAGE NOTE:*********************************************** - This is an extra function used for overloading of functions - it checks the args & then calls the relevant fn - nost of the real work in again typemaps: - look for %typecheck(SWIG_TYPECHECK_*) in the .swg file - NEW LANGUAGE NOTE:END ************************************************/ + This is an extra function used for overloading of functions + it checks the args & then calls the relevant fn + nost of the real work in again typemaps: + look for %typecheck(SWIG_TYPECHECK_*) in the .swg file + NEW LANGUAGE NOTE:END *********************************************** */ int dispatchFunction(Node *n) { //REPORT("dispatchFunction", n); /* Last node in overloaded chain */ @@ -855,7 +845,7 @@ public: Replaceall(dispatch, "$args", "self,args"); Printv(f->code, dispatch, "\n", NIL); - + Node *sibl = n; while (Getattr(sibl, "sym:previousSibling")) sibl = Getattr(sibl, "sym:previousSibling"); // go all the way up @@ -866,7 +856,7 @@ public: Delete(fulldecl); } while ((sibl = Getattr(sibl, "sym:nextSibling"))); Printf(f->code, "SWIG_Lua_pusherrstring(L,\"Wrong arguments for overloaded function '%s'\\n\"\n" - "\" Possible C/C++ prototypes are:\\n\"%s);\n",symname,protoTypes); + "\" Possible C/C++ prototypes are:\\n\"%s);\n", symname, protoTypes); Delete(protoTypes); Printf(f->code, "lua_error(L);return 0;\n"); @@ -876,12 +866,12 @@ public: // Remember C name of the wrapping function rememberWrapName(n, wname); - if (functionWrapperRegisterNow()) { // emit normal fns & static fns + if (functionWrapperRegisterNow()) { // emit normal fns & static fns registerMethod(luaCurrentSymbolNSpace(), n); } if (current[CONSTRUCTOR]) { - if( constructor_name != 0 ) - Delete(constructor_name); + if (constructor_name != 0) + Delete(constructor_name); constructor_name = Copy(wname); } @@ -899,45 +889,45 @@ public: // Add variable to the "attributes" (or "get"/"set" in // case of elua_ltr) C arrays of given namespace or class - void registerVariable(String *nspace_or_class_name, Node* n, const char *getAttrName, const char *setAttrName) { - String *unassignable = NewString("SWIG_Lua_set_immutable"); - String *getName = Getattr(n,getAttrName); - String *setName = Getattr(n,setAttrName); - if(setName == 0 || GetFlag(n, "feature:immutable")) { - setName = unassignable; - } - Hash* nspaceHash = getNamespaceHash( nspace_or_class_name ); - String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); - String* s_ns_var_tab = Getattr(nspaceHash, "attributes"); - String *target_name = Getattr(n, "lua:name"); - if (elua_ltr) { - String* s_ns_dot_get = Getattr(nspaceHash, "get"); - String* s_ns_dot_set = Getattr(nspaceHash, "set"); - Printf(s_ns_dot_get, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, target_name, getName); - Printf(s_ns_dot_set, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, target_name, setName); - } else if (eluac_ltr) { - Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", target_name, "_get", "\")", ", LFUNCVAL(", getName, ")", "},\n", NIL); - Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", target_name, "_set", "\")", ", LFUNCVAL(", setName, ")", "},\n", NIL); - } else { - Printf(s_ns_var_tab, "%s{ \"%s\", %s, %s },\n", tab4, target_name, getName, setName); - } + void registerVariable(String *nspace_or_class_name, Node *n, const char *getAttrName, const char *setAttrName) { + String *unassignable = NewString("SWIG_Lua_set_immutable"); + String *getName = Getattr(n, getAttrName); + String *setName = Getattr(n, setAttrName); + if (setName == 0 || GetFlag(n, "feature:immutable")) { + setName = unassignable; + } + Hash *nspaceHash = getNamespaceHash(nspace_or_class_name); + String *s_ns_methods_tab = Getattr(nspaceHash, "methods"); + String *s_ns_var_tab = Getattr(nspaceHash, "attributes"); + String *target_name = Getattr(n, "lua:name"); + if (elua_ltr) { + String *s_ns_dot_get = Getattr(nspaceHash, "get"); + String *s_ns_dot_set = Getattr(nspaceHash, "set"); + Printf(s_ns_dot_get, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, target_name, getName); + Printf(s_ns_dot_set, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, target_name, setName); + } else if (eluac_ltr) { + Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", target_name, "_get", "\")", ", LFUNCVAL(", getName, ")", "},\n", NIL); + Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", target_name, "_set", "\")", ", LFUNCVAL(", setName, ")", "},\n", NIL); + } else { + Printf(s_ns_var_tab, "%s{ \"%s\", %s, %s },\n", tab4, target_name, getName, setName); + } } virtual int variableWrapper(Node *n) { /* NEW LANGUAGE NOTE:*********************************************** - Language::variableWrapper(n) will generate two wrapper fns - Foo_get & Foo_set by calling functionWrapper() - so we will just add these into the variable lists - ideally we should not have registered these as functions, - only WRT this variable will look into this later. - NEW LANGUAGE NOTE:END ************************************************/ + Language::variableWrapper(n) will generate two wrapper fns + Foo_get & Foo_set by calling functionWrapper() + so we will just add these into the variable lists + ideally we should not have registered these as functions, + only WRT this variable will look into this later. + NEW LANGUAGE NOTE:END *********************************************** */ // REPORT("variableWrapper", n); String *target_name = Getattr(n, "lua:name"); assert(target_name != 0); current[VARIABLE] = true; // let SWIG generate the wrappers int result = Language::variableWrapper(n); - registerVariable( luaCurrentSymbolNSpace(), n, "varget:wrap:name", "varset:wrap:name" ); + registerVariable(luaCurrentSymbolNSpace(), n, "varget:wrap:name", "varset:wrap:name"); current[VARIABLE] = false; return result; } @@ -950,24 +940,24 @@ public: /* Add constant to appropriate C array. constantRecord is an array record. * Actually, in current implementation it is resolved consttab typemap */ - void registerConstant( String *nspace, String *constantRecord ) { - Hash *nspaceHash = getNamespaceHash( nspace ); - String *s_const_tab = 0; - if( eluac_ltr || elua_ltr ) - // In elua everything goes to "methods" tab - s_const_tab = Getattr(nspaceHash, "methods"); - else - s_const_tab = Getattr(nspaceHash, "constants"); + void registerConstant(String *nspace, String *constantRecord) { + Hash *nspaceHash = getNamespaceHash(nspace); + String *s_const_tab = 0; + if (eluac_ltr || elua_ltr) + // In elua everything goes to "methods" tab + s_const_tab = Getattr(nspaceHash, "methods"); + else + s_const_tab = Getattr(nspaceHash, "constants"); + assert(s_const_tab != 0); + Printf(s_const_tab, " %s,\n", constantRecord); + + if ((eluac_ltr || elua_ltr) && v2_compatibility) { + s_const_tab = Getattr(nspaceHash, "constants"); assert(s_const_tab != 0); Printf(s_const_tab, " %s,\n", constantRecord); + } - if( ( eluac_ltr || elua_ltr ) && v2_compatibility ) { - s_const_tab = Getattr(nspaceHash, "constants"); - assert(s_const_tab != 0); - Printf(s_const_tab, " %s,\n", constantRecord); - } - } virtual int constantWrapper(Node *n) { @@ -975,7 +965,7 @@ public: String *name = Getattr(n, "name"); String *iname = Getattr(n, "sym:name"); String *target_name = Getattr(n, "lua:name"); - if(target_name == 0) + if (target_name == 0) target_name = iname; String *nsname = Copy(iname); SwigType *type = Getattr(n, "type"); @@ -1005,7 +995,7 @@ public: Replaceall(tm, "$target", target_name); Replaceall(tm, "$value", value); Replaceall(tm, "$nsname", nsname); - registerConstant( luaCurrentSymbolNSpace(), tm); + registerConstant(luaCurrentSymbolNSpace(), tm); } else if ((tm = Swig_typemap_lookup("constcode", n, name, 0))) { Replaceall(tm, "$source", value); Replaceall(tm, "$target", target_name); @@ -1021,37 +1011,37 @@ public: bool make_v2_compatible = v2_compatibility && getCurrentClass() != 0; - if( make_v2_compatible ) { + if (make_v2_compatible) { target_name_v2 = Swig_name_member(0, class_symname, target_name); iname_v2 = Swig_name_member(0, class_symname, iname); n_v2 = Copy(n); //Printf( stdout, "target name v2: %s, symname v2 %s\n", target_name_v2.ptr(), iname_v2.ptr());// TODO:REMOVE if (!luaAddSymbol(iname_v2, n, class_parent_nspace)) { - return SWIG_ERROR; + return SWIG_ERROR; } Setattr(n_v2, "sym:name", target_name_v2); tm_v2 = Swig_typemap_lookup("consttab", n_v2, name, 0); if (tm_v2) { - //Printf(stdout, "tm v2: %s\n", tm_v2.ptr()); // TODO:REMOVE - Replaceall(tm_v2, "$source", value); - Replaceall(tm_v2, "$target", target_name_v2); - Replaceall(tm_v2, "$value", value); - Replaceall(tm_v2, "$nsname", nsname); - registerConstant( class_parent_nspace, tm_v2); + //Printf(stdout, "tm v2: %s\n", tm_v2.ptr()); // TODO:REMOVE + Replaceall(tm_v2, "$source", value); + Replaceall(tm_v2, "$target", target_name_v2); + Replaceall(tm_v2, "$value", value); + Replaceall(tm_v2, "$nsname", nsname); + registerConstant(class_parent_nspace, tm_v2); } else { - tm_v2 = Swig_typemap_lookup("constcode", n_v2, name, 0); - if( !tm_v2) { - // This can't be. - assert(false); - Swig_restore(n); - return SWIG_ERROR; - } - Replaceall(tm_v2, "$source", value); - Replaceall(tm_v2, "$target", target_name_v2); - Replaceall(tm_v2, "$value", value); - Replaceall(tm_v2, "$nsname", nsname); - Printf(f_init, "%s\n", tm_v2); + tm_v2 = Swig_typemap_lookup("constcode", n_v2, name, 0); + if (!tm_v2) { + // This can't be. + assert(false); + Swig_restore(n); + return SWIG_ERROR; + } + Replaceall(tm_v2, "$source", value); + Replaceall(tm_v2, "$target", target_name_v2); + Replaceall(tm_v2, "$value", value); + Replaceall(tm_v2, "$nsname", nsname); + Printf(f_init, "%s\n", tm_v2); } Delete(n_v2); } @@ -1072,8 +1062,8 @@ public: if (!luaAddSymbol(wrapname, n)) return SWIG_ERROR; - Hash *nspaceHash = getNamespaceHash( getNSpace() ); - String* s_ns_methods_tab = Getattr(nspaceHash, "methods"); + Hash *nspaceHash = getNamespaceHash(getNSpace()); + String *s_ns_methods_tab = Getattr(nspaceHash, "methods"); Printv(s_ns_methods_tab, tab4, "{ \"", symname, "\",", wrapname, "},\n", NIL); // return Language::nativeWrapper(n); // this does nothing... return SWIG_OK; @@ -1084,10 +1074,10 @@ public: * ------------------------------------------------------------ */ virtual int enumDeclaration(Node *n) { - current[STATIC_CONST] = true; - int result = Language::enumDeclaration(n); - current[STATIC_CONST] = false; - return result; + current[STATIC_CONST] = true; + int result = Language::enumDeclaration(n); + current[STATIC_CONST] = false; + return result; } /* ------------------------------------------------------------ @@ -1134,7 +1124,7 @@ public: String *mangled_class_fq_symname; String *destructor_name; - String* nspace = getNSpace(); + String *nspace = getNSpace(); constructor_name = 0; have_constructor = 0; @@ -1161,10 +1151,10 @@ public: assert(class_fq_symname != 0); mangled_class_fq_symname = Swig_name_mangle(class_fq_symname); - SwigType *t( Copy(Getattr(n, "name")) ); - SwigType *fr_t( SwigType_typedef_resolve_all(t) ); /* Create fully resolved type */ + SwigType *t(Copy(Getattr(n, "name"))); + SwigType *fr_t(SwigType_typedef_resolve_all(t)); /* Create fully resolved type */ SwigType *t_tmp = 0; - t_tmp = SwigType_typedef_qualified(fr_t); // Temporal variable + t_tmp = SwigType_typedef_qualified(fr_t); // Temporal variable Delete(fr_t); fr_t = SwigType_strip_qualifiers(t_tmp); String *mangled_fr_t = 0; @@ -1195,10 +1185,10 @@ public: // And we can guarantee that there will not be any name collision because names starting with 2 underscores // and capital letter are forbiden to use in C++. So, under know circumstances could our class contain // any member or subclass with name "__Static". Thus, never any name clash. - Hash* instance_cls = getNamespaceHash(class_fq_symname, false); + Hash *instance_cls = getNamespaceHash(class_fq_symname, false); assert(instance_cls != 0); - String* s_attr_tab_name = Getattr(instance_cls, "attributes:name"); - String* s_methods_tab_name = Getattr(instance_cls, "methods:name"); + String *s_attr_tab_name = Getattr(instance_cls, "attributes:name"); + String *s_methods_tab_name = Getattr(instance_cls, "methods:name"); Setattr(instance_cls, "lua:no_namespaces", "1"); Setattr(instance_cls, "lua:no_classes", "1"); Setattr(instance_cls, "lua:class_instance", "1"); @@ -1240,24 +1230,24 @@ public: // Adding class to apropriate namespace Hash *nspaceHash = getNamespaceHash(nspace); String *ns_classes = Getattr(nspaceHash, "classes"); - Printv( ns_classes, wrap_class, ",\n", NIL ); + Printv(ns_classes, wrap_class, ",\n", NIL); // Register the class structure with the type checker // Printf(f_init,"SWIG_TypeClientData(SWIGTYPE%s, (void *) &_wrap_class_%s);\n", SwigType_manglestr(t), mangled_class_fq_symname); - + // emit a function to be called to delete the object if (have_destructor) { destructor_name = NewStringf("swig_delete_%s", mangled_class_fq_symname); Printv(f_wrappers, "static void ", destructor_name, "(void *obj) {\n", NIL); if (destructor_action) { - Printv(f_wrappers, SwigType_str(rt, "arg1"), " = (", SwigType_str(rt, 0), ") obj;\n", NIL); - Printv(f_wrappers, destructor_action, "\n", NIL); + Printv(f_wrappers, SwigType_str(rt, "arg1"), " = (", SwigType_str(rt, 0), ") obj;\n", NIL); + Printv(f_wrappers, destructor_action, "\n", NIL); } else { - if (CPlusPlus) { - Printv(f_wrappers, " delete (", SwigType_str(rt, 0), ") obj;\n", NIL); - } else { - Printv(f_wrappers, " free((char *) obj);\n", NIL); - } + if (CPlusPlus) { + Printv(f_wrappers, " delete (", SwigType_str(rt, 0), ") obj;\n", NIL); + } else { + Printv(f_wrappers, " free((char *) obj);\n", NIL); + } } Printf(f_wrappers, "}\n"); } @@ -1266,33 +1256,32 @@ public: // Module.ClassName.StaticMethod to access static method/variable/constant // Module.ClassName() to create new object if (have_constructor) { - String* constructor_proxy_name = NewStringf("_proxy_%s", constructor_name); + String *constructor_proxy_name = NewStringf("_proxy_%s", constructor_name); Printv(f_wrappers, "static int ", constructor_proxy_name, "(lua_State *L) {\n", NIL); Printv(f_wrappers, - tab4, "assert(lua_istable(L,1));\n", - tab4, "lua_pushcfunction(L,", constructor_name, ");\n", - tab4, "assert(!lua_isnil(L,-1));\n", - tab4, "lua_replace(L,1); /* replace our table with real constructor */\n", - tab4, "lua_call(L,lua_gettop(L)-1,1);\n", - tab4, "return 1;\n}\n", NIL); + tab4, "assert(lua_istable(L,1));\n", + tab4, "lua_pushcfunction(L,", constructor_name, ");\n", + tab4, "assert(!lua_isnil(L,-1));\n", + tab4, "lua_replace(L,1); /* replace our table with real constructor */\n", + tab4, "lua_call(L,lua_gettop(L)-1,1);\n", + tab4, "return 1;\n}\n", NIL); Delete(constructor_name); constructor_name = constructor_proxy_name; if (elua_ltr) { - String* static_cls_metatable_tab = Getattr(static_cls, "metatable"); - assert(static_cls_metatable_tab != 0); - Printf(static_cls_metatable_tab, " {LSTRKEY(\"__call\"), LFUNCVAL(%s)},\n", constructor_name); + String *static_cls_metatable_tab = Getattr(static_cls, "metatable"); + assert(static_cls_metatable_tab != 0); + Printf(static_cls_metatable_tab, " {LSTRKEY(\"__call\"), LFUNCVAL(%s)},\n", constructor_name); } else if (eluac_ltr) { - String* ns_methods_tab = Getattr(nspaceHash, "methods"); - assert(ns_methods_tab != 0); - Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "new_", class_symname, "\")", ", LFUNCVAL(", \ - constructor_name, ")", "},\n", NIL); + String *ns_methods_tab = Getattr(nspaceHash, "methods"); + assert(ns_methods_tab != 0); + Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "new_", class_symname, "\")", ", LFUNCVAL(", constructor_name, ")", "},\n", NIL); } } if (have_destructor) { if (eluac_ltr) { - String* ns_methods_tab = Getattr(nspaceHash, "methods"); - assert(ns_methods_tab != 0); - Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "free_", mangled_class_fq_symname, "\")", ", LFUNCVAL(", destructor_name, ")", "},\n", NIL); + String *ns_methods_tab = Getattr(nspaceHash, "methods"); + assert(ns_methods_tab != 0); + Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "free_", mangled_class_fq_symname, "\")", ", LFUNCVAL(", destructor_name, ")", "},\n", NIL); } } @@ -1318,20 +1307,19 @@ public: int index = 0; b = First(baselist); while (b.item) { - String *bname = Getattr(b.item, "name"); - if ((!bname) || GetFlag(b.item, "feature:ignore") || (!Getattr(b.item, "module"))) { - b = Next(b); - continue; - } - // stores a null pointer & the name - Printf(base_class, "0,"); - Printf(base_class_names, "\"%s *\",", SwigType_namestr(bname)); + String *bname = Getattr(b.item, "name"); + if ((!bname) || GetFlag(b.item, "feature:ignore") || (!Getattr(b.item, "module"))) { + b = Next(b); + continue; + } + // stores a null pointer & the name + Printf(base_class, "0,"); + Printf(base_class_names, "\"%s *\",", SwigType_namestr(bname)); - b = Next(b); - index++; + b = Next(b); + index++; } } - // First, print class static part printNamespaceDefinition(class_static_nspace, class_symname, f_wrappers); @@ -1341,7 +1329,8 @@ public: Printv(f_wrappers, "static const char *swig_", mangled_class_fq_symname, "_base_names[] = {", base_class_names, "0};\n", NIL); Delete(base_class_names); - Printv(f_wrappers, "static swig_lua_class _wrap_class_", mangled_class_fq_symname, " = { \"", class_symname, "\", \"", class_fq_symname,"\", &SWIGTYPE", SwigType_manglestr(t), ",", NIL); + Printv(f_wrappers, "static swig_lua_class _wrap_class_", mangled_class_fq_symname, " = { \"", class_symname, "\", \"", class_fq_symname, "\", &SWIGTYPE", + SwigType_manglestr(t), ",", NIL); if (have_constructor) { Printv(f_wrappers, constructor_name, NIL); @@ -1352,13 +1341,12 @@ public: } if (have_destructor) { - Printv(f_wrappers, ", ", destructor_name, NIL); + Printv(f_wrappers, ", ", destructor_name, NIL); } else { Printf(f_wrappers, ",0"); } - Printf(f_wrappers, ", %s, %s, &%s", s_methods_tab_name, s_attr_tab_name, Getattr(static_cls, "cname") ); - Printf(f_wrappers, ", swig_%s_bases, swig_%s_base_names };\n\n", - mangled_class_fq_symname, mangled_class_fq_symname); + Printf(f_wrappers, ", %s, %s, &%s", s_methods_tab_name, s_attr_tab_name, Getattr(static_cls, "cname")); + Printf(f_wrappers, ", swig_%s_bases, swig_%s_base_names };\n\n", mangled_class_fq_symname, mangled_class_fq_symname); current[NO_CPP] = true; Delete(class_static_nspace); @@ -1393,7 +1381,7 @@ public: if (!Getattr(n, "sym:nextSibling")) { //Printf( stdout, "add member function: %s to %s\n", symname, luaCurrentSymbolNSpace());// TODO: REMOVE - registerMethod( luaCurrentSymbolNSpace(), n); + registerMethod(luaCurrentSymbolNSpace(), n); } current[MEMBER_FUNC] = false; return SWIG_OK; @@ -1407,7 +1395,7 @@ public: // REPORT("membervariableHandler",n); current[MEMBER_VAR] = true; Language::membervariableHandler(n); - registerVariable( luaCurrentSymbolNSpace(), n, "memberget:wrap:name", "memberset:wrap:name" ); + registerVariable(luaCurrentSymbolNSpace(), n, "memberget:wrap:name", "memberset:wrap:name"); current[MEMBER_VAR] = false; return SWIG_OK; } @@ -1451,7 +1439,7 @@ public: * ---------------------------------------------------------------------- */ int globalfunctionHandler(Node *n) { bool oldVal = current[NO_CPP]; - if(!current[STATIC_FUNC]) // If static funct, don't switch to NO_CPP + if (!current[STATIC_FUNC]) // If static funct, don't switch to NO_CPP current[NO_CPP] = true; int result = Language::globalfunctionHandler(n); current[NO_CPP] = oldVal; @@ -1473,12 +1461,12 @@ public: if (result != SWIG_OK) return result; - if(v2_compatibility) { + if (v2_compatibility) { Swig_require("lua_staticmemberfunctionHandler", n, "*lua:name", NIL); String *target_name = Getattr(n, "lua:name"); String *compat_name = Swig_name_member(0, class_symname, target_name); Setattr(n, "lua:name", compat_name); - registerMethod( class_parent_nspace, n ); + registerMethod(class_parent_nspace, n); Delete(compat_name); Swig_restore(n); } @@ -1493,7 +1481,7 @@ public: * ------------------------------------------------------------ */ virtual int memberconstantHandler(Node *n) { - REPORT("memberconstantHandler",n); + REPORT("memberconstantHandler", n); int result = Language::memberconstantHandler(n); return result; @@ -1504,27 +1492,27 @@ public: * --------------------------------------------------------------------- */ virtual int staticmembervariableHandler(Node *n) { - REPORT("staticmembervariableHandler",n); + REPORT("staticmembervariableHandler", n); current[STATIC_VAR] = true; //String *symname = Getattr(n, "sym:name"); int result = Language::staticmembervariableHandler(n); if (result == SWIG_OK) { // This will add static member variable to the class namespace with name ClassName_VarName - if(v2_compatibility) { - Swig_save("lua_staticmembervariableHandler",n,"lua:name"); - String *target_name = Getattr(n, "lua:name"); - String *v2_name = Swig_name_member(NIL, class_symname, target_name); - //Printf( stdout, "Name %s, class %s, compt. name %s\n", target_name, class_symname, v2_name ); // TODO: REMOVE - if( !GetFlag(n,"wrappedasconstant") ) { - Setattr(n, "lua:name", v2_name); - registerVariable( class_parent_nspace, n, "varget:wrap:name", "varset:wrap:name"); - } - // If static member variable was wrapped as constant, then - // constant wrapper has already performed all actions - // necessary for v2_compatibility - Delete(v2_name); - Swig_restore(n); + if (v2_compatibility) { + Swig_save("lua_staticmembervariableHandler", n, "lua:name"); + String *target_name = Getattr(n, "lua:name"); + String *v2_name = Swig_name_member(NIL, class_symname, target_name); + //Printf( stdout, "Name %s, class %s, compt. name %s\n", target_name, class_symname, v2_name ); // TODO: REMOVE + if (!GetFlag(n, "wrappedasconstant")) { + Setattr(n, "lua:name", v2_name); + registerVariable(class_parent_nspace, n, "varget:wrap:name", "varset:wrap:name"); + } + // If static member variable was wrapped as constant, then + // constant wrapper has already performed all actions + // necessary for v2_compatibility + Delete(v2_name); + Swig_restore(n); } } current[STATIC_VAR] = false; @@ -1546,7 +1534,7 @@ public: */ String *runtimeCode() { String *s = NewString(""); - const char *filenames[] = { "luarun.swg", 0 } ; // must be 0 terminated + const char *filenames[] = { "luarun.swg", 0 }; // must be 0 terminated emitLuaFlavor(s); @@ -1554,10 +1542,10 @@ public: for (int i = 0; filenames[i] != 0; i++) { sfile = Swig_include_sys(filenames[i]); if (!sfile) { - Printf(stderr, "*** Unable to open '%s'\n", filenames[i]); + Printf(stderr, "*** Unable to open '%s'\n", filenames[i]); } else { - Append(s, sfile); - Delete(sfile); + Append(s, sfile); + Delete(sfile); } } @@ -1567,7 +1555,7 @@ public: String *defaultExternalRuntimeFilename() { return NewString("swigluarun.h"); } - + /* --------------------------------------------------------------------- * helpers * --------------------------------------------------------------------- */ @@ -1580,75 +1568,73 @@ public: else Printf(s, "#define SWIG_LUA_TARGET SWIG_LUA_FLAVOR_LUA\n"); } - + /* This is to convert the string of Lua code into a proper string, which can then be emitted into the C/C++ code. Basically is is a lot of search & replacing of odd sequences */ - void EscapeCode(String* str) - { + void EscapeCode(String *str) { //Printf(f_runtime,"/* original luacode:[[[\n%s\n]]]\n*/\n",str); - Chop(str); // trim - Replace(str,"\\","\\\\",DOH_REPLACE_ANY); // \ to \\ (this must be done first) - Replace(str,"\"","\\\"",DOH_REPLACE_ANY); // " to \" - Replace(str,"\n","\\n\"\n \"",DOH_REPLACE_ANY); // \n to \n"\n" (ie quoting every line) + Chop(str); // trim + Replace(str, "\\", "\\\\", DOH_REPLACE_ANY); // \ to \\ (this must be done first) + Replace(str, "\"", "\\\"", DOH_REPLACE_ANY); // " to \" + Replace(str, "\n", "\\n\"\n \"", DOH_REPLACE_ANY); // \n to \n"\n" (ie quoting every line) //Printf(f_runtime,"/* hacked luacode:[[[\n%s\n]]]\n*/\n",str); - } + } /* Each namespace can be described with hash that stores C arrays - where members of the namespace should be added. All these hashes are stored - inside namespaces_hash. - nspace could be NULL (NSPACE_TODO), that means functions and variables and classes - that are not in any namespace (this is default for SWIG unless %nspace feature is used) - You can later set some attributes that will affect behaviour of functions that use this hash: - "lua:no_namespaces" will disable "namespaces" array. - "lua:no_classes" will disable "classes" array. - For every component ("attributes", "methods", etc) there are subcomponents: - * XXX:name - name of the C array that stores data for component - * XXX:decl - statement with forward declaration of this array; + where members of the namespace should be added. All these hashes are stored + inside namespaces_hash. + nspace could be NULL (NSPACE_TODO), that means functions and variables and classes + that are not in any namespace (this is default for SWIG unless %nspace feature is used) + You can later set some attributes that will affect behaviour of functions that use this hash: + "lua:no_namespaces" will disable "namespaces" array. + "lua:no_classes" will disable "classes" array. + For every component ("attributes", "methods", etc) there are subcomponents: + * XXX:name - name of the C array that stores data for component + * XXX:decl - statement with forward declaration of this array; */ - Hash* getNamespaceHash(String *nspace, bool reg = true) - { - Hash* nspace_hash = Getattr(namespaces_hash, nspace?nspace:"" ); + Hash *getNamespaceHash(String *nspace, bool reg = true) { + Hash *nspace_hash = Getattr(namespaces_hash, nspace ? nspace : ""); if (nspace_hash != 0) return nspace_hash; nspace_hash = NewHash(); - String* mangled_name = 0; + String *mangled_name = 0; if (nspace == 0 || Len(nspace) == 0) - mangled_name = NewString("__Global"); // C++ names can't start with "__ + capital letter" + mangled_name = NewString("__Global"); // C++ names can't start with "__ + capital letter" else mangled_name = Swig_name_mangle(nspace); - String* cname = NewStringf("swig_%s", mangled_name); + String *cname = NewStringf("swig_%s", mangled_name); if (reg && nspace != 0 && Len(nspace) != 0 && Getattr(nspace_hash, "lua:no_reg") == 0) { // Split names into components - List* components = Split(nspace, '.', -1); + List *components = Split(nspace, '.', -1); String *parent_path = NewString(""); int len = Len(components); - String* name = Copy(Getitem(components, len-1)); - for( int i = 0; i < len-1; i++ ) { - if (i > 0) - Printv(parent_path, NSPACE_SEPARATOR, NIL); - String* item = Getitem(components, i); - Printv(parent_path, item, NIL); + String *name = Copy(Getitem(components, len - 1)); + for (int i = 0; i < len - 1; i++) { + if (i > 0) + Printv(parent_path, NSPACE_SEPARATOR, NIL); + String *item = Getitem(components, i); + Printv(parent_path, item, NIL); } //Printf(stdout, "Registering %s. User name %s. C-name %s, Parent is %s\n", mangled_name, name, cname, parent_path); // TODO: REMOVE - Hash* parent = getNamespaceHash(parent_path, true); - String* namespaces_tab = Getattr(parent, "namespaces"); + Hash *parent = getNamespaceHash(parent_path, true); + String *namespaces_tab = Getattr(parent, "namespaces"); Printv(namespaces_tab, "&", cname, ",\n", NIL); Setattr(nspace_hash, "name", name); Delete(components); Delete(parent_path); - } else if (!reg) // This namespace shouldn't be registered. Lets remember it + } else if (!reg) // This namespace shouldn't be registered. Lets remember it Setattr(nspace_hash, "lua:no_reg", "1"); Setattr(nspace_hash, "cname", cname); String *attr_tab = NewString(""); - String *attr_tab_name = NewStringf("swig_%s_attributes", mangled_name ); + String *attr_tab_name = NewStringf("swig_%s_attributes", mangled_name); String *attr_tab_decl = NewString(""); Printv(attr_tab, "static swig_lua_attribute ", NIL); Printv(attr_tab, attr_tab_name, "[]", NIL); @@ -1659,54 +1645,54 @@ public: Setattr(nspace_hash, "attributes:decl", attr_tab_decl); String *methods_tab = NewString(""); - String *methods_tab_name = NewStringf("swig_%s_methods", mangled_name ); + String *methods_tab_name = NewStringf("swig_%s_methods", mangled_name); String *methods_tab_decl = NewString(""); - if (elua_ltr || eluac_ltr) // In this case methods array also acts as namespace rotable + if (elua_ltr || eluac_ltr) // In this case methods array also acts as namespace rotable Printf(methods_tab, "const LUA_REG_TYPE "); else Printf(methods_tab, "static swig_lua_method "); Printv(methods_tab, methods_tab_name, "[]", NIL); Printv(methods_tab_decl, methods_tab, ";\n", NIL); Printv(methods_tab, "= {\n", NIL); - Setattr(nspace_hash, "methods", methods_tab ); - Setattr(nspace_hash, "methods:name", methods_tab_name ); - Setattr(nspace_hash, "methods:decl", methods_tab_decl ); + Setattr(nspace_hash, "methods", methods_tab); + Setattr(nspace_hash, "methods:name", methods_tab_name); + Setattr(nspace_hash, "methods:decl", methods_tab_decl); String *const_tab = NewString(""); - String *const_tab_name = NewStringf("swig_%s_constants", mangled_name ); + String *const_tab_name = NewStringf("swig_%s_constants", mangled_name); String *const_tab_decl = NewString(""); - if (elua_ltr || eluac_ltr) // In this case const array holds rotable with namespace constants + if (elua_ltr || eluac_ltr) // In this case const array holds rotable with namespace constants Printf(const_tab, "const LUA_REG_TYPE "); else Printf(const_tab, "static swig_lua_const_info "); Printv(const_tab, const_tab_name, "[]", NIL); Printv(const_tab_decl, const_tab, ";", NIL); Printv(const_tab, "= {\n", NIL); - Setattr(nspace_hash, "constants", const_tab ); - Setattr(nspace_hash, "constants:name", const_tab_name ); - Setattr(nspace_hash, "constants:decl", const_tab_decl ); + Setattr(nspace_hash, "constants", const_tab); + Setattr(nspace_hash, "constants:name", const_tab_name); + Setattr(nspace_hash, "constants:decl", const_tab_decl); String *classes_tab = NewString(""); - String *classes_tab_name = NewStringf("swig_%s_classes", mangled_name ); + String *classes_tab_name = NewStringf("swig_%s_classes", mangled_name); String *classes_tab_decl = NewString(""); Printf(classes_tab, "static swig_lua_class* "); Printv(classes_tab, classes_tab_name, "[]", NIL); Printv(classes_tab_decl, classes_tab, ";", NIL); Printv(classes_tab, "= {\n", NIL); - Setattr(nspace_hash, "classes", classes_tab ); - Setattr(nspace_hash, "classes:name", classes_tab_name ); - Setattr(nspace_hash, "classes:decl", classes_tab_decl ); + Setattr(nspace_hash, "classes", classes_tab); + Setattr(nspace_hash, "classes:name", classes_tab_name); + Setattr(nspace_hash, "classes:decl", classes_tab_decl); - String* namespaces_tab = NewString(""); - String* namespaces_tab_name = NewStringf("swig_%s_namespaces", mangled_name ); - String* namespaces_tab_decl = NewString(""); + String *namespaces_tab = NewString(""); + String *namespaces_tab_name = NewStringf("swig_%s_namespaces", mangled_name); + String *namespaces_tab_decl = NewString(""); Printf(namespaces_tab, "static swig_lua_namespace* "); Printv(namespaces_tab, namespaces_tab_name, "[]", NIL); Printv(namespaces_tab_decl, namespaces_tab, ";", NIL); Printv(namespaces_tab, " = {\n", NIL); - Setattr(nspace_hash, "namespaces", namespaces_tab ); - Setattr(nspace_hash, "namespaces:name", namespaces_tab_name ); - Setattr(nspace_hash, "namespaces:decl", namespaces_tab_decl ); + Setattr(nspace_hash, "namespaces", namespaces_tab); + Setattr(nspace_hash, "namespaces:name", namespaces_tab_name); + Setattr(nspace_hash, "namespaces:decl", namespaces_tab_decl); if (elua_ltr) { String *get_tab = NewString(""); @@ -1730,21 +1716,21 @@ public: Setattr(nspace_hash, "set:decl", set_tab_decl); if (!eluac_ltr) { - String* metatable_tab = NewString(""); - String* metatable_tab_name = NewStringf("swig_%s_meta", mangled_name); - String *metatable_tab_decl = NewString(""); - Printv(metatable_tab, "const LUA_REG_TYPE ", metatable_tab_name, "[]", NIL); - Printv(metatable_tab_decl, metatable_tab, ";", NIL); - Printv(metatable_tab, " = {\n", NIL); - Setattr(nspace_hash, "metatable", metatable_tab); - Setattr(nspace_hash, "metatable:name", metatable_tab_name); - Setattr(nspace_hash, "metatable:decl", metatable_tab_decl); + String *metatable_tab = NewString(""); + String *metatable_tab_name = NewStringf("swig_%s_meta", mangled_name); + String *metatable_tab_decl = NewString(""); + Printv(metatable_tab, "const LUA_REG_TYPE ", metatable_tab_name, "[]", NIL); + Printv(metatable_tab_decl, metatable_tab, ";", NIL); + Printv(metatable_tab, " = {\n", NIL); + Setattr(nspace_hash, "metatable", metatable_tab); + Setattr(nspace_hash, "metatable:name", metatable_tab_name); + Setattr(nspace_hash, "metatable:decl", metatable_tab_decl); } } - String* key = 0; + String *key = 0; if (nspace != 0) key = Copy(nspace); - Setattr(namespaces_hash, key?key:"", nspace_hash); + Setattr(namespaces_hash, key ? key : "", nspace_hash); Delete(mangled_name); return nspace_hash; @@ -1758,20 +1744,19 @@ public: * if "lua:no_namespaces" is set, then array for "namespaces" won't be printed * if "lua:no_classes" is set, then array for "classes" won't be printed * */ - void closeNamespaceHash(String *nspace, File *output) - { - Hash* nspace_hash = Getattr(namespaces_hash, nspace ); + void closeNamespaceHash(String *nspace, File *output) { + Hash *nspace_hash = Getattr(namespaces_hash, nspace); assert(nspace_hash != 0); assert(Getattr(nspace_hash, "lua:closed") == 0); Setattr(nspace_hash, "lua:closed", "1"); - String* attr_tab = Getattr(nspace_hash, "attributes"); + String *attr_tab = Getattr(nspace_hash, "attributes"); Printf(attr_tab, " {0,0,0}\n};\n"); Printv(output, attr_tab, NIL); - String* const_tab = Getattr(nspace_hash, "constants"); - String* const_tab_name = Getattr(nspace_hash, "constants:name"); + String *const_tab = Getattr(nspace_hash, "constants"); + String *const_tab_name = Getattr(nspace_hash, "constants:name"); if (elua_ltr || eluac_ltr) Printv(const_tab, tab4, "{LNILKEY, LNILVAL}\n", "};\n", NIL); else @@ -1782,27 +1767,27 @@ public: // Put forward declaration of metatable array Printv(output, "extern ", Getattr(nspace_hash, "metatable:decl"), "\n", NIL); } - String* methods_tab = Getattr(nspace_hash, "methods"); - String* metatable_tab_name = Getattr(nspace_hash, "metatable:name"); + String *methods_tab = Getattr(nspace_hash, "methods"); + String *metatable_tab_name = Getattr(nspace_hash, "metatable:name"); if (elua_ltr || eluac_ltr) { - if( v2_compatibility ) - Printv(methods_tab, tab4, "{LSTRKEY(\"const\"), LROVAL(", const_tab_name, ")},\n", NIL); + if (v2_compatibility) + Printv(methods_tab, tab4, "{LSTRKEY(\"const\"), LROVAL(", const_tab_name, ")},\n", NIL); if (elua_ltr) - Printv(methods_tab, tab4, "{LSTRKEY(\"__metatable\"), LROVAL(", metatable_tab_name, ")},\n", NIL); + Printv(methods_tab, tab4, "{LSTRKEY(\"__metatable\"), LROVAL(", metatable_tab_name, ")},\n", NIL); Printv(methods_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); } else Printf(methods_tab, " {0,0}\n};\n"); Printv(output, methods_tab, NIL); - if (!Getattr(nspace_hash, "lua:no_classes") ) { - String* classes_tab = Getattr(nspace_hash, "classes"); + if (!Getattr(nspace_hash, "lua:no_classes")) { + String *classes_tab = Getattr(nspace_hash, "classes"); Printf(classes_tab, " 0\n};\n"); Printv(output, classes_tab, NIL); } - if (!Getattr(nspace_hash, "lua:no_namespaces") ) { - String* namespaces_tab = Getattr(nspace_hash, "namespaces"); + if (!Getattr(nspace_hash, "lua:no_namespaces")) { + String *namespaces_tab = Getattr(nspace_hash, "namespaces"); Printf(namespaces_tab, " 0\n};\n"); Printv(output, namespaces_tab, NIL); } @@ -1823,21 +1808,21 @@ public: Printv(metatable_tab, tab4, "{LSTRKEY(\".get\"), LROVAL(", get_tab_name, ")},\n", NIL); Printv(metatable_tab, tab4, "{LSTRKEY(\".set\"), LROVAL(", set_tab_name, ")},\n", NIL); if (Getattr(nspace_hash, "lua:class_instance")) { - String *static_cls = Getattr(nspace_hash, "lua:class_instance:static_hash"); - assert(static_cls != 0); - // static_cls is swig_lua_namespace. This structure can't be use with eLua(LTR) - // Instead structure describing its methods isused - String *static_cls_cname = Getattr(static_cls, "methods:name"); - assert(static_cls_cname != 0); - Printv(metatable_tab, tab4, "{LSTRKEY(\".static\"), LROVAL(", static_cls_cname, ")},\n", NIL); - // Put forward declaration of this array - Printv(output, "extern ", Getattr(static_cls, "methods:decl"), "\n", NIL); - } else if (Getattr(nspace_hash, "lua:class_static") ) { - Hash *instance_cls = Getattr(nspace_hash, "lua:class_static:instance_hash"); - assert(instance_cls != 0); - String *instance_cls_metatable_name = Getattr(instance_cls, "metatable:name"); - assert(instance_cls_metatable_name != 0); - Printv(metatable_tab, tab4, "{LSTRKEY(\".instance\"), LROVAL(", instance_cls_metatable_name, ")},\n", NIL); + String *static_cls = Getattr(nspace_hash, "lua:class_instance:static_hash"); + assert(static_cls != 0); + // static_cls is swig_lua_namespace. This structure can't be use with eLua(LTR) + // Instead structure describing its methods isused + String *static_cls_cname = Getattr(static_cls, "methods:name"); + assert(static_cls_cname != 0); + Printv(metatable_tab, tab4, "{LSTRKEY(\".static\"), LROVAL(", static_cls_cname, ")},\n", NIL); + // Put forward declaration of this array + Printv(output, "extern ", Getattr(static_cls, "methods:decl"), "\n", NIL); + } else if (Getattr(nspace_hash, "lua:class_static")) { + Hash *instance_cls = Getattr(nspace_hash, "lua:class_static:instance_hash"); + assert(instance_cls != 0); + String *instance_cls_metatable_name = Getattr(instance_cls, "metatable:name"); + assert(instance_cls_metatable_name != 0); + Printv(metatable_tab, tab4, "{LSTRKEY(\".instance\"), LROVAL(", instance_cls_metatable_name, ")},\n", NIL); } Printv(metatable_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); @@ -1846,36 +1831,37 @@ public: Printv(output, "\n", NIL); } - static int compareByLen( const DOH* f, const DOH* s) { return Len(s) - Len(f); } + static int compareByLen(const DOH *f, const DOH *s) { + return Len(s) - Len(f); + } // Recursively close all non-closed namespaces. Prints data to dataOutput, - void closeNamespaces(File *dataOutput) - { + void closeNamespaces(File *dataOutput) { // Special handling for empty module. - if( Getattr(namespaces_hash, "") == 0 ) { + if (Getattr(namespaces_hash, "") == 0) { // Module is empty. Create hash for global scope in order to have swig__Global // variable in resulting file getNamespaceHash(0); } Iterator ki = First(namespaces_hash); - List* to_close = NewList(); + List *to_close = NewList(); while (ki.key) { if (Getattr(ki.item, "lua:closed") == 0) - Append(to_close, ki.key); + Append(to_close, ki.key); ki = Next(ki); } SortList(to_close, &compareByLen); int len = Len(to_close); - for( int i = 0; i < len; i++ ) { - String* key = Getitem(to_close,i); + for (int i = 0; i < len; i++) { + String *key = Getitem(to_close, i); closeNamespaceHash(key, dataOutput); - Hash* nspace = Getattr(namespaces_hash, key); - String *name = 0; // name - name of the namespace as it should be visible in Lua - if (DohLen(key) == 0) // This is global module - name = module; + Hash *nspace = Getattr(namespaces_hash, key); + String *name = 0; // name - name of the namespace as it should be visible in Lua + if (DohLen(key) == 0) // This is global module + name = module; else - name = Getattr(nspace, "name"); + name = Getattr(nspace, "name"); assert(name != 0); - printNamespaceDefinition( key, name, dataOutput ); + printNamespaceDefinition(key, name, dataOutput); } Delete(to_close); } @@ -1885,11 +1871,10 @@ public: // You can call this function as many times as necessary. // 'name' is a user-visible name that this namespace will have in Lua. It shouldn't // be fully qualified name, just it's own name. - void printNamespaceDefinition(String *nspace, String* name, File *output) - { + void printNamespaceDefinition(String *nspace, String *name, File *output) { Hash *nspace_hash = getNamespaceHash(nspace, false); - String* cname = Getattr(nspace_hash, "cname"); // cname - name of the C structure that describes namespace + String *cname = Getattr(nspace_hash, "cname"); // cname - name of the C structure that describes namespace assert(cname != 0); Printv(output, "static swig_lua_namespace ", cname, " = ", NIL); @@ -1904,14 +1889,12 @@ public: bool has_namespaces = Getattr(nspace_hash, "lua:no_namespaces") == 0; Printv(output, "{\n", - tab4, "\"", name, "\",\n", - tab4, methods_tab_name, ",\n", - tab4, attr_tab_name, ",\n", - tab4, const_tab_name, ",\n", - tab4, (has_classes)?classes_tab_name:null_string, ",\n", - tab4, (has_namespaces)?namespaces_tab_name:null_string, "\n};\n", - NIL - ); + tab4, "\"", name, "\",\n", + tab4, methods_tab_name, ",\n", + tab4, attr_tab_name, ",\n", + tab4, const_tab_name, ",\n", + tab4, (has_classes) ? classes_tab_name : null_string, ",\n", + tab4, (has_namespaces) ? namespaces_tab_name : null_string, "\n};\n", NIL); Delete(null_string); } @@ -1921,22 +1904,22 @@ public: // instance class member/function or just global functions decides // where symbol should be put. // The namespace/scope doesn't depend from symbol, only from 'current' - String* luaCurrentSymbolNSpace() { - String* scope = 0; + String *luaCurrentSymbolNSpace() { + String *scope = 0; // If ouside class, than NSpace is used. // If inside class, but current[NO_CPP], then this is friend function. It belongs to NSpace - if( !getCurrentClass() || current[NO_CPP]) { + if (!getCurrentClass() || current[NO_CPP]) { scope = getNSpace(); } else { // If inside class, then either class static namespace or class fully qualified name is used assert(!current[NO_CPP]); - if(current[STATIC_FUNC] || current[STATIC_VAR] || current[STATIC_CONST] ) { - scope = class_static_nspace; - } else if(current[MEMBER_VAR] || current[CONSTRUCTOR] || current[DESTRUCTOR] - || current[MEMBER_FUNC] ) { - scope = class_fq_symname; - } else { // Friend functions are handled this way - scope = class_static_nspace; + if (current[STATIC_FUNC] || current[STATIC_VAR] || current[STATIC_CONST]) { + scope = class_static_nspace; + } else if (current[MEMBER_VAR] || current[CONSTRUCTOR] || current[DESTRUCTOR] + || current[MEMBER_FUNC]) { + scope = class_fq_symname; + } else { // Friend functions are handled this way + scope = class_static_nspace; } assert(scope != 0); } @@ -1947,35 +1930,34 @@ public: int luaAddSymbol(const String *s, const Node *n) { String *scope = luaCurrentSymbolNSpace(); //Printf(stdout, "luaAddSymbol: %s scope: %s\n", s, scope); - int result = Language::addSymbol(s,n,scope); - if( !result ) - Printf(stderr,"addSymbol(%s to scope %s) failed\n",s, scope); + int result = Language::addSymbol(s, n, scope); + if (!result) + Printf(stderr, "addSymbol(%s to scope %s) failed\n", s, scope); return result; } // Overload. Enforces given scope. Actually, it simply forwards call to Language::addSymbol - int luaAddSymbol(const String*s, const Node*n, const_String_or_char_ptr scope) { + int luaAddSymbol(const String *s, const Node *n, const_String_or_char_ptr scope) { //Printf(stdout, "luaAddSymbol: %s scope: %s\n", s, scope); - int result = Language::addSymbol(s,n,scope); - if( !result ) - Printf(stderr,"addSymbol(%s to scope %s) failed\n",s, scope); + int result = Language::addSymbol(s, n, scope); + if (!result) + Printf(stderr, "addSymbol(%s to scope %s) failed\n", s, scope); return result; } // Function creates fully qualified name of given symbol. Current NSpace and current class // are used - String* fully_qualified_name(const_String_or_char_ptr name) - { + String *fully_qualified_name(const_String_or_char_ptr name) { assert(name != 0); - String* scope= 0; - if( getCurrentClass() ) + String *scope = 0; + if (getCurrentClass()) scope = class_fq_symname; else scope = getNSpace(); String *fqname = 0; - if( scope ) - fqname = NewStringf("%s::%s",scope,name); + if (scope) + fqname = NewStringf("%s::%s", scope, name); else fqname = Copy(name); @@ -1984,10 +1966,9 @@ public: // Input: symname // Output - wrapper around fully qualified form of symname - String* symname_wrapper( String *symname) - { + String *symname_wrapper(String *symname) { String *fqname = fully_qualified_name(symname); - String* wname = Swig_name_wrapper(fqname); + String *wname = Swig_name_wrapper(fqname); Delete(fqname); return wname; } From eb7c0f011b173728f928163d5a1f2812aaf7119f Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Mon, 11 Nov 2013 18:19:12 +0400 Subject: [PATCH 406/481] Manually beautifying luarun.swg --- Lib/lua/luarun.swg | 106 ++++++++++++++++++++++----------------------- 1 file changed, 53 insertions(+), 53 deletions(-) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index fb8b0c89f..ff807a785 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -254,7 +254,7 @@ it gets the address, casts it, then dereferences it */ /* storing/access of swig_module_info */ SWIGRUNTIME swig_module_info * -SWIG_Lua_GetModule(lua_State* L) { +SWIG_Lua_GetModule(lua_State *L) { swig_module_info *ret = 0; lua_pushstring(L,"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME); lua_rawget(L,LUA_REGISTRYINDEX); @@ -265,7 +265,7 @@ SWIG_Lua_GetModule(lua_State* L) { } SWIGRUNTIME void -SWIG_Lua_SetModule(lua_State* L, swig_module_info *module) { +SWIG_Lua_SetModule(lua_State *L, swig_module_info *module) { /* add this all into the Lua registry: */ lua_pushstring(L,"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME); lua_pushlightuserdata(L,(void*)module); @@ -279,7 +279,7 @@ SWIG_Lua_SetModule(lua_State* L, swig_module_info *module) { /* this function is called when trying to set an immutable. default action is to print an error. This can removed with a compile flag SWIGLUA_IGNORE_SET_IMMUTABLE */ -SWIGINTERN int SWIG_Lua_set_immutable(lua_State* L) +SWIGINTERN int SWIG_Lua_set_immutable(lua_State *L) { /* there should be 1 param passed in: the new value */ #ifndef SWIGLUA_IGNORE_SET_IMMUTABLE @@ -293,7 +293,7 @@ SWIGINTERN int SWIG_Lua_set_immutable(lua_State* L) * global variable support code: namespaces and modules (which are the same thing) * ----------------------------------------------------------------------------- */ -SWIGINTERN int SWIG_Lua_namespace_get(lua_State* L) +SWIGINTERN int SWIG_Lua_namespace_get(lua_State *L) { /* there should be 2 params passed in (1) table (not the meta table) @@ -330,7 +330,7 @@ SWIGINTERN int SWIG_Lua_namespace_get(lua_State* L) return 0; } -SWIGINTERN int SWIG_Lua_namespace_set(lua_State* L) +SWIGINTERN int SWIG_Lua_namespace_set(lua_State *L) { /* there should be 3 params passed in (1) table (not the meta table) @@ -361,12 +361,12 @@ SWIGINTERN int SWIG_Lua_namespace_set(lua_State* L) } #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) // In elua this is useless -SWIGINTERN void SWIG_Lua_InstallConstants(lua_State* L, swig_lua_const_info constants[]); // forward declaration -SWIGINTERN void SWIG_Lua_add_variable(lua_State* L,const char* name,lua_CFunction getFn,lua_CFunction setFn); // forward declaration -SWIGINTERN void SWIG_Lua_class_register(lua_State* L,swig_lua_class* clss); +SWIGINTERN void SWIG_Lua_InstallConstants(lua_State *L, swig_lua_const_info constants[]); // forward declaration +SWIGINTERN void SWIG_Lua_add_variable(lua_State *L,const char *name,lua_CFunction getFn,lua_CFunction setFn); // forward declaration +SWIGINTERN void SWIG_Lua_class_register(lua_State *L,swig_lua_class *clss); /* helper function - register namespace methods and attributes into namespace */ -SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State* L, swig_lua_namespace* ns) +SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State *L, swig_lua_namespace *ns) { int i = 0; /* There must be namespace table (not metatable) at the top of the stack */ @@ -391,12 +391,12 @@ SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State* L, swig_lua_namespace* /* Register all classes in the namespace */ -SWIGINTERN void SWIG_Lua_add_namespace_classes(lua_State* L, swig_lua_namespace* ns) +SWIGINTERN void SWIG_Lua_add_namespace_classes(lua_State *L, swig_lua_namespace *ns) { // There must be module/namespace table at the top of the stack assert(lua_istable(L,-1)); - swig_lua_class** classes = ns->ns_classes; + swig_lua_class **classes = ns->ns_classes; if( classes != 0 ) { while(*classes != 0) { @@ -411,7 +411,7 @@ SWIGINTERN void SWIG_Lua_add_namespace_classes(lua_State* L, swig_lua_namespace* when function is called) Function always returns newly registered table on top of the stack */ -SWIGINTERN int SWIG_Lua_namespace_register(lua_State* L, swig_lua_namespace* ns, int reg) +SWIGINTERN int SWIG_Lua_namespace_register(lua_State *L, swig_lua_namespace *ns, int reg) { int begin = lua_gettop(L); assert(lua_istable(L,-1)); /* just in case. This is supposed to be module table or parent namespace table */ @@ -443,7 +443,7 @@ SWIGINTERN int SWIG_Lua_namespace_register(lua_State* L, swig_lua_namespace* ns, // Register classes SWIG_Lua_add_namespace_classes(L,ns); - swig_lua_namespace** sub_namespace = ns->ns_namespaces; + swig_lua_namespace **sub_namespace = ns->ns_namespaces; if( sub_namespace != 0) { while(*sub_namespace != 0) { SWIG_Lua_namespace_register(L, *sub_namespace, 1); @@ -464,7 +464,7 @@ SWIGINTERN int SWIG_Lua_namespace_register(lua_State* L, swig_lua_namespace* ns, * global variable support code: classes * ----------------------------------------------------------------------------- */ -SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State* L,const char* cname); +SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State *L,const char *cname); /* Macroses for iteration among class bases */ #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) @@ -485,7 +485,7 @@ SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State* L,const char* cname); #else // en elua .bases table doesn't exist. Use table from swig_lua_class #define SWIG_LUA_INIT_BASE_SEARCH(bases_count)\ - swig_module_info* module=SWIG_GetModule(L);\ + swig_module_info *module=SWIG_GetModule(L);\ swig_lua_class **bases= ((swig_lua_class*)(swig_type->clientdata))->bases;\ const char **base_names= ((swig_lua_class*)(swig_type->clientdata))->base_names;\ bases_count = 0;\ @@ -505,7 +505,7 @@ SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State* L,const char* cname); typedef int (*swig_lua_base_iterator_func)(lua_State*,swig_type_info*, int, int *ret); -int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info* swig_type, int first_arg, swig_lua_base_iterator_func func, int * const ret) +int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info *swig_type, int first_arg, swig_lua_base_iterator_func func, int *const ret) { // first_arg - position of the object in stack. Everything that is above are arguments // and is passed to every evocation of the func @@ -638,7 +638,7 @@ SWIGINTERN int SWIG_Lua_class_do_get(lua_State *L, swig_type_info *type, int fi /* the class.get method, performs the lookup of class attributes */ -SWIGINTERN int SWIG_Lua_class_get(lua_State* L) +SWIGINTERN int SWIG_Lua_class_get(lua_State *L) { /* there should be 2 params passed in (1) userdata (not the meta table) @@ -658,7 +658,7 @@ SWIGINTERN int SWIG_Lua_class_get(lua_State* L) /* helper for the class.set method, performs the lookup of class attributes * It returns error code. Number of function return values is passed inside 'ret' */ -SWIGINTERN int SWIG_Lua_class_do_set(lua_State* L, swig_type_info *type, int first_arg, int *ret) +SWIGINTERN int SWIG_Lua_class_do_set(lua_State *L, swig_type_info *type, int first_arg, int *ret) { /* there should be 3 params passed in (1) table (not the meta table) @@ -720,7 +720,7 @@ SWIGINTERN int SWIG_Lua_class_do_set(lua_State* L, swig_type_info *type, int fi /* This is actuall method exported to Lua. It calls SWIG_Lua_class_do_set and correctly * handlers return value */ -SWIGINTERN int SWIG_Lua_class_set(lua_State* L) +SWIGINTERN int SWIG_Lua_class_set(lua_State *L) { /* there should be 3 params passed in (1) table (not the meta table) @@ -742,12 +742,12 @@ SWIGINTERN int SWIG_Lua_class_set(lua_State* L) } /* the class.destruct method called by the interpreter */ -SWIGINTERN int SWIG_Lua_class_destruct(lua_State* L) +SWIGINTERN int SWIG_Lua_class_destruct(lua_State *L) { /* there should be 1 params passed in (1) userdata (not the meta table) */ - swig_lua_userdata* usr; - swig_lua_class* clss; + swig_lua_userdata *usr; + swig_lua_class *clss; assert(lua_isuserdata(L,-1)); /* just in case */ usr=(swig_lua_userdata*)lua_touserdata(L,-1); /* get it */ /* if must be destroyed & has a destructor */ @@ -763,7 +763,7 @@ SWIGINTERN int SWIG_Lua_class_destruct(lua_State* L) } /* the class.__tostring method called by the interpreter and print */ -SWIGINTERN int SWIG_Lua_class_tostring(lua_State* L) +SWIGINTERN int SWIG_Lua_class_tostring(lua_State *L) { /* there should be 1 param passed in (1) userdata (not the metatable) */ @@ -773,7 +773,7 @@ SWIGINTERN int SWIG_Lua_class_tostring(lua_State* L) assert(lua_istable(L,-1)); /* just in case */ lua_getfield(L, -1, ".type"); - const char* className = lua_tostring(L, -1); + const char *className = lua_tostring(L, -1); char output[256]; snprintf(output, 255, "<%s userdata: %lX>", className, userData); @@ -783,11 +783,11 @@ SWIGINTERN int SWIG_Lua_class_tostring(lua_State* L) } /* to manually disown some userdata */ -SWIGINTERN int SWIG_Lua_class_disown(lua_State* L) +SWIGINTERN int SWIG_Lua_class_disown(lua_State *L) { /* there should be 1 params passed in (1) userdata (not the meta table) */ - swig_lua_userdata* usr; + swig_lua_userdata *usr; assert(lua_isuserdata(L,-1)); /* just in case */ usr=(swig_lua_userdata*)lua_touserdata(L,-1); /* get it */ @@ -796,7 +796,7 @@ SWIGINTERN int SWIG_Lua_class_disown(lua_State* L) } /* gets the swig class registry (or creates it) */ -SWIGINTERN void SWIG_Lua_get_class_registry(lua_State* L) +SWIGINTERN void SWIG_Lua_get_class_registry(lua_State *L) { /* add this all into the swig registry: */ lua_pushstring(L,"SWIG"); @@ -814,7 +814,7 @@ SWIGINTERN void SWIG_Lua_get_class_registry(lua_State* L) } /* helper fn to get the classes metatable from the register */ -SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State* L,const char* cname) +SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State *L,const char *cname) { SWIG_Lua_get_class_registry(L); /* get the registry */ lua_pushstring(L,cname); /* get the name */ @@ -829,10 +829,10 @@ It cannot be done at compile time, as this will not work with hireachies spread over more than one swig file. Therefore it must be done at runtime, querying the SWIG type system. */ -SWIGINTERN void SWIG_Lua_init_base_class(lua_State* L,swig_lua_class* clss) +SWIGINTERN void SWIG_Lua_init_base_class(lua_State *L,swig_lua_class *clss) { int i=0; - swig_module_info* module=SWIG_GetModule(L); + swig_module_info *module=SWIG_GetModule(L); for(i=0;clss->base_names[i];i++) { if (clss->bases[i]==0) /* not found yet */ @@ -846,7 +846,7 @@ SWIGINTERN void SWIG_Lua_init_base_class(lua_State* L,swig_lua_class* clss) #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) // In elua this is useless /* helper add a variable to a registered class */ -SWIGINTERN void SWIG_Lua_add_variable(lua_State* L,const char* name,lua_CFunction getFn,lua_CFunction setFn) +SWIGINTERN void SWIG_Lua_add_variable(lua_State *L,const char *name,lua_CFunction getFn,lua_CFunction setFn) { assert(lua_istable(L,-1)); /* just in case */ SWIG_Lua_get_table(L,".get"); /* find the .get table */ @@ -863,7 +863,7 @@ SWIGINTERN void SWIG_Lua_add_variable(lua_State* L,const char* name,lua_CFuncti } /* helper to recursively add class static details (static attributes, operations and constants) */ -SWIGINTERN void SWIG_Lua_add_class_static_details(lua_State* L, swig_lua_class* clss) +SWIGINTERN void SWIG_Lua_add_class_static_details(lua_State *L, swig_lua_class *clss) { int i = 0; /* The class namespace table must be on the top of the stack */ @@ -878,7 +878,7 @@ SWIGINTERN void SWIG_Lua_add_class_static_details(lua_State* L, swig_lua_class* } /* helper to recursively add class details (attributes & operations) */ -SWIGINTERN void SWIG_Lua_add_class_instance_details(lua_State* L,swig_lua_class* clss) +SWIGINTERN void SWIG_Lua_add_class_instance_details(lua_State *L,swig_lua_class *clss) { int i; // Add bases to .bases table @@ -918,7 +918,7 @@ SWIGINTERN void SWIG_Lua_add_class_instance_details(lua_State* L,swig_lua_class } /* Register class static methods,attributes etc as well as constructor proxy */ -SWIGINTERN void SWIG_Lua_class_register_static(lua_State* L, swig_lua_class* clss) +SWIGINTERN void SWIG_Lua_class_register_static(lua_State *L, swig_lua_class *clss) { int begin = lua_gettop(L); lua_checkstack(L,5); /* just in case */ @@ -952,7 +952,7 @@ SWIGINTERN void SWIG_Lua_class_register_static(lua_State* L, swig_lua_class* cls /* performs the instance(non-static) class registration process. Metatable for class is created * and added to the class registry. */ -SWIGINTERN void SWIG_Lua_class_register_instance(lua_State* L,swig_lua_class* clss) +SWIGINTERN void SWIG_Lua_class_register_instance(lua_State *L,swig_lua_class *clss) { int begin = lua_gettop(L); // if name already there (class is already registered) then do nothing @@ -1014,7 +1014,7 @@ SWIGINTERN void SWIG_Lua_class_register_instance(lua_State* L,swig_lua_class* c assert( lua_gettop(L) == begin ); } -SWIGINTERN void SWIG_Lua_class_register(lua_State* L,swig_lua_class* clss) +SWIGINTERN void SWIG_Lua_class_register(lua_State *L,swig_lua_class *clss) { assert(lua_istable(L,-1)); /* This is table(module or namespace) where class will be added */ SWIG_Lua_class_register_instance(L,clss); @@ -1054,7 +1054,7 @@ SWIGINTERN void SWIG_Lua_class_register(lua_State* L,swig_lua_class* clss) * ----------------------------------------------------------------------------- */ /* helper to add metatable to new lua object */ -SWIGINTERN void _SWIG_Lua_AddMetatable(lua_State* L,swig_type_info *type) +SWIGINTERN void _SWIG_Lua_AddMetatable(lua_State *L,swig_type_info *type) { if (type->clientdata) /* there is clientdata: so add the metatable */ { @@ -1071,9 +1071,9 @@ SWIGINTERN void _SWIG_Lua_AddMetatable(lua_State* L,swig_type_info *type) } /* pushes a new object into the lua stack */ -SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State* L,void* ptr,swig_type_info *type, int own) +SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State *L,void *ptr,swig_type_info *type, int own) { - swig_lua_userdata* usr; + swig_lua_userdata *usr; if (!ptr){ lua_pushnil(L); return; @@ -1089,9 +1089,9 @@ SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State* L,void* ptr,swig_type_info *t /* takes a object from the lua stack & converts it into an object of the correct type (if possible) */ -SWIGRUNTIME int SWIG_Lua_ConvertPtr(lua_State* L,int index,void** ptr,swig_type_info *type,int flags) +SWIGRUNTIME int SWIG_Lua_ConvertPtr(lua_State *L,int index,void **ptr,swig_type_info *type,int flags) { - swig_lua_userdata* usr; + swig_lua_userdata *usr; swig_cast_info *cast; if (lua_isnil(L,index)){*ptr=0; return SWIG_OK;} /* special case: lua nil => NULL pointer */ usr=(swig_lua_userdata*)lua_touserdata(L,index); /* get data */ @@ -1118,9 +1118,9 @@ SWIGRUNTIME int SWIG_Lua_ConvertPtr(lua_State* L,int index,void** ptr,swig_type return SWIG_ERROR; /* error */ } -SWIGRUNTIME void* SWIG_Lua_MustGetPtr(lua_State* L,int index,swig_type_info *type,int flags, - int argnum,const char* func_name){ - void* result; +SWIGRUNTIME void* SWIG_Lua_MustGetPtr(lua_State *L,int index,swig_type_info *type,int flags, + int argnum,const char *func_name){ + void *result; 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); @@ -1129,9 +1129,9 @@ SWIGRUNTIME void* SWIG_Lua_MustGetPtr(lua_State* L,int index,swig_type_info *typ } /* pushes a packed userdata. user for member fn pointers only */ -SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State* L,void* ptr,size_t size,swig_type_info *type) +SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State *L,void *ptr,size_t size,swig_type_info *type) { - swig_lua_rawdata* raw; + swig_lua_rawdata *raw; assert(ptr); /* not acceptable to pass in a NULL value */ raw=(swig_lua_rawdata*)lua_newuserdata(L,sizeof(swig_lua_rawdata)-1+size); /* alloc data */ raw->type=type; @@ -1141,9 +1141,9 @@ SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State* L,void* ptr,size_t size,swig_t } /* converts a packed userdata. user for member fn pointers only */ -SWIGRUNTIME int SWIG_Lua_ConvertPacked(lua_State* L,int index,void* ptr,size_t size,swig_type_info *type) +SWIGRUNTIME int SWIG_Lua_ConvertPacked(lua_State *L,int index,void *ptr,size_t size,swig_type_info *type) { - swig_lua_rawdata* raw; + swig_lua_rawdata *raw; raw=(swig_lua_rawdata*)lua_touserdata(L,index); /* get data */ if (!raw) return SWIG_ERROR; /* error */ if (type==0 || type==raw->type) /* void* or identical type */ @@ -1157,7 +1157,7 @@ SWIGRUNTIME int SWIG_Lua_ConvertPacked(lua_State* L,int index,void* ptr,size_t /* a function to get the typestring of a piece of data */ SWIGRUNTIME const char *SWIG_Lua_typename(lua_State *L, int tp) { - swig_lua_userdata* usr; + swig_lua_userdata *usr; if (lua_isuserdata(L,tp)) { usr=(swig_lua_userdata*)lua_touserdata(L,tp); /* get data */ @@ -1169,7 +1169,7 @@ SWIGRUNTIME const char *SWIG_Lua_typename(lua_State *L, int tp) } /* lua callable function to get the userdata's type */ -SWIGRUNTIME int SWIG_Lua_type(lua_State* L) +SWIGRUNTIME int SWIG_Lua_type(lua_State *L) { lua_pushstring(L,SWIG_Lua_typename(L,1)); return 1; @@ -1178,7 +1178,7 @@ SWIGRUNTIME int SWIG_Lua_type(lua_State* L) /* lua callable function to compare userdata's value the issue is that two userdata may point to the same thing but to lua, they are different objects */ -SWIGRUNTIME int SWIG_Lua_equal(lua_State* L) +SWIGRUNTIME int SWIG_Lua_equal(lua_State *L) { int result; swig_lua_userdata *usr1,*usr2; @@ -1199,7 +1199,7 @@ SWIGRUNTIME int SWIG_Lua_equal(lua_State* L) #if ((SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUA) && (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC)) /* Install Constants */ SWIGINTERN void -SWIG_Lua_InstallConstants(lua_State* L, swig_lua_const_info constants[]) { +SWIG_Lua_InstallConstants(lua_State *L, swig_lua_const_info constants[]) { int i; for (i = 0; constants[i].type; i++) { switch(constants[i].type) { @@ -1253,7 +1253,7 @@ In lua 5.0.X its lua_dostring() In lua 5.1.X its luaL_dostring() */ SWIGINTERN int -SWIG_Lua_dostring(lua_State *L, const char* str) { +SWIG_Lua_dostring(lua_State *L, const char *str) { int ok,top; if (str==0 || str[0]==0) return 0; /* nothing to do */ top=lua_gettop(L); /* save stack */ From 02c4a8e39c30ec972da4d5bf0dc8d34519b24b27 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Mon, 11 Nov 2013 18:29:49 +0400 Subject: [PATCH 407/481] Remove some obsolete code --- Lib/lua/lua.swg | 2 -- Lib/lua/luaruntime.swg | 5 ----- 2 files changed, 7 deletions(-) diff --git a/Lib/lua/lua.swg b/Lib/lua/lua.swg index c470d9298..4ea1ac98a 100644 --- a/Lib/lua/lua.swg +++ b/Lib/lua/lua.swg @@ -42,12 +42,10 @@ %typemap(consttab) SWIGTYPE *, SWIGTYPE *const, SWIGTYPE &, SWIGTYPE [] { SWIG_LUA_CONSTTAB_POINTER("$symname",$value, $1_descriptor) } - //{ SWIG_LUA_POINTER, (char *)"$symname", 0, 0, (void *)$value, &$1_descriptor}// TODO: REMOVE // member function pointers %typemap(consttab) SWIGTYPE (CLASS::*) { SWIG_LUA_CONSTTAB_BINARY("$symname", sizeof($type),&$value, $1_descriptor) } - //{ SWIG_LUA_BINARY, (char *)"$symname", sizeof($type), 0, (void *)&$value, &$1_descriptor}// TODO:REMOVE /* ----------------------------------------------------------------------------- diff --git a/Lib/lua/luaruntime.swg b/Lib/lua/luaruntime.swg index 758544185..52b698051 100644 --- a/Lib/lua/luaruntime.swg +++ b/Lib/lua/luaruntime.swg @@ -61,11 +61,6 @@ SWIGEXPORT int SWIG_init(lua_State* L) /* default Lua action */ #endif -#if ((SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUA) && (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC)) - /* constants */ - /* TODO: REMOVE */ -#endif - #if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC) /* invoke user-specific initialization */ SWIG_init_user(L); From 7e09b6687ed3624094bcf4f24602a25ede4e11e5 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Mon, 11 Nov 2013 19:29:48 +0400 Subject: [PATCH 408/481] Remove some typos --- Source/Modules/swigmod.h | 1 - Source/Swig/typesys.c | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/Source/Modules/swigmod.h b/Source/Modules/swigmod.h index 09fc37c87..2929993b3 100644 --- a/Source/Modules/swigmod.h +++ b/Source/Modules/swigmod.h @@ -278,7 +278,6 @@ protected: /* Return the namespace for the class/enum - the nspace feature */ String *getNSpace() const; - void setNSpace(String *nspace); /* Return the real name of the current class */ String *getClassName() const; diff --git a/Source/Swig/typesys.c b/Source/Swig/typesys.c index c5ddb56f6..e11fc781a 100644 --- a/Source/Swig/typesys.c +++ b/Source/Swig/typesys.c @@ -1594,7 +1594,7 @@ void SwigType_remember_clientdata(const SwigType *t, const_String_or_char_ptr cl Delete(qr); /*Printf(stdout,"t = '%s'\n", t); - Printf(stdout,"fr= '%s'\n\n", fr);*/ + Printf(stdout,"fr= '%s'\n\n", fr); */ if (t) { char *ct = Char(t); From ce2760f77e9ab04ce276244ee4329aeba7ddea54 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Mon, 11 Nov 2013 21:58:07 +0400 Subject: [PATCH 409/481] Fixes for examples. Wrapped keywords into guardian in keyword_rename test --- Examples/lua/dual/dual.cpp | 4 ++++ Examples/lua/embed/Makefile | 3 ++- Examples/lua/embed/embed.c | 4 ++++ Examples/lua/embed2/Makefile | 3 ++- Examples/test-suite/keyword_rename.i | 2 ++ Lib/lua/luarun.swg | 5 ++++- 6 files changed, 18 insertions(+), 3 deletions(-) diff --git a/Examples/lua/dual/dual.cpp b/Examples/lua/dual/dual.cpp index d2a9ecaa9..ad7897953 100644 --- a/Examples/lua/dual/dual.cpp +++ b/Examples/lua/dual/dual.cpp @@ -36,6 +36,10 @@ extern "C" int luaopen_example2(lua_State*L); #define DEBUG2(X,Y) {printf(X,Y);fflush(stdout);} #define DEBUG3(X,Y,Z) {printf(X,Y,Z);fflush(stdout);} +#if LUA_VERSION_NUM > 501 +#define lua_open luaL_newstate +#endif + void testModule(lua_State *L) { swig_type_info *pTypeInfo=0,*pTypeInfo2=0; diff --git a/Examples/lua/embed/Makefile b/Examples/lua/embed/Makefile index df1f8fa04..57979c061 100644 --- a/Examples/lua/embed/Makefile +++ b/Examples/lua/embed/Makefile @@ -4,6 +4,7 @@ TARGET = embed SRCS = example.c INTERFACE = example.i LUA_INTERP = embed.c +LIBS = -lm # this is a little different to normal as we have our own special interpreter # which we want to static link @@ -12,7 +13,7 @@ check: build build: $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) SRCS='$(SRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' LIBS='$(LIBS)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static clean: $(MAKE) -f $(TOP)/Makefile lua_clean diff --git a/Examples/lua/embed/embed.c b/Examples/lua/embed/embed.c index 9df168f94..f21c933a5 100644 --- a/Examples/lua/embed/embed.c +++ b/Examples/lua/embed/embed.c @@ -18,6 +18,10 @@ We will be using the luaL_dostring()/lua_dostring() function to call into lua #include #include +#if LUA_VERSION_NUM > 501 +#define lua_open luaL_newstate +#endif + /* the SWIG wrappered library */ extern int luaopen_example(lua_State*L); diff --git a/Examples/lua/embed2/Makefile b/Examples/lua/embed2/Makefile index fc309ac7e..ec22bdcae 100644 --- a/Examples/lua/embed2/Makefile +++ b/Examples/lua/embed2/Makefile @@ -4,6 +4,7 @@ TARGET = embed2 SRCS = example.c INTERFACE = example.i LUA_INTERP = embed2.c +LIBS = -lm # this is a little different to normal as we have our own special interpreter # which we want to static link @@ -12,7 +13,7 @@ check: build build: $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) SRCS='$(SRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' LIBS='$(LIBS)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static clean: $(MAKE) -f $(TOP)/Makefile lua_clean diff --git a/Examples/test-suite/keyword_rename.i b/Examples/test-suite/keyword_rename.i index 46c3338b3..a9f58ebef 100644 --- a/Examples/test-suite/keyword_rename.i +++ b/Examples/test-suite/keyword_rename.i @@ -32,8 +32,10 @@ KW(go, defer) KW(chan, fallthrough) /* Lua keywords */ +#ifdef SWIGLUA KW(end, function) KW(nil,local) +#endif %} diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index ff807a785..5ae08f5d0 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -357,6 +357,9 @@ SWIGINTERN int SWIG_Lua_namespace_set(lua_State *L) lua_pop(L,1); /* remove the value */ } lua_pop(L,1); /* remove the value .set table */ + lua_pop(L,1); /* remote metatable */ + assert(lua_gettop(L) == 3); // TODO: REMOVE + lua_rawset(L,-3); return 0; } @@ -505,7 +508,7 @@ SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State *L,const char *cname); typedef int (*swig_lua_base_iterator_func)(lua_State*,swig_type_info*, int, int *ret); -int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info *swig_type, int first_arg, swig_lua_base_iterator_func func, int *const ret) +SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info *swig_type, int first_arg, swig_lua_base_iterator_func func, int *const ret) { // first_arg - position of the object in stack. Everything that is above are arguments // and is passed to every evocation of the func From 89c6fbb780dfaacc840a84bcb64a9d684e6dd72c Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Mon, 11 Nov 2013 22:30:29 +0400 Subject: [PATCH 410/481] Attempt to fix unreproducable bug (from Travis CI build) --- Source/Modules/lua.cxx | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index f1803e068..e5e6e7ab0 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -170,7 +170,13 @@ public: f_initbeforefunc(0), s_luacode(0), module(0), - have_constructor(0), have_destructor(0), destructor_action(0), class_symname(0), class_fq_symname(0), class_static_nspace(0), constructor_name(0) { + have_constructor(0), + have_destructor(0), + destructor_action(0), + class_symname(0), + class_fq_symname(0), + class_static_nspace(0), + constructor_name(0) { namespaces_hash = NewHash(); for (int i = 0; i < STATES_COUNT; i++) current[i] = false; @@ -415,7 +421,9 @@ public: // But we need to know what was the name of function/variable // etc that user desired, that's why we store correct symname // as lua:name - Setattr(n, "lua:name", Getattr(n, "sym:name")); + String *symname = Getattr(n, "sym:name"); + if (symname) + Setattr(n, "lua:name", symname); return Language::cDeclaration(n); } virtual int constructorDeclaration(Node *n) { @@ -1004,6 +1012,7 @@ public: Printf(f_init, "%s\n", tm); } else { Delete(nsname); + nsname = 0; Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value.\n"); Swig_restore(n); return SWIG_NOWRAP; @@ -1017,6 +1026,7 @@ public: n_v2 = Copy(n); //Printf( stdout, "target name v2: %s, symname v2 %s\n", target_name_v2.ptr(), iname_v2.ptr());// TODO:REMOVE if (!luaAddSymbol(iname_v2, n, class_parent_nspace)) { + Swig_restore(n); return SWIG_ERROR; } @@ -1122,8 +1132,8 @@ public: virtual int classHandler(Node *n) { //REPORT("classHandler", n); - String *mangled_class_fq_symname; - String *destructor_name; + String *mangled_class_fq_symname = 0; + String *destructor_name = 0; String *nspace = getNSpace(); constructor_name = 0; @@ -1151,8 +1161,8 @@ public: assert(class_fq_symname != 0); mangled_class_fq_symname = Swig_name_mangle(class_fq_symname); - SwigType *t(Copy(Getattr(n, "name"))); - SwigType *fr_t(SwigType_typedef_resolve_all(t)); /* Create fully resolved type */ + SwigType *t = Copy(Getattr(n, "name")); + SwigType *fr_t = SwigType_typedef_resolve_all(t); /* Create fully resolved type */ SwigType *t_tmp = 0; t_tmp = SwigType_typedef_qualified(fr_t); // Temporal variable Delete(fr_t); @@ -1350,9 +1360,11 @@ public: current[NO_CPP] = true; Delete(class_static_nspace); - Delete(mangled_class_fq_symname); - Delete(destructor_name); class_static_nspace = 0; + Delete(mangled_class_fq_symname); + mangled_class_fq_symname = 0; + Delete(destructor_name); + destructor_name = 0; Delete(class_fq_symname); class_fq_symname = 0; class_symname = 0; @@ -1538,7 +1550,7 @@ public: emitLuaFlavor(s); - String *sfile; + String *sfile = 0; for (int i = 0; filenames[i] != 0; i++) { sfile = Swig_include_sys(filenames[i]); if (!sfile) { @@ -1733,6 +1745,7 @@ public: Setattr(namespaces_hash, key ? key : "", nspace_hash); Delete(mangled_name); + mangled_name = 0; return nspace_hash; } @@ -1878,8 +1891,7 @@ public: assert(cname != 0); Printv(output, "static swig_lua_namespace ", cname, " = ", NIL); - String *null_string; - null_string = NewString("0"); + String *null_string = NewString("0"); String *attr_tab_name = Getattr(nspace_hash, "attributes:name"); String *methods_tab_name = Getattr(nspace_hash, "methods:name"); String *const_tab_name = Getattr(nspace_hash, "constants:name"); From a87710275df70e6a1c6690713b851f0050e1a698 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Tue, 12 Nov 2013 16:41:20 +0400 Subject: [PATCH 411/481] Some fixes for elua --- Source/Modules/lua.cxx | 35 ++++++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index e5e6e7ab0..eda5589fc 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -370,12 +370,10 @@ public: Printf(f_init, "/* exec Lua code if applicable */\nSWIG_Lua_dostring(L,SWIG_LUACODE);\n"); Printf(f_init, "}\n"); + // Done. Close up the module & write to the wrappers + closeNamespaces(f_wrappers); Printf(f_wrappers, "#ifdef __cplusplus\n}\n#endif\n"); - // Done. Close up the module & write to the wrappers - - //Printv(f_wrappers, s_cmd_tab, s_var_tab, s_const_tab, NIL); - closeNamespaces(f_wrappers); SwigType_emit_type_table(f_runtime, f_wrappers); /* NEW LANGUAGE NOTE:*********************************************** @@ -1129,6 +1127,24 @@ public: * classHandler() * ------------------------------------------------------------ */ + /* Helper function that adds record to appropriate + * C arrays + */ + void registerClass(String *scope, Node *n) { + String *wrap_class = Getattr(n,"wrap:class_name"); + assert(wrap_class != 0); + Hash *nspaceHash = getNamespaceHash(scope); + String *ns_classes = Getattr(nspaceHash, "classes"); + Printv(ns_classes, "&", wrap_class, ",\n", NIL); + if (elua_ltr || eluac_ltr) { + String *ns_methods = Getattr(nspaceHash, "methods"); + Hash *class_hash = getNamespaceHash(class_fq_symname); + assert(class_hash != 0); + String *cls_methods = Getattr(class_hash, "methods:name"); + assert(cls_methods != 0); + Printv(ns_methods, tab4, "{LSTRKEY(\"", class_symname, "\")", ", LROVAL(", cls_methods, ")", "},\n", NIL); + } + } virtual int classHandler(Node *n) { //REPORT("classHandler", n); @@ -1231,16 +1247,17 @@ public: SwigType_add_pointer(t); // Catch all: eg. a class with only static functions and/or variables will not have 'remembered' - String *wrap_class = NewStringf("&_wrap_class_%s", mangled_class_fq_symname); + String *wrap_class_name = NewStringf("_wrap_class_%s", mangled_class_fq_symname); + String *wrap_class = NewStringf("&%s", wrap_class_name); + Setattr(n, "wrap:class_name", wrap_class_name); SwigType_remember_clientdata(t, wrap_class); String *rt = Copy(getClassType()); SwigType_add_pointer(rt); // Adding class to apropriate namespace + registerClass(nspace, n); Hash *nspaceHash = getNamespaceHash(nspace); - String *ns_classes = Getattr(nspaceHash, "classes"); - Printv(ns_classes, wrap_class, ",\n", NIL); // Register the class structure with the type checker // Printf(f_init,"SWIG_TypeClientData(SWIGTYPE%s, (void *) &_wrap_class_%s);\n", SwigType_manglestr(t), mangled_class_fq_symname); @@ -1635,6 +1652,10 @@ public: Hash *parent = getNamespaceHash(parent_path, true); String *namespaces_tab = Getattr(parent, "namespaces"); Printv(namespaces_tab, "&", cname, ",\n", NIL); + if (elua_ltr || eluac_ltr) { + String *methods_tab = Getattr(parent, "methods"); + Printv(methods_tab, tab4, "{LSTRKEY(\"", name, "\")", ", LROVAL(", cname, ")", "},\n", NIL); + } Setattr(nspace_hash, "name", name); Delete(components); From 4b0ed733172c410103cb7bcc74b13243e10b06aa Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Wed, 13 Nov 2013 14:52:04 +0400 Subject: [PATCH 412/481] Style fixes. Comments fixes. Fixing cmd options. etc --- Lib/lua/luarun.swg | 99 +++++++++-------- Source/Modules/lua.cxx | 241 ++++++++++++++++++++++------------------- 2 files changed, 179 insertions(+), 161 deletions(-) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index 5ae08f5d0..bb1cbb444 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -32,7 +32,7 @@ extern "C" { # define SWIG_LUA_CONSTTAB_FLOAT(B, C) LSTRKEY(B), LNUMVAL(C) # define SWIG_LUA_CONSTTAB_STRING(B, C) LSTRKEY(B), LSTRVAL(C) # define SWIG_LUA_CONSTTAB_CHAR(B, C) LSTRKEY(B), LNUMVAL(C) - // Those two types of constants are not supported in elua + /* Those two types of constants are not supported in elua */ # define SWIG_LUA_CONSTTAB_POINTER(B,C,D) LSTRKEY(B), LNILVAL # define SWIG_LUA_CONSTTAB_BINARY(B, S, C, D) LSTRKEY(B), LNILVAL #else /* SWIG_LUA_FLAVOR_LUA */ @@ -137,7 +137,7 @@ typedef struct { #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC) typedef const LUA_REG_TYPE swig_lua_method; typedef const LUA_REG_TYPE swig_lua_const_info; -#else // Normal lua +#else /* Normal lua */ typedef luaL_Reg swig_lua_method; /* Constant information structure */ @@ -159,28 +159,27 @@ typedef struct { } swig_lua_attribute; -struct _swig_lua_class; -// Can be used to create namespaces. Currently used to -// wrap class static methods/variables/constants -typedef struct _swig_lua_namespace { +struct swig_lua_class; +/* Can be used to create namespaces. Currently used to wrap class static methods/variables/constants */ +typedef struct swig_lua_namespace { const char *name; swig_lua_method *ns_methods; swig_lua_attribute *ns_attributes; swig_lua_const_info *ns_constants; - struct _swig_lua_class **ns_classes; - struct _swig_lua_namespace **ns_namespaces; + struct swig_lua_class **ns_classes; + struct swig_lua_namespace **ns_namespaces; } swig_lua_namespace; -typedef struct _swig_lua_class { - const char *name; // Name that this class has in Lua - const char *fqname; // Fully qualified name - Scope + class name +typedef struct swig_lua_class { + const char *name; /* Name that this class has in Lua */ + const char *fqname; /* Fully qualified name - Scope + class name */ swig_type_info **type; lua_CFunction constructor; void (*destructor)(void *); swig_lua_method *methods; swig_lua_attribute *attributes; swig_lua_namespace *cls_static; - struct _swig_lua_class **bases; + struct swig_lua_class **bases; const char **base_names; } swig_lua_class; @@ -249,7 +248,7 @@ typedef struct { #ifdef __cplusplus /* Special helper for member function pointers it gets the address, casts it, then dereferences it */ -//#define SWIG_mem_fn_as_voidptr(a) (*((char**)&(a))) +/*#define SWIG_mem_fn_as_voidptr(a) (*((char**)&(a))) */ #endif /* storing/access of swig_module_info */ @@ -363,9 +362,9 @@ SWIGINTERN int SWIG_Lua_namespace_set(lua_State *L) return 0; } -#if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) // In elua this is useless -SWIGINTERN void SWIG_Lua_InstallConstants(lua_State *L, swig_lua_const_info constants[]); // forward declaration -SWIGINTERN void SWIG_Lua_add_variable(lua_State *L,const char *name,lua_CFunction getFn,lua_CFunction setFn); // forward declaration +#if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) /* In elua this is useless */ +SWIGINTERN void SWIG_Lua_InstallConstants(lua_State *L, swig_lua_const_info constants[]); /* forward declaration */ +SWIGINTERN void SWIG_Lua_add_variable(lua_State *L,const char *name,lua_CFunction getFn,lua_CFunction setFn); /* forward declaration */ SWIGINTERN void SWIG_Lua_class_register(lua_State *L,swig_lua_class *clss); /* helper function - register namespace methods and attributes into namespace */ @@ -396,7 +395,7 @@ SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State *L, swig_lua_namespace * */ SWIGINTERN void SWIG_Lua_add_namespace_classes(lua_State *L, swig_lua_namespace *ns) { - // There must be module/namespace table at the top of the stack + /* There must be module/namespace table at the top of the stack */ assert(lua_istable(L,-1)); swig_lua_class **classes = ns->ns_classes; @@ -441,16 +440,16 @@ SWIGINTERN int SWIG_Lua_namespace_register(lua_State *L, swig_lua_namespace *ns, lua_setmetatable(L,-2); /* set metatable */ - // Register all functions, variables etc + /* Register all functions, variables etc */ SWIG_Lua_add_namespace_details(L,ns); - // Register classes + /* Register classes */ SWIG_Lua_add_namespace_classes(L,ns); swig_lua_namespace **sub_namespace = ns->ns_namespaces; if( sub_namespace != 0) { while(*sub_namespace != 0) { SWIG_Lua_namespace_register(L, *sub_namespace, 1); - lua_pop(L,1); // removing sub-namespace table + lua_pop(L,1); /* removing sub-namespace table */ sub_namespace++; } } @@ -462,7 +461,7 @@ SWIGINTERN int SWIG_Lua_namespace_register(lua_State *L, swig_lua_namespace *ns, } assert(lua_gettop(L) == begin+1); } -#endif // SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA +#endif /* SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA */ /* ----------------------------------------------------------------------------- * global variable support code: classes * ----------------------------------------------------------------------------- */ @@ -485,14 +484,14 @@ SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State *L,const char *cname); } else\ valid = 1; -#else // en elua .bases table doesn't exist. Use table from swig_lua_class +#else /* en elua .bases table doesn't exist. Use table from swig_lua_class */ #define SWIG_LUA_INIT_BASE_SEARCH(bases_count)\ swig_module_info *module=SWIG_GetModule(L);\ swig_lua_class **bases= ((swig_lua_class*)(swig_type->clientdata))->bases;\ const char **base_names= ((swig_lua_class*)(swig_type->clientdata))->base_names;\ bases_count = 0;\ - for(;base_names[bases_count];bases_count++);// get length of bases + for(;base_names[bases_count];bases_count++);/* get length of bases */ #define SWIG_LUA_GET_BASE_METATABLE(i,base_swig_type, valid)\ swig_lua_class *base_class = bases[i];\ @@ -510,9 +509,9 @@ typedef int (*swig_lua_base_iterator_func)(lua_State*,swig_type_info*, int, int SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info *swig_type, int first_arg, swig_lua_base_iterator_func func, int *const ret) { - // first_arg - position of the object in stack. Everything that is above are arguments - // and is passed to every evocation of the func - int last_arg = lua_gettop(L);// position of last argument + /* first_arg - position of the object in stack. Everything that is above are arguments + * and is passed to every evocation of the func */ + int last_arg = lua_gettop(L);/* position of last argument */ lua_getmetatable(L,first_arg); int original_metatable = last_arg + 1; int bases_count; @@ -523,39 +522,39 @@ SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info *swig_type, i { int i; int j; - int subcall_first_arg = lua_gettop(L) + 1;// Here a copy of first_arg and arguments begin + int subcall_first_arg = lua_gettop(L) + 1;/* Here a copy of first_arg and arguments begin */ int valid = 1; for(j=first_arg;j<=last_arg;j++) lua_pushvalue(L,j); int subcall_last_arg = lua_gettop(L); swig_type_info *base_swig_type = 0; - // Trick: temporaly replacing original metatable - // with metatable for base class and call getter + /* Trick: temporaly replacing original metatable + * with metatable for base class and call getter */ for(i=0;ibases[i];i++) { SWIG_Lua_get_class_metatable(L,clss->bases[i]->fqname); - // Base class must be already registered + /* Base class must be already registered */ assert(lua_istable(L,-1)); - lua_rawseti(L,-2,i+1); // In lua indexing starts from 1 + lua_rawseti(L,-2,i+1); /* In lua indexing starts from 1 */ bases_count++; } assert(lua_rawlen(L,-1) == bases_count); - lua_pop(L,1); // remove .bases table + lua_pop(L,1); /* remove .bases table */ /* add attributes */ for(i=0;clss->attributes[i].name;i++){ SWIG_Lua_add_variable(L,clss->attributes[i].name,clss->attributes[i].getmethod,clss->attributes[i].setmethod); @@ -958,7 +957,7 @@ SWIGINTERN void SWIG_Lua_class_register_static(lua_State *L, swig_lua_class *cls SWIGINTERN void SWIG_Lua_class_register_instance(lua_State *L,swig_lua_class *clss) { int begin = lua_gettop(L); - // if name already there (class is already registered) then do nothing + /* if name already there (class is already registered) then do nothing */ SWIG_Lua_get_class_registry(L); /* get the registry */ lua_pushstring(L,clss->fqname); /* get the name */ lua_rawget(L,-2); @@ -967,14 +966,14 @@ SWIGINTERN void SWIG_Lua_class_register_instance(lua_State *L,swig_lua_class *c assert(lua_gettop(L)==begin); return; } - lua_pop(L,2); // tidy stack - // Recursively initialize all bases + lua_pop(L,2); /* tidy stack */ + /* Recursively initialize all bases */ int i = 0; for(i=0;clss->bases[i];i++) { SWIG_Lua_class_register_instance(L,clss->bases[i]); } - // Again, get registry and push name + /* Again, get registry and push name */ SWIG_Lua_get_class_registry(L); /* get the registry */ lua_pushstring(L,clss->fqname); /* get the name */ lua_newtable(L); /* create the metatable */ @@ -1051,7 +1050,7 @@ SWIGINTERN void SWIG_Lua_class_register(lua_State *L,swig_lua_class *clss) lua_pop(L,2); assert(lua_gettop(L) == begin); } -#endif // SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA +#endif /* SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA */ /* ----------------------------------------------------------------------------- * Class/structure conversion fns * ----------------------------------------------------------------------------- */ diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index eda5589fc..75c94cc6b 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -86,16 +86,7 @@ Lua Options (available with -lua)\n\ Optional NUM is default value for MIN_OPT_LEVEL\n\ -nomoduleglobal - Do not register the module name as a global variable \n\ but return the module table from calls to require.\n\ - -api-lvl-from NUM\n\ - - Force support for old-style bindings. All old-style bindings\n\ - from NUM to current new-style bindings will be supported. For example,\n\ - if current lua bindings API version is 10 and NUM==7 then SWIG will\n\ - generate bindings compatible with lua bindings versions 7,8,9 and,\n\ - of course current version of bindings, 10.\n\ - API levels:\n\ - 2 - SWIG 2.*\n\ - 3 - SWIG 3.*\n\ - Default NUM is 2.\n\ + -swig3 - Disable support for old-style bindings name generation.\n\ \n"; static int nomoduleglobal = 0; @@ -186,12 +177,6 @@ public: Delete(namespaces_hash); } - /* NEW LANGUAGE NOTE:*********************************************** - This is called to initalise the system & read any command line args - most of this is boilerplate code, except the command line args - which depends upon what args your code supports - NEW LANGUAGE NOTE:END *********************************************** */ - bool strToInt(const char *string, int &value) { long int tmp; char *p_end = 0; @@ -203,6 +188,12 @@ public: value = tmp; return true; } + /* NEW LANGUAGE NOTE:*********************************************** + This is called to initalise the system & read any command line args + most of this is boilerplate code, except the command line args + which depends upon what args your code supports + NEW LANGUAGE NOTE:END *********************************************** */ + /* --------------------------------------------------------------------- * main() * @@ -237,15 +228,9 @@ public: Swig_mark_arg(i + 1); i++; } - } else if (strcmp(argv[i], "-api-lvl-from") == 0) { - if (argv[i + 1]) { - if (!strToInt(argv[i + 1], api_level)) - Swig_arg_error(); - Swig_mark_arg(i + 1); - i++; - } else { - Swig_arg_error(); - } + } else if (strcmp(argv[i], "-swig3") == 0) { + Swig_mark_arg(i); + api_level = 3; } } } @@ -409,6 +394,10 @@ public: return Language::importDirective(n); } + /* ------------------------------------------------------------ + * cDeclaration() + * It copies sym:name to lua:name to preserve it's original value + * ------------------------------------------------------------ */ virtual int cDeclaration(Node *n) { // class 'Language' is messing with symname in a really heavy way. // Although documentation states that sym:name is a name in @@ -463,7 +452,7 @@ public: // Add method to the "methods" C array of given namespace/class void registerMethod(String *nspace_or_class_name, Node *n) { - assert(n != 0); + assert(n); Hash *nspaceHash = getNamespaceHash(nspace_or_class_name); String *s_ns_methods_tab = Getattr(nspaceHash, "methods"); String *wname = Getattr(n, "wrap:name"); @@ -491,7 +480,7 @@ public: String *name = Getattr(n, "name"); String *iname = Getattr(n, "sym:name"); String *target_name = Getattr(n, "lua:name"); - assert(target_name != 0); + assert(target_name); SwigType *d = Getattr(n, "type"); ParmList *l = Getattr(n, "parms"); Parm *p; @@ -516,7 +505,7 @@ public: Wrapper_add_local(f, "SWIG_arg", "int SWIG_arg = 0"); - String *wname = symname_wrapper(iname); + String *wname = symnameWrapper(iname); if (overname) { Append(wname, overname); } @@ -830,8 +819,8 @@ public: Wrapper *f = NewWrapper(); String *symname = Getattr(n, "sym:name"); String *target_name = Getattr(n, "lua:name"); - assert(target_name != 0); - String *wname = symname_wrapper(symname); + assert(target_name); + String *wname = symnameWrapper(symname); //Printf(stdout,"Swig_overload_dispatch %s %s '%s' %d\n",symname,wname,dispatch,maxargs); @@ -890,11 +879,9 @@ public: /* ------------------------------------------------------------ - * variableWrapper() + * Add variable to the "attributes" (or "get"/"set" in + * case of elua_ltr) C arrays of given namespace or class * ------------------------------------------------------------ */ - - // Add variable to the "attributes" (or "get"/"set" in - // case of elua_ltr) C arrays of given namespace or class void registerVariable(String *nspace_or_class_name, Node *n, const char *getAttrName, const char *setAttrName) { String *unassignable = NewString("SWIG_Lua_set_immutable"); String *getName = Getattr(n, getAttrName); @@ -919,6 +906,10 @@ public: } } + /* ------------------------------------------------------------ + * variableWrapper() + * ------------------------------------------------------------ */ + virtual int variableWrapper(Node *n) { /* NEW LANGUAGE NOTE:*********************************************** Language::variableWrapper(n) will generate two wrapper fns @@ -929,7 +920,7 @@ public: NEW LANGUAGE NOTE:END *********************************************** */ // REPORT("variableWrapper", n); String *target_name = Getattr(n, "lua:name"); - assert(target_name != 0); + assert(target_name); current[VARIABLE] = true; // let SWIG generate the wrappers int result = Language::variableWrapper(n); @@ -940,12 +931,9 @@ public: /* ------------------------------------------------------------ - * constantWrapper() - * ------------------------------------------------------------ */ - - /* Add constant to appropriate C array. constantRecord is an array record. + * Add constant to appropriate C array. constantRecord is an array record. * Actually, in current implementation it is resolved consttab typemap - */ + * ------------------------------------------------------------ */ void registerConstant(String *nspace, String *constantRecord) { Hash *nspaceHash = getNamespaceHash(nspace); String *s_const_tab = 0; @@ -955,17 +943,20 @@ public: else s_const_tab = Getattr(nspaceHash, "constants"); - assert(s_const_tab != 0); + assert(s_const_tab); Printf(s_const_tab, " %s,\n", constantRecord); if ((eluac_ltr || elua_ltr) && v2_compatibility) { s_const_tab = Getattr(nspaceHash, "constants"); - assert(s_const_tab != 0); + assert(s_const_tab); Printf(s_const_tab, " %s,\n", constantRecord); } } + /* ------------------------------------------------------------ + * constantWrapper() + * ------------------------------------------------------------ */ virtual int constantWrapper(Node *n) { REPORT("constantWrapper", n); String *name = Getattr(n, "name"); @@ -990,7 +981,7 @@ public: Setattr(n, "sym:name", target_name); /* Special hook for member pointer */ if (SwigType_type(type) == T_MPOINTER) { - String *wname = symname_wrapper(iname); + String *wname = symnameWrapper(iname); Printf(f_wrappers, "static %s = %s;\n", SwigType_str(type, wname), value); value = Char(wname); } @@ -1123,28 +1114,29 @@ public: return Language::classDeclaration(n); } - /* ------------------------------------------------------------ - * classHandler() - * ------------------------------------------------------------ */ - /* Helper function that adds record to appropriate + /* ------------------------------------------------------------ + * Helper function that adds record to appropriate * C arrays - */ + * ------------------------------------------------------------ */ void registerClass(String *scope, Node *n) { String *wrap_class = Getattr(n,"wrap:class_name"); - assert(wrap_class != 0); + assert(wrap_class); Hash *nspaceHash = getNamespaceHash(scope); String *ns_classes = Getattr(nspaceHash, "classes"); Printv(ns_classes, "&", wrap_class, ",\n", NIL); if (elua_ltr || eluac_ltr) { String *ns_methods = Getattr(nspaceHash, "methods"); Hash *class_hash = getNamespaceHash(class_fq_symname); - assert(class_hash != 0); + assert(class_hash); String *cls_methods = Getattr(class_hash, "methods:name"); - assert(cls_methods != 0); + assert(cls_methods); Printv(ns_methods, tab4, "{LSTRKEY(\"", class_symname, "\")", ", LROVAL(", cls_methods, ")", "},\n", NIL); } } + /* ------------------------------------------------------------ + * classHandler() + * ------------------------------------------------------------ */ virtual int classHandler(Node *n) { //REPORT("classHandler", n); @@ -1174,7 +1166,7 @@ public: else class_fq_symname = NewStringf("%s.%s", nspace, class_symname); - assert(class_fq_symname != 0); + assert(class_fq_symname); mangled_class_fq_symname = Swig_name_mangle(class_fq_symname); SwigType *t = Copy(Getattr(n, "name")); @@ -1212,7 +1204,7 @@ public: // and capital letter are forbiden to use in C++. So, under know circumstances could our class contain // any member or subclass with name "__Static". Thus, never any name clash. Hash *instance_cls = getNamespaceHash(class_fq_symname, false); - assert(instance_cls != 0); + assert(instance_cls); String *s_attr_tab_name = Getattr(instance_cls, "attributes:name"); String *s_methods_tab_name = Getattr(instance_cls, "methods:name"); Setattr(instance_cls, "lua:no_namespaces", "1"); @@ -1225,7 +1217,7 @@ public: class_static_nspace = NewStringf("%s%s__Static", class_fq_symname, NSPACE_SEPARATOR); Hash *static_cls = getNamespaceHash(class_static_nspace, false); - assert(static_cls != 0); + assert(static_cls); Setattr(static_cls, "lua:no_namespaces", "1"); Setattr(static_cls, "lua:class_static", "1"); @@ -1296,18 +1288,18 @@ public: constructor_name = constructor_proxy_name; if (elua_ltr) { String *static_cls_metatable_tab = Getattr(static_cls, "metatable"); - assert(static_cls_metatable_tab != 0); + assert(static_cls_metatable_tab); Printf(static_cls_metatable_tab, " {LSTRKEY(\"__call\"), LFUNCVAL(%s)},\n", constructor_name); } else if (eluac_ltr) { String *ns_methods_tab = Getattr(nspaceHash, "methods"); - assert(ns_methods_tab != 0); + assert(ns_methods_tab); Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "new_", class_symname, "\")", ", LFUNCVAL(", constructor_name, ")", "},\n", NIL); } } if (have_destructor) { if (eluac_ltr) { String *ns_methods_tab = Getattr(nspaceHash, "methods"); - assert(ns_methods_tab != 0); + assert(ns_methods_tab); Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "free_", mangled_class_fq_symname, "\")", ", LFUNCVAL(", destructor_name, ")", "},\n", NIL); } } @@ -1599,10 +1591,12 @@ public: } - /* This is to convert the string of Lua code into a proper string, which can then be - emitted into the C/C++ code. - Basically is is a lot of search & replacing of odd sequences - */ + /* ----------------------------------------------------------------------------- + * EscapeCode() + * This is to convert the string of Lua code into a proper string, which can then be + * emitted into the C/C++ code. + * Basically is is a lot of search & replacing of odd sequences + * ---------------------------------------------------------------------------- */ void EscapeCode(String *str) { //Printf(f_runtime,"/* original luacode:[[[\n%s\n]]]\n*/\n",str); Chop(str); // trim @@ -1612,18 +1606,22 @@ public: //Printf(f_runtime,"/* hacked luacode:[[[\n%s\n]]]\n*/\n",str); } - /* Each namespace can be described with hash that stores C arrays - where members of the namespace should be added. All these hashes are stored - inside namespaces_hash. - nspace could be NULL (NSPACE_TODO), that means functions and variables and classes - that are not in any namespace (this is default for SWIG unless %nspace feature is used) - You can later set some attributes that will affect behaviour of functions that use this hash: - "lua:no_namespaces" will disable "namespaces" array. - "lua:no_classes" will disable "classes" array. - For every component ("attributes", "methods", etc) there are subcomponents: - * XXX:name - name of the C array that stores data for component - * XXX:decl - statement with forward declaration of this array; - */ + /* ----------------------------------------------------------------------------- + * getNamespaceHash() + * Each namespace can be described with hash that stores C arrays + * where members of the namespace should be added. All these hashes are stored + * inside namespaces_hash. + * nspace could be NULL (NSPACE_TODO), that means functions and variables and classes + * that are not in any namespace (this is default for SWIG unless %nspace feature is used) + * You can later set some attributes that will affect behaviour of functions that use this hash: + * "lua:no_namespaces" will disable "namespaces" array. + * "lua:no_classes" will disable "classes" array. + * For every component ("attributes", "methods", etc) there are subcomponents: + * XXX:name - name of the C array that stores data for component + * XXX:decl - statement with forward declaration of this array; + * Namespace could be automatically registered to it's parent if 'reg' == true. It can be done + * only at first call (a.k.a when nspace is created). + * ---------------------------------------------------------------------------- */ Hash *getNamespaceHash(String *nspace, bool reg = true) { Hash *nspace_hash = Getattr(namespaces_hash, nspace ? nspace : ""); if (nspace_hash != 0) @@ -1770,17 +1768,19 @@ public: return nspace_hash; } - /* Functions add end markers {0,0,...,0} to all arrays, prints them to + /* ----------------------------------------------------------------------------- + * closeNamespaceHash() + * Functions add end markers {0,0,...,0} to all arrays, prints them to * output and marks hash as closed (lua:closed). Consequent attempts to * close same hash will result in error * closeNamespaceHash DOES NOT print structure that describes namespace, it only * prints array. You can use printNamespaceDefinition to print structure. * if "lua:no_namespaces" is set, then array for "namespaces" won't be printed * if "lua:no_classes" is set, then array for "classes" won't be printed - * */ + * ----------------------------------------------------------------------------- */ void closeNamespaceHash(String *nspace, File *output) { Hash *nspace_hash = Getattr(namespaces_hash, nspace); - assert(nspace_hash != 0); + assert(nspace_hash); assert(Getattr(nspace_hash, "lua:closed") == 0); Setattr(nspace_hash, "lua:closed", "1"); @@ -1836,26 +1836,26 @@ public: Printv(output, set_tab, NIL); String *metatable_tab = Getattr(nspace_hash, "metatable"); - assert(metatable_tab != 0); + assert(metatable_tab); Printv(metatable_tab, tab4, "{LSTRKEY(\"__index\"), LFUNCVAL(SWIG_Lua_namespace_get)},\n", NIL); Printv(metatable_tab, tab4, "{LSTRKEY(\"__newindex\"), LFUNCVAL(SWIG_Lua_namespace_set)},\n", NIL); Printv(metatable_tab, tab4, "{LSTRKEY(\".get\"), LROVAL(", get_tab_name, ")},\n", NIL); Printv(metatable_tab, tab4, "{LSTRKEY(\".set\"), LROVAL(", set_tab_name, ")},\n", NIL); if (Getattr(nspace_hash, "lua:class_instance")) { String *static_cls = Getattr(nspace_hash, "lua:class_instance:static_hash"); - assert(static_cls != 0); + assert(static_cls); // static_cls is swig_lua_namespace. This structure can't be use with eLua(LTR) // Instead structure describing its methods isused String *static_cls_cname = Getattr(static_cls, "methods:name"); - assert(static_cls_cname != 0); + assert(static_cls_cname); Printv(metatable_tab, tab4, "{LSTRKEY(\".static\"), LROVAL(", static_cls_cname, ")},\n", NIL); // Put forward declaration of this array Printv(output, "extern ", Getattr(static_cls, "methods:decl"), "\n", NIL); } else if (Getattr(nspace_hash, "lua:class_static")) { Hash *instance_cls = Getattr(nspace_hash, "lua:class_static:instance_hash"); - assert(instance_cls != 0); + assert(instance_cls); String *instance_cls_metatable_name = Getattr(instance_cls, "metatable:name"); - assert(instance_cls_metatable_name != 0); + assert(instance_cls_metatable_name); Printv(metatable_tab, tab4, "{LSTRKEY(\".instance\"), LROVAL(", instance_cls_metatable_name, ")},\n", NIL); } @@ -1868,7 +1868,11 @@ public: static int compareByLen(const DOH *f, const DOH *s) { return Len(s) - Len(f); } - // Recursively close all non-closed namespaces. Prints data to dataOutput, + + /* ----------------------------------------------------------------------------- + * closeNamespaceHash() + * Recursively close all non-closed namespaces. Prints data to dataOutput. + * ----------------------------------------------------------------------------- */ void closeNamespaces(File *dataOutput) { // Special handling for empty module. if (Getattr(namespaces_hash, "") == 0) { @@ -1894,22 +1898,26 @@ public: name = module; else name = Getattr(nspace, "name"); - assert(name != 0); + assert(name); printNamespaceDefinition(key, name, dataOutput); } Delete(to_close); } - // This function prints to output a definition of namespace in - // form of swig_lua_namespace: { attr_array, methods_array, ... , namespaces_array }. - // You can call this function as many times as necessary. - // 'name' is a user-visible name that this namespace will have in Lua. It shouldn't - // be fully qualified name, just it's own name. + /* ----------------------------------------------------------------------------- + * printNamespaceDefinition() + * This function prints to output a definition of namespace in + * form + * swig_lua_namespace $cname = { attr_array, methods_array, ... , namespaces_array }; + * You can call this function as many times as necessary. + * 'name' is a user-visible name that this namespace will have in Lua. It shouldn't + * be fully qualified name, just it's own name. + * ----------------------------------------------------------------------------- */ void printNamespaceDefinition(String *nspace, String *name, File *output) { Hash *nspace_hash = getNamespaceHash(nspace, false); String *cname = Getattr(nspace_hash, "cname"); // cname - name of the C structure that describes namespace - assert(cname != 0); + assert(cname); Printv(output, "static swig_lua_namespace ", cname, " = ", NIL); String *null_string = NewString("0"); @@ -1931,12 +1939,15 @@ public: Delete(null_string); } - // This function determines actual namespace/scope where any symbol at the - // current moment should be placed. It looks at the 'current' array - // and depending on where are we - static class member/function, - // instance class member/function or just global functions decides - // where symbol should be put. - // The namespace/scope doesn't depend from symbol, only from 'current' + /* ----------------------------------------------------------------------------- + * luaCurrentSymbolNSpace() + * This function determines actual namespace/scope where any symbol at the + * current moment should be placed. It looks at the 'current' array + * and depending on where are we - static class member/function, + * instance class member/function or just global functions decides + * where symbol should be put. + * The namespace/scope doesn't depend from symbol, only from 'current' + * ----------------------------------------------------------------------------- */ String *luaCurrentSymbolNSpace() { String *scope = 0; // If ouside class, than NSpace is used. @@ -1954,12 +1965,15 @@ public: } else { // Friend functions are handled this way scope = class_static_nspace; } - assert(scope != 0); + assert(scope); } return scope; } - // Our implementation of addSymbol. Determines scope correctly, then calls Language::addSymbol + /* ----------------------------------------------------------------------------- + * luaAddSymbol() + * Our implementation of addSymbol. Determines scope correctly, then calls Language::addSymbol + * ----------------------------------------------------------------------------- */ int luaAddSymbol(const String *s, const Node *n) { String *scope = luaCurrentSymbolNSpace(); //Printf(stdout, "luaAddSymbol: %s scope: %s\n", s, scope); @@ -1969,7 +1983,10 @@ public: return result; } - // Overload. Enforces given scope. Actually, it simply forwards call to Language::addSymbol + /* ----------------------------------------------------------------------------- + * luaAddSymbol() + * Overload. Enforces given scope. Actually, it simply forwards call to Language::addSymbol + * ----------------------------------------------------------------------------- */ int luaAddSymbol(const String *s, const Node *n, const_String_or_char_ptr scope) { //Printf(stdout, "luaAddSymbol: %s scope: %s\n", s, scope); int result = Language::addSymbol(s, n, scope); @@ -1978,15 +1995,14 @@ public: return result; } - // Function creates fully qualified name of given symbol. Current NSpace and current class - // are used - String *fully_qualified_name(const_String_or_char_ptr name) { - assert(name != 0); - String *scope = 0; - if (getCurrentClass()) - scope = class_fq_symname; - else - scope = getNSpace(); + /* ----------------------------------------------------------------------------- + * fullyQualifiedName() + * Function creates fully qualified name of given symbol. The scope is deremined + * automatically based on luaCurrentSymbolNSpace() + * ----------------------------------------------------------------------------- */ + String *fullyQualifiedName(const_String_or_char_ptr name) { + assert(name); + String *scope = luaCurrentSymbolNSpace(); String *fqname = 0; if (scope) @@ -1997,10 +2013,13 @@ public: return fqname; } - // Input: symname - // Output - wrapper around fully qualified form of symname - String *symname_wrapper(String *symname) { - String *fqname = fully_qualified_name(symname); + /* ----------------------------------------------------------------------------- + * symnameWrapper() + * Input: symname + * Output - Swig_name_wrapper around fully qualified form of symname + * ----------------------------------------------------------------------------- */ + String *symnameWrapper(String *symname) { + String *fqname = fullyQualifiedName(symname); String *wname = Swig_name_wrapper(fqname); Delete(fqname); return wname; From 6d49a57b535a0a9cc479b2cd8367371c64808d39 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Wed, 13 Nov 2013 15:16:09 +0400 Subject: [PATCH 413/481] Add support for C-style enums in C mode. And tests. In backward compatible mode C style enums binding are correctly generated --- Examples/test-suite/lua/enums_runme.lua | 8 ++++++++ Source/Modules/lua.cxx | 15 +++++++++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/Examples/test-suite/lua/enums_runme.lua b/Examples/test-suite/lua/enums_runme.lua index 6211581fe..998f01cfc 100644 --- a/Examples/test-suite/lua/enums_runme.lua +++ b/Examples/test-suite/lua/enums_runme.lua @@ -19,4 +19,12 @@ assert(enums.globalinstance3==30) assert(enums.AnonEnum1==0) assert(enums.AnonEnum2==100) +-- In C enums from struct are exported without prefixing with struct name +-- In C++ they are prefixed. +-- We are emulating xor :) +assert(enums.BAR1 ~= enums.Foo_BAR1) -- It is either C style, or C++ style, but not both +assert((enums.BAR1 ~= nil ) or (enums.Foo_BAR1 ~= nil)) + +assert(enums.Phoo ~= enums.iFoo_Phoo) +assert((enums.Phoo == 50) or (enums.iFoo_Phoo == 50)) -- no point in checking fns, C will allow any value diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 75c94cc6b..116e6a26a 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -139,6 +139,7 @@ private: STATIC_FUNC, STATIC_VAR, STATIC_CONST, // enums and things like static const int x = 5; + ENUM_CONST, // This is only needed for backward compatibility in C mode STATES_COUNT }; @@ -1010,8 +1011,16 @@ public: bool make_v2_compatible = v2_compatibility && getCurrentClass() != 0; if (make_v2_compatible) { - target_name_v2 = Swig_name_member(0, class_symname, target_name); - iname_v2 = Swig_name_member(0, class_symname, iname); + // Special handling for enums in C mode - they are not prefixed with structure name + if(!CPlusPlus && current[ENUM_CONST]) { + target_name_v2 = target_name; + DohIncref(target_name_v2); + iname_v2 = iname; + DohIncref(iname_v2); + } else { + target_name_v2 = Swig_name_member(0, class_symname, target_name); + iname_v2 = Swig_name_member(0, class_symname, iname); + } n_v2 = Copy(n); //Printf( stdout, "target name v2: %s, symname v2 %s\n", target_name_v2.ptr(), iname_v2.ptr());// TODO:REMOVE if (!luaAddSymbol(iname_v2, n, class_parent_nspace)) { @@ -1074,8 +1083,10 @@ public: virtual int enumDeclaration(Node *n) { current[STATIC_CONST] = true; + current[ENUM_CONST] = true; int result = Language::enumDeclaration(n); current[STATIC_CONST] = false; + current[ENUM_CONST] = false; return result; } From 0ee724ca80ac8f47c9365fbb729c52b03959ad06 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Wed, 13 Nov 2013 19:51:20 +0400 Subject: [PATCH 414/481] Add compatibility option for old-style inheritance --- Lib/lua/luarun.swg | 101 +++++++++++++++++++++++++++++++++++++++++ Source/Modules/lua.cxx | 11 ++++- 2 files changed, 111 insertions(+), 1 deletion(-) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index bb1cbb444..9f5bf5869 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -627,6 +627,15 @@ SWIGINTERN int SWIG_Lua_class_do_get(lua_State *L, swig_type_info *type, int fi lua_pop(L,1); /* Search in base classes */ assert(lua_gettop(L) == substack_start + 2); // TODO: REMOVE + + /* TODO: REMOVE +#ifdef SWIG_LUA_SQUASH_BASES + if(ret) *ret = 0; + return SWIG_ERROR; // TODO:ERROR:FIX:REMOVE!!!! +//#warning REMOVE REMOVE REMOVE +#endif + END OF REMOVE */ + //printf("failed, searching bases\n"); // TODO: REMOVE int bases_search_result = SWIG_Lua_iterate_bases(L,type,substack_start+1,SWIG_Lua_class_do_get,ret); if(ret) assert(lua_gettop(L) == substack_start + 2 + *ret); // TODO: REMOVE @@ -846,6 +855,77 @@ SWIGINTERN void SWIG_Lua_init_base_class(lua_State *L,swig_lua_class *clss) } } +#if defined(SWIG_LUA_SQUASH_BASES) && (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) +/* Merges two tables */ +SWIGINTERN int SWIG_Lua_merge_tables_by_index(lua_State *L, int target, int source) +{ + /* iterating */ + lua_pushnil(L); + while (lua_next(L,source) != 0) { + /* -1 - value, -2 - index */ + /* have to copy to assign */ + lua_pushvalue(L,-2); /* copy of index */ + lua_pushvalue(L,-2); /* copy of value */ + lua_rawset(L, target); + lua_pop(L,1); + /* only key is left */ + } +} + +/* Merges two tables with given name. original - index of target metatable, base - index of source metatable */ +SWIGINTERN int SWIG_Lua_merge_tables(lua_State *L, const char* name, int original, int base) +{ + int begin = lua_gettop(L); // TODO:REMOVE + /* push original[name], then base[name] */ + lua_pushstring(L,name); + lua_rawget(L,original); + int original_table = lua_gettop(L); + lua_pushstring(L,name); + lua_rawget(L,base); + int base_table = lua_gettop(L); + SWIG_Lua_merge_tables_by_index(L, original_table, base_table); + /* clearing stack */ + lua_pop(L,2); + assert(lua_gettop(L) == begin); // TODO: REMOVE +} + +/* Function takes all symbols from base and adds it to derived class. It's just a helper*/ +SWIGINTERN int SWIG_Lua_class_squash_base(lua_State *L, swig_lua_class *base_cls) +{ + int begin = lua_gettop(L); // TODO:REMOVE + /* There is one parameter - original, i.e. 'derived' class metatable */ + assert(lua_istable(L,-1)); + int original = lua_gettop(L); + SWIG_Lua_get_class_metatable(L,base_cls->fqname); + int base = lua_gettop(L); + SWIG_Lua_merge_tables(L, ".fn", original, base ); + SWIG_Lua_merge_tables(L, ".set", original, base ); + SWIG_Lua_merge_tables(L, ".get", original, base ); + lua_pop(L,1); + assert(lua_gettop(L) == begin); // TODO: REMOVE +} + +/* Function squashes all symbols from 'clss' bases into itself */ +SWIGINTERN int SWIG_Lua_class_squash_bases(lua_State *L, swig_lua_class *clss) +{ + int begin = lua_gettop(L); // TODO: REMOVE + int i; + SWIG_Lua_get_class_metatable(L,clss->fqname); + for(i=0;clss->base_names[i];i++) + { + if (clss->bases[i]==0) /* Somehow it's not found. Skip it */ + continue; + /* Thing is: all bases are already registered. Thus they have already executed + * this function. So we just need to squash them into us, because their bases + * are already squashed into them. No need for recursion here! + */ + SWIG_Lua_class_squash_base(L, clss->bases[i]); + } + lua_pop(L,1); /*tidy stack*/ + assert(lua_gettop(L) == begin); // TODO: REMOVE +} +#endif + #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) /* In elua this is useless */ /* helper add a variable to a registered class */ SWIGINTERN void SWIG_Lua_add_variable(lua_State *L,const char *name,lua_CFunction getFn,lua_CFunction setFn) @@ -977,6 +1057,23 @@ SWIGINTERN void SWIG_Lua_class_register_instance(lua_State *L,swig_lua_class *c SWIG_Lua_get_class_registry(L); /* get the registry */ lua_pushstring(L,clss->fqname); /* get the name */ lua_newtable(L); /* create the metatable */ +#if defined(SWIG_LUA_SQUASH_BASES) && (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) + /* If squashing is requested, then merges all bases metatable into this one. + * It would get us all special methods: __getitem, __add etc. + * This would set .fn, .type, and other .xxx incorrectly, but we will overwrite it right away + */ + int squash_begin = lua_gettop(L); // TODO:REMOVE + int new_metatable_index = lua_absindex(L,-1); + for(i=0;clss->bases[i];i++) + { + SWIG_Lua_get_class_metatable(L,clss->bases[i]->fqname); + int base_metatable = lua_absindex(L,-1); + SWIG_Lua_merge_tables_by_index(L,new_metatable_index, base_metatable); + lua_pop(L,1); + } + assert(lua_gettop(L) == squash_begin); // TODO: REMOVE + /* And now we will overwrite all incorrectly set data */ +#endif /* add string of class name called ".type" */ lua_pushstring(L,".type"); lua_pushstring(L,clss->fqname); @@ -1010,6 +1107,10 @@ SWIGINTERN void SWIG_Lua_class_register_instance(lua_State *L,swig_lua_class *c lua_pop(L,1); /* tidy stack (remove registry) */ assert(lua_gettop(L)==begin); +#if defined(SWIG_LUA_SQUASH_BASES) && (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) + /* Now merge all symbols from .fn, .set, .get etc from bases to our tables */ + SWIG_Lua_class_squash_bases(L,clss); +#endif SWIG_Lua_get_class_metatable(L,clss->fqname); SWIG_Lua_add_class_instance_details(L,clss); /* recursive adding of details (atts & ops) */ lua_pop(L,1); /* tidy stack (remove class metatable) */ diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 116e6a26a..1d7b831b1 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -86,13 +86,17 @@ Lua Options (available with -lua)\n\ Optional NUM is default value for MIN_OPT_LEVEL\n\ -nomoduleglobal - Do not register the module name as a global variable \n\ but return the module table from calls to require.\n\ - -swig3 - Disable support for old-style bindings name generation.\n\ + -swig3 - Disable support for old-style bindings name generation.\n\ + -squash-bases - Squashes symbols from all inheritance tree of a given class\n\ + into itself. Emulates pre-SWIG3.0 inheritance. Insignificantly\n\ + speeds things up, but increases memory consumption.\n\ \n"; static int nomoduleglobal = 0; static int elua_ltr = 0; static int elua_opt_lvl = 2; static int eluac_ltr = 0; +static int squash_bases = 0; static int v2_compatibility = 0; static const int default_api_level = 2; @@ -232,6 +236,9 @@ public: } else if (strcmp(argv[i], "-swig3") == 0) { Swig_mark_arg(i); api_level = 3; + } else if (strcmp(argv[i], "-squash-bases") == 0) { + Swig_mark_arg(i); + squash_bases = 1; } } } @@ -331,6 +338,8 @@ public: } else { Printf(f_runtime, "#define SWIG_LUA_MODULE_GLOBAL\n"); } + if (squash_bases) + Printf(f_runtime, "#define SWIG_LUA_SQUASH_BASES\n"); // if (NoInclude) { // Printf(f_runtime, "#define SWIG_NOINCLUDE\n"); From 705beb67530f6bbbdd85a776831dbd48be675262 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Sun, 17 Nov 2013 01:11:50 +0400 Subject: [PATCH 415/481] Bugfixes for eLua. eLua emulation mode --- Examples/test-suite/lua/grouping_runme.lua | 1 + Examples/test-suite/lua/newobject1_runme.lua | 4 +- Lib/lua/luarun.swg | 311 ++++++++++++++++++- Lib/lua/luaruntime.swg | 23 +- Source/Modules/lua.cxx | 189 +++++++---- 5 files changed, 445 insertions(+), 83 deletions(-) diff --git a/Examples/test-suite/lua/grouping_runme.lua b/Examples/test-suite/lua/grouping_runme.lua index 7ab08499f..b13409514 100644 --- a/Examples/test-suite/lua/grouping_runme.lua +++ b/Examples/test-suite/lua/grouping_runme.lua @@ -14,4 +14,5 @@ assert(g.test3 == 37) g.test3 = 42 assert(g.test3 == 42) +assert(g.NEGATE ~= nil) assert(g.do_unary(5, g.NEGATE) == -5) diff --git a/Examples/test-suite/lua/newobject1_runme.lua b/Examples/test-suite/lua/newobject1_runme.lua index 5de8276db..55d04eeb7 100644 --- a/Examples/test-suite/lua/newobject1_runme.lua +++ b/Examples/test-suite/lua/newobject1_runme.lua @@ -1,8 +1,8 @@ require("import") -- the import fn import("newobject1") -- import code -foo1 = newobject1.Foo_makeFoo() -- lua doesnt yet support static fns properly -assert(newobject1.Foo_fooCount() == 1) -- lua doesnt yet support static fns properly +foo1 = newobject1.Foo_makeFoo() +assert(newobject1.Foo_fooCount() == 1) foo2 = foo1:makeMore() assert(newobject1.Foo_fooCount() == 2) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index 9f5bf5869..9f8f69476 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -27,14 +27,80 @@ extern "C" { # error SWIG_LUA_TARGET not defined #endif +#if defined(SWIG_LUA_ELUA_EMULATE) + +struct swig_elua_entry; + +typedef struct swig_elua_key { + int type; + union { + const char* strkey; + lua_Number numkey; + } key; +} swig_elua_key; + +typedef struct swig_elua_val { + int type; + union { + lua_Number number; + const struct swig_elua_entry *table; + const char *string; + lua_CFunction function; + struct { + char member; + long lvalue; + void *pvalue; + swig_type_info **ptype; + } userdata; + } value; +} swig_elua_val; + +typedef struct swig_elua_entry { + swig_elua_key key; + swig_elua_val value; +} swig_elua_entry; + +#define LSTRKEY(x) {LUA_TSTRING, {.strkey = x} } +#define LNUMKEY(x) {LUA_TNUMBER, {.numkey = x} } +#define LNILKEY {LUA_TNIL, {.strkey = 0} } + +#define LNUMVAL(x) {LUA_TNUMBER, {.number = x} } +#define LFUNCVAL(x) {LUA_TFUNCTION, {.function = x} } +#define LROVAL(x) {LUA_TTABLE, {.table = x} } +#define LNILVAL {LUA_TNIL, {.string = 0} } +#define LSTRVAL(x) {LUA_TSTRING, {.string = x} } + +#define LUA_REG_TYPE swig_elua_entry + +#define SWIG_LUA_ELUA_EMUL_METATABLE_KEY "__metatable" + +#define lua_pushrotable(L,p)\ + lua_newtable(L);\ + SWIG_Lua_elua_emulate_register(L,p); + +#define SWIG_LUA_CONSTTAB_POINTER(B,C,D)\ + LSTRKEY(B), {LUA_TUSERDATA, { .userdata={0,0,(void*)(C),&D} } } + +#define SWIG_LUA_CONSTTAB_BINARY(B,S,C,D)\ + LSTRKEY(B), {LUA_TUSERDATA, { .userdata={1,S,(void*)(C),&D} } } +#endif + #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC) # define SWIG_LUA_CONSTTAB_INT(B, C) LSTRKEY(B), LNUMVAL(C) # define SWIG_LUA_CONSTTAB_FLOAT(B, C) LSTRKEY(B), LNUMVAL(C) # define SWIG_LUA_CONSTTAB_STRING(B, C) LSTRKEY(B), LSTRVAL(C) # define SWIG_LUA_CONSTTAB_CHAR(B, C) LSTRKEY(B), LNUMVAL(C) /* Those two types of constants are not supported in elua */ -# define SWIG_LUA_CONSTTAB_POINTER(B,C,D) LSTRKEY(B), LNILVAL -# define SWIG_LUA_CONSTTAB_BINARY(B, S, C, D) LSTRKEY(B), LNILVAL + +#ifndef SWIG_LUA_CONSTTAB_POINTER +#warning eLua does not support pointers as constants. By default, nil will be used as value +#define SWIG_LUA_CONSTTAB_POINTER(B,C,D) LSTRKEY(B), LNILVAL +#endif + +#ifndef SWIG_LUA_CONSTTAB_BINARY +#warning eLua does not support pointers to member as constants. By default, nil will be used as value +#define SWIG_LUA_CONSTTAB_BINARY(B, S, C, D) LSTRKEY(B), LNILVAL +#endif #else /* SWIG_LUA_FLAVOR_LUA */ # define SWIG_LUA_CONSTTAB_INT(B, C) SWIG_LUA_INT, (char *)B, (long)C, 0, 0, 0 # define SWIG_LUA_CONSTTAB_FLOAT(B, C) SWIG_LUA_FLOAT, (char *)B, 0, (double)C, 0, 0 @@ -46,15 +112,19 @@ extern "C" { SWIG_LUA_BINARY, (char *)B, S, 0, (void *)C, &D #endif +#ifndef SWIG_LUA_ELUA_EMULATE #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC) # define LRO_STRVAL(v) {{.p = (char *) v}, LUA_TSTRING} # define LSTRVAL LRO_STRVAL #endif +#endif /* SWIG_LUA_ELUA_EMULATE*/ +#ifndef SWIG_LUA_ELUA_EMULATE #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC) #include "lrodefs.h" #include "lrotable.h" #endif +#endif /* SWIG_LUA_ELUA_EMULATE*/ /* ----------------------------------------------------------------------------- * compatibility defines * ----------------------------------------------------------------------------- */ @@ -86,6 +156,19 @@ extern "C" { # define lua_absindex(L,i) ((i)>0 || (i) <= LUA_REGISTRYINDEX ? (i) : lua_gettop(L) + (i) + 1) #endif +/* lua_rawsetp was introduced in Lua 5.2 */ +#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502 +#define lua_rawsetp(L,index,ptr)\ + lua_pushlightuserdata(L,(void*)(ptr));\ + lua_insert(L,-2);\ + lua_rawset(L,index); + +#define lua_rawgetp(L,index,ptr)\ + lua_pushlightuserdata(L,(void*)(ptr));\ + lua_rawget(L,index); + +#endif + /* -------------------------------------------------------------------------- * Helper functions for error handling * -------------------------------------------------------------------------- */ @@ -179,6 +262,7 @@ typedef struct swig_lua_class { swig_lua_method *methods; swig_lua_attribute *attributes; swig_lua_namespace *cls_static; + swig_lua_method *metatable; // only for eLua struct swig_lua_class **bases; const char **base_names; } swig_lua_class; @@ -288,6 +372,179 @@ SWIGINTERN int SWIG_Lua_set_immutable(lua_State *L) return 0; /* should not return anything */ } +#ifdef SWIG_LUA_ELUA_EMULATE +//#define report(...) printf(__VA_ARGS__) // TODO: REMOVE +#define report(...) // TODO : REMOVE + +SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State *L,void *ptr,swig_type_info *type, int own); +SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State *L,void *ptr,size_t size,swig_type_info *type); +static int swig_lua_elua_emulate_unique_key; +/* This is function that emulates eLua rotables behaviour. It loads rotable definition + * into the usual lua table. + */ +SWIGINTERN void SWIG_Lua_elua_emulate_register(lua_State *L, const swig_elua_entry *table) +{ + assert(lua_istable(L,-1)); + int target_table = lua_gettop(L); + /* Get the registry where we put all parsed tables to avoid loops */ + lua_rawgetp(L, LUA_REGISTRYINDEX, &swig_lua_elua_emulate_unique_key); + if(lua_isnil(L,-1)) { + lua_pop(L,1); + lua_newtable(L); + lua_pushvalue(L,-1); + lua_rawsetp(L,LUA_REGISTRYINDEX,(void*)(&swig_lua_elua_emulate_unique_key)); + } + int parsed_tables_array = lua_gettop(L); + lua_pushvalue(L,target_table); + lua_rawsetp(L, parsed_tables_array, table); + int i; + int table_parsed = 0; + int pairs_start = lua_gettop(L); + static int tabs_count = 0; // TODO: REMOVE + for(i = 0;table[i].key.type != LUA_TNIL || table[i].value.type != LUA_TNIL;i++) + { + /* TODO: REMOVE */ + int j = 0; + for(j=0;jkey.type) { + case LUA_TSTRING: + lua_pushstring(L,entry->key.key.strkey); + report(" %s :", entry->key.key.strkey); // TODO: REMOVE + if(strcmp(entry->key.key.strkey, SWIG_LUA_ELUA_EMUL_METATABLE_KEY) == 0) + is_metatable = 1; + break; + case LUA_TNUMBER: + lua_pushnumber(L,entry->key.key.numkey); + report(" %f :", (double)(entry->key.key.numkey)); // TODO: REMOVE + break; + case LUA_TNIL: + report(" nil :"); // TODO: REMOVE + lua_pushnil(L); + break; + default: + assert(0); + } + switch(entry->value.type) { + case LUA_TSTRING: + lua_pushstring(L,entry->value.value.string); + report(" %s", entry->value.value.string); // TODO: REMOVE + break; + case LUA_TNUMBER: + lua_pushnumber(L,entry->value.value.number); + report(" %f", (double)(entry->value.value.number)); // TODO: REMOVE + break; + case LUA_TFUNCTION: + report(" %p", (void*)(entry->value.value.function)); // TODO: REMOVE + lua_pushcfunction(L,entry->value.value.function); + break; + case LUA_TTABLE: + /* TODO: REMOVE */ + report(" table"); + tabs_count++; + /* END OF REMOVE */ + lua_rawgetp(L,parsed_tables_array, entry->value.value.table); + table_parsed = !lua_isnil(L,-1); + if(!table_parsed) { + lua_pop(L,1); /*remove nil */ + report("\n"); // TODO: REMOVE + lua_newtable(L); + SWIG_Lua_elua_emulate_register(L,entry->value.value.table); + } else { + report(" already parsed"); // TODO: REMOVE + } + if(is_metatable) { + report(" (registering metatable)"); // TODO: REMOVE + assert(lua_istable(L,-1)); + lua_pushvalue(L,-1); + lua_setmetatable(L,target_table); + } + + tabs_count--; /*TODO: REMOVE*/ + break; + case LUA_TUSERDATA: + if(entry->value.value.userdata.member) + SWIG_NewMemberObj(L,entry->value.value.userdata.pvalue, + entry->value.value.userdata.lvalue, + *(entry->value.value.userdata.ptype)); + else + SWIG_NewPointerObj(L,entry->value.value.userdata.pvalue, + *(entry->value.value.userdata.ptype),0); + break; + case LUA_TNIL: + report(" nil"); // TODO: REMOVE + lua_pushnil(L); + break; + default: + assert(0); + } + assert(lua_gettop(L) == pairs_start + 2); + lua_rawset(L,target_table); + report("\n"); // TODO: REMOVE + } + lua_pop(L,1); /* Removing parsed tables storage */ + assert(lua_gettop(L) == target_table); +} + +SWIGINTERN void SWIG_Lua_elua_emulate_register_clear(lua_State *L) +{ + lua_pushnil(L); + lua_rawsetp(L, LUA_REGISTRYINDEX, &swig_lua_elua_emulate_unique_key); +} + +/* TODO: REMOVE */ +SWIGINTERN void SWIG_Lua_get_class_registry(lua_State *L); + +SWIGINTERN int SWIG_Lua_emulate_elua_getmetatable(lua_State *L) +{ + SWIG_check_num_args("getmetatable(SWIG eLua emulation)", 1, 1); + SWIG_Lua_get_class_registry(L); + lua_getfield(L,-1,"lua_getmetatable"); + lua_remove(L,-2); /* remove the registry*/ + assert(!lua_isnil(L,-1)); + lua_pushvalue(L,1); + assert(lua_gettop(L) == 3); /* object | function | object again */ + lua_call(L,1,1); + if(!lua_isnil(L,-1)) /*There is an ordinary metatable */ + return 1; + /*if it is a table, then emulate elua behaviour - check for __metatable attribute of a table*/ + assert(lua_gettop(L) == 2); + if(lua_istable(L,-2)) { + printf("getmetatable: elua emulation part\n"); // TODO: REMOVE + lua_pop(L,1); /*remove the nil*/ + lua_getfield(L,-1, SWIG_LUA_ELUA_EMUL_METATABLE_KEY); + } + assert(lua_gettop(L) == 2); + return 1; + +fail: + lua_error(L); + return 0; +} + +SWIGINTERN void SWIG_Lua_emulate_elua_swap_getmetatable(lua_State *L) +{ + int begin = lua_gettop(L); // TODO: REMOVE + SWIG_Lua_get_class_registry(L); + lua_pushglobaltable(L); + lua_pushstring(L,"lua_getmetatable"); + lua_getfield(L,-2,"getmetatable"); + assert(!lua_isnil(L,-1)); + lua_rawset(L,-4); + lua_pushstring(L, "getmetatable"); + lua_pushcfunction(L, SWIG_Lua_emulate_elua_getmetatable); + lua_rawset(L,-3); + lua_pop(L,2); + assert(lua_gettop(L) == begin); // TODO: REMOVE + +} +/* END OF REMOVE */ + +#endif /* ----------------------------------------------------------------------------- * global variable support code: namespaces and modules (which are the same thing) * ----------------------------------------------------------------------------- */ @@ -415,6 +672,7 @@ SWIGINTERN void SWIG_Lua_add_namespace_classes(lua_State *L, swig_lua_namespace */ SWIGINTERN int SWIG_Lua_namespace_register(lua_State *L, swig_lua_namespace *ns, int reg) { + /* 1 argument - table on the top of the stack */ int begin = lua_gettop(L); assert(lua_istable(L,-1)); /* just in case. This is supposed to be module table or parent namespace table */ lua_checkstack(L,5); @@ -487,6 +745,7 @@ SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State *L,const char *cname); #else /* en elua .bases table doesn't exist. Use table from swig_lua_class */ #define SWIG_LUA_INIT_BASE_SEARCH(bases_count)\ + assert(swig_type!=0);\ swig_module_info *module=SWIG_GetModule(L);\ swig_lua_class **bases= ((swig_lua_class*)(swig_type->clientdata))->bases;\ const char **base_names= ((swig_lua_class*)(swig_type->clientdata))->base_names;\ @@ -500,7 +759,8 @@ SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State *L,const char *cname); else {\ valid = 1;\ SWIG_Lua_get_class_metatable(L,base_class->fqname);\ - base_swig_type = SWIG_TypeQueryModule(module,module,base_class->fqname);\ + base_swig_type = SWIG_TypeQueryModule(module,module,base_names[i]);\ + assert(base_swig_type != 0);\ } #endif @@ -989,14 +1249,11 @@ SWIGINTERN void SWIG_Lua_add_class_instance_details(lua_State *L,swig_lua_class } lua_pop(L,1); /* tidy stack (remove table) */ /* add operator overloads - these look ANY method which start with "__" and assume they - are operator overloads & add them to the metatable - (this might mess up if someone defines a method __gc (the destructor)*/ - for(i=0;clss->methods[i].name;i++){ - if (clss->methods[i].name[0]=='_' && clss->methods[i].name[1]=='_'){ - SWIG_Lua_add_function(L,clss->methods[i].name,clss->methods[i].func); - } - } + This adds methods from metatable array to metatable. Can mess up garbage + collectind if someone defines __gc method + */ + for(i=0;clss->metatable[i].name;i++) + SWIG_Lua_add_function(L,clss->metatable[i].name,clss->metatable[i].func); } /* Register class static methods,attributes etc as well as constructor proxy */ @@ -1152,6 +1409,38 @@ SWIGINTERN void SWIG_Lua_class_register(lua_State *L,swig_lua_class *clss) assert(lua_gettop(L) == begin); } #endif /* SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA */ + +#if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC) +SWIGINTERN void SWIG_Lua_elua_class_register_instance(lua_State *L, swig_lua_class *clss) +{ + int begin = lua_gettop(L); + /* if name already there (class is already registered) then do nothing */ + SWIG_Lua_get_class_registry(L); /* get the registry */ + lua_pushstring(L,clss->fqname); /* get the name */ + lua_rawget(L,-2); + if(!lua_isnil(L,-1)) { + lua_pop(L,2); + assert(lua_gettop(L)==begin); + return; + } + lua_pop(L,2); /* tidy stack */ + /* Recursively initialize all bases */ + int i = 0; + for(i=0;clss->bases[i];i++) + { + SWIG_Lua_elua_class_register_instance(L,clss->bases[i]); + } + /* Again, get registry and push name */ + SWIG_Lua_get_class_registry(L); /* get the registry */ + lua_pushstring(L,clss->fqname); /* get the name */ + assert(clss->metatable); + lua_pushrotable(L, (void*)(clss->metatable)); /* create the metatable */ + lua_rawset(L,-3); + lua_pop(L,1); + assert(lua_gettop(L) == begin); +} +#endif // elua && eluac + /* ----------------------------------------------------------------------------- * Class/structure conversion fns * ----------------------------------------------------------------------------- */ diff --git a/Lib/lua/luaruntime.swg b/Lib/lua/luaruntime.swg index 52b698051..0f0cd5501 100644 --- a/Lib/lua/luaruntime.swg +++ b/Lib/lua/luaruntime.swg @@ -36,7 +36,7 @@ SWIGEXPORT int SWIG_init(lua_State* L) /* default Lua action */ SWIG_PropagateClientData(); #endif -#if ((SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUA) && (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC)) +#if ((SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUA) && (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC)) || defined(SWIG_LUA_ELUA_EMULATE) /* add a global fn */ SWIG_Lua_add_function(L,"swig_type",SWIG_Lua_type); SWIG_Lua_add_function(L,"swig_equals",SWIG_Lua_equal); @@ -56,7 +56,26 @@ SWIGEXPORT int SWIG_init(lua_State* L) /* default Lua action */ #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) - SWIG_Lua_namespace_register(L,&swig___Global, globalRegister); + SWIG_Lua_namespace_register(L,&swig___Module, globalRegister); +#endif + +#if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC) + for (i = 0; swig_types[i]; i++){ + if (swig_types[i]->clientdata){ + SWIG_Lua_elua_class_register_instance(L,(swig_lua_class*)(swig_types[i]->clientdata)); + } + } +#endif + +#if defined(SWIG_LUA_ELUA_EMULATE) + lua_newtable(L); + SWIG_Lua_elua_emulate_register(L,swig___Module.ns_methods); + SWIG_Lua_elua_emulate_register_clear(L); + if(globalRegister) { + lua_pushstring(L,swig___Module.name); + lua_pushvalue(L,-2); + lua_rawset(L,-4); + } #endif #endif diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 1d7b831b1..c68782e75 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -90,12 +90,15 @@ Lua Options (available with -lua)\n\ -squash-bases - Squashes symbols from all inheritance tree of a given class\n\ into itself. Emulates pre-SWIG3.0 inheritance. Insignificantly\n\ speeds things up, but increases memory consumption.\n\ + -elua-emulate - Emulates behaviour of eLua. Usefull only for testing.\n\ + Incompatible with -elua/-eluac options.\n\ \n"; static int nomoduleglobal = 0; static int elua_ltr = 0; static int elua_opt_lvl = 2; static int eluac_ltr = 0; +static int elua_emulate = 0; static int squash_bases = 0; static int v2_compatibility = 0; static const int default_api_level = 2; @@ -239,10 +242,18 @@ public: } else if (strcmp(argv[i], "-squash-bases") == 0) { Swig_mark_arg(i); squash_bases = 1; + } else if (strcmp(argv[i], "-elua-emulate") == 0) { + Swig_mark_arg(i); + elua_emulate = 1; } } } + if (elua_emulate && (eluac_ltr || elua_ltr )) { + Printf(stderr, "Can't have -elua-emulate and -eluac/-elua at the same time\n"); + Swig_arg_error(); + } + // Set API-compatibility options if (api_level <= 2) // Must be compatible with SWIG 2.* v2_compatibility = 1; @@ -252,6 +263,9 @@ public: //if(api_level <= 4) // v4_compatibility = 1; + // Set elua_ltr if elua_emulate is requested + if(elua_emulate) + elua_ltr = 1; /* NEW LANGUAGE NOTE:*********************************************** This is the boilerplate code, setting a few #defines @@ -466,12 +480,21 @@ public: Hash *nspaceHash = getNamespaceHash(nspace_or_class_name); String *s_ns_methods_tab = Getattr(nspaceHash, "methods"); String *wname = Getattr(n, "wrap:name"); - String *iname = Getattr(n, "sym:name"); String *target_name = Getattr(n, "lua:name"); if (elua_ltr || eluac_ltr) - Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", iname, "\")", ", LFUNCVAL(", wname, ")", "},\n", NIL); + Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", target_name, "\")", ", LFUNCVAL(", wname, ")", "},\n", NIL); else Printv(s_ns_methods_tab, tab4, "{ \"", target_name, "\", ", wname, "},\n", NIL); + // Add to the metatable if method starts with '__' + const char * tn = Char(target_name); + if (tn[0]=='_' && tn[1] == '_' && !eluac_ltr) { + String *metatable_tab = Getattr(nspaceHash, "metatable"); + assert(metatable_tab); + if (elua_ltr) + Printv(metatable_tab, tab4, "{LSTRKEY(\"", target_name, "\")", ", LFUNCVAL(", wname, ")", "},\n", NIL); + else + Printv(metatable_tab, tab4, "{ \"", target_name, "\", ", wname, "},\n", NIL); + } } // Helper for functionWrapper - determines whether we should @@ -1147,7 +1170,7 @@ public: Printv(ns_classes, "&", wrap_class, ",\n", NIL); if (elua_ltr || eluac_ltr) { String *ns_methods = Getattr(nspaceHash, "methods"); - Hash *class_hash = getNamespaceHash(class_fq_symname); + Hash *class_hash = getNamespaceHash(class_static_nspace); assert(class_hash); String *cls_methods = Getattr(class_hash, "methods:name"); assert(cls_methods); @@ -1385,6 +1408,12 @@ public: Printf(f_wrappers, ",0"); } Printf(f_wrappers, ", %s, %s, &%s", s_methods_tab_name, s_attr_tab_name, Getattr(static_cls, "cname")); + + if (!eluac_ltr) + Printf(f_wrappers, ", %s", Getattr(instance_cls,"metatable:name")); + else + Printf(f_wrappers, ", 0"); + Printf(f_wrappers, ", swig_%s_bases, swig_%s_base_names };\n\n", mangled_class_fq_symname, mangled_class_fq_symname); current[NO_CPP] = true; @@ -1602,7 +1631,11 @@ public: * --------------------------------------------------------------------- */ void emitLuaFlavor(String *s) { - if (elua_ltr) + if (elua_emulate) { + Printf(s, "/*This is only emulation!*/\n"); + Printf(s, "#define SWIG_LUA_TARGET SWIG_LUA_FLAVOR_ELUA\n"); + Printf(s, "#define SWIG_LUA_ELUA_EMULATE\n"); + } else if (elua_ltr) Printf(s, "#define SWIG_LUA_TARGET SWIG_LUA_FLAVOR_ELUA\n"); else if (eluac_ltr) Printf(s, "#define SWIG_LUA_TARGET SWIG_LUA_FLAVOR_ELUAC\n"); @@ -1649,39 +1682,11 @@ public: nspace_hash = NewHash(); String *mangled_name = 0; if (nspace == 0 || Len(nspace) == 0) - mangled_name = NewString("__Global"); // C++ names can't start with "__ + capital letter" + mangled_name = NewString("__Module"); // C++ names can't start with "__ + capital letter" else mangled_name = Swig_name_mangle(nspace); String *cname = NewStringf("swig_%s", mangled_name); - if (reg && nspace != 0 && Len(nspace) != 0 && Getattr(nspace_hash, "lua:no_reg") == 0) { - // Split names into components - List *components = Split(nspace, '.', -1); - String *parent_path = NewString(""); - int len = Len(components); - String *name = Copy(Getitem(components, len - 1)); - for (int i = 0; i < len - 1; i++) { - if (i > 0) - Printv(parent_path, NSPACE_SEPARATOR, NIL); - String *item = Getitem(components, i); - Printv(parent_path, item, NIL); - } - //Printf(stdout, "Registering %s. User name %s. C-name %s, Parent is %s\n", mangled_name, name, cname, parent_path); // TODO: REMOVE - Hash *parent = getNamespaceHash(parent_path, true); - String *namespaces_tab = Getattr(parent, "namespaces"); - Printv(namespaces_tab, "&", cname, ",\n", NIL); - if (elua_ltr || eluac_ltr) { - String *methods_tab = Getattr(parent, "methods"); - Printv(methods_tab, tab4, "{LSTRKEY(\"", name, "\")", ", LROVAL(", cname, ")", "},\n", NIL); - } - Setattr(nspace_hash, "name", name); - - Delete(components); - Delete(parent_path); - } else if (!reg) // This namespace shouldn't be registered. Lets remember it - Setattr(nspace_hash, "lua:no_reg", "1"); - - Setattr(nspace_hash, "cname", cname); String *attr_tab = NewString(""); @@ -1766,23 +1771,52 @@ public: Setattr(nspace_hash, "set:name", set_tab_name); Setattr(nspace_hash, "set:decl", set_tab_decl); - if (!eluac_ltr) { - String *metatable_tab = NewString(""); - String *metatable_tab_name = NewStringf("swig_%s_meta", mangled_name); - String *metatable_tab_decl = NewString(""); - Printv(metatable_tab, "const LUA_REG_TYPE ", metatable_tab_name, "[]", NIL); - Printv(metatable_tab_decl, metatable_tab, ";", NIL); - Printv(metatable_tab, " = {\n", NIL); - Setattr(nspace_hash, "metatable", metatable_tab); - Setattr(nspace_hash, "metatable:name", metatable_tab_name); - Setattr(nspace_hash, "metatable:decl", metatable_tab_decl); - } + } + if (!eluac_ltr) { + String *metatable_tab = NewString(""); + String *metatable_tab_name = NewStringf("swig_%s_meta", mangled_name); + String *metatable_tab_decl = NewString(""); + Printv(metatable_tab, "swig_lua_method ", metatable_tab_name, "[]", NIL); + Printv(metatable_tab_decl, metatable_tab, ";", NIL); + Printv(metatable_tab, " = {\n", NIL); + Setattr(nspace_hash, "metatable", metatable_tab); + Setattr(nspace_hash, "metatable:name", metatable_tab_name); + Setattr(nspace_hash, "metatable:decl", metatable_tab_decl); } String *key = 0; if (nspace != 0) key = Copy(nspace); Setattr(namespaces_hash, key ? key : "", nspace_hash); + if (reg && nspace != 0 && Len(nspace) != 0 && Getattr(nspace_hash, "lua:no_reg") == 0) { + // Split names into components + List *components = Split(nspace, '.', -1); + String *parent_path = NewString(""); + int len = Len(components); + String *name = Copy(Getitem(components, len - 1)); + for (int i = 0; i < len - 1; i++) { + if (i > 0) + Printv(parent_path, NSPACE_SEPARATOR, NIL); + String *item = Getitem(components, i); + Printv(parent_path, item, NIL); + } + //Printf(stdout, "Registering %s. User name %s. C-name %s, Parent is %s\n", mangled_name, name, cname, parent_path); // TODO: REMOVE + Hash *parent = getNamespaceHash(parent_path, true); + String *namespaces_tab = Getattr(parent, "namespaces"); + Printv(namespaces_tab, "&", cname, ",\n", NIL); + if (elua_ltr || eluac_ltr) { + String *methods_tab = Getattr(parent, "methods"); + Printv(methods_tab, tab4, "{LSTRKEY(\"", name, "\")", ", LROVAL(", methods_tab_name, ")", "},\n", NIL); + } + Setattr(nspace_hash, "name", name); + + Delete(components); + Delete(parent_path); + } else if (!reg) // This namespace shouldn't be registered. Lets remember it + Setattr(nspace_hash, "lua:no_reg", "1"); + + + Delete(mangled_name); mangled_name = 0; return nspace_hash; @@ -1829,6 +1863,7 @@ public: if (elua_ltr) Printv(methods_tab, tab4, "{LSTRKEY(\"__metatable\"), LROVAL(", metatable_tab_name, ")},\n", NIL); + Printv(methods_tab, tab4, "{LSTRKEY(\"__disown\"), LFUNCVAL(SWIG_Lua_class_disown)},\n", NIL); Printv(methods_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); } else Printf(methods_tab, " {0,0}\n};\n"); @@ -1847,41 +1882,59 @@ public: } if (elua_ltr) { String *get_tab = Getattr(nspace_hash, "get"); - String *get_tab_name = Getattr(nspace_hash, "get:name"); String *set_tab = Getattr(nspace_hash, "set"); - String *set_tab_name = Getattr(nspace_hash, "set:name"); Printv(get_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); Printv(set_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); Printv(output, get_tab, NIL); Printv(output, set_tab, NIL); + } + if (!eluac_ltr) { String *metatable_tab = Getattr(nspace_hash, "metatable"); assert(metatable_tab); - Printv(metatable_tab, tab4, "{LSTRKEY(\"__index\"), LFUNCVAL(SWIG_Lua_namespace_get)},\n", NIL); - Printv(metatable_tab, tab4, "{LSTRKEY(\"__newindex\"), LFUNCVAL(SWIG_Lua_namespace_set)},\n", NIL); - Printv(metatable_tab, tab4, "{LSTRKEY(\".get\"), LROVAL(", get_tab_name, ")},\n", NIL); - Printv(metatable_tab, tab4, "{LSTRKEY(\".set\"), LROVAL(", set_tab_name, ")},\n", NIL); - if (Getattr(nspace_hash, "lua:class_instance")) { - String *static_cls = Getattr(nspace_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 - 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); - // Put forward declaration of this array - Printv(output, "extern ", Getattr(static_cls, "methods:decl"), "\n", NIL); - } else if (Getattr(nspace_hash, "lua:class_static")) { - Hash *instance_cls = Getattr(nspace_hash, "lua:class_static:instance_hash"); - assert(instance_cls); - String *instance_cls_metatable_name = Getattr(instance_cls, "metatable:name"); - assert(instance_cls_metatable_name); - Printv(metatable_tab, tab4, "{LSTRKEY(\".instance\"), LROVAL(", instance_cls_metatable_name, ")},\n", NIL); + if (elua_ltr) { + String *get_tab_name = Getattr(nspace_hash, "get:name"); + String *set_tab_name = Getattr(nspace_hash, "set:name"); + + if (Getattr(nspace_hash, "lua:class_instance")) { + Printv(metatable_tab, tab4, "{LSTRKEY(\"__index\"), LFUNCVAL(SWIG_Lua_class_get)},\n", NIL); + Printv(metatable_tab, tab4, "{LSTRKEY(\"__newindex\"), LFUNCVAL(SWIG_Lua_class_set)},\n", NIL); + } else { + Printv(metatable_tab, tab4, "{LSTRKEY(\"__index\"), LFUNCVAL(SWIG_Lua_namespace_get)},\n", NIL); + Printv(metatable_tab, tab4, "{LSTRKEY(\"__newindex\"), LFUNCVAL(SWIG_Lua_namespace_set)},\n", NIL); + } + + Printv(metatable_tab, tab4, "{LSTRKEY(\"__gc\"), LFUNCVAL(SWIG_Lua_class_destruct)},\n", NIL); + Printv(metatable_tab, tab4, "{LSTRKEY(\".get\"), LROVAL(", get_tab_name, ")},\n", NIL); + Printv(metatable_tab, tab4, "{LSTRKEY(\".set\"), LROVAL(", set_tab_name, ")},\n", NIL); + Printv(metatable_tab, tab4, "{LSTRKEY(\".fn\"), LROVAL(", Getattr(nspace_hash, "methods:name"), ")},\n", NIL); + + if (Getattr(nspace_hash, "lua:class_instance")) { + String *static_cls = Getattr(nspace_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 + 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); + // Put forward declaration of this array + Printv(output, "extern ", Getattr(static_cls, "methods:decl"), "\n", NIL); + } else if (Getattr(nspace_hash, "lua:class_static")) { + Hash *instance_cls = Getattr(nspace_hash, "lua:class_static:instance_hash"); + assert(instance_cls); + String *instance_cls_metatable_name = Getattr(instance_cls, "metatable:name"); + assert(instance_cls_metatable_name); + Printv(metatable_tab, tab4, "{LSTRKEY(\".instance\"), LROVAL(", instance_cls_metatable_name, ")},\n", NIL); + } + + Printv(metatable_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); + } else { + Printf(metatable_tab, " {0,0}\n};\n"); } - Printv(metatable_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); Printv(output, metatable_tab, NIL); } + Printv(output, "\n", NIL); } @@ -1896,7 +1949,7 @@ public: void closeNamespaces(File *dataOutput) { // Special handling for empty module. if (Getattr(namespaces_hash, "") == 0) { - // Module is empty. Create hash for global scope in order to have swig__Global + // Module is empty. Create hash for global scope in order to have swig__Module // variable in resulting file getNamespaceHash(0); } From 0c6263a0c2f6c5794c6a2c943493579ea95eb72e Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Sun, 17 Nov 2013 04:08:58 +0400 Subject: [PATCH 416/481] Small bugfixes --- Lib/lua/luarun.swg | 2 +- Source/Modules/lua.cxx | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index 9f8f69476..a20b20806 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -76,7 +76,7 @@ typedef struct swig_elua_entry { #define lua_pushrotable(L,p)\ lua_newtable(L);\ - SWIG_Lua_elua_emulate_register(L,p); + SWIG_Lua_elua_emulate_register(L,(swig_elua_entry*)(p)); #define SWIG_LUA_CONSTTAB_POINTER(B,C,D)\ LSTRKEY(B), {LUA_TUSERDATA, { .userdata={0,0,(void*)(C),&D} } } diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index c68782e75..7e598517d 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -1776,7 +1776,11 @@ public: String *metatable_tab = NewString(""); String *metatable_tab_name = NewStringf("swig_%s_meta", mangled_name); String *metatable_tab_decl = NewString(""); - Printv(metatable_tab, "swig_lua_method ", metatable_tab_name, "[]", NIL); + if (elua_ltr || eluac_ltr) // In this case const array holds rotable with namespace constants + Printf(metatable_tab, "const LUA_REG_TYPE "); + else + Printf(metatable_tab, "static swig_lua_method "); + Printv(metatable_tab, metatable_tab_name, "[]", NIL); Printv(metatable_tab_decl, metatable_tab, ";", NIL); Printv(metatable_tab, " = {\n", NIL); Setattr(nspace_hash, "metatable", metatable_tab); From 14452cad031b464d9d1d4b4c06dd36c67b121dc6 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Sun, 17 Nov 2013 05:26:23 +0400 Subject: [PATCH 417/481] Attempt to catch unreproducable bug from Travis CI build --- Lib/lua/luarun.swg | 11 ++++++++--- Source/Modules/lua.cxx | 21 ++++++++++++++++++--- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index a20b20806..4aaa6eee7 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -76,6 +76,7 @@ typedef struct swig_elua_entry { #define lua_pushrotable(L,p)\ lua_newtable(L);\ + assert(p);\ SWIG_Lua_elua_emulate_register(L,(swig_elua_entry*)(p)); #define SWIG_LUA_CONSTTAB_POINTER(B,C,D)\ @@ -262,7 +263,7 @@ typedef struct swig_lua_class { swig_lua_method *methods; swig_lua_attribute *attributes; swig_lua_namespace *cls_static; - swig_lua_method *metatable; // only for eLua + swig_lua_method *metatable; // 0 for -eluac struct swig_lua_class **bases; const char **base_names; } swig_lua_class; @@ -1252,8 +1253,12 @@ SWIGINTERN void SWIG_Lua_add_class_instance_details(lua_State *L,swig_lua_class This adds methods from metatable array to metatable. Can mess up garbage collectind if someone defines __gc method */ - for(i=0;clss->metatable[i].name;i++) - SWIG_Lua_add_function(L,clss->metatable[i].name,clss->metatable[i].func); + if(clss->metatable) { + for(i=0;clss->metatable[i].name;i++) { + assert(clss->metatable[i].func != 0); // TODO: REMOVE + SWIG_Lua_add_function(L,clss->metatable[i].name,clss->metatable[i].func); + } + } } /* Register class static methods,attributes etc as well as constructor proxy */ diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 7e598517d..7349ce662 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -1194,6 +1194,7 @@ public: assert(class_static_nspace == 0); assert(class_fq_symname == 0); assert(class_symname == 0); + assert(class_parent_nspace == 0); current[NO_CPP] = false; @@ -1318,6 +1319,7 @@ public: // Module.ClassName.StaticMethod to access static method/variable/constant // Module.ClassName() to create new object if (have_constructor) { + assert(constructor_name); String *constructor_proxy_name = NewStringf("_proxy_%s", constructor_name); Printv(f_wrappers, "static int ", constructor_proxy_name, "(lua_State *L) {\n", NIL); Printv(f_wrappers, @@ -1385,6 +1387,12 @@ public: // First, print class static part printNamespaceDefinition(class_static_nspace, class_symname, f_wrappers); + assert(mangled_class_fq_symname); + assert(base_class); + assert(base_class_names); + assert(class_symname); + assert(class_fq_symname); + // Then print class isntance part Printv(f_wrappers, "static swig_lua_class *swig_", mangled_class_fq_symname, "_bases[] = {", base_class, "0};\n", NIL); Delete(base_class); @@ -1409,8 +1417,10 @@ public: } Printf(f_wrappers, ", %s, %s, &%s", s_methods_tab_name, s_attr_tab_name, Getattr(static_cls, "cname")); - if (!eluac_ltr) + if (!eluac_ltr) { + assert(Getattr(instance_cls, "metatable:name")); // TODO: REMOVE Printf(f_wrappers, ", %s", Getattr(instance_cls,"metatable:name")); + } else Printf(f_wrappers, ", 0"); @@ -1776,10 +1786,12 @@ public: String *metatable_tab = NewString(""); String *metatable_tab_name = NewStringf("swig_%s_meta", mangled_name); String *metatable_tab_decl = NewString(""); - if (elua_ltr || eluac_ltr) // In this case const array holds rotable with namespace constants + if (elua_ltr) // In this case const array holds rotable with namespace constants Printf(metatable_tab, "const LUA_REG_TYPE "); else Printf(metatable_tab, "static swig_lua_method "); + assert(metatable_tab); // TODO: REMOVE + assert(metatable_tab_name); // TODO: REMOVE Printv(metatable_tab, metatable_tab_name, "[]", NIL); Printv(metatable_tab_decl, metatable_tab, ";", NIL); Printv(metatable_tab, " = {\n", NIL); @@ -1861,11 +1873,14 @@ public: } String *methods_tab = Getattr(nspace_hash, "methods"); String *metatable_tab_name = Getattr(nspace_hash, "metatable:name"); + assert(methods_tab); // TODO: REMOVE if (elua_ltr || eluac_ltr) { if (v2_compatibility) Printv(methods_tab, tab4, "{LSTRKEY(\"const\"), LROVAL(", const_tab_name, ")},\n", NIL); - if (elua_ltr) + if (elua_ltr) { + assert(metatable_tab_name); // TODO: REMOVE Printv(methods_tab, tab4, "{LSTRKEY(\"__metatable\"), LROVAL(", metatable_tab_name, ")},\n", NIL); + } Printv(methods_tab, tab4, "{LSTRKEY(\"__disown\"), LFUNCVAL(SWIG_Lua_class_disown)},\n", NIL); Printv(methods_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); From e6d0f1327bea9917332e23e3653ef7f341f8bf9e Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Wed, 25 Dec 2013 17:50:22 +0400 Subject: [PATCH 418/481] Eliminating namespaces_hash and using symbols table instead --- Source/Modules/lang.cxx | 72 ++++++++++- Source/Modules/lua.cxx | 257 +++++++++++++++++++++------------------ Source/Modules/swigmod.h | 5 +- 3 files changed, 209 insertions(+), 125 deletions(-) diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 6e0e88507..92781c043 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -319,8 +319,7 @@ overloading(0), multiinput(0), cplus_runtime(0), directors(0) { - Hash *symbols = NewHash(); - Setattr(symtabs, "", symbols); // create top level/global symbol table scope + addScope(""); // create top level/global symbol table scope argc_template_string = NewString("argc"); argv_template_string = NewString("argv[%d]"); @@ -3061,9 +3060,7 @@ int Language::addSymbol(const String *s, const Node *n, const_String_or_char_ptr //Printf( stdout, "addSymbol: %s %s\n", s, scope ); Hash *symbols = Getattr(symtabs, scope ? scope : ""); if (!symbols) { - // New scope which has not been added by the target language - lazily created. - symbols = NewHash(); - Setattr(symtabs, scope, symbols); + symbols = addScope(scope); } else { Node *c = Getattr(symbols, s); if (c && (c != n)) { @@ -3079,6 +3076,71 @@ int Language::addSymbol(const String *s, const Node *n, const_String_or_char_ptr return 1; } +/* ----------------------------------------------------------------------------- + * Lanugage::addScope( const_String_or_char_ptr scopeName ) + * + * Creates a scope (symbols Hash) for given name. This method is auxilary, + * you don't have to call it - addSymbols will lazily create scopes automatically. + * If scope with given name already exists, then do nothing. + * Returns newly created (or already existing) scope. + * ----------------------------------------------------------------------------- */ +Hash* Language::addScope(const_String_or_char_ptr scope) { + Hash *symbols = scopeLookup(scope); + if(!symbols) { + // Order in which to following parts are executed is important. In Lanugage + // constructor addScope("") is called to create a top level scope itself. + // Thus we must first add symbols hash to symtab and only then add pseudo + // symbol to top-level scope + + // New scope which has not been added by the target language - lazily created. + symbols = NewHash(); + Setattr(symtabs, scope, symbols); + + // Add the new scope as a symbol in the top level scope. + // Alternatively the target language must add it in before attempting to add symbols into the scope. + const_String_or_char_ptr top_scope = ""; + Hash *topscope_symbols = Getattr(symtabs, top_scope); + Hash *pseudo_symbol = NewHash(); + Setattr(pseudo_symbol, "sym:is_scope", "1"); + Setattr(topscope_symbols, scope, pseudo_symbol); + } + return symbols; +} + +/* ----------------------------------------------------------------------------- + * Lanugage::scopeLookup( const_String_or_char_ptr scope ) + * + * Lookup and returns a symtable (hash) representing given scope. Hash contains + * all symbols in this scope. + * ----------------------------------------------------------------------------- */ +Hash* Language::scopeLookup( const_String_or_char_ptr scope ) { + Hash *symbols = Getattr(symtabs, scope ? scope : ""); + return symbols; +} + +/* ----------------------------------------------------------------------------- + * Lanugage::scopeSymbolLookup( const_String_or_char_ptr scope ) + * + * For every scope there is a special pseudo-symbol in the top scope (""). It + * exists solely to detect name clashes. This pseudo symbol may contain a few properties, + * but you can more if you need to. This is also true fro top level scope (""). + * It contains a pseudo symbol with name "" (empty). Pseudo symbol contains the + * following properties: + * sym:scope = "1" - a flag that this is scope pseudo symbol + * + * Pseudo symbols are a Hash*, not a Node* (not that there is a difference + * in DOH) + * There is no difference from symbolLookup() method except for signature + * and return type. + * ----------------------------------------------------------------------------- */ +Hash* Language::scopeSymbolLookup( const_String_or_char_ptr scope ) +{ + /* Getting top scope */ + const_String_or_char_ptr top_scope = ""; + Hash *symbols = Getattr(symtabs, top_scope); + return Getattr(symbols, scope); +} + /* ----------------------------------------------------------------------------- * Language::dumpSymbols() * ----------------------------------------------------------------------------- */ diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 7349ce662..6317f0910 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -120,7 +120,6 @@ private: File *f_initbeforefunc; String *s_luacode; // luacode to be called during init String *module; //name of the module - Hash *namespaces_hash; // Parameters for current class. NIL if not parsing class int have_constructor; @@ -176,13 +175,10 @@ public: class_fq_symname(0), class_static_nspace(0), constructor_name(0) { - namespaces_hash = NewHash(); for (int i = 0; i < STATES_COUNT; i++) current[i] = false; } ~LUA() { - if (namespaces_hash) - Delete(namespaces_hash); } bool strToInt(const char *string, int &value) { @@ -477,7 +473,7 @@ public: // Add method to the "methods" C array of given namespace/class void registerMethod(String *nspace_or_class_name, Node *n) { assert(n); - Hash *nspaceHash = getNamespaceHash(nspace_or_class_name); + Hash *nspaceHash = getCArraysHash(nspace_or_class_name); String *s_ns_methods_tab = Getattr(nspaceHash, "methods"); String *wname = Getattr(n, "wrap:name"); String *target_name = Getattr(n, "lua:name"); @@ -922,7 +918,7 @@ public: if (setName == 0 || GetFlag(n, "feature:immutable")) { setName = unassignable; } - Hash *nspaceHash = getNamespaceHash(nspace_or_class_name); + Hash *nspaceHash = getCArraysHash(nspace_or_class_name); String *s_ns_methods_tab = Getattr(nspaceHash, "methods"); String *s_ns_var_tab = Getattr(nspaceHash, "attributes"); String *target_name = Getattr(n, "lua:name"); @@ -968,7 +964,7 @@ public: * Actually, in current implementation it is resolved consttab typemap * ------------------------------------------------------------ */ void registerConstant(String *nspace, String *constantRecord) { - Hash *nspaceHash = getNamespaceHash(nspace); + Hash *nspaceHash = getCArraysHash(nspace); String *s_const_tab = 0; if (eluac_ltr || elua_ltr) // In elua everything goes to "methods" tab @@ -1102,7 +1098,7 @@ public: if (!luaAddSymbol(wrapname, n)) return SWIG_ERROR; - Hash *nspaceHash = getNamespaceHash(getNSpace()); + Hash *nspaceHash = getCArraysHash(getNSpace()); String *s_ns_methods_tab = Getattr(nspaceHash, "methods"); Printv(s_ns_methods_tab, tab4, "{ \"", symname, "\",", wrapname, "},\n", NIL); // return Language::nativeWrapper(n); // this does nothing... @@ -1165,12 +1161,12 @@ public: void registerClass(String *scope, Node *n) { String *wrap_class = Getattr(n,"wrap:class_name"); assert(wrap_class); - Hash *nspaceHash = getNamespaceHash(scope); + Hash *nspaceHash = getCArraysHash(scope); String *ns_classes = Getattr(nspaceHash, "classes"); Printv(ns_classes, "&", wrap_class, ",\n", NIL); if (elua_ltr || eluac_ltr) { String *ns_methods = Getattr(nspaceHash, "methods"); - Hash *class_hash = getNamespaceHash(class_static_nspace); + Hash *class_hash = getCArraysHash(class_static_nspace); assert(class_hash); String *cls_methods = Getattr(class_hash, "methods:name"); assert(cls_methods); @@ -1240,14 +1236,14 @@ public: // and constants are considered part of namespace T, all members - part of the 'class' // Now, here is a trick. Static methods, attributes and non-static methods and attributes // are described with same structures - swig_lua_attribute/swig_lua_method. Instead of calling - // getNamespaceHash(class name) to initialize things for static methods/attributes and then - // manually doing same initialization for non-static methods, we call getNamespaceHash 2 times: + // getCArraysHash(class name) to initialize things for static methods/attributes and then + // manually doing same initialization for non-static methods, we call getCArraysHash 2 times: // 1) With name "class name" + "." + "__Static" to initialize static things // 2) With "class name" to initialize non-static things // And we can guarantee that there will not be any name collision because names starting with 2 underscores // and capital letter are forbiden to use in C++. So, under know circumstances could our class contain // any member or subclass with name "__Static". Thus, never any name clash. - Hash *instance_cls = getNamespaceHash(class_fq_symname, false); + Hash *instance_cls = getCArraysHash(class_fq_symname, false); assert(instance_cls); String *s_attr_tab_name = Getattr(instance_cls, "attributes:name"); String *s_methods_tab_name = Getattr(instance_cls, "methods:name"); @@ -1260,7 +1256,7 @@ public: */ class_static_nspace = NewStringf("%s%s__Static", class_fq_symname, NSPACE_SEPARATOR); - Hash *static_cls = getNamespaceHash(class_static_nspace, false); + Hash *static_cls = getCArraysHash(class_static_nspace, false); assert(static_cls); Setattr(static_cls, "lua:no_namespaces", "1"); Setattr(static_cls, "lua:class_static", "1"); @@ -1272,8 +1268,6 @@ public: /* There is no use for "classes" and "namespaces" arrays. Subclasses are not supported * by SWIG and namespaces couldn't be nested inside classes (C++ Standard) */ - // Replacing namespace with namespace + class in order to static - // member be put inside class static area class_parent_nspace = getNSpace(); // Generate normal wrappers Language::classHandler(n); @@ -1293,7 +1287,7 @@ public: // Adding class to apropriate namespace registerClass(nspace, n); - Hash *nspaceHash = getNamespaceHash(nspace); + Hash *nspaceHash = getCArraysHash(nspace); // Register the class structure with the type checker // Printf(f_init,"SWIG_TypeClientData(SWIGTYPE%s, (void *) &_wrap_class_%s);\n", SwigType_manglestr(t), mangled_class_fq_symname); @@ -1349,8 +1343,8 @@ public: } } - closeNamespaceHash(class_fq_symname, f_wrappers); - closeNamespaceHash(class_static_nspace, f_wrappers); + closeCArraysHash(class_fq_symname, f_wrappers); + closeCArraysHash(class_static_nspace, f_wrappers); // Handle inheritance @@ -1385,7 +1379,7 @@ public: } } // First, print class static part - printNamespaceDefinition(class_static_nspace, class_symname, f_wrappers); + printCArraysDefinition(class_static_nspace, class_symname, f_wrappers); assert(mangled_class_fq_symname); assert(base_class); @@ -1670,10 +1664,24 @@ public: } /* ----------------------------------------------------------------------------- - * getNamespaceHash() + * rawGetCArraysHash(String *name) + * + * A small helper to hide impelementation of how CArrays hashes are stored + * ---------------------------------------------------------------------------- */ + Hash *rawGetCArraysHash(const_String_or_char_ptr name) { + Hash *scope = scopeLookup( name ? name : "" ); + if(!scope) + return 0; + + Hash *carrays_hash = Getattr(scope, "lua:cdata"); + return carrays_hash; + } + + /* ----------------------------------------------------------------------------- + * getCArraysHash() * Each namespace can be described with hash that stores C arrays * where members of the namespace should be added. All these hashes are stored - * inside namespaces_hash. + * inside symbols table, in pseudo-symbol for every namespace. * nspace could be NULL (NSPACE_TODO), that means functions and variables and classes * that are not in any namespace (this is default for SWIG unless %nspace feature is used) * You can later set some attributes that will affect behaviour of functions that use this hash: @@ -1685,11 +1693,17 @@ public: * Namespace could be automatically registered to it's parent if 'reg' == true. It can be done * only at first call (a.k.a when nspace is created). * ---------------------------------------------------------------------------- */ - Hash *getNamespaceHash(String *nspace, bool reg = true) { - Hash *nspace_hash = Getattr(namespaces_hash, nspace ? nspace : ""); - if (nspace_hash != 0) - return nspace_hash; - nspace_hash = NewHash(); + Hash *getCArraysHash(String *nspace, bool reg = true) { + Hash *scope = scopeLookup(nspace ? nspace : ""); + if(!scope) { + addScope( nspace ? nspace : "" ); + scope = scopeLookup(nspace ? nspace : ""); + assert(scope); + } + Hash *carrays_hash = Getattr(scope, "lua:cdata"); + if (carrays_hash != 0) + return carrays_hash; + carrays_hash = NewHash(); String *mangled_name = 0; if (nspace == 0 || Len(nspace) == 0) mangled_name = NewString("__Module"); // C++ names can't start with "__ + capital letter" @@ -1697,7 +1711,7 @@ public: mangled_name = Swig_name_mangle(nspace); String *cname = NewStringf("swig_%s", mangled_name); - Setattr(nspace_hash, "cname", cname); + Setattr(carrays_hash, "cname", cname); String *attr_tab = NewString(""); String *attr_tab_name = NewStringf("swig_%s_attributes", mangled_name); @@ -1706,9 +1720,9 @@ public: Printv(attr_tab, attr_tab_name, "[]", NIL); Printv(attr_tab_decl, attr_tab, ";\n", NIL); Printv(attr_tab, " = {\n", NIL); - Setattr(nspace_hash, "attributes", attr_tab); - Setattr(nspace_hash, "attributes:name", attr_tab_name); - Setattr(nspace_hash, "attributes:decl", attr_tab_decl); + Setattr(carrays_hash, "attributes", attr_tab); + Setattr(carrays_hash, "attributes:name", attr_tab_name); + Setattr(carrays_hash, "attributes:decl", attr_tab_decl); String *methods_tab = NewString(""); String *methods_tab_name = NewStringf("swig_%s_methods", mangled_name); @@ -1720,9 +1734,9 @@ public: Printv(methods_tab, methods_tab_name, "[]", NIL); Printv(methods_tab_decl, methods_tab, ";\n", NIL); Printv(methods_tab, "= {\n", NIL); - Setattr(nspace_hash, "methods", methods_tab); - Setattr(nspace_hash, "methods:name", methods_tab_name); - Setattr(nspace_hash, "methods:decl", methods_tab_decl); + Setattr(carrays_hash, "methods", methods_tab); + Setattr(carrays_hash, "methods:name", methods_tab_name); + Setattr(carrays_hash, "methods:decl", methods_tab_decl); String *const_tab = NewString(""); String *const_tab_name = NewStringf("swig_%s_constants", mangled_name); @@ -1734,9 +1748,9 @@ public: Printv(const_tab, const_tab_name, "[]", NIL); Printv(const_tab_decl, const_tab, ";", NIL); Printv(const_tab, "= {\n", NIL); - Setattr(nspace_hash, "constants", const_tab); - Setattr(nspace_hash, "constants:name", const_tab_name); - Setattr(nspace_hash, "constants:decl", const_tab_decl); + Setattr(carrays_hash, "constants", const_tab); + Setattr(carrays_hash, "constants:name", const_tab_name); + Setattr(carrays_hash, "constants:decl", const_tab_decl); String *classes_tab = NewString(""); String *classes_tab_name = NewStringf("swig_%s_classes", mangled_name); @@ -1745,9 +1759,9 @@ public: Printv(classes_tab, classes_tab_name, "[]", NIL); Printv(classes_tab_decl, classes_tab, ";", NIL); Printv(classes_tab, "= {\n", NIL); - Setattr(nspace_hash, "classes", classes_tab); - Setattr(nspace_hash, "classes:name", classes_tab_name); - Setattr(nspace_hash, "classes:decl", classes_tab_decl); + Setattr(carrays_hash, "classes", classes_tab); + Setattr(carrays_hash, "classes:name", classes_tab_name); + Setattr(carrays_hash, "classes:decl", classes_tab_decl); String *namespaces_tab = NewString(""); String *namespaces_tab_name = NewStringf("swig_%s_namespaces", mangled_name); @@ -1756,9 +1770,9 @@ public: Printv(namespaces_tab, namespaces_tab_name, "[]", NIL); Printv(namespaces_tab_decl, namespaces_tab, ";", NIL); Printv(namespaces_tab, " = {\n", NIL); - Setattr(nspace_hash, "namespaces", namespaces_tab); - Setattr(nspace_hash, "namespaces:name", namespaces_tab_name); - Setattr(nspace_hash, "namespaces:decl", namespaces_tab_decl); + Setattr(carrays_hash, "namespaces", namespaces_tab); + Setattr(carrays_hash, "namespaces:name", namespaces_tab_name); + Setattr(carrays_hash, "namespaces:decl", namespaces_tab_decl); if (elua_ltr) { String *get_tab = NewString(""); @@ -1767,9 +1781,9 @@ public: Printv(get_tab, "const LUA_REG_TYPE ", get_tab_name, "[]", NIL); Printv(get_tab_decl, get_tab, ";", NIL); Printv(get_tab, " = {\n", NIL); - Setattr(nspace_hash, "get", get_tab); - Setattr(nspace_hash, "get:name", get_tab_name); - Setattr(nspace_hash, "get:decl", get_tab_decl); + Setattr(carrays_hash, "get", get_tab); + Setattr(carrays_hash, "get:name", get_tab_name); + Setattr(carrays_hash, "get:decl", get_tab_decl); String *set_tab = NewString(""); String *set_tab_name = NewStringf("swig_%s_set", mangled_name); @@ -1777,9 +1791,9 @@ public: Printv(set_tab, "const LUA_REG_TYPE ", set_tab_name, "[]", NIL); Printv(set_tab_decl, set_tab, ";", NIL); Printv(set_tab, " = {\n", NIL); - Setattr(nspace_hash, "set", set_tab); - Setattr(nspace_hash, "set:name", set_tab_name); - Setattr(nspace_hash, "set:decl", set_tab_decl); + Setattr(carrays_hash, "set", set_tab); + Setattr(carrays_hash, "set:name", set_tab_name); + Setattr(carrays_hash, "set:decl", set_tab_decl); } if (!eluac_ltr) { @@ -1795,16 +1809,15 @@ public: Printv(metatable_tab, metatable_tab_name, "[]", NIL); Printv(metatable_tab_decl, metatable_tab, ";", NIL); Printv(metatable_tab, " = {\n", NIL); - Setattr(nspace_hash, "metatable", metatable_tab); - Setattr(nspace_hash, "metatable:name", metatable_tab_name); - Setattr(nspace_hash, "metatable:decl", metatable_tab_decl); + Setattr(carrays_hash, "metatable", metatable_tab); + Setattr(carrays_hash, "metatable:name", metatable_tab_name); + Setattr(carrays_hash, "metatable:decl", metatable_tab_decl); } - String *key = 0; - if (nspace != 0) - key = Copy(nspace); - Setattr(namespaces_hash, key ? key : "", nspace_hash); - if (reg && nspace != 0 && Len(nspace) != 0 && Getattr(nspace_hash, "lua:no_reg") == 0) { + Setattr(scope, "lua:cdata", carrays_hash); + assert(rawGetCArraysHash(nspace)); + + if (reg && nspace != 0 && Len(nspace) != 0 && Getattr(carrays_hash, "lua:no_reg") == 0) { // Split names into components List *components = Split(nspace, '.', -1); String *parent_path = NewString(""); @@ -1817,50 +1830,49 @@ public: Printv(parent_path, item, NIL); } //Printf(stdout, "Registering %s. User name %s. C-name %s, Parent is %s\n", mangled_name, name, cname, parent_path); // TODO: REMOVE - Hash *parent = getNamespaceHash(parent_path, true); + Hash *parent = getCArraysHash(parent_path, true); String *namespaces_tab = Getattr(parent, "namespaces"); Printv(namespaces_tab, "&", cname, ",\n", NIL); if (elua_ltr || eluac_ltr) { String *methods_tab = Getattr(parent, "methods"); Printv(methods_tab, tab4, "{LSTRKEY(\"", name, "\")", ", LROVAL(", methods_tab_name, ")", "},\n", NIL); } - Setattr(nspace_hash, "name", name); + Setattr(carrays_hash, "name", name); Delete(components); Delete(parent_path); } else if (!reg) // This namespace shouldn't be registered. Lets remember it - Setattr(nspace_hash, "lua:no_reg", "1"); - + Setattr(carrays_hash, "lua:no_reg", "1"); Delete(mangled_name); mangled_name = 0; - return nspace_hash; + return carrays_hash; } /* ----------------------------------------------------------------------------- - * closeNamespaceHash() + * closeCArraysHash() * Functions add end markers {0,0,...,0} to all arrays, prints them to * output and marks hash as closed (lua:closed). Consequent attempts to * close same hash will result in error - * closeNamespaceHash DOES NOT print structure that describes namespace, it only - * prints array. You can use printNamespaceDefinition to print structure. + * closeCArraysHash DOES NOT print structure that describes namespace, it only + * prints array. You can use printCArraysDefinition to print structure. * if "lua:no_namespaces" is set, then array for "namespaces" won't be printed * if "lua:no_classes" is set, then array for "classes" won't be printed * ----------------------------------------------------------------------------- */ - void closeNamespaceHash(String *nspace, File *output) { - Hash *nspace_hash = Getattr(namespaces_hash, nspace); - assert(nspace_hash); - assert(Getattr(nspace_hash, "lua:closed") == 0); + void closeCArraysHash(String *nspace, File *output) { + Hash *carrays_hash = rawGetCArraysHash(nspace); + assert(carrays_hash); + assert(Getattr(carrays_hash, "lua:closed") == 0); - Setattr(nspace_hash, "lua:closed", "1"); + Setattr(carrays_hash, "lua:closed", "1"); - String *attr_tab = Getattr(nspace_hash, "attributes"); + String *attr_tab = Getattr(carrays_hash, "attributes"); Printf(attr_tab, " {0,0,0}\n};\n"); Printv(output, attr_tab, NIL); - String *const_tab = Getattr(nspace_hash, "constants"); - String *const_tab_name = Getattr(nspace_hash, "constants:name"); + String *const_tab = Getattr(carrays_hash, "constants"); + String *const_tab_name = Getattr(carrays_hash, "constants:name"); if (elua_ltr || eluac_ltr) Printv(const_tab, tab4, "{LNILKEY, LNILVAL}\n", "};\n", NIL); else @@ -1869,10 +1881,10 @@ public: if (elua_ltr) { // Put forward declaration of metatable array - Printv(output, "extern ", Getattr(nspace_hash, "metatable:decl"), "\n", NIL); + Printv(output, "extern ", Getattr(carrays_hash, "metatable:decl"), "\n", NIL); } - String *methods_tab = Getattr(nspace_hash, "methods"); - String *metatable_tab_name = Getattr(nspace_hash, "metatable:name"); + String *methods_tab = Getattr(carrays_hash, "methods"); + String *metatable_tab_name = Getattr(carrays_hash, "metatable:name"); assert(methods_tab); // TODO: REMOVE if (elua_ltr || eluac_ltr) { if (v2_compatibility) @@ -1888,20 +1900,20 @@ public: Printf(methods_tab, " {0,0}\n};\n"); Printv(output, methods_tab, NIL); - if (!Getattr(nspace_hash, "lua:no_classes")) { - String *classes_tab = Getattr(nspace_hash, "classes"); + if (!Getattr(carrays_hash, "lua:no_classes")) { + String *classes_tab = Getattr(carrays_hash, "classes"); Printf(classes_tab, " 0\n};\n"); Printv(output, classes_tab, NIL); } - if (!Getattr(nspace_hash, "lua:no_namespaces")) { - String *namespaces_tab = Getattr(nspace_hash, "namespaces"); + if (!Getattr(carrays_hash, "lua:no_namespaces")) { + String *namespaces_tab = Getattr(carrays_hash, "namespaces"); Printf(namespaces_tab, " 0\n};\n"); Printv(output, namespaces_tab, NIL); } if (elua_ltr) { - String *get_tab = Getattr(nspace_hash, "get"); - String *set_tab = Getattr(nspace_hash, "set"); + String *get_tab = Getattr(carrays_hash, "get"); + String *set_tab = Getattr(carrays_hash, "set"); Printv(get_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); Printv(set_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL); Printv(output, get_tab, NIL); @@ -1909,13 +1921,13 @@ public: } if (!eluac_ltr) { - String *metatable_tab = Getattr(nspace_hash, "metatable"); + String *metatable_tab = Getattr(carrays_hash, "metatable"); assert(metatable_tab); if (elua_ltr) { - String *get_tab_name = Getattr(nspace_hash, "get:name"); - String *set_tab_name = Getattr(nspace_hash, "set:name"); + String *get_tab_name = Getattr(carrays_hash, "get:name"); + String *set_tab_name = Getattr(carrays_hash, "set:name"); - if (Getattr(nspace_hash, "lua:class_instance")) { + if (Getattr(carrays_hash, "lua:class_instance")) { Printv(metatable_tab, tab4, "{LSTRKEY(\"__index\"), LFUNCVAL(SWIG_Lua_class_get)},\n", NIL); Printv(metatable_tab, tab4, "{LSTRKEY(\"__newindex\"), LFUNCVAL(SWIG_Lua_class_set)},\n", NIL); } else { @@ -1926,10 +1938,10 @@ public: Printv(metatable_tab, tab4, "{LSTRKEY(\"__gc\"), LFUNCVAL(SWIG_Lua_class_destruct)},\n", NIL); Printv(metatable_tab, tab4, "{LSTRKEY(\".get\"), LROVAL(", get_tab_name, ")},\n", NIL); Printv(metatable_tab, tab4, "{LSTRKEY(\".set\"), LROVAL(", set_tab_name, ")},\n", NIL); - Printv(metatable_tab, tab4, "{LSTRKEY(\".fn\"), LROVAL(", Getattr(nspace_hash, "methods:name"), ")},\n", NIL); + Printv(metatable_tab, tab4, "{LSTRKEY(\".fn\"), LROVAL(", Getattr(carrays_hash, "methods:name"), ")},\n", NIL); - if (Getattr(nspace_hash, "lua:class_instance")) { - String *static_cls = Getattr(nspace_hash, "lua:class_instance:static_hash"); + if (Getattr(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 @@ -1938,8 +1950,8 @@ public: Printv(metatable_tab, tab4, "{LSTRKEY(\".static\"), LROVAL(", static_cls_cname, ")},\n", NIL); // Put forward declaration of this array Printv(output, "extern ", Getattr(static_cls, "methods:decl"), "\n", NIL); - } else if (Getattr(nspace_hash, "lua:class_static")) { - Hash *instance_cls = Getattr(nspace_hash, "lua:class_static:instance_hash"); + } else if (Getattr(carrays_hash, "lua:class_static")) { + Hash *instance_cls = Getattr(carrays_hash, "lua:class_static:instance_hash"); assert(instance_cls); String *instance_cls_metatable_name = Getattr(instance_cls, "metatable:name"); assert(instance_cls_metatable_name); @@ -1962,42 +1974,53 @@ public: } /* ----------------------------------------------------------------------------- - * closeNamespaceHash() + * closeCArraysHash() * Recursively close all non-closed namespaces. Prints data to dataOutput. * ----------------------------------------------------------------------------- */ void closeNamespaces(File *dataOutput) { // Special handling for empty module. - if (Getattr(namespaces_hash, "") == 0) { + if (scopeLookup("") == 0 || rawGetCArraysHash("") == 0) { // Module is empty. Create hash for global scope in order to have swig__Module // variable in resulting file - getNamespaceHash(0); + getCArraysHash(0); } - Iterator ki = First(namespaces_hash); + // Because we cant access directly 'symtabs', instead we access + // top-level scope and look on all scope pseudo-symbols in it. + Hash *top_scope = scopeLookup(""); + assert(top_scope); + Iterator ki = First(top_scope); List *to_close = NewList(); while (ki.key) { - if (Getattr(ki.item, "lua:closed") == 0) - Append(to_close, ki.key); + assert(ki.item); + if (Getattr(ki.item, "sym:is_scope")) { + // We have a pseudo symbol. Lets get actuall scope for this + // pseudo symbol + Hash *carrays_hash = rawGetCArraysHash(ki.key); + assert(carrays_hash); + if (Getattr(carrays_hash, "lua:closed") == 0) + Append(to_close, ki.key); + } ki = Next(ki); } SortList(to_close, &compareByLen); int len = Len(to_close); for (int i = 0; i < len; i++) { String *key = Getitem(to_close, i); - closeNamespaceHash(key, dataOutput); - Hash *nspace = Getattr(namespaces_hash, key); + closeCArraysHash(key, dataOutput); + Hash *carrays_hash = rawGetCArraysHash(key); String *name = 0; // name - name of the namespace as it should be visible in Lua if (DohLen(key) == 0) // This is global module name = module; else - name = Getattr(nspace, "name"); + name = Getattr(carrays_hash, "name"); assert(name); - printNamespaceDefinition(key, name, dataOutput); + printCArraysDefinition(key, name, dataOutput); } Delete(to_close); } /* ----------------------------------------------------------------------------- - * printNamespaceDefinition() + * printCArraysDefinition() * This function prints to output a definition of namespace in * form * swig_lua_namespace $cname = { attr_array, methods_array, ... , namespaces_array }; @@ -2005,21 +2028,21 @@ public: * 'name' is a user-visible name that this namespace will have in Lua. It shouldn't * be fully qualified name, just it's own name. * ----------------------------------------------------------------------------- */ - void printNamespaceDefinition(String *nspace, String *name, File *output) { - Hash *nspace_hash = getNamespaceHash(nspace, false); + void printCArraysDefinition(String *nspace, String *name, File *output) { + Hash *carrays_hash = getCArraysHash(nspace, false); - String *cname = Getattr(nspace_hash, "cname"); // cname - name of the C structure that describes namespace + String *cname = Getattr(carrays_hash, "cname"); // cname - name of the C structure that describes namespace assert(cname); Printv(output, "static swig_lua_namespace ", cname, " = ", NIL); String *null_string = NewString("0"); - String *attr_tab_name = Getattr(nspace_hash, "attributes:name"); - String *methods_tab_name = Getattr(nspace_hash, "methods:name"); - String *const_tab_name = Getattr(nspace_hash, "constants:name"); - String *classes_tab_name = Getattr(nspace_hash, "classes:name"); - String *namespaces_tab_name = Getattr(nspace_hash, "namespaces:name"); - bool has_classes = Getattr(nspace_hash, "lua:no_classes") == 0; - bool has_namespaces = Getattr(nspace_hash, "lua:no_namespaces") == 0; + String *attr_tab_name = Getattr(carrays_hash, "attributes:name"); + String *methods_tab_name = Getattr(carrays_hash, "methods:name"); + String *const_tab_name = Getattr(carrays_hash, "constants:name"); + String *classes_tab_name = Getattr(carrays_hash, "classes:name"); + String *namespaces_tab_name = Getattr(carrays_hash, "namespaces:name"); + bool has_classes = Getattr(carrays_hash, "lua:no_classes") == 0; + bool has_namespaces = Getattr(carrays_hash, "lua:no_namespaces") == 0; Printv(output, "{\n", tab4, "\"", name, "\",\n", @@ -2064,15 +2087,12 @@ public: /* ----------------------------------------------------------------------------- * luaAddSymbol() - * Our implementation of addSymbol. Determines scope correctly, then calls Language::addSymbol + * Our implementation of addSymbol. Determines scope correctly, then + * forwards to Language::addSymbol * ----------------------------------------------------------------------------- */ int luaAddSymbol(const String *s, const Node *n) { String *scope = luaCurrentSymbolNSpace(); - //Printf(stdout, "luaAddSymbol: %s scope: %s\n", s, scope); - int result = Language::addSymbol(s, n, scope); - if (!result) - Printf(stderr, "addSymbol(%s to scope %s) failed\n", s, scope); - return result; + return luaAddSymbol(s, n, scope); } /* ----------------------------------------------------------------------------- @@ -2080,7 +2100,6 @@ public: * Overload. Enforces given scope. Actually, it simply forwards call to Language::addSymbol * ----------------------------------------------------------------------------- */ int luaAddSymbol(const String *s, const Node *n, const_String_or_char_ptr scope) { - //Printf(stdout, "luaAddSymbol: %s scope: %s\n", s, scope); int result = Language::addSymbol(s, n, scope); if (!result) Printf(stderr, "addSymbol(%s to scope %s) failed\n", s, scope); diff --git a/Source/Modules/swigmod.h b/Source/Modules/swigmod.h index 2929993b3..40064ea38 100644 --- a/Source/Modules/swigmod.h +++ b/Source/Modules/swigmod.h @@ -215,7 +215,10 @@ public: virtual int validIdentifier(String *s); /* valid identifier? */ virtual int addSymbol(const String *s, const Node *n, const_String_or_char_ptr scope = ""); /* Add symbol */ virtual void dumpSymbols(); - virtual Node *symbolLookup(String *s, const_String_or_char_ptr scope = ""); /* Symbol lookup */ + virtual Node *symbolLookup(String *s, const_String_or_char_ptr scope = ""); /* Symbol lookup */ + virtual Hash* addScope(const_String_or_char_ptr scope); + virtual Hash* scopeLookup( const_String_or_char_ptr scope ); + virtual Hash* scopeSymbolLookup( const_String_or_char_ptr scope ); virtual Node *classLookup(const SwigType *s) const; /* Class lookup */ virtual Node *enumLookup(SwigType *s); /* Enum lookup */ virtual int abstractClassTest(Node *n); /* Is class really abstract? */ From 3d36a69d81bd47b43163a49c65c3c7b1e0edd133 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Wed, 13 Nov 2013 18:10:43 +0400 Subject: [PATCH 419/481] Updating Lua documentation --- Doc/Manual/Lua.html | 207 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 202 insertions(+), 5 deletions(-) diff --git a/Doc/Manual/Lua.html b/Doc/Manual/Lua.html index 88d26f385..b890a7138 100644 --- a/Doc/Manual/Lua.html +++ b/Doc/Manual/Lua.html @@ -70,6 +70,7 @@ Lua is an extension programming language designed to support general procedural programming with data description facilities. It also offers good support for object-oriented programming, functional programming, and data-driven programming. Lua is intended to be used as a powerful, light-weight configuration language for any program that needs one. Lua is implemented as a library, written in clean C (that is, in the common subset of ANSI C and C++). It's also a really tiny language, less than 6000 lines of code, which compiles to <100 kilobytes of binary code. It can be found at http://www.lua.org

      +TODO: Fix if elua disabled eLua stands for Embedded Lua (can be thought of as a flavor of Lua) and offers the full implementation of the Lua programming language to the embedded world, extending it with specific features for efficient and portable software embedded development. eLua runs on smaller devices like microcontrollers and provides the full features of the regular Lua desktop version. More information on eLua can be found here: http://www.eluaproject.net

      @@ -77,6 +78,7 @@ eLua stands for Embedded Lua (can be thought of as a flavor of Lua) and offers t

      +TODO: Fix if elua disabled The current SWIG implementation is designed to work with Lua 5.0.x, 5.1.x and 5.2.x. It should work with later versions of Lua, but certainly not with Lua 4.0 due to substantial API changes. It is possible to either static link or dynamic link a Lua module into the interpreter (normally Lua static links its libraries, as dynamic linking is not available on all platforms). SWIG also supports eLua and works with eLua 0.8. SWIG generated code for eLua has been tested on Stellaris ARM Cortex-M3 LM3S and Infineon TriCore.

      @@ -159,6 +161,10 @@ swig -lua -help Do not register the module name as a global variable but return the module table from calls to require. + + -swig3 + Disable backward compatibility: old-style binding names generations and a few other things. Explanations are included into appropriate sections. +

      26.2.2 Compiling and Linking and Interpreter

      @@ -349,7 +355,8 @@ creates a built-in function example.fact(n) that works exactly like you >

      -To avoid name collisions, SWIG create a Lua table which it keeps all the functions and global variables in. It is possible to copy the functions out of this and into the global environment with the following code. This can easily overwrite existing functions, so this must be used with care. +To avoid name collisions, SWIG create a Lua table which it keeps all the functions, constants, classes and global variables in. It is possible to copy the functions, constants and classes (but not variables) out of this and into the global environment with the following code. This can easily overwrite existing functions, so this must be used with care. +This option is considered deprecated and will be removed in near future.

       > for k,v in pairs(example) do _G[k]=v end
      @@ -490,6 +497,52 @@ If you're using eLua and have used -elua or -eluac to generate
       > print(example.const.SCONST)
       Hello World
       
      + +

      Constants/enums and classes/structures

      +

      +Unlike previous version of bindings, enums are now exported into class table. For example, given some enums: +

      +
      %module example
      +enum Days{SUNDAY = 0,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY};
      +class Test {
      +    enum { TEST1 = 10, TEST2 = 10 }
      +    static const int ICONST = 12;
      +};
      +
      +

      +This is 'effectively' converted into the following Lua code: +

      +
      +> print(example.const.SUNDAY)
      +0
      +> print(example.Test.TEST1)
      +10
      +> print(example.Test.ICONST)
      +12
      +
      +

      Backward compatibility

      +

      +If -swig3 option is not given, then in addition to previously described bindings, the old-style ones are generated: +

      +
      +> print(example.Test_TEST1)
      +10
      +> print(example.Test_ICONST)
      +12
      +
      +

      +However, in C mode, names of enums are not prefixed with names of structure. This is the due to C Standard. +

      +
      +> print(example.TEST1)
      +10
      +> print(example.ICONST)
      +12
      +
      +

      +It worth mentioning, that example.Test.TEST1 and example.Test_TEST1 are different entities and changind one wouldn't change another. +Given the fact, that these are constantes and they are not supposed to be changed, it is up to you to avoid such issues. +

      26.3.5 Pointers

      @@ -551,7 +604,7 @@ is used as follows:

      Similar access is provided for unions and the data members of C++ classes.
      -C structures are created using a function new_Point(), but for C++ classes are created using just the name Point(). +C structures can be created using a function new_Point(), and both C structures and C++ classes can be created using just the name Point().

      If you print out the value of p in the above example, you will see something like this: @@ -679,9 +732,9 @@ public: In Lua, the static members can be accessed as follows:

      -> example.Spam_foo()            -- calling Spam::foo()
      -> a=example.Spam_bar            -- reading Spam::bar 
      -> example.Spam_bar=b            -- writing to Spam::bar
      +> example.Spam.foo()            -- calling Spam::foo()
      +> a=example.Spam.bar            -- reading Spam::bar 
      +> example.Spam.bar=b            -- writing to Spam::bar
       

      It is not (currently) possible to access static members of an instance: @@ -692,6 +745,13 @@ It is not (currently) possible to access static members of an instance: -- does NOT work +

      Backward compatibility

      +

      If -swig3 option is not given, then backward compatible names are generated in addition to ordinary ones:

      +
      +> example.Spam_foo()            -- calling Spam::foo()
      +> a=example.Spam_bar            -- reading Spam::bar 
      +> example.Spam_bar=b            -- writing to Spam::bar
      +

      26.3.8 C++ inheritance

      @@ -1256,6 +1316,143 @@ and the "Exception handling add exception specification to functions or globally (respectively).

      +

      26.3.17 Namespaces

      +

      +Since SWIG 3.0 C++ namespaces are supported. You can enabled handling namespaces with %nspace feature. Everything below is valid only after you enabled %nspace. +

      +

      Namespaces are mapped into lua tables. Each of those tables contains names that were defined within appropriate namespace. Namespaces structure (a.k.a nested namespaces is preserved). Consider the following C++ code: +

      +
      %module example
      +%nspace MyWorld::Nested::Dweller;
      +%nspace MyWorld::World;
      +/* and so on */
      +int module_function() { return 7;}
      +int module_variable; // = 9
      +namespace MyWorld {
      +  class World {
      +  public:
      +    int create_world() { return 17;}
      +    const int world_max_count = 9;
      +  };
      +  namespace Nested {
      +    class Dweller {
      +      enum Gender {MALE, FEMALE;
      +      static int populate_cave() { return 19; }
      +      int create_cave() { return 13;}
      +      int food_count; // = 11
      +    }
      +  }
      +}
      +
      +Now, in Lua it could be used like this: +
      +> example.module_function()
      +7
      +> print(example.module_variable)
      +8
      +> print(example.MyWorld.World():create_world())
      +17
      +> print(example.MyWorld.World.world_max_count)
      +9
      +> print(example.MyWordl.Nested.Dweller.MALE)
      +0
      +> print(example.MyWordl.Nested.Dweller().food_count)
      +11
      +>
      +
      +

      Backward compatibility

      +

      +If SWIG is running in backward compatible way, i.e. without -swig3 option, then additional old-style names are generated(notice the underscore): +

      +
      +9
      +> print(example.MyWorld.Nested.Dweller_MALE)
      +0
      +> print(example.MyWorld.Nested.Dweller_populate_cave())
      +11
      +>
      +
      +

      Backward compatibility

      +

      Names

      +

      If SWIG is launched without -swig3 option, then it enters backward-compatible mode. While in this mode, it tries +to generate additional names for static functions, class static constants and class enums. +Those names are in a form $classname_$symbolname and are added to the scope surrounding the class. +If %nspace is enabled, then class namespace is taken as scope. If there is no namespace, or %nspace is disabled, +then module is considered a class namespace.

      +

      Consider the following C++ code

      +
      %module example
      +%nspace MyWorld::Test;
      +namespace MyWorld {
      +class Test {
      +  public:
      +  enum { TEST1 = 10, TEST2 }
      +  static const int ICONST = 12;
      +};
      +class Test2 {
      +  public:
      +  enum { TEST3 = 20, TEST4 }
      +  static const int ICONST2 = 23;
      +}
      +
      +

      When in backward compatible mode, in addition to usual names, the following ones will be generated (notice the underscore):

      +
      +9
      +> print(example.MyWorld.Test_TEST1) -- Test has %nspace enabled
      +10
      +> print(example.MyWorld.Test_ICONST) -- Test has %nspace enabled
      +12
      +> print(example.Test2_TEST3) -- Test2 doesn't have %nspace enabled
      +20
      +> print(example.Test2_ICONST2) -- Test2 doesn't have %nspace enabled
      +23
      +>
      +
      +

      There is a slight difference with enums when in C mode. As per C standard, enums from C structures are exported to +surrounding scope without any prefixing. Pretending that Test2 is a struct, not class, that would be:

      +
      +> print(example.TEST3) -- NOT Test2_TEST3
      +20
      +>
      +
      + +

      Inheritance

      +

      There internal organization of inheritance has changed. +Consider the following C++ code:

      +
      %module example
      +class Base {
      +  public:
      +  int base_func()
      +};
      +class Derived : public Base {
      +  public:
      +  int derived_func()
      +}
      +
      +

      Lets assume for a moment that class member functions are stored in .fn table. Previously, when classes +were exported to Lua during module initialization, for every derived class all service tables ST(i.e. ".fn") +were squashed and added to corresponding derived class ST: Everything from .fn table of class Base +was copied to .fn table of class Derived and so on. This was a recursive procedure, so in the end the whole +inheritance tree of derived class was squashed into derived class.

      +

      That means that any changes done to class Base after module initialization wouldn't affect class Derived:

      +
      +base = example.Base()
      +der = example.Derived()
      +> print(base.base_func)
      +function: 0x1367940
      +> getmetatable(base)[".fn"].new_func = function (x) return x -- Adding new function to class Base (to class, not to an instance!)
      +> print(base.new_func) -- Checking this function
      +function
      +> print(der.new_func) -- Wouldn't work. Derived doesn't check Base any more.
      +nil
      +>
      +
      +

      This has been fixed. Now Derived store a list of it's bases and if some symbol is not found in it's own service tables +then its bases are searched for it. +

      +> print(der.new_func) -- Now it works
      +function
      +>
      +

      26.4 Typemaps

      From 00f59ac497c5a6e4fa4a3b3eddcfdbc727f13771 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Wed, 25 Dec 2013 18:24:17 +0400 Subject: [PATCH 420/481] Small documenation fixes --- Doc/Manual/Lua.html | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/Doc/Manual/Lua.html b/Doc/Manual/Lua.html index b890a7138..31c9dd564 100644 --- a/Doc/Manual/Lua.html +++ b/Doc/Manual/Lua.html @@ -70,7 +70,6 @@ Lua is an extension programming language designed to support general procedural programming with data description facilities. It also offers good support for object-oriented programming, functional programming, and data-driven programming. Lua is intended to be used as a powerful, light-weight configuration language for any program that needs one. Lua is implemented as a library, written in clean C (that is, in the common subset of ANSI C and C++). It's also a really tiny language, less than 6000 lines of code, which compiles to <100 kilobytes of binary code. It can be found at http://www.lua.org

      -TODO: Fix if elua disabled eLua stands for Embedded Lua (can be thought of as a flavor of Lua) and offers the full implementation of the Lua programming language to the embedded world, extending it with specific features for efficient and portable software embedded development. eLua runs on smaller devices like microcontrollers and provides the full features of the regular Lua desktop version. More information on eLua can be found here: http://www.eluaproject.net

      @@ -78,8 +77,7 @@ eLua stands for Embedded Lua (can be thought of as a flavor of Lua) and offers t

      -TODO: Fix if elua disabled -The current SWIG implementation is designed to work with Lua 5.0.x, 5.1.x and 5.2.x. It should work with later versions of Lua, but certainly not with Lua 4.0 due to substantial API changes. It is possible to either static link or dynamic link a Lua module into the interpreter (normally Lua static links its libraries, as dynamic linking is not available on all platforms). SWIG also supports eLua and works with eLua 0.8. SWIG generated code for eLua has been tested on Stellaris ARM Cortex-M3 LM3S and Infineon TriCore. +The current SWIG implementation is designed to work with Lua 5.0.x, 5.1.x and 5.2.x. It should work with later versions of Lua, but certainly not with Lua 4.0 due to substantial API changes. It is possible to either static link or dynamic link a Lua module into the interpreter (normally Lua static links its libraries, as dynamic linking is not available on all platforms). SWIG also has support for eLua starting from eLua 0.8. Due to substantial changes between SWIG 2.x and SWIG 3.0 and unavailability of testing platform, eLua status was downgraded to 'experimental'.

      26.2 Running SWIG

      @@ -165,6 +163,10 @@ swig -lua -help -swig3 Disable backward compatibility: old-style binding names generations and a few other things. Explanations are included into appropriate sections. + + -squash-bases + Squashes symbols from all inheritance tree of a given class into itself. Emulates pre-SWIG3.0 inheritance. Insignificantly speeds things up, but increases memory consumption. +

      26.2.2 Compiling and Linking and Interpreter

      @@ -1320,7 +1322,7 @@ add exception specification to functions or globally (respectively).

      Since SWIG 3.0 C++ namespaces are supported. You can enabled handling namespaces with %nspace feature. Everything below is valid only after you enabled %nspace.

      -

      Namespaces are mapped into lua tables. Each of those tables contains names that were defined within appropriate namespace. Namespaces structure (a.k.a nested namespaces is preserved). Consider the following C++ code: +

      Namespaces are mapped into lua tables. Each of those tables contains names that were defined within appropriate namespace. Namespaces structure (a.k.a nested namespaces) is preserved. Consider the following C++ code:

      %module example
       %nspace MyWorld::Nested::Dweller;
      @@ -1416,7 +1418,7 @@ surrounding scope without any prefixing. Pretending that Test2 is a struct, not
       

      Inheritance

      -

      There internal organization of inheritance has changed. +

      The internal organization of inheritance has changed. Consider the following C++ code:

      %module example
       class Base {
      @@ -1446,8 +1448,8 @@ function
       nil
       >
       
      -

      This has been fixed. Now Derived store a list of it's bases and if some symbol is not found in it's own service tables -then its bases are searched for it. +

      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 +then its bases are searched for it. Option -squash-bases will effectively return old behaviour.

       > print(der.new_func) -- Now it works
       function
      
      From 4eef510e33e2381c515af199127842ff84d6e8f1 Mon Sep 17 00:00:00 2001
      From: Artem Serebriyskiy 
      Date: Thu, 26 Dec 2013 16:32:45 +0400
      Subject: [PATCH 421/481] Rename methods to make it clear what 'symbols table'
       they operate on.
      
      ---
       Source/Modules/lang.cxx  | 18 +++++++++---------
       Source/Modules/lua.cxx   | 12 ++++++------
       Source/Modules/swigmod.h |  6 +++---
       3 files changed, 18 insertions(+), 18 deletions(-)
      
      diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx
      index 92781c043..7933d5a49 100644
      --- a/Source/Modules/lang.cxx
      +++ b/Source/Modules/lang.cxx
      @@ -319,7 +319,7 @@ overloading(0),
       multiinput(0),
       cplus_runtime(0),
       directors(0) {
      -  addScope(""); // create top level/global symbol table scope
      +  symbolAddScope(""); // create top level/global symbol table scope
         argc_template_string = NewString("argc");
         argv_template_string = NewString("argv[%d]");
       
      @@ -3060,7 +3060,7 @@ int Language::addSymbol(const String *s, const Node *n, const_String_or_char_ptr
         //Printf( stdout, "addSymbol: %s %s\n", s, scope );
         Hash *symbols = Getattr(symtabs, scope ? scope : "");
         if (!symbols) {
      -    symbols = addScope(scope);
      +    symbols = symbolAddScope(scope);
         } else {
           Node *c = Getattr(symbols, s);
           if (c && (c != n)) {
      @@ -3077,15 +3077,15 @@ int Language::addSymbol(const String *s, const Node *n, const_String_or_char_ptr
       }
       
       /* -----------------------------------------------------------------------------
      - * Lanugage::addScope( const_String_or_char_ptr scopeName )
      + * Lanugage::symbolAddScope( const_String_or_char_ptr scopeName )
        *
        * Creates a scope (symbols Hash) for given name. This method is auxilary,
        * you don't have to call it - addSymbols will lazily create scopes automatically.
        * If scope with given name already exists, then do nothing.
        * Returns newly created (or already existing) scope.
        * ----------------------------------------------------------------------------- */
      -Hash* Language::addScope(const_String_or_char_ptr scope) {
      -  Hash *symbols = scopeLookup(scope);
      +Hash* Language::symbolAddScope(const_String_or_char_ptr scope) {
      +  Hash *symbols = symbolScopeLookup(scope);
         if(!symbols) {
           // Order in which to following parts are executed is important. In Lanugage
           // constructor addScope("") is called to create a top level scope itself.
      @@ -3108,18 +3108,18 @@ Hash* Language::addScope(const_String_or_char_ptr scope) {
       }
       
       /* -----------------------------------------------------------------------------
      - * Lanugage::scopeLookup( const_String_or_char_ptr scope )
      + * Lanugage::symbolSscopeLookup( const_String_or_char_ptr scope )
        *
        * Lookup and returns a symtable (hash) representing given scope. Hash contains
        * all symbols in this scope.
        * ----------------------------------------------------------------------------- */
      -Hash* Language::scopeLookup( const_String_or_char_ptr scope ) {
      +Hash* Language::symbolScopeLookup( const_String_or_char_ptr scope ) {
         Hash *symbols = Getattr(symtabs, scope ? scope : "");
         return symbols;
       }
       
       /* -----------------------------------------------------------------------------
      - * Lanugage::scopeSymbolLookup( const_String_or_char_ptr scope )
      + * Lanugage::symbolScopeSymbolLookup( const_String_or_char_ptr scope )
        *
        * For every scope there is a special pseudo-symbol in the top scope (""). It
        * exists solely to detect name clashes. This pseudo symbol may contain a few properties,
      @@ -3133,7 +3133,7 @@ Hash* Language::scopeLookup( const_String_or_char_ptr scope ) {
        * There is no difference from symbolLookup() method except for signature
        * and return type.
        * ----------------------------------------------------------------------------- */
      -Hash* Language::scopeSymbolLookup( const_String_or_char_ptr scope )
      +Hash* Language::symbolScopePseudoSymbolLookup( const_String_or_char_ptr scope )
       {
         /* Getting top scope */
         const_String_or_char_ptr top_scope = "";
      diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx
      index 6317f0910..b60490918 100644
      --- a/Source/Modules/lua.cxx
      +++ b/Source/Modules/lua.cxx
      @@ -1669,7 +1669,7 @@ public:
          * A small helper to hide impelementation of how CArrays hashes are stored
          * ---------------------------------------------------------------------------- */
         Hash *rawGetCArraysHash(const_String_or_char_ptr name) {
      -    Hash *scope = scopeLookup( name ? name : "" );
      +    Hash *scope = symbolScopeLookup( name ? name : "" );
           if(!scope)
             return 0;
       
      @@ -1694,10 +1694,10 @@ public:
          * only at first call (a.k.a when nspace is created).
          * ---------------------------------------------------------------------------- */
         Hash *getCArraysHash(String *nspace, bool reg = true) {
      -    Hash *scope = scopeLookup(nspace ? nspace : "");
      +    Hash *scope = symbolScopeLookup(nspace ? nspace : "");
           if(!scope) {
      -      addScope( nspace ? nspace : "" );
      -      scope = scopeLookup(nspace ? nspace : "");
      +      symbolAddScope( nspace ? nspace : "" );
      +      scope = symbolScopeLookup(nspace ? nspace : "");
             assert(scope);
           }
           Hash *carrays_hash = Getattr(scope, "lua:cdata");
      @@ -1979,14 +1979,14 @@ public:
          * ----------------------------------------------------------------------------- */
         void closeNamespaces(File *dataOutput) {
           // Special handling for empty module.
      -    if (scopeLookup("") == 0 || rawGetCArraysHash("") == 0) {
      +    if (symbolScopeLookup("") == 0 || rawGetCArraysHash("") == 0) {
             // Module is empty. Create hash for global scope in order to have swig__Module
             // variable in resulting file
             getCArraysHash(0);
           }
           // Because we cant access directly 'symtabs', instead we access
           // top-level scope and look on all scope pseudo-symbols in it.
      -    Hash *top_scope = scopeLookup("");
      +    Hash *top_scope = symbolScopeLookup("");
           assert(top_scope);
           Iterator ki = First(top_scope);
           List *to_close = NewList();
      diff --git a/Source/Modules/swigmod.h b/Source/Modules/swigmod.h
      index 40064ea38..afffebef9 100644
      --- a/Source/Modules/swigmod.h
      +++ b/Source/Modules/swigmod.h
      @@ -216,9 +216,9 @@ public:
         virtual int addSymbol(const String *s, const Node *n, const_String_or_char_ptr scope = "");	/* Add symbol        */
         virtual void dumpSymbols();
         virtual Node *symbolLookup(String *s, const_String_or_char_ptr scope = ""); /* Symbol lookup */
      -  virtual Hash* addScope(const_String_or_char_ptr scope);
      -  virtual Hash* scopeLookup( const_String_or_char_ptr scope );
      -  virtual Hash* scopeSymbolLookup( const_String_or_char_ptr scope );
      +  virtual Hash* symbolAddScope(const_String_or_char_ptr scope);
      +  virtual Hash* symbolScopeLookup( const_String_or_char_ptr scope );
      +  virtual Hash* symbolScopePseudoSymbolLookup( const_String_or_char_ptr scope );
         virtual Node *classLookup(const SwigType *s) const; /* Class lookup      */
         virtual Node *enumLookup(SwigType *s);	/* Enum lookup       */
         virtual int abstractClassTest(Node *n);	/* Is class really abstract? */
      
      From dcf121f534a5c06d5ccc47bc0b04de982c1df3b2 Mon Sep 17 00:00:00 2001
      From: Olly Betts 
      Date: Wed, 19 Feb 2014 22:35:45 +1300
      Subject: [PATCH 422/481] Make Lib/ocaml/swigp4.ml a non-generated file.
      
      We used to have configure substitute values into it, but that's not been
      the case for just over 3 years, since patch #3151788 was applied.
      ---
       .gitignore                            |  1 -
       Lib/ocaml/{swigp4.ml.in => swigp4.ml} |  0
       Makefile.in                           |  2 +-
       configure.ac                          | 57 +++++++++++++--------------
       4 files changed, 29 insertions(+), 31 deletions(-)
       rename Lib/ocaml/{swigp4.ml.in => swigp4.ml} (100%)
      
      diff --git a/.gitignore b/.gitignore
      index eb3aa012c..67a6ee936 100644
      --- a/.gitignore
      +++ b/.gitignore
      @@ -67,7 +67,6 @@ Examples/Makefile
       Examples/guile/Makefile
       Examples/test-suite/*/Makefile
       Examples/xml/Makefile
      -Lib/ocaml/swigp4.ml
       /Makefile
       Source/Include/stamp-h1
       Source/Include/swigconfig.h
      diff --git a/Lib/ocaml/swigp4.ml.in b/Lib/ocaml/swigp4.ml
      similarity index 100%
      rename from Lib/ocaml/swigp4.ml.in
      rename to Lib/ocaml/swigp4.ml
      diff --git a/Makefile.in b/Makefile.in
      index ea7814242..4407d1316 100644
      --- a/Makefile.in
      +++ b/Makefile.in
      @@ -391,7 +391,7 @@ clean-ccache:
       # DISTCLEAN - clean what configure built
       #####################################################################
       
      -DISTCLEAN-DEAD = config.status config.log config.cache swig.spec Makefile mkmf.log libtool preinst-swig Lib/ocaml/swigp4.ml
      +DISTCLEAN-DEAD = config.status config.log config.cache swig.spec Makefile mkmf.log libtool preinst-swig
       
       distclean-helper: distclean-test-suite distclean-examples distclean-dead
       
      diff --git a/configure.ac b/configure.ac
      index bb62068ae..be4e6e3c9 100644
      --- a/configure.ac
      +++ b/configure.ac
      @@ -2409,35 +2409,34 @@ case $build in
       esac
       AC_DEFINE_UNQUOTED(SWIG_LIB_WIN_UNIX, ["$SWIG_LIB_WIN_UNIX"], [Directory for SWIG system-independent libraries (Unix install on native Windows)])
       
      -AC_CONFIG_FILES([			        \
      -    Makefile				        \
      -    swig.spec				        \
      -    Source/Makefile			        \
      -    Examples/Makefile			        \
      -    Examples/xml/Makefile		        \
      -    Examples/test-suite/errors/Makefile		\
      -    Examples/test-suite/chicken/Makefile	\
      -    Examples/test-suite/csharp/Makefile	        \
      -    Examples/test-suite/d/Makefile	        \
      -    Examples/test-suite/guile/Makefile	        \
      -    Examples/test-suite/java/Makefile	        \
      -    Examples/test-suite/mzscheme/Makefile	\
      -    Examples/test-suite/ocaml/Makefile	        \
      -    Examples/test-suite/octave/Makefile	        \
      -    Examples/test-suite/perl5/Makefile	        \
      -    Examples/test-suite/php/Makefile	        \
      -    Examples/test-suite/pike/Makefile	        \
      -    Examples/test-suite/python/Makefile	        \
      -    Examples/test-suite/ruby/Makefile	        \
      -    Examples/test-suite/tcl/Makefile	        \
      -    Examples/test-suite/lua/Makefile	        \
      -    Examples/test-suite/allegrocl/Makefile	\
      -    Examples/test-suite/clisp/Makefile		\
      -    Examples/test-suite/cffi/Makefile		\
      -    Examples/test-suite/uffi/Makefile		\
      -    Examples/test-suite/r/Makefile		\
      -    Examples/test-suite/go/Makefile		\
      -    Lib/ocaml/swigp4.ml
      +AC_CONFIG_FILES([
      +    Makefile
      +    swig.spec
      +    Source/Makefile
      +    Examples/Makefile
      +    Examples/xml/Makefile
      +    Examples/test-suite/errors/Makefile
      +    Examples/test-suite/chicken/Makefile
      +    Examples/test-suite/csharp/Makefile
      +    Examples/test-suite/d/Makefile
      +    Examples/test-suite/guile/Makefile
      +    Examples/test-suite/java/Makefile
      +    Examples/test-suite/mzscheme/Makefile
      +    Examples/test-suite/ocaml/Makefile
      +    Examples/test-suite/octave/Makefile
      +    Examples/test-suite/perl5/Makefile
      +    Examples/test-suite/php/Makefile
      +    Examples/test-suite/pike/Makefile
      +    Examples/test-suite/python/Makefile
      +    Examples/test-suite/ruby/Makefile
      +    Examples/test-suite/tcl/Makefile
      +    Examples/test-suite/lua/Makefile
      +    Examples/test-suite/allegrocl/Makefile
      +    Examples/test-suite/clisp/Makefile
      +    Examples/test-suite/cffi/Makefile
      +    Examples/test-suite/uffi/Makefile
      +    Examples/test-suite/r/Makefile
      +    Examples/test-suite/go/Makefile
       ])
       AC_CONFIG_FILES([preinst-swig], [chmod +x preinst-swig])
       AC_CONFIG_FILES([CCache/ccache_swig_config.h])
      
      From 1097fc99ff7463c4535e84f50706a292e94147e0 Mon Sep 17 00:00:00 2001
      From: Olly Betts 
      Date: Wed, 19 Feb 2014 23:04:40 +1300
      Subject: [PATCH 423/481] [Lua] Add keyword warnings for Lua keywords and Basic
       Functions.
      
      ---
       CHANGES.current                               |  3 +
       .../test-suite/lua/keyword_rename_runme.lua   | 10 +--
       Lib/allkw.swg                                 |  1 +
       Lib/lua/lua.swg                               |  3 +-
       Lib/lua/luakw.swg                             | 67 +++++++++++++++++++
       5 files changed, 76 insertions(+), 8 deletions(-)
       create mode 100644 Lib/lua/luakw.swg
      
      diff --git a/CHANGES.current b/CHANGES.current
      index 6595c248e..897ff53c4 100644
      --- a/CHANGES.current
      +++ b/CHANGES.current
      @@ -5,6 +5,9 @@ See the RELEASENOTES file for a summary of changes in each release.
       Version 3.0.0 (in progress)
       ============================
       
      +2014-02-19: olly
      +	    [Lua] Add keyword warnings for Lua keywords and Basic Functions.
      +
       2014-02-19: olly
       	    -Wallkw now includes keywords for all languages with keyword
       	    warnings (previously Go and R were missing).
      diff --git a/Examples/test-suite/lua/keyword_rename_runme.lua b/Examples/test-suite/lua/keyword_rename_runme.lua
      index a9dea466a..1fe5b5756 100644
      --- a/Examples/test-suite/lua/keyword_rename_runme.lua
      +++ b/Examples/test-suite/lua/keyword_rename_runme.lua
      @@ -7,10 +7,6 @@ local env = _ENV -- Lua 5.2
       if not env then env = getfenv () end -- Lua 5.1
       setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end})
       
      -
      --- assert(kn.end(5) == 5) -- Curretly  SWIG/Lua doesn't rename keywords
      --- assert(kn.nil(7) == 7)
      -
      --- But you can always access wrongly named members using string constants
      -assert(kn["end"](5) == 5)
      -assert(kn["nil"](7) == 7)
      +-- Check renaming of Lua keywords
      +assert(kn.c_end(5) == 5)
      +assert(kn.c_nil(7) == 7)
      diff --git a/Lib/allkw.swg b/Lib/allkw.swg
      index 99c2969e4..563190e19 100644
      --- a/Lib/allkw.swg
      +++ b/Lib/allkw.swg
      @@ -21,6 +21,7 @@
       %include 
       %include 
       %include 
      +%include 
       %include 
       %include 
       %include 
      diff --git a/Lib/lua/lua.swg b/Lib/lua/lua.swg
      index 80c4c04c1..ee83d11b7 100644
      --- a/Lib/lua/lua.swg
      +++ b/Lib/lua/lua.swg
      @@ -9,8 +9,9 @@
        *                          includes
        * ----------------------------------------------------------------------------- */
       
      -%include           /* The typemaps */
      +%include          /* The typemaps */
       %include           /* The runtime stuff */
      +%include                /* Warnings for Lua keywords */
       
       //%include 
       /* -----------------------------------------------------------------------------
      diff --git a/Lib/lua/luakw.swg b/Lib/lua/luakw.swg
      new file mode 100644
      index 000000000..fc2f92bfe
      --- /dev/null
      +++ b/Lib/lua/luakw.swg
      @@ -0,0 +1,67 @@
      +/*
      +  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 LUABN(x) %namewarn(%warningmsg(SWIGWARN_PARSE_BUILTIN_NAME, "'" `x` "' conflicts with a basic function in Lua"), %$not %$ismember)  `x`
      +
      +/*
      +  Warnings for Lua keywords 
      +  http://www.lua.org/manual/5.2/manual.html#3.1
      +*/
      +
      +LUAKW(and);
      +LUAKW(break);
      +LUAKW(do);
      +LUAKW(else);
      +LUAKW(elseif);
      +LUAKW(end);
      +LUAKW(false);
      +LUAKW(for);
      +LUAKW(function);
      +LUAKW(goto);
      +LUAKW(if);
      +LUAKW(in);
      +LUAKW(local);
      +LUAKW(nil);
      +LUAKW(not);
      +LUAKW(or);
      +LUAKW(repeat);
      +LUAKW(return);
      +LUAKW(then);
      +LUAKW(true);
      +LUAKW(until);
      +LUAKW(while);
      +
      +/*
      +  Basic functions
      +  http://www.lua.org/manual/5.2/manual.html#6.1
      +*/ 
      +
      +LUABN(assert);
      +LUABN(collectgarbage);
      +LUABN(dofile);
      +LUABN(error);
      +LUABN(_G); // Not actually a function
      +LUABN(getmetatable);
      +LUABN(ipairs);
      +LUABN(load);
      +LUABN(loadfile);
      +LUABN(next);
      +LUABN(pairs);
      +LUABN(pcall);
      +LUABN(print);
      +LUABN(rawequal);
      +LUABN(rawget);
      +LUABN(rawlen);
      +LUABN(rawset);
      +LUABN(select);
      +LUABN(setmetatable);
      +LUABN(tonumber);
      +LUABN(tostring);
      +LUABN(type);
      +LUABN(_VERSION); // Not actually a function
      +LUABN(xpcall);
      +
      +#undef LUABN
      +#undef LUAKW
      
      From 66b22e617820e6305b5176f828546e78ebaec907 Mon Sep 17 00:00:00 2001
      From: Olly Betts 
      Date: Wed, 19 Feb 2014 23:05:15 +1300
      Subject: [PATCH 424/481] Improve ignore pattern for vim swap files to not
       match SWIG *.swg files
      
      ---
       .gitignore | 2 +-
       1 file changed, 1 insertion(+), 1 deletion(-)
      
      diff --git a/.gitignore b/.gitignore
      index 67a6ee936..48826d914 100644
      --- a/.gitignore
      +++ b/.gitignore
      @@ -3,7 +3,7 @@
       *.class
       
       # Editor files and various other junk
      -*.sw?
      +.*.sw?
       *.bak
       
       # Local PCRE
      
      From 2767f2a55e2453781031f4bab1f8fd67c9f28f7a Mon Sep 17 00:00:00 2001
      From: Artem Serebriyskiy 
      Date: Wed, 19 Feb 2014 14:05:29 +0400
      Subject: [PATCH 425/481] Fixes to module options
      
      ---
       Source/Modules/lua.cxx | 28 ++++++++--------------------
       1 file changed, 8 insertions(+), 20 deletions(-)
      
      diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx
      index b60490918..04241ec21 100644
      --- a/Source/Modules/lua.cxx
      +++ b/Source/Modules/lua.cxx
      @@ -80,23 +80,22 @@ void display_mapping(DOH *d) {
       NEW LANGUAGE NOTE:END ************************************************/
       static const char *usage = (char *) "\
       Lua Options (available with -lua)\n\
      -     -elua [NUM]     - Generates LTR compatible wrappers for smaller devices running elua\n\
      -                       Optional NUM is default value for MIN_OPT_LEVEL\n\
      -     -eluac  [NUM]   - LTR compatible wrappers in \"crass compress\" mode for elua\n\
      -                       Optional NUM is default value for MIN_OPT_LEVEL\n\
      +     -drop-old-scheme\n\
      +                     - Disable support for old-style bindings name generation, some\n\
      +                       old-style members scheme etc.\n\
      +     -elua           - Generates LTR compatible wrappers for smaller devices running elua\n\
      +     -eluac          - LTR compatible wrappers in \"crass compress\" mode for elua\n\
      +     -elua-emulate   - Emulates behaviour of eLua. Usefull only for testing.\n\
      +                       Incompatible with -elua/-eluac options.\n\
            -nomoduleglobal - Do not register the module name as a global variable \n\
                              but return the module table from calls to require.\n\
      -     -swig3          - Disable support for old-style bindings name generation.\n\
            -squash-bases   - Squashes symbols from all inheritance tree of a given class\n\
                              into itself. Emulates pre-SWIG3.0 inheritance. Insignificantly\n\
                              speeds things up, but increases memory consumption.\n\
      -     -elua-emulate   - Emulates behaviour of eLua. Usefull only for testing.\n\
      -                       Incompatible with -elua/-eluac options.\n\
       \n";
       
       static int nomoduleglobal = 0;
       static int elua_ltr = 0;
      -static int elua_opt_lvl = 2;
       static int eluac_ltr = 0;
       static int elua_emulate = 0;
       static int squash_bases = 0;
      @@ -221,18 +220,10 @@ public:
       	} else if (strcmp(argv[i], "-elua") == 0) {
       	  elua_ltr = 1;
       	  Swig_mark_arg(i);
      -	  if (strToInt(argv[i + 1], elua_opt_lvl)) {
      -	    Swig_mark_arg(i + 1);
      -	    i++;
      -	  }
       	} else if (strcmp(argv[i], "-eluac") == 0) {
       	  eluac_ltr = 1;
       	  Swig_mark_arg(i);
      -	  if (strToInt(argv[i + 1], elua_opt_lvl)) {
      -	    Swig_mark_arg(i + 1);
      -	    i++;
      -	  }
      -	} else if (strcmp(argv[i], "-swig3") == 0) {
      +	} else if (strcmp(argv[i], "-drop-old-scheme") == 0) {
       	  Swig_mark_arg(i);
       	  api_level = 3;
       	} else if (strcmp(argv[i], "-squash-bases") == 0) {
      @@ -340,9 +331,6 @@ public:
       
           emitLuaFlavor(f_runtime);
       
      -    if (elua_ltr || eluac_ltr)
      -      Printf(f_runtime, "#ifndef MIN_OPT_LEVEL\n" "#define MIN_OPT_LEVEL %d\n" "#endif\n", elua_opt_lvl);
      -
           if (nomoduleglobal) {
             Printf(f_runtime, "#define SWIG_LUA_NO_MODULE_GLOBAL\n");
           } else {
      
      From b30aa53709c138913bca9cb68096540f0a101b02 Mon Sep 17 00:00:00 2001
      From: Artem Serebriyskiy 
      Date: Wed, 19 Feb 2014 16:02:49 +0400
      Subject: [PATCH 426/481] Removed class_parent_nspace
      
      ---
       Source/Modules/lua.cxx | 13 ++++---------
       1 file changed, 4 insertions(+), 9 deletions(-)
      
      diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx
      index 04241ec21..f521824a0 100644
      --- a/Source/Modules/lua.cxx
      +++ b/Source/Modules/lua.cxx
      @@ -127,7 +127,6 @@ private:
         String *class_symname;
         String *class_fq_symname;	// Fully qualified symname - NSpace + '.' + class_symname
         String *class_static_nspace;
      -  String *class_parent_nspace;
         String *constructor_name;
       
         // Many wrappers forward calls to each other, for example staticmembervariableHandler
      @@ -1039,7 +1038,7 @@ public:
             }
             n_v2 = Copy(n);
             //Printf( stdout, "target name v2: %s, symname v2 %s\n", target_name_v2.ptr(), iname_v2.ptr());// TODO:REMOVE
      -      if (!luaAddSymbol(iname_v2, n, class_parent_nspace)) {
      +      if (!luaAddSymbol(iname_v2, n, getNSpace())) {
       	Swig_restore(n);
       	return SWIG_ERROR;
             }
      @@ -1052,7 +1051,7 @@ public:
       	Replaceall(tm_v2, "$target", target_name_v2);
       	Replaceall(tm_v2, "$value", value);
       	Replaceall(tm_v2, "$nsname", nsname);
      -	registerConstant(class_parent_nspace, tm_v2);
      +	registerConstant(getNSpace(), tm_v2);
             } else {
       	tm_v2 = Swig_typemap_lookup("constcode", n_v2, name, 0);
       	if (!tm_v2) {
      @@ -1178,7 +1177,6 @@ public:
           assert(class_static_nspace == 0);
           assert(class_fq_symname == 0);
           assert(class_symname == 0);
      -    assert(class_parent_nspace == 0);
       
           current[NO_CPP] = false;
       
      @@ -1256,11 +1254,8 @@ public:
           /* There is no use for "classes" and "namespaces" arrays. Subclasses are not supported
            * by SWIG and namespaces couldn't be nested inside classes (C++ Standard)
            */
      -    class_parent_nspace = getNSpace();
           // Generate normal wrappers
           Language::classHandler(n);
      -    // Restore correct nspace
      -    class_parent_nspace = 0;
       
           SwigType_add_pointer(t);
       
      @@ -1528,7 +1523,7 @@ public:
             String *target_name = Getattr(n, "lua:name");
             String *compat_name = Swig_name_member(0, class_symname, target_name);
             Setattr(n, "lua:name", compat_name);
      -      registerMethod(class_parent_nspace, n);
      +      registerMethod(getNSpace(), n);
             Delete(compat_name);
             Swig_restore(n);
           }
      @@ -1568,7 +1563,7 @@ public:
       	//Printf( stdout, "Name %s, class %s, compt. name %s\n", target_name, class_symname, v2_name ); // TODO: REMOVE
       	if (!GetFlag(n, "wrappedasconstant")) {
       	  Setattr(n, "lua:name", v2_name);
      -	  registerVariable(class_parent_nspace, n, "varget:wrap:name", "varset:wrap:name");
      +	  registerVariable(getNSpace(), n, "varget:wrap:name", "varset:wrap:name");
       	}
       	// If static member variable was wrapped as constant, then
       	// constant wrapper has already performed all actions
      
      From fe91d6449f33a57d0168fcbb50a0d5ceeac014a0 Mon Sep 17 00:00:00 2001
      From: Curtis Dunham 
      Date: Wed, 19 Feb 2014 11:58:27 -0600
      Subject: [PATCH 427/481] Remove register storage class declarations
      
      They're unnecessary, anacronistic, deprecated in modern
      standards, generally ignored, useless, and (most importantly)
      clang complains about them.
      ---
       Lib/csharp/csharp.swg             | 14 +++++++-------
       Lib/d/dmemberfunctionpointers.swg | 14 +++++++-------
       Lib/java/java.swg                 | 14 +++++++-------
       Lib/python/pyrun.swg              |  6 +++---
       Lib/swigrun.swg                   | 24 ++++++++++++------------
       5 files changed, 36 insertions(+), 36 deletions(-)
      
      diff --git a/Lib/csharp/csharp.swg b/Lib/csharp/csharp.swg
      index 70e9fd4b4..94a0771ba 100644
      --- a/Lib/csharp/csharp.swg
      +++ b/Lib/csharp/csharp.swg
      @@ -35,10 +35,10 @@ using global::System.Runtime.InteropServices;
       /* Pack binary data into a string */
       SWIGINTERN char * SWIG_PackData(char *c, void *ptr, size_t sz) {
         static const char hex[17] = "0123456789abcdef";
      -  register const unsigned char *u = (unsigned char *) ptr;
      -  register const unsigned char *eu =  u + sz;
      +  const unsigned char *u = (unsigned char *) ptr;
      +  const unsigned char *eu =  u + sz;
         for (; u != eu; ++u) {
      -    register unsigned char uu = *u;
      +    unsigned char uu = *u;
           *(c++) = hex[(uu & 0xf0) >> 4];
           *(c++) = hex[uu & 0xf];
         }
      @@ -49,11 +49,11 @@ SWIGINTERN char * SWIG_PackData(char *c, void *ptr, size_t sz) {
       %fragment("SWIG_UnPackData", "header") {
       /* Unpack binary data from a string */
       SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) {
      -  register unsigned char *u = (unsigned char *) ptr;
      -  register const unsigned char *eu = u + sz;
      +  unsigned char *u = (unsigned char *) ptr;
      +  const unsigned char *eu = u + sz;
         for (; u != eu; ++u) {
      -    register char d = *(c++);
      -    register unsigned char uu;
      +    char d = *(c++);
      +    unsigned char uu;
           if ((d >= '0') && (d <= '9'))
             uu = ((d - '0') << 4);
           else if ((d >= 'a') && (d <= 'f'))
      diff --git a/Lib/d/dmemberfunctionpointers.swg b/Lib/d/dmemberfunctionpointers.swg
      index c33ff3840..c63eca23e 100644
      --- a/Lib/d/dmemberfunctionpointers.swg
      +++ b/Lib/d/dmemberfunctionpointers.swg
      @@ -53,10 +53,10 @@
       /* Pack binary data into a string */
       SWIGINTERN char * SWIG_PackData(char *c, void *ptr, size_t sz) {
         static const char hex[17] = "0123456789abcdef";
      -  register const unsigned char *u = (unsigned char *) ptr;
      -  register const unsigned char *eu =  u + sz;
      +  const unsigned char *u = (unsigned char *) ptr;
      +  const unsigned char *eu =  u + sz;
         for (; u != eu; ++u) {
      -    register unsigned char uu = *u;
      +    unsigned char uu = *u;
           *(c++) = hex[(uu & 0xf0) >> 4];
           *(c++) = hex[uu & 0xf];
         }
      @@ -67,11 +67,11 @@ SWIGINTERN char * SWIG_PackData(char *c, void *ptr, size_t sz) {
       %fragment("SWIG_UnPackData", "header") {
       /* Unpack binary data from a string */
       SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) {
      -  register unsigned char *u = (unsigned char *) ptr;
      -  register const unsigned char *eu = u + sz;
      +  unsigned char *u = (unsigned char *) ptr;
      +  const unsigned char *eu = u + sz;
         for (; u != eu; ++u) {
      -    register char d = *(c++);
      -    register unsigned char uu;
      +    char d = *(c++);
      +    unsigned char uu;
           if ((d >= '0') && (d <= '9'))
             uu = ((d - '0') << 4);
           else if ((d >= 'a') && (d <= 'f'))
      diff --git a/Lib/java/java.swg b/Lib/java/java.swg
      index 84d018083..3d4d83730 100644
      --- a/Lib/java/java.swg
      +++ b/Lib/java/java.swg
      @@ -16,10 +16,10 @@
       /* Pack binary data into a string */
       SWIGINTERN char * SWIG_PackData(char *c, void *ptr, size_t sz) {
         static const char hex[17] = "0123456789abcdef";
      -  register const unsigned char *u = (unsigned char *) ptr;
      -  register const unsigned char *eu =  u + sz;
      +  const unsigned char *u = (unsigned char *) ptr;
      +  const unsigned char *eu =  u + sz;
         for (; u != eu; ++u) {
      -    register unsigned char uu = *u;
      +    unsigned char uu = *u;
           *(c++) = hex[(uu & 0xf0) >> 4];
           *(c++) = hex[uu & 0xf];
         }
      @@ -30,11 +30,11 @@ SWIGINTERN char * SWIG_PackData(char *c, void *ptr, size_t sz) {
       %fragment("SWIG_UnPackData", "header") {
       /* Unpack binary data from a string */
       SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) {
      -  register unsigned char *u = (unsigned char *) ptr;
      -  register const unsigned char *eu = u + sz;
      +  unsigned char *u = (unsigned char *) ptr;
      +  const unsigned char *eu = u + sz;
         for (; u != eu; ++u) {
      -    register char d = *(c++);
      -    register unsigned char uu;
      +    char d = *(c++);
      +    unsigned char uu;
           if ((d >= '0') && (d <= '9'))
             uu = ((d - '0') << 4);
           else if ((d >= 'a') && (d <= 'f'))
      diff --git a/Lib/python/pyrun.swg b/Lib/python/pyrun.swg
      index 53fc3a75b..a713486d1 100644
      --- a/Lib/python/pyrun.swg
      +++ b/Lib/python/pyrun.swg
      @@ -175,7 +175,7 @@ SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssi
         }  
         if (!PyTuple_Check(args)) {
           if (min <= 1 && max >= 1) {
      -      register int i;
      +      int i;
             objs[0] = args;
             for (i = 1; i < max; ++i) {
       	objs[i] = 0;
      @@ -185,7 +185,7 @@ SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssi
           PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple");
           return 0;
         } else {
      -    register Py_ssize_t l = PyTuple_GET_SIZE(args);
      +    Py_ssize_t l = PyTuple_GET_SIZE(args);
           if (l < min) {
             PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", 
       		   name, (min == max ? "" : "at least "), (int)min, (int)l);
      @@ -195,7 +195,7 @@ SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssi
       		   name, (min == max ? "" : "at most "), (int)max, (int)l);
             return 0;
           } else {
      -      register int i;
      +      int i;
             for (i = 0; i < l; ++i) {
       	objs[i] = PyTuple_GET_ITEM(args, i);
             }
      diff --git a/Lib/swigrun.swg b/Lib/swigrun.swg
      index 7066e670e..a314bf239 100644
      --- a/Lib/swigrun.swg
      +++ b/Lib/swigrun.swg
      @@ -404,14 +404,14 @@ SWIG_MangledTypeQueryModule(swig_module_info *start,
         swig_module_info *iter = start;
         do {
           if (iter->size) {
      -      register size_t l = 0;
      -      register size_t r = iter->size - 1;
      +      size_t l = 0;
      +      size_t r = iter->size - 1;
             do {
       	/* since l+r >= 0, we can (>> 1) instead (/ 2) */
      -	register size_t i = (l + r) >> 1;
      +	size_t i = (l + r) >> 1;
       	const char *iname = iter->types[i]->name;
       	if (iname) {
      -	  register int compare = strcmp(name, iname);
      +	  int compare = strcmp(name, iname);
       	  if (compare == 0) {
       	    return iter->types[i];
       	  } else if (compare < 0) {
      @@ -455,7 +455,7 @@ SWIG_TypeQueryModule(swig_module_info *start,
              of the str field (the human readable name) */
           swig_module_info *iter = start;
           do {
      -      register size_t i = 0;
      +      size_t i = 0;
             for (; i < iter->size; ++i) {
       	if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name)))
       	  return iter->types[i];
      @@ -474,10 +474,10 @@ SWIG_TypeQueryModule(swig_module_info *start,
       SWIGRUNTIME char *
       SWIG_PackData(char *c, void *ptr, size_t sz) {
         static const char hex[17] = "0123456789abcdef";
      -  register const unsigned char *u = (unsigned char *) ptr;
      -  register const unsigned char *eu =  u + sz;
      +  const unsigned char *u = (unsigned char *) ptr;
      +  const unsigned char *eu =  u + sz;
         for (; u != eu; ++u) {
      -    register unsigned char uu = *u;
      +    unsigned char uu = *u;
           *(c++) = hex[(uu & 0xf0) >> 4];
           *(c++) = hex[uu & 0xf];
         }
      @@ -489,11 +489,11 @@ SWIG_PackData(char *c, void *ptr, size_t sz) {
       */
       SWIGRUNTIME const char *
       SWIG_UnpackData(const char *c, void *ptr, size_t sz) {
      -  register unsigned char *u = (unsigned char *) ptr;
      -  register const unsigned char *eu = u + sz;
      +  unsigned char *u = (unsigned char *) ptr;
      +  const unsigned char *eu = u + sz;
         for (; u != eu; ++u) {
      -    register char d = *(c++);
      -    register unsigned char uu;
      +    char d = *(c++);
      +    unsigned char uu;
           if ((d >= '0') && (d <= '9'))
             uu = ((d - '0') << 4);
           else if ((d >= 'a') && (d <= 'f'))
      
      From de7ed84f77d2e27b5fdea1ad0774994df2720caa Mon Sep 17 00:00:00 2001
      From: Olly Betts 
      Date: Fri, 21 Feb 2014 08:09:58 +1300
      Subject: [PATCH 428/481] Recommend compiling with PIC consistently.
      
      While shared objects with non-PIC code work on some architectures
      (notably x86), unless code is always PIC on that arch (not true for x86)
      doing so requires runtime relocations, which prevents the object
      actually being shared, and means such segments can't be marked as
      read-only.
      ---
       Doc/Manual/Java.html      |  7 +++----
       Doc/Manual/Lua.html       |  4 ++--
       Doc/Manual/Perl5.html     |  4 ++--
       Doc/Manual/Ruby.html      | 20 ++++++++++++++------
       Doc/Manual/SWIGPlus.html  |  2 +-
       Doc/Manual/Scripting.html |  7 +------
       Doc/Manual/Tcl.html       | 12 ++++++------
       7 files changed, 29 insertions(+), 27 deletions(-)
      
      diff --git a/Doc/Manual/Java.html b/Doc/Manual/Java.html
      index 08c80c83a..c1b42f605 100644
      --- a/Doc/Manual/Java.html
      +++ b/Doc/Manual/Java.html
      @@ -332,8 +332,8 @@ Assuming you have code you need to link to in a file called example.c,
       
       
       $ swig -java example.i
      -$ gcc -c example_wrap.c  -I/usr/java/include -I/usr/java/include/solaris
      -$ gcc -c example.c
      +$ gcc -fPIC -c example_wrap.c -I/usr/java/include -I/usr/java/include/solaris
      +$ gcc -fPIC -c example.c
       $ ld -G example_wrap.o example.o -o libexample.so
       
      @@ -493,8 +493,7 @@ compiler. For example:
       % swig -c++ -java example.i
       % g++ -c -fpic example.cxx
      -% g++ -c -fpic example_wrap.cxx -I/usr/java/j2sdk1.4.1/include -I/usr/java/
      -j2sdk1.4.1/include/linux
      +% g++ -c -fpic example_wrap.cxx -I/usr/java/j2sdk1.4.1/include -I/usr/java/j2sdk1.4.1/include/linux
       % g++ -shared example.o example_wrap.o -o libexample.so
       
      diff --git a/Doc/Manual/Lua.html b/Doc/Manual/Lua.html index 88d26f385..aab6a2ceb 100644 --- a/Doc/Manual/Lua.html +++ b/Doc/Manual/Lua.html @@ -240,8 +240,8 @@ Most, but not all platforms support the dynamic loading of modules (Windows &

       $ swig -lua example.i -o example_wrap.c
      -$ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o
      -$ gcc -c example.c -o example.o
      +$ gcc -fPIC -I/usr/include/lua -c example_wrap.c -o example_wrap.o
      +$ gcc -fPIC -c example.c -o example.o
       $ gcc -shared -I/usr/include/lua -L/usr/lib/lua example_wrap.o example.o -o example.so
       

      diff --git a/Doc/Manual/Perl5.html b/Doc/Manual/Perl5.html index db8c0e602..9e577b08b 100644 --- a/Doc/Manual/Perl5.html +++ b/Doc/Manual/Perl5.html @@ -493,8 +493,8 @@ Solaris, you often need to add an extra library -lCrun like this:

       $ swig -c++ -perl example.i
      -$ CC -c example.cxx
      -$ CC -c example_wrap.cxx -I/usr/lib/perl/5.14/i386-linux/CORE
      +$ CC -Kpic -c example.cxx
      +$ CC -Kpic -c example_wrap.cxx -I/usr/lib/perl/5.14/i386-linux/CORE
       $ CC -shared example.o example_wrap.o -o example.so -lCrun
       
      diff --git a/Doc/Manual/Ruby.html b/Doc/Manual/Ruby.html index 301631a20..6ff98ca23 100644 --- a/Doc/Manual/Ruby.html +++ b/Doc/Manual/Ruby.html @@ -259,14 +259,22 @@ operating system would look something like this:

      $ swig -ruby example.i
      -$ gcc -c example.c
      -$ gcc -c example_wrap.c -I/usr/local/lib/ruby/1.6/i686-linux
      +$ gcc -O2 -fPIC -c example.c
      +$ gcc -O2 -fPIC -c example_wrap.c -I/usr/local/lib/ruby/1.6/i686-linux
       $ gcc -shared example.o example_wrap.o -o example.so
       
      -

      For other platforms it may be necessary to compile with the -fPIC -option to generate position-independent code. If in doubt, consult the +

      +The -fPIC option tells GCC to generate position-independent code (PIC) +which is required for most architectures (it's not vital on x86, but +still a good idea as it allows code pages from the library to be shared between +processes). Other compilers may need a different option specified instead of +-fPIC. +

      + +

      +If in doubt, consult the manual pages for your compiler and linker to determine the correct set of options. You might also check the SWIG Wiki for additional information.

      @@ -325,8 +333,8 @@ using the C++ compiler. For example:

       $ swig -c++ -ruby example.i
      -$ g++ -c example.cxx
      -$ g++ -c example_wrap.cxx -I/usr/local/lib/ruby/1.6/i686-linux
      +$ g++ -fPIC -c example.cxx
      +$ g++ -fPIC -c example_wrap.cxx -I/usr/local/lib/ruby/1.6/i686-linux
       $ g++ -shared example.o example_wrap.o -o example.so
       
      diff --git a/Doc/Manual/SWIGPlus.html b/Doc/Manual/SWIGPlus.html index e0e7dbcaf..aa02b2dee 100644 --- a/Doc/Manual/SWIGPlus.html +++ b/Doc/Manual/SWIGPlus.html @@ -216,7 +216,7 @@ to use the C++ compiler. For example:
       $ swig -c++ -tcl example.i
      -$ c++ -c example_wrap.cxx 
      +$ c++ -fPIC -c example_wrap.cxx 
       $ c++ example_wrap.o $(OBJS) -o example.so
       
      diff --git a/Doc/Manual/Scripting.html b/Doc/Manual/Scripting.html index 26a8dd017..c714fa0d7 100644 --- a/Doc/Manual/Scripting.html +++ b/Doc/Manual/Scripting.html @@ -368,17 +368,12 @@ for a few common platforms is shown below:

       # Build a shared library for Solaris
      -gcc -c example.c example_wrap.c -I/usr/local/include
      +gcc -fpic -c example.c example_wrap.c -I/usr/local/include
       ld -G example.o example_wrap.o -o example.so
       
       # Build a shared library for Linux
       gcc -fpic -c example.c example_wrap.c -I/usr/local/include
       gcc -shared example.o example_wrap.o -o example.so
      -
      -# Build a shared library for Irix
      -gcc -c example.c example_wrap.c -I/usr/local/include
      -ld -shared example.o example_wrap.o -o example.so
      -
       

      diff --git a/Doc/Manual/Tcl.html b/Doc/Manual/Tcl.html index e6b3b4a43..9b9cd7218 100644 --- a/Doc/Manual/Tcl.html +++ b/Doc/Manual/Tcl.html @@ -139,8 +139,8 @@ using commands like this (shown for Linux):

       $ swig -tcl example.i
      -$ gcc -c example.c
      -$ gcc -c example_wrap.c -I/usr/local/include
      +$ gcc -fPIC -c example.c
      +$ gcc -fPIC -c example_wrap.c -I/usr/local/include
       $ gcc -shared example.o example_wrap.o -o example.so
       
      @@ -374,8 +374,8 @@ compiler. For example:
       % swig -c++ -tcl example.i
      -% g++ -c example.cxx
      -% g++ -c example_wrap.cxx -I/usr/local/include
      +% g++ -fPIC -c example.cxx
      +% g++ -fPIC -c example_wrap.cxx -I/usr/local/include
       % g++ -shared example.o example_wrap.o -o example.so
       
      @@ -387,8 +387,8 @@ Solaris, you often need to add an extra library -lCrun like this:
       % swig -c++ -tcl example.i
      -% CC -c example.cxx
      -% CC -c example_wrap.cxx -I/usr/local/include
      +% CC -KPIC -c example.cxx
      +% CC -KPIC -c example_wrap.cxx -I/usr/local/include
       % CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o example.so -lCrun
       
      From c5bc0aa47283efc71a4ccab40334df9225b727ca Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Fri, 21 Feb 2014 08:14:24 +1300 Subject: [PATCH 429/481] Improve Examples/README --- Examples/README | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/Examples/README b/Examples/README index 4dda3222d..eff0f2c98 100644 --- a/Examples/README +++ b/Examples/README @@ -1,24 +1,18 @@ SWIG Examples -The "perl5", "python", "tcl", "guile", "java", "mzscheme", "ruby", and -"chicken" directories contain a number of simple examples that are -primarily used for testing. +The subdirectories of "Examples" named after SWIG's language backends +contain a number of simple examples that are primarily used for testing. The file 'index.html' is the top of a hyperlinked document that contains information about all of the examples along with various notes related to each example. -The Examples directory is currently quite incomplete because it -is being reorganized. A more complete set of examples can be found -in the SWIG1.1p5 distribution (most of which should still work with -SWIG1.3). - Note: All of the examples rely upon the Makefile in this directory. You may need to edit it to reflect the configuration of your machine in case the configure script guesses incorrect settings. -*** Special note concering C++ *** +*** Special note concerning C++ *** The configure script is currently unable to handle all of the possible options for producing dynamically loadable C++ extensions. Here are From d55692c31e72f8a5f99bf78eb2f37f4ba52479a7 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 21 Feb 2014 08:27:42 +0000 Subject: [PATCH 430/481] Fix warning suppression using %warnfilter for PHP reserved class names. The features need to be merged in before issuing a warning as %warnfilter is a %feature. --- CHANGES.current | 3 +++ Source/CParse/parser.y | 5 +++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index 897ff53c4..50f3decd1 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,9 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2014-02-21: wsfulton + [PHP] Fix warning suppression using %warnfilter for PHP reserved class names. + 2014-02-19: olly [Lua] Add keyword warnings for Lua keywords and Basic Functions. diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index dd8de45ff..1bd351560 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -3488,6 +3488,7 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { Setattr($$, "nested:outer", currentOuterClass); set_access_mode($$); } + Swig_features_get(Swig_cparse_features(), Namespaceprefix, Getattr($$, "name"), 0, $$); /* save yyrename to the class attribute, to be used later in add_symbols()*/ Setattr($$, "class_rename", make_name($$, $3, 0)); Setattr($$, "Classprefix", $3); @@ -3631,7 +3632,6 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { Delattr($$, "Classprefix"); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); - Swig_features_get(Swig_cparse_features(), Namespaceprefix, Getattr($$, "name"), 0, $$); if (cplus_mode == CPLUS_PRIVATE) { $$ = 0; /* skip private nested classes */ } else if (cparse_cplusplus && currentOuterClass && ignore_nested_classes && !GetFlag($$, "feature:flatnested")) { @@ -3712,6 +3712,8 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { Setattr($$, "nested:outer", currentOuterClass); set_access_mode($$); } + Swig_features_get(Swig_cparse_features(), Namespaceprefix, 0, 0, $$); + /* save yyrename to the class attribute, to be used later in add_symbols()*/ Setattr($$, "class_rename", make_name($$,0,0)); if (strcmp($2,"class") == 0) { cplus_mode = CPLUS_PRIVATE; @@ -3745,7 +3747,6 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { /* Check for pure-abstract class */ Setattr($$,"abstracts", pure_abstracts($6)); n = $8; - Swig_features_get(Swig_cparse_features(), Namespaceprefix, 0, 0, $$); if (cparse_cplusplus && currentOuterClass && ignore_nested_classes && !GetFlag($$, "feature:flatnested")) { String *name = n ? Copy(Getattr(n, "name")) : 0; $$ = nested_forward_declaration($1, $2, 0, name, n); From 0d9a8721f46a7ab0ca168edb97c410566ead026d Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 21 Feb 2014 19:02:14 +0000 Subject: [PATCH 431/481] Move some header file includes into fragments for UTL languages --- Lib/octave/octcontainer.swg | 4 +--- Lib/perl5/std_list.i | 4 ++-- Lib/perl5/std_map.i | 4 ++-- Lib/perl5/std_vector.i | 4 ++-- Lib/python/pycontainer.swg | 4 +--- Lib/ruby/rubycontainer.swg | 4 +--- Lib/std/_std_deque.i | 2 +- Lib/std/std_common.i | 6 ++---- Lib/std/std_except.i | 4 +--- Lib/std/std_map.i | 4 ++-- Lib/std/std_unordered_map.i | 4 ++-- Lib/tcl/std_map.i | 4 ++-- Lib/tcl/std_vector.i | 4 ++-- Lib/typemaps/exception.swg | 6 +++--- Lib/typemaps/fragments.swg | 8 ++++++++ Lib/typemaps/traits.swg | 4 +--- 16 files changed, 33 insertions(+), 37 deletions(-) diff --git a/Lib/octave/octcontainer.swg b/Lib/octave/octcontainer.swg index b14b8c194..723256ca0 100644 --- a/Lib/octave/octcontainer.swg +++ b/Lib/octave/octcontainer.swg @@ -26,9 +26,7 @@ // The Octave C++ Wrap -%insert(header) %{ -#include -%} +%fragment(""); %include diff --git a/Lib/perl5/std_list.i b/Lib/perl5/std_list.i index ea264d6a1..8248ca679 100644 --- a/Lib/perl5/std_list.i +++ b/Lib/perl5/std_list.i @@ -36,9 +36,9 @@ %{ #include -#include -#include %} +%fragment(""); +%fragment(""); // exported class diff --git a/Lib/perl5/std_map.i b/Lib/perl5/std_map.i index e7812f38a..493307dd9 100644 --- a/Lib/perl5/std_map.i +++ b/Lib/perl5/std_map.i @@ -12,9 +12,9 @@ %{ #include -#include -#include %} +%fragment(""); +%fragment(""); // exported class diff --git a/Lib/perl5/std_vector.i b/Lib/perl5/std_vector.i index a3998ff92..860cdba7e 100644 --- a/Lib/perl5/std_vector.i +++ b/Lib/perl5/std_vector.i @@ -32,9 +32,9 @@ %{ #include -#include -#include %} +%fragment(""); +%fragment(""); // exported class diff --git a/Lib/python/pycontainer.swg b/Lib/python/pycontainer.swg index d4386622e..dcada87c7 100644 --- a/Lib/python/pycontainer.swg +++ b/Lib/python/pycontainer.swg @@ -32,9 +32,7 @@ /**** The PySequence C++ Wrap ***/ -%insert(header) %{ -#include -%} +%fragment(""); %include diff --git a/Lib/ruby/rubycontainer.swg b/Lib/ruby/rubycontainer.swg index dd6389ce4..69db367d9 100644 --- a/Lib/ruby/rubycontainer.swg +++ b/Lib/ruby/rubycontainer.swg @@ -26,9 +26,7 @@ /**** The RubySequence C++ Wrap ***/ -%insert(header) %{ -#include -%} +%fragment(""); %include diff --git a/Lib/std/_std_deque.i b/Lib/std/_std_deque.i index 7dd3552db..8e701668e 100644 --- a/Lib/std/_std_deque.i +++ b/Lib/std/_std_deque.i @@ -10,8 +10,8 @@ %{ #include -#include %} +%fragment(""); /* This macro defines all of the standard methods for a deque. This diff --git a/Lib/std/std_common.i b/Lib/std/std_common.i index 35baf2206..6e93e29f6 100644 --- a/Lib/std/std_common.i +++ b/Lib/std/std_common.i @@ -24,10 +24,8 @@ // %fragment(""); -%{ -#include -#include -%} +%fragment(""); +%fragment(""); %fragment("StdIteratorTraits","header",fragment="") %{ diff --git a/Lib/std/std_except.i b/Lib/std/std_except.i index 75b8d0fd6..18bbd4ef1 100644 --- a/Lib/std/std_except.i +++ b/Lib/std/std_except.i @@ -2,9 +2,7 @@ #error "do not use this version of std_except.i" #endif -%{ -#include -%} +%fragment(""); #if defined(SWIG_STD_EXCEPTIONS_AS_CLASSES) diff --git a/Lib/std/std_map.i b/Lib/std/std_map.i index e523c3deb..d1f6b3a16 100644 --- a/Lib/std/std_map.i +++ b/Lib/std/std_map.i @@ -57,9 +57,9 @@ %{ #include -#include -#include %} +%fragment(""); +%fragment(""); // exported class diff --git a/Lib/std/std_unordered_map.i b/Lib/std/std_unordered_map.i index 3d80788e2..8c276172a 100644 --- a/Lib/std/std_unordered_map.i +++ b/Lib/std/std_unordered_map.i @@ -60,9 +60,9 @@ %{ #include -#include -#include %} +%fragment(""); +%fragment(""); // exported class diff --git a/Lib/tcl/std_map.i b/Lib/tcl/std_map.i index 1b7e7696c..78f6e3276 100644 --- a/Lib/tcl/std_map.i +++ b/Lib/tcl/std_map.i @@ -13,9 +13,9 @@ %{ #include -#include -#include %} +%fragment(""); +%fragment(""); // exported class diff --git a/Lib/tcl/std_vector.i b/Lib/tcl/std_vector.i index 37e23ba71..3fc0fd61d 100644 --- a/Lib/tcl/std_vector.i +++ b/Lib/tcl/std_vector.i @@ -29,10 +29,10 @@ // ------------------------------------------------------------------------ %fragment(""); +%fragment(""); +%fragment(""); %{ #include -#include -#include Tcl_Obj* SwigString_FromString(const std::string &s) { return Tcl_NewStringObj(s.data(), (int)s.length()); diff --git a/Lib/typemaps/exception.swg b/Lib/typemaps/exception.swg index 12c4ea658..b60a32996 100644 --- a/Lib/typemaps/exception.swg +++ b/Lib/typemaps/exception.swg @@ -52,9 +52,9 @@ } } */ -%{ -#include -%} + +%fragment(""); + %define SWIG_CATCH_STDEXCEPT /* catching std::exception */ catch (std::invalid_argument& e) { diff --git a/Lib/typemaps/fragments.swg b/Lib/typemaps/fragments.swg index ce87c8cc0..447df6e2e 100644 --- a/Lib/typemaps/fragments.swg +++ b/Lib/typemaps/fragments.swg @@ -157,6 +157,14 @@ #include %} +%fragment("", "header") %{ +#include +%} + +%fragment("", "header") %{ +#include +%} + %fragment("SWIG_isfinite","header",fragment=",") %{ /* Getting isfinite working pre C99 across multiple platforms is non-trivial. Users can provide SWIG_isfinite on older platforms. */ #ifndef SWIG_isfinite diff --git a/Lib/typemaps/traits.swg b/Lib/typemaps/traits.swg index 09cc7e295..406f16066 100644 --- a/Lib/typemaps/traits.swg +++ b/Lib/typemaps/traits.swg @@ -22,9 +22,7 @@ // %fragment(""); -%{ -#include -%} +%fragment(""); %fragment("Traits","header",fragment="") { From ae7b34ce0363c351a0b84f8a65707113f49a7acd Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 21 Feb 2014 19:07:35 +0000 Subject: [PATCH 432/481] Remove duplicate header includes in director.swg --- Lib/perl5/director.swg | 1 - Lib/python/director.swg | 1 - 2 files changed, 2 deletions(-) diff --git a/Lib/perl5/director.swg b/Lib/perl5/director.swg index a66869725..714a87877 100644 --- a/Lib/perl5/director.swg +++ b/Lib/perl5/director.swg @@ -27,7 +27,6 @@ */ # ifndef SWIG_DIRECTOR_RTDIR # define SWIG_DIRECTOR_RTDIR -#include namespace Swig { class Director; diff --git a/Lib/python/director.swg b/Lib/python/director.swg index 50f735a89..90c58c107 100644 --- a/Lib/python/director.swg +++ b/Lib/python/director.swg @@ -62,7 +62,6 @@ */ # ifndef SWIG_DIRECTOR_RTDIR # define SWIG_DIRECTOR_RTDIR -#include namespace Swig { class Director; From 0ed98c0606d2a46660902437b9fa4cdef14dfc97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Tomulik?= Date: Tue, 24 Dec 2013 22:30:12 +0100 Subject: [PATCH 433/481] added example with %pythonbegin This was requested in PR #7 but overlooked. Contains an example where one does: from __future__ import absolute_import using %pythonbegin directive. --- Doc/Manual/Python.html | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Doc/Manual/Python.html b/Doc/Manual/Python.html index c6cc2f40f..4584ff726 100644 --- a/Doc/Manual/Python.html +++ b/Doc/Manual/Python.html @@ -5551,7 +5551,15 @@ from __future__ import absolute_import

      at the very beginning of his proxy *.py file. In SWIG, it may be -accomplished with %pythonbegin directive.

      +accomplished with %pythonbegin directive as follows:

      + +
      +
      +%pythonbegin %{
      +from __future__ import absolute_import
      +%}
      +
      +

      34.11.4 Importing from __init__.py

      From bf313809ae8a441e71b3cfafa29e905df0882a56 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 22 Feb 2014 00:43:18 +0000 Subject: [PATCH 434/481] Fix Lua examples for running under Lua 5.2 Includes cherry picking parts of https://github.com/v-for-vandal/swig/commit/ce2760f77e9ab04ce276244ee4329aeba7ddea54 --- Examples/lua/dual/dual.cpp | 4 ++++ Examples/lua/embed/Makefile | 3 ++- Examples/lua/embed/embed.c | 4 ++++ Examples/lua/embed2/Makefile | 3 ++- Examples/lua/embed2/embed2.c | 6 ++++-- Examples/lua/embed3/embed3.cpp | 17 ++++++++++------- 6 files changed, 26 insertions(+), 11 deletions(-) diff --git a/Examples/lua/dual/dual.cpp b/Examples/lua/dual/dual.cpp index d2a9ecaa9..ad7897953 100644 --- a/Examples/lua/dual/dual.cpp +++ b/Examples/lua/dual/dual.cpp @@ -36,6 +36,10 @@ extern "C" int luaopen_example2(lua_State*L); #define DEBUG2(X,Y) {printf(X,Y);fflush(stdout);} #define DEBUG3(X,Y,Z) {printf(X,Y,Z);fflush(stdout);} +#if LUA_VERSION_NUM > 501 +#define lua_open luaL_newstate +#endif + void testModule(lua_State *L) { swig_type_info *pTypeInfo=0,*pTypeInfo2=0; diff --git a/Examples/lua/embed/Makefile b/Examples/lua/embed/Makefile index df1f8fa04..57979c061 100644 --- a/Examples/lua/embed/Makefile +++ b/Examples/lua/embed/Makefile @@ -4,6 +4,7 @@ TARGET = embed SRCS = example.c INTERFACE = example.i LUA_INTERP = embed.c +LIBS = -lm # this is a little different to normal as we have our own special interpreter # which we want to static link @@ -12,7 +13,7 @@ check: build build: $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) SRCS='$(SRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' LIBS='$(LIBS)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static clean: $(MAKE) -f $(TOP)/Makefile lua_clean diff --git a/Examples/lua/embed/embed.c b/Examples/lua/embed/embed.c index 9df168f94..f21c933a5 100644 --- a/Examples/lua/embed/embed.c +++ b/Examples/lua/embed/embed.c @@ -18,6 +18,10 @@ We will be using the luaL_dostring()/lua_dostring() function to call into lua #include #include +#if LUA_VERSION_NUM > 501 +#define lua_open luaL_newstate +#endif + /* the SWIG wrappered library */ extern int luaopen_example(lua_State*L); diff --git a/Examples/lua/embed2/Makefile b/Examples/lua/embed2/Makefile index fc309ac7e..ec22bdcae 100644 --- a/Examples/lua/embed2/Makefile +++ b/Examples/lua/embed2/Makefile @@ -4,6 +4,7 @@ TARGET = embed2 SRCS = example.c INTERFACE = example.i LUA_INTERP = embed2.c +LIBS = -lm # this is a little different to normal as we have our own special interpreter # which we want to static link @@ -12,7 +13,7 @@ check: build build: $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) SRCS='$(SRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' LIBS='$(LIBS)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static clean: $(MAKE) -f $(TOP)/Makefile lua_clean diff --git a/Examples/lua/embed2/embed2.c b/Examples/lua/embed2/embed2.c index 8d28ee6ea..3145d3b10 100644 --- a/Examples/lua/embed2/embed2.c +++ b/Examples/lua/embed2/embed2.c @@ -31,6 +31,9 @@ We will be using the luaL_dostring()/lua_dostring() function to call into lua #include #include +#if LUA_VERSION_NUM > 501 +#define lua_open luaL_newstate +#endif /* the SWIG wrappered library */ extern int luaopen_example(lua_State*L); @@ -46,8 +49,7 @@ int call_add(lua_State *L,int a,int b,int* res) { push a, push b, call 'add' check & return res */ top=lua_gettop(L); /* for later */ - lua_pushstring(L, "add"); /* function name */ - lua_gettable(L, LUA_GLOBALSINDEX); /* function to be called */ + lua_getglobal(L, "add"); /* function to be called */ if (!lua_isfunction(L,-1)) { printf("[C] error: cannot find function 'add'\n"); lua_settop(L,top); // reset diff --git a/Examples/lua/embed3/embed3.cpp b/Examples/lua/embed3/embed3.cpp index e5e0e0a7d..cdf56268d 100644 --- a/Examples/lua/embed3/embed3.cpp +++ b/Examples/lua/embed3/embed3.cpp @@ -26,11 +26,15 @@ extern "C" { #include #include } - -/* The SWIG external runtime is generated by using. -swig -lua -externalruntime swigluarun.h -It contains useful function used by SWIG in its wrappering -SWIG_TypeQuery() SWIG_NewPointerObj() + +#if LUA_VERSION_NUM > 501 +#define lua_open luaL_newstate +#endif + +/* The SWIG external runtime is generated by using. +swig -lua -externalruntime swigluarun.h +It contains useful function used by SWIG in its wrappering +SWIG_TypeQuery() SWIG_NewPointerObj() */ #include "swigluarun.h" // the SWIG external runtime @@ -65,8 +69,7 @@ int call_onEvent(lua_State *L, Event e) { push a, push b, call 'add' check & return res */ top = lua_gettop(L); /* for later */ - lua_pushstring(L, "onEvent"); /* function name */ - lua_gettable(L, LUA_GLOBALSINDEX); /* function to be called */ + lua_getglobal(L, "onEvent"); /* function to be called */ if (!lua_isfunction(L, -1)) { printf("[C++] error: cannot find function 'OnEvent'\n"); lua_settop(L, top); // reset From 91f4828a4aa0cf53155ace45e3f33f9ac76c4bed Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 22 Feb 2014 01:04:50 +0000 Subject: [PATCH 435/481] Fix missing fragment name in warning message about missing fragment --- Examples/test-suite/errors/swig_fragment_missing.i | 4 ++++ .../test-suite/errors/swig_fragment_missing.stderr | 1 + Source/Swig/fragment.c | 10 +++++----- 3 files changed, 10 insertions(+), 5 deletions(-) create mode 100644 Examples/test-suite/errors/swig_fragment_missing.i create mode 100644 Examples/test-suite/errors/swig_fragment_missing.stderr diff --git a/Examples/test-suite/errors/swig_fragment_missing.i b/Examples/test-suite/errors/swig_fragment_missing.i new file mode 100644 index 000000000..e1e83350b --- /dev/null +++ b/Examples/test-suite/errors/swig_fragment_missing.i @@ -0,0 +1,4 @@ +%module xxx + +%fragment("awol"); + diff --git a/Examples/test-suite/errors/swig_fragment_missing.stderr b/Examples/test-suite/errors/swig_fragment_missing.stderr new file mode 100644 index 000000000..1debb0090 --- /dev/null +++ b/Examples/test-suite/errors/swig_fragment_missing.stderr @@ -0,0 +1 @@ +swig_fragment_missing.i:3: Warning 490: Fragment 'awol' not found. diff --git a/Source/Swig/fragment.c b/Source/Swig/fragment.c index 927c772b8..5b30e86e0 100644 --- a/Source/Swig/fragment.c +++ b/Source/Swig/fragment.c @@ -94,16 +94,16 @@ void Swig_fragment_emit(Node *n) { String *name = 0; String *type = 0; + name = Getattr(n, "value"); + if (!name) { + name = n; + } + if (!fragments) { Swig_warning(WARN_FRAGMENT_NOT_FOUND, Getfile(n), Getline(n), "Fragment '%s' not found.\n", name); return; } - - name = Getattr(n, "value"); - if (!name) { - name = n; - } type = Getattr(n, "type"); if (type) { mangle = Swig_string_mangle(type); From 2feb2e6fc600f8663911c36d362f9764c2ccee0e Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 22 Feb 2014 01:11:40 +0000 Subject: [PATCH 436/481] Revert fragment for non-UTL languages --- Lib/std/std_except.i | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Lib/std/std_except.i b/Lib/std/std_except.i index 18bbd4ef1..75b8d0fd6 100644 --- a/Lib/std/std_except.i +++ b/Lib/std/std_except.i @@ -2,7 +2,9 @@ #error "do not use this version of std_except.i" #endif -%fragment(""); +%{ +#include +%} #if defined(SWIG_STD_EXCEPTIONS_AS_CLASSES) From ec629beb3145302e96ac6d8844a4dc29d011dbc8 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Sat, 22 Feb 2014 15:46:22 +0400 Subject: [PATCH 437/481] Fixing segfault --- Source/Modules/lua.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index f521824a0..a516b5eb0 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -1557,7 +1557,7 @@ public: if (result == SWIG_OK) { // This will add static member variable to the class namespace with name ClassName_VarName if (v2_compatibility) { - Swig_save("lua_staticmembervariableHandler", n, "lua:name"); + Swig_save("lua_staticmembervariableHandler", n, "lua:name", NIL); String *target_name = Getattr(n, "lua:name"); String *v2_name = Swig_name_member(NIL, class_symname, target_name); //Printf( stdout, "Name %s, class %s, compt. name %s\n", target_name, class_symname, v2_name ); // TODO: REMOVE From 77a7069f9eb128a671968d4c9a20cd5fc2561939 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Sat, 22 Feb 2014 17:56:21 +0400 Subject: [PATCH 438/481] Fixing cmd options, again --- Source/Modules/lua.cxx | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index a516b5eb0..58424d16d 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -80,7 +80,7 @@ void display_mapping(DOH *d) { NEW LANGUAGE NOTE:END ************************************************/ static const char *usage = (char *) "\ Lua Options (available with -lua)\n\ - -drop-old-scheme\n\ + -no-old-metatable-bindings\n\ - Disable support for old-style bindings name generation, some\n\ old-style members scheme etc.\n\ -elua - Generates LTR compatible wrappers for smaller devices running elua\n\ @@ -99,6 +99,16 @@ static int elua_ltr = 0; static int eluac_ltr = 0; static int elua_emulate = 0; static int squash_bases = 0; +/* This variable defines internal(!) module API level and compatibility options. + * This variable is controled by -no-old-metatable-bindings option. + * v2_compatibility - + * 1. static methods will be put into the scope their respective class + * belongs to as well as into the class scope itself. + * 2. The layout in elua mode is somewhat different + * 3. C enums defined inside struct will oblige to C Standard and + * will be defined in the scope surrounding the struct, not scope + * associated with it/ + */ static int v2_compatibility = 0; static const int default_api_level = 2; @@ -222,7 +232,7 @@ public: } else if (strcmp(argv[i], "-eluac") == 0) { eluac_ltr = 1; Swig_mark_arg(i); - } else if (strcmp(argv[i], "-drop-old-scheme") == 0) { + } else if (strcmp(argv[i], "-no-old-metatable-bindings") == 0) { Swig_mark_arg(i); api_level = 3; } else if (strcmp(argv[i], "-squash-bases") == 0) { From f12d8aa174c430cbfb313e1aa83b6d3950022b4b Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Sat, 22 Feb 2014 18:06:47 +0400 Subject: [PATCH 439/481] target_name -> lua_name --- Source/Modules/lua.cxx | 80 +++++++++++++++++++++--------------------- 1 file changed, 40 insertions(+), 40 deletions(-) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 58424d16d..b4fb7bed1 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -473,20 +473,20 @@ public: Hash *nspaceHash = getCArraysHash(nspace_or_class_name); String *s_ns_methods_tab = Getattr(nspaceHash, "methods"); String *wname = Getattr(n, "wrap:name"); - String *target_name = Getattr(n, "lua:name"); + String *lua_name = Getattr(n, "lua:name"); if (elua_ltr || eluac_ltr) - Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", target_name, "\")", ", LFUNCVAL(", wname, ")", "},\n", NIL); + Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", lua_name, "\")", ", LFUNCVAL(", wname, ")", "},\n", NIL); else - Printv(s_ns_methods_tab, tab4, "{ \"", target_name, "\", ", wname, "},\n", NIL); + Printv(s_ns_methods_tab, tab4, "{ \"", lua_name, "\", ", wname, "},\n", NIL); // Add to the metatable if method starts with '__' - const char * tn = Char(target_name); + const char * tn = Char(lua_name); if (tn[0]=='_' && tn[1] == '_' && !eluac_ltr) { String *metatable_tab = Getattr(nspaceHash, "metatable"); assert(metatable_tab); if (elua_ltr) - Printv(metatable_tab, tab4, "{LSTRKEY(\"", target_name, "\")", ", LFUNCVAL(", wname, ")", "},\n", NIL); + Printv(metatable_tab, tab4, "{LSTRKEY(\"", lua_name, "\")", ", LFUNCVAL(", wname, ")", "},\n", NIL); else - Printv(metatable_tab, tab4, "{ \"", target_name, "\", ", wname, "},\n", NIL); + Printv(metatable_tab, tab4, "{ \"", lua_name, "\", ", wname, "},\n", NIL); } } @@ -505,8 +505,8 @@ public: String *name = Getattr(n, "name"); String *iname = Getattr(n, "sym:name"); - String *target_name = Getattr(n, "lua:name"); - assert(target_name); + String *lua_name = Getattr(n, "lua:name"); + assert(lua_name); SwigType *d = Getattr(n, "type"); ParmList *l = Getattr(n, "parms"); Parm *p; @@ -518,7 +518,7 @@ public: if (Getattr(n, "sym:overloaded")) { overname = Getattr(n, "sym:overname"); } else { - if (!luaAddSymbol(target_name, n)) { + if (!luaAddSymbol(lua_name, n)) { return SWIG_ERROR; } } @@ -844,13 +844,13 @@ public: Wrapper *f = NewWrapper(); String *symname = Getattr(n, "sym:name"); - String *target_name = Getattr(n, "lua:name"); - assert(target_name); + String *lua_name = Getattr(n, "lua:name"); + assert(lua_name); String *wname = symnameWrapper(symname); //Printf(stdout,"Swig_overload_dispatch %s %s '%s' %d\n",symname,wname,dispatch,maxargs); - if (!luaAddSymbol(target_name, n)) { + if (!luaAddSymbol(lua_name, n)) { return SWIG_ERROR; } @@ -918,17 +918,17 @@ public: Hash *nspaceHash = getCArraysHash(nspace_or_class_name); String *s_ns_methods_tab = Getattr(nspaceHash, "methods"); String *s_ns_var_tab = Getattr(nspaceHash, "attributes"); - String *target_name = Getattr(n, "lua:name"); + String *lua_name = Getattr(n, "lua:name"); if (elua_ltr) { String *s_ns_dot_get = Getattr(nspaceHash, "get"); String *s_ns_dot_set = Getattr(nspaceHash, "set"); - Printf(s_ns_dot_get, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, target_name, getName); - Printf(s_ns_dot_set, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, target_name, setName); + Printf(s_ns_dot_get, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, lua_name, getName); + Printf(s_ns_dot_set, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, lua_name, setName); } else if (eluac_ltr) { - Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", target_name, "_get", "\")", ", LFUNCVAL(", getName, ")", "},\n", NIL); - Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", target_name, "_set", "\")", ", LFUNCVAL(", setName, ")", "},\n", NIL); + Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", lua_name, "_get", "\")", ", LFUNCVAL(", getName, ")", "},\n", NIL); + Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", lua_name, "_set", "\")", ", LFUNCVAL(", setName, ")", "},\n", NIL); } else { - Printf(s_ns_var_tab, "%s{ \"%s\", %s, %s },\n", tab4, target_name, getName, setName); + Printf(s_ns_var_tab, "%s{ \"%s\", %s, %s },\n", tab4, lua_name, getName, setName); } } @@ -945,8 +945,8 @@ public: only WRT this variable will look into this later. NEW LANGUAGE NOTE:END *********************************************** */ // REPORT("variableWrapper", n); - String *target_name = Getattr(n, "lua:name"); - assert(target_name); + String *lua_name = Getattr(n, "lua:name"); + assert(lua_name); current[VARIABLE] = true; // let SWIG generate the wrappers int result = Language::variableWrapper(n); @@ -987,24 +987,24 @@ public: REPORT("constantWrapper", n); String *name = Getattr(n, "name"); String *iname = Getattr(n, "sym:name"); - String *target_name = Getattr(n, "lua:name"); - if (target_name == 0) - target_name = iname; + String *lua_name = Getattr(n, "lua:name"); + if (lua_name == 0) + lua_name = iname; String *nsname = Copy(iname); SwigType *type = Getattr(n, "type"); String *rawval = Getattr(n, "rawval"); String *value = rawval ? rawval : Getattr(n, "value"); String *tm; - String *target_name_v2 = 0; + String *lua_name_v2 = 0; String *tm_v2 = 0; String *iname_v2 = 0; Node *n_v2 = 0; - if (!luaAddSymbol(target_name, n)) + if (!luaAddSymbol(lua_name, n)) return SWIG_ERROR; Swig_save("lua_constantMember", n, "sym:name", NIL); - Setattr(n, "sym:name", target_name); + Setattr(n, "sym:name", lua_name); /* Special hook for member pointer */ if (SwigType_type(type) == T_MPOINTER) { String *wname = symnameWrapper(iname); @@ -1015,13 +1015,13 @@ public: if ((tm = Swig_typemap_lookup("consttab", n, name, 0))) { //Printf(stdout, "tm v1: %s\n", tm); // TODO:REMOVE Replaceall(tm, "$source", value); - Replaceall(tm, "$target", target_name); + 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", target_name); + Replaceall(tm, "$target", lua_name); Replaceall(tm, "$value", value); Replaceall(tm, "$nsname", nsname); Printf(f_init, "%s\n", tm); @@ -1038,27 +1038,27 @@ public: if (make_v2_compatible) { // Special handling for enums in C mode - they are not prefixed with structure name if(!CPlusPlus && current[ENUM_CONST]) { - target_name_v2 = target_name; - DohIncref(target_name_v2); + lua_name_v2 = lua_name; + DohIncref(lua_name_v2); iname_v2 = iname; DohIncref(iname_v2); } else { - target_name_v2 = Swig_name_member(0, class_symname, target_name); + lua_name_v2 = Swig_name_member(0, class_symname, lua_name); iname_v2 = Swig_name_member(0, class_symname, iname); } n_v2 = Copy(n); - //Printf( stdout, "target name v2: %s, symname v2 %s\n", target_name_v2.ptr(), iname_v2.ptr());// TODO:REMOVE + //Printf( stdout, "target name v2: %s, symname v2 %s\n", lua_name_v2.ptr(), iname_v2.ptr());// TODO:REMOVE if (!luaAddSymbol(iname_v2, n, getNSpace())) { Swig_restore(n); return SWIG_ERROR; } - Setattr(n_v2, "sym:name", target_name_v2); + Setattr(n_v2, "sym:name", lua_name_v2); tm_v2 = Swig_typemap_lookup("consttab", n_v2, name, 0); if (tm_v2) { //Printf(stdout, "tm v2: %s\n", tm_v2.ptr()); // TODO:REMOVE Replaceall(tm_v2, "$source", value); - Replaceall(tm_v2, "$target", target_name_v2); + Replaceall(tm_v2, "$target", lua_name_v2); Replaceall(tm_v2, "$value", value); Replaceall(tm_v2, "$nsname", nsname); registerConstant(getNSpace(), tm_v2); @@ -1071,7 +1071,7 @@ public: return SWIG_ERROR; } Replaceall(tm_v2, "$source", value); - Replaceall(tm_v2, "$target", target_name_v2); + Replaceall(tm_v2, "$target", lua_name_v2); Replaceall(tm_v2, "$value", value); Replaceall(tm_v2, "$nsname", nsname); Printf(f_init, "%s\n", tm_v2); @@ -1530,8 +1530,8 @@ public: if (v2_compatibility) { Swig_require("lua_staticmemberfunctionHandler", n, "*lua:name", NIL); - String *target_name = Getattr(n, "lua:name"); - String *compat_name = Swig_name_member(0, class_symname, target_name); + String *lua_name = Getattr(n, "lua:name"); + String *compat_name = Swig_name_member(0, class_symname, lua_name); Setattr(n, "lua:name", compat_name); registerMethod(getNSpace(), n); Delete(compat_name); @@ -1568,9 +1568,9 @@ public: // This will add static member variable to the class namespace with name ClassName_VarName if (v2_compatibility) { Swig_save("lua_staticmembervariableHandler", n, "lua:name", NIL); - String *target_name = Getattr(n, "lua:name"); - String *v2_name = Swig_name_member(NIL, class_symname, target_name); - //Printf( stdout, "Name %s, class %s, compt. name %s\n", target_name, class_symname, v2_name ); // TODO: REMOVE + String *lua_name = Getattr(n, "lua:name"); + String *v2_name = Swig_name_member(NIL, class_symname, lua_name); + //Printf( stdout, "Name %s, class %s, compt. name %s\n", lua_name, class_symname, v2_name ); // TODO: REMOVE if (!GetFlag(n, "wrappedasconstant")) { Setattr(n, "lua:name", v2_name); registerVariable(getNSpace(), n, "varget:wrap:name", "varset:wrap:name"); From 166b19e860573f8f9cfa5bbaf6c1e7d66e630c8b Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Sat, 22 Feb 2014 18:26:46 +0400 Subject: [PATCH 440/481] Members renaming --- Source/Modules/lua.cxx | 97 +++++++++++++++++++++++------------------- 1 file changed, 54 insertions(+), 43 deletions(-) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index b4fb7bed1..31418cb8e 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -134,9 +134,20 @@ private: int have_constructor; int have_destructor; String *destructor_action; - String *class_symname; - String *class_fq_symname; // Fully qualified symname - NSpace + '.' + class_symname + // This variable holds the name of the current class in Lua. Usually it is + // the same as C++ class name, but rename directives can change it. + String *proxy_class_name; + // This is a so calld fully qualified symname - the above proxy class name + // prepended with class namespace. If class Lua name is the same as class C++ name, + // then it is basically C++ fully qualified name with colons replaced with dots. + String *full_proxy_class_name; + // All static methods and/or variables are treated as if they were in the + // special C++ namespace $(classname).__Static. This is internal mechanism only + // and is not visible to user in any manner. This variable holds the name + // of such pseudo-namespace a.k.a the result of above expression evaluation String *class_static_nspace; + // This variable holds the name of generated C function that acts as constructor + // for currently parsed class. String *constructor_name; // Many wrappers forward calls to each other, for example staticmembervariableHandler @@ -179,8 +190,8 @@ public: have_constructor(0), have_destructor(0), destructor_action(0), - class_symname(0), - class_fq_symname(0), + proxy_class_name(0), + full_proxy_class_name(0), class_static_nspace(0), constructor_name(0) { for (int i = 0; i < STATES_COUNT; i++) @@ -1043,8 +1054,8 @@ public: iname_v2 = iname; DohIncref(iname_v2); } else { - lua_name_v2 = Swig_name_member(0, class_symname, lua_name); - iname_v2 = Swig_name_member(0, class_symname, iname); + lua_name_v2 = Swig_name_member(0, proxy_class_name, lua_name); + iname_v2 = Swig_name_member(0, proxy_class_name, iname); } n_v2 = Copy(n); //Printf( stdout, "target name v2: %s, symname v2 %s\n", lua_name_v2.ptr(), iname_v2.ptr());// TODO:REMOVE @@ -1167,7 +1178,7 @@ public: assert(class_hash); String *cls_methods = Getattr(class_hash, "methods:name"); assert(cls_methods); - Printv(ns_methods, tab4, "{LSTRKEY(\"", class_symname, "\")", ", LROVAL(", cls_methods, ")", "},\n", NIL); + Printv(ns_methods, tab4, "{LSTRKEY(\"", proxy_class_name, "\")", ", LROVAL(", cls_methods, ")", "},\n", NIL); } } /* ------------------------------------------------------------ @@ -1176,7 +1187,7 @@ public: virtual int classHandler(Node *n) { //REPORT("classHandler", n); - String *mangled_class_fq_symname = 0; + String *mangled_full_proxy_class_name = 0; String *destructor_name = 0; String *nspace = getNSpace(); @@ -1185,25 +1196,25 @@ public: have_destructor = 0; destructor_action = 0; assert(class_static_nspace == 0); - assert(class_fq_symname == 0); - assert(class_symname == 0); + assert(full_proxy_class_name == 0); + assert(proxy_class_name == 0); current[NO_CPP] = false; - class_symname = Getattr(n, "sym:name"); + proxy_class_name = Getattr(n, "sym:name"); // We have to enforce nspace here, because technically we are already // inside class parsing (getCurrentClass != 0), but we should register // class in the it's parent namespace - if (!luaAddSymbol(class_symname, n, nspace)) + if (!luaAddSymbol(proxy_class_name, n, nspace)) return SWIG_ERROR; if (nspace == 0) - class_fq_symname = NewStringf("%s", class_symname); + full_proxy_class_name = NewStringf("%s", proxy_class_name); else - class_fq_symname = NewStringf("%s.%s", nspace, class_symname); + full_proxy_class_name = NewStringf("%s.%s", nspace, proxy_class_name); - assert(class_fq_symname); - mangled_class_fq_symname = Swig_name_mangle(class_fq_symname); + assert(full_proxy_class_name); + mangled_full_proxy_class_name = Swig_name_mangle(full_proxy_class_name); SwigType *t = Copy(Getattr(n, "name")); SwigType *fr_t = SwigType_typedef_resolve_all(t); /* Create fully resolved type */ @@ -1222,8 +1233,8 @@ public: static Hash *emitted = NewHash(); if (Getattr(emitted, mangled_fr_t)) { - class_fq_symname = 0; - class_symname = 0; + full_proxy_class_name = 0; + proxy_class_name = 0; return SWIG_NOWRAP; } Setattr(emitted, mangled_fr_t, "1"); @@ -1239,7 +1250,7 @@ public: // And we can guarantee that there will not be any name collision because names starting with 2 underscores // and capital letter are forbiden to use in C++. So, under know circumstances could our class contain // any member or subclass with name "__Static". Thus, never any name clash. - Hash *instance_cls = getCArraysHash(class_fq_symname, false); + Hash *instance_cls = getCArraysHash(full_proxy_class_name, false); assert(instance_cls); String *s_attr_tab_name = Getattr(instance_cls, "attributes:name"); String *s_methods_tab_name = Getattr(instance_cls, "methods:name"); @@ -1251,7 +1262,7 @@ public: * All constants are considered part of static part of class. */ - class_static_nspace = NewStringf("%s%s__Static", class_fq_symname, NSPACE_SEPARATOR); + class_static_nspace = NewStringf("%s%s__Static", full_proxy_class_name, NSPACE_SEPARATOR); Hash *static_cls = getCArraysHash(class_static_nspace, false); assert(static_cls); Setattr(static_cls, "lua:no_namespaces", "1"); @@ -1270,7 +1281,7 @@ public: SwigType_add_pointer(t); // Catch all: eg. a class with only static functions and/or variables will not have 'remembered' - String *wrap_class_name = NewStringf("_wrap_class_%s", mangled_class_fq_symname); + String *wrap_class_name = NewStringf("_wrap_class_%s", mangled_full_proxy_class_name); String *wrap_class = NewStringf("&%s", wrap_class_name); Setattr(n, "wrap:class_name", wrap_class_name); SwigType_remember_clientdata(t, wrap_class); @@ -1283,11 +1294,11 @@ public: Hash *nspaceHash = getCArraysHash(nspace); // Register the class structure with the type checker - // Printf(f_init,"SWIG_TypeClientData(SWIGTYPE%s, (void *) &_wrap_class_%s);\n", SwigType_manglestr(t), mangled_class_fq_symname); + // Printf(f_init,"SWIG_TypeClientData(SWIGTYPE%s, (void *) &_wrap_class_%s);\n", SwigType_manglestr(t), mangled_full_proxy_class_name); // emit a function to be called to delete the object if (have_destructor) { - destructor_name = NewStringf("swig_delete_%s", mangled_class_fq_symname); + destructor_name = NewStringf("swig_delete_%s", mangled_full_proxy_class_name); Printv(f_wrappers, "static void ", destructor_name, "(void *obj) {\n", NIL); if (destructor_action) { Printv(f_wrappers, SwigType_str(rt, "arg1"), " = (", SwigType_str(rt, 0), ") obj;\n", NIL); @@ -1325,18 +1336,18 @@ public: } else if (eluac_ltr) { String *ns_methods_tab = Getattr(nspaceHash, "methods"); assert(ns_methods_tab); - Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "new_", class_symname, "\")", ", LFUNCVAL(", constructor_name, ")", "},\n", NIL); + Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "new_", proxy_class_name, "\")", ", LFUNCVAL(", constructor_name, ")", "},\n", NIL); } } if (have_destructor) { if (eluac_ltr) { String *ns_methods_tab = Getattr(nspaceHash, "methods"); assert(ns_methods_tab); - Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "free_", mangled_class_fq_symname, "\")", ", LFUNCVAL(", destructor_name, ")", "},\n", NIL); + Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "free_", mangled_full_proxy_class_name, "\")", ", LFUNCVAL(", destructor_name, ")", "},\n", NIL); } } - closeCArraysHash(class_fq_symname, f_wrappers); + closeCArraysHash(full_proxy_class_name, f_wrappers); closeCArraysHash(class_static_nspace, f_wrappers); @@ -1372,21 +1383,21 @@ public: } } // First, print class static part - printCArraysDefinition(class_static_nspace, class_symname, f_wrappers); + printCArraysDefinition(class_static_nspace, proxy_class_name, f_wrappers); - assert(mangled_class_fq_symname); + assert(mangled_full_proxy_class_name); assert(base_class); assert(base_class_names); - assert(class_symname); - assert(class_fq_symname); + assert(proxy_class_name); + assert(full_proxy_class_name); // Then print class isntance part - Printv(f_wrappers, "static swig_lua_class *swig_", mangled_class_fq_symname, "_bases[] = {", base_class, "0};\n", NIL); + Printv(f_wrappers, "static swig_lua_class *swig_", mangled_full_proxy_class_name, "_bases[] = {", base_class, "0};\n", NIL); Delete(base_class); - Printv(f_wrappers, "static const char *swig_", mangled_class_fq_symname, "_base_names[] = {", base_class_names, "0};\n", NIL); + Printv(f_wrappers, "static const char *swig_", mangled_full_proxy_class_name, "_base_names[] = {", base_class_names, "0};\n", NIL); Delete(base_class_names); - Printv(f_wrappers, "static swig_lua_class _wrap_class_", mangled_class_fq_symname, " = { \"", class_symname, "\", \"", class_fq_symname, "\", &SWIGTYPE", + Printv(f_wrappers, "static swig_lua_class _wrap_class_", mangled_full_proxy_class_name, " = { \"", proxy_class_name, "\", \"", full_proxy_class_name, "\", &SWIGTYPE", SwigType_manglestr(t), ",", NIL); if (have_constructor) { @@ -1411,18 +1422,18 @@ public: else Printf(f_wrappers, ", 0"); - Printf(f_wrappers, ", swig_%s_bases, swig_%s_base_names };\n\n", mangled_class_fq_symname, mangled_class_fq_symname); + Printf(f_wrappers, ", swig_%s_bases, swig_%s_base_names };\n\n", mangled_full_proxy_class_name, mangled_full_proxy_class_name); current[NO_CPP] = true; Delete(class_static_nspace); class_static_nspace = 0; - Delete(mangled_class_fq_symname); - mangled_class_fq_symname = 0; + Delete(mangled_full_proxy_class_name); + mangled_full_proxy_class_name = 0; Delete(destructor_name); destructor_name = 0; - Delete(class_fq_symname); - class_fq_symname = 0; - class_symname = 0; + Delete(full_proxy_class_name); + full_proxy_class_name = 0; + proxy_class_name = 0; return SWIG_OK; } @@ -1531,7 +1542,7 @@ public: if (v2_compatibility) { Swig_require("lua_staticmemberfunctionHandler", n, "*lua:name", NIL); String *lua_name = Getattr(n, "lua:name"); - String *compat_name = Swig_name_member(0, class_symname, lua_name); + String *compat_name = Swig_name_member(0, proxy_class_name, lua_name); Setattr(n, "lua:name", compat_name); registerMethod(getNSpace(), n); Delete(compat_name); @@ -1569,8 +1580,8 @@ public: if (v2_compatibility) { Swig_save("lua_staticmembervariableHandler", n, "lua:name", NIL); String *lua_name = Getattr(n, "lua:name"); - String *v2_name = Swig_name_member(NIL, class_symname, lua_name); - //Printf( stdout, "Name %s, class %s, compt. name %s\n", lua_name, class_symname, v2_name ); // TODO: REMOVE + String *v2_name = Swig_name_member(NIL, proxy_class_name, lua_name); + //Printf( stdout, "Name %s, class %s, compt. name %s\n", lua_name, proxy_class_name, v2_name ); // TODO: REMOVE if (!GetFlag(n, "wrappedasconstant")) { Setattr(n, "lua:name", v2_name); registerVariable(getNSpace(), n, "varget:wrap:name", "varset:wrap:name"); @@ -2069,7 +2080,7 @@ public: scope = class_static_nspace; } else if (current[MEMBER_VAR] || current[CONSTRUCTOR] || current[DESTRUCTOR] || current[MEMBER_FUNC]) { - scope = class_fq_symname; + scope = full_proxy_class_name; } else { // Friend functions are handled this way scope = class_static_nspace; } From dac0e989e3c7603e6da6f67e5258665b8abb5aa5 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Sat, 22 Feb 2014 19:01:48 +0400 Subject: [PATCH 441/481] Options in alphabetical order --- Source/Modules/lua.cxx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 31418cb8e..e2bba5bea 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -80,15 +80,15 @@ void display_mapping(DOH *d) { NEW LANGUAGE NOTE:END ************************************************/ static const char *usage = (char *) "\ Lua Options (available with -lua)\n\ - -no-old-metatable-bindings\n\ - - Disable support for old-style bindings name generation, some\n\ - old-style members scheme etc.\n\ -elua - Generates LTR compatible wrappers for smaller devices running elua\n\ -eluac - LTR compatible wrappers in \"crass compress\" mode for elua\n\ -elua-emulate - Emulates behaviour of eLua. Usefull only for testing.\n\ Incompatible with -elua/-eluac options.\n\ -nomoduleglobal - Do not register the module name as a global variable \n\ but return the module table from calls to require.\n\ + -no-old-metatable-bindings\n\ + - Disable support for old-style bindings name generation, some\n\ + old-style members scheme etc.\n\ -squash-bases - Squashes symbols from all inheritance tree of a given class\n\ into itself. Emulates pre-SWIG3.0 inheritance. Insignificantly\n\ speeds things up, but increases memory consumption.\n\ From 4f3c77051f5aff194dfea70574dfcf00b48c0ace Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 22 Feb 2014 20:51:27 +0000 Subject: [PATCH 442/481] Slight wording change when running test-suite Should be easier to parse 'by eye' --- Doc/Manual/Extending.html | 8 ++++---- Examples/test-suite/chicken/Makefile.in | 6 +++--- Examples/test-suite/common.mk | 4 ++-- Examples/test-suite/csharp/Makefile.in | 4 ++-- Examples/test-suite/d/Makefile.in | 4 ++-- Examples/test-suite/java/Makefile.in | 4 ++-- 6 files changed, 15 insertions(+), 15 deletions(-) diff --git a/Doc/Manual/Extending.html b/Doc/Manual/Extending.html index 1fc65d0e1..c757bc289 100644 --- a/Doc/Manual/Extending.html +++ b/Doc/Manual/Extending.html @@ -3350,10 +3350,10 @@ Note that if a runtime test is available, a message "(with run test)" is display
       $ make check-python-test-suite
       checking python test-suite
      -checking testcase argcargvtest (with run test) under python
      -checking testcase python_autodoc under python
      -checking testcase python_append (with run test) under python
      -checking testcase callback (with run test) under python
      +checking python testcase argcargvtest (with run test)
      +checking python testcase python_autodoc
      +checking python testcase python_append (with run test)
      +checking python testcase callback (with run test)
       

      diff --git a/Examples/test-suite/chicken/Makefile.in b/Examples/test-suite/chicken/Makefile.in index 42fe6100a..3c2f3de54 100644 --- a/Examples/test-suite/chicken/Makefile.in +++ b/Examples/test-suite/chicken/Makefile.in @@ -69,17 +69,17 @@ SWIGOPT += -nounit $(run_testcase) %.cppproxy: - echo "$(ACTION)ing testcase $* (with run test) under chicken with -proxy" + echo "$(ACTION)ing $(LANGUAGE) testcase $* (with run test) with -proxy" +$(swig_and_compile_cpp) $(run_testcase) %.cproxy: - echo "$(ACTION)ing testcase $* (with run test) under chicken with -proxy" + echo "$(ACTION)ing $(LANGUAGE) testcase $* (with run test) with -proxy" +$(swig_and_compile_c) $(run_testcase) %.multiproxy: - echo "$(ACTION)ing testcase $* (with run test) under chicken with -proxy" + echo "$(ACTION)ing $(LANGUAGE) testcase $* (with run test) with -proxy" +$(swig_and_compile_multi_cpp) $(run_testcase) diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 836984476..6ea80670d 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -708,9 +708,9 @@ swig_and_compile_runtime = \ setup = \ if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - echo "$(ACTION)ing testcase $* (with run test) under $(LANGUAGE)" ; \ + echo "$(ACTION)ing $(LANGUAGE) testcase $* (with run test)" ; \ else \ - echo "$(ACTION)ing testcase $* under $(LANGUAGE)" ; \ + echo "$(ACTION)ing $(LANGUAGE) testcase $*" ; \ fi; diff --git a/Examples/test-suite/csharp/Makefile.in b/Examples/test-suite/csharp/Makefile.in index 4284a775d..993699bc8 100644 --- a/Examples/test-suite/csharp/Makefile.in +++ b/Examples/test-suite/csharp/Makefile.in @@ -58,9 +58,9 @@ csharp_swig2_compatibility.cpptest: SWIGOPT += -DSWIG2_CSHARP # Makes a directory for the testcase if it does not exist setup = \ if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - echo "$(ACTION)ing testcase $* (with run test) under $(LANGUAGE)" ; \ + echo "$(ACTION)ing $(LANGUAGE) testcase $* (with run test)" ; \ else \ - echo "$(ACTION)ing testcase $* under $(LANGUAGE)" ; \ + echo "$(ACTION)ing $(LANGUAGE) testcase $*" ; \ fi; \ if [ ! -d $* ]; then \ mkdir $*; \ diff --git a/Examples/test-suite/d/Makefile.in b/Examples/test-suite/d/Makefile.in index 8128e4f7a..61c2749dc 100644 --- a/Examples/test-suite/d/Makefile.in +++ b/Examples/test-suite/d/Makefile.in @@ -46,9 +46,9 @@ SWIGOPT+=-splitproxy -package $* # Makes a directory for the testcase if it does not exist setup = \ if [ -f $(srcdir)/$(TESTPREFIX)$*$(TESTSUFFIX) ]; then \ - echo "$(ACTION)ing testcase $* (with run test) under $(LANGUAGE)" ; \ + echo "$(ACTION)ing $(LANGUAGE) testcase $* (with run test)" ; \ else \ - echo "$(ACTION)ing testcase $* under $(LANGUAGE)" ; \ + echo "$(ACTION)ing $(LANGUAGE) testcase $*" ; \ fi; \ if [ ! -d $*$(VERSIONSUFFIX) ]; then \ mkdir $*$(VERSIONSUFFIX); \ diff --git a/Examples/test-suite/java/Makefile.in b/Examples/test-suite/java/Makefile.in index 1bd4b0261..ee0e13fba 100644 --- a/Examples/test-suite/java/Makefile.in +++ b/Examples/test-suite/java/Makefile.in @@ -73,9 +73,9 @@ director_nspace_director_name_collision.%: JAVA_PACKAGE = $*Package # Makes a directory for the testcase if it does not exist setup = \ if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - echo "$(ACTION)ing testcase $* (with run test) under $(LANGUAGE)" ; \ + echo "$(ACTION)ing $(LANGUAGE) testcase $* (with run test)" ; \ else \ - echo "$(ACTION)ing testcase $* under $(LANGUAGE)" ; \ + echo "$(ACTION)ing $(LANGUAGE) testcase $* $(LANGUAGE)" ; \ fi; \ if [ ! -d $(JAVA_PACKAGE) ]; then \ mkdir $(JAVA_PACKAGE); \ From be49f5caeed5fe421a631a2e8724ca4ba38ed342 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 22 Feb 2014 20:53:26 +0000 Subject: [PATCH 443/481] Another revert fragment for non-UTL languages --- Lib/std/_std_deque.i | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/std/_std_deque.i b/Lib/std/_std_deque.i index 8e701668e..7dd3552db 100644 --- a/Lib/std/_std_deque.i +++ b/Lib/std/_std_deque.i @@ -10,8 +10,8 @@ %{ #include +#include %} -%fragment(""); /* This macro defines all of the standard methods for a deque. This From 894de07c3d676268cbfc83cf92e0bd6e7850e2dc Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 22 Feb 2014 21:24:55 +0000 Subject: [PATCH 444/481] Add missing executable bit --- Examples/guile/matrix/runme.scm | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 Examples/guile/matrix/runme.scm diff --git a/Examples/guile/matrix/runme.scm b/Examples/guile/matrix/runme.scm old mode 100644 new mode 100755 From 087a66a6587a5b34d167a5c8b98b0ba7014dbd80 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Sun, 23 Feb 2014 02:08:34 +0400 Subject: [PATCH 445/481] updated documentation following comd options renaming --- Doc/Manual/Lua.html | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Doc/Manual/Lua.html b/Doc/Manual/Lua.html index 31c9dd564..44384b1a3 100644 --- a/Doc/Manual/Lua.html +++ b/Doc/Manual/Lua.html @@ -160,7 +160,7 @@ swig -lua -help - -swig3 + -no-old-metatable-bindings Disable backward compatibility: old-style binding names generations and a few other things. Explanations are included into appropriate sections. @@ -524,7 +524,7 @@ This is 'effectively' converted into the following Lua code:

      Backward compatibility

      -If -swig3 option is not given, then in addition to previously described bindings, the old-style ones are generated: +If -no-old-metatable-bindings option is not given, then in addition to previously described bindings, the old-style ones are generated:

       > print(example.Test_TEST1)
      @@ -748,7 +748,7 @@ It is not (currently) possible to access static members of an instance:
       

      Backward compatibility

      -

      If -swig3 option is not given, then backward compatible names are generated in addition to ordinary ones:

      +

      If -no-old-metatable-bindings option is not given, then backward compatible names are generated in addition to ordinary ones:

       > example.Spam_foo()            -- calling Spam::foo()
       > a=example.Spam_bar            -- reading Spam::bar 
      @@ -1364,7 +1364,7 @@ Now, in Lua it could be used like this:
       

      Backward compatibility

      -If SWIG is running in backward compatible way, i.e. without -swig3 option, then additional old-style names are generated(notice the underscore): +If SWIG is running in backward compatible way, i.e. without -no-old-metatable-bindings option, then additional old-style names are generated(notice the underscore):

       9
      @@ -1376,7 +1376,7 @@ If SWIG is running in backward compatible way, i.e. without -swig3 opti
       

      Backward compatibility

      Names

      -

      If SWIG is launched without -swig3 option, then it enters backward-compatible mode. While in this mode, it tries +

      If SWIG is launched without -no-old-metatable-bindings option, then it enters backward-compatible mode. While in this mode, it tries to generate additional names for static functions, class static constants and class enums. Those names are in a form $classname_$symbolname and are added to the scope surrounding the class. If %nspace is enabled, then class namespace is taken as scope. If there is no namespace, or %nspace is disabled, From 2f3bf144c685585dab7d4d8ae1ae805dda0edab8 Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Sun, 23 Feb 2014 16:52:08 +1300 Subject: [PATCH 446/481] Fix assorted comment and documentation typos --- CHANGES | 6 +++--- Doc/Devel/internals.html | 4 ++-- Doc/Devel/tree.html | 2 +- Doc/Manual/Allegrocl.html | 18 +++++++++--------- Doc/Manual/CSharp.html | 2 +- Doc/Manual/Extending.html | 6 +++--- Doc/Manual/Introduction.html | 2 +- Doc/Manual/Lisp.html | 2 +- Doc/Manual/Modula3.html | 8 ++++---- Doc/Manual/Modules.html | 2 +- Doc/Manual/Ocaml.html | 4 ++-- Doc/Manual/Octave.html | 2 +- Examples/Makefile.in | 2 +- Examples/go/template/index.html | 2 +- Examples/java/template/index.html | 2 +- Examples/lua/import.lua | 8 ++++---- Examples/python/callback/runme.py | 2 +- Examples/python/multimap/example.i | 2 +- Examples/ruby/index.html | 2 +- Examples/test-suite/java/README | 2 +- Examples/test-suite/lua/import.lua | 6 +++--- Lib/chicken/chickenrun.swg | 4 ++-- Lib/lua/luaruntime.swg | 2 +- Lib/octave/octtypemaps.swg | 2 +- Lib/perl5/Makefile.in | 2 +- Lib/perl5/perltypemaps.swg | 2 +- Lib/ruby/rubytypemaps.swg | 2 +- Lib/swig.swg | 2 +- Lib/swiginit.swg | 2 +- Source/CParse/templ.c | 2 +- Source/Modules/typepass.cxx | 2 +- Source/Swig/typeobj.c | 2 +- configure.ac | 2 +- 33 files changed, 56 insertions(+), 56 deletions(-) diff --git a/CHANGES b/CHANGES index 988f0fb5e..db9adab03 100644 --- a/CHANGES +++ b/CHANGES @@ -5684,7 +5684,7 @@ Version 1.3.28 (February 12, 2006) %rename("%(utitle)s",%$isfunction,%$ismember) ""; - to avoid clashings with other swig macros/directives. + to avoid clashes with other swig macros/directives. 01/14/2006: cfisavage [Ruby] @@ -11787,7 +11787,7 @@ Version 1.3.20 (December 17, 2003) 11/30/2003: cheetah (William Fulton) [Java] Fixed [ 766409 ] missing symbol SWIG_JavaThrowException during module load - SWIGs internal functions are all static as there is no need for different SWIG + SWIG's internal functions are all static as there is no need for different SWIG generated modules to share any code at runtime. 11/30/2003: beazley @@ -21368,7 +21368,7 @@ Version 1.1 Patch 4 (January 4, 1998) 12/29/97: Fixed configure script and a few makefiles to support Python 1.5 12/29/97: Added 'embed15.i' library file. This file should be used to - staticly link versions of Python 1.5. To make it the default, + statically link versions of Python 1.5. To make it the default, simply copy 'swig_lib/python/embed15.i' to 'swig_lib/python/embed.i' Version 1.1 Patch 3 (November 24, 1997) diff --git a/Doc/Devel/internals.html b/Doc/Devel/internals.html index 94a82519d..c9082d3f6 100644 --- a/Doc/Devel/internals.html +++ b/Doc/Devel/internals.html @@ -347,7 +347,7 @@ Delete(a); /* Destroy a */ All objects are referenced counted and given a reference count of 1 when initially created. The Delete() function only destroys an object when the reference count reaches zero. When -an object is placed in a list or hash table, it's reference count is automatically increased. For example: +an object is placed in a list or hash table, its reference count is automatically increased. For example:

      @@ -844,7 +844,7 @@ Returns a type object corresponding to the type string produced by the Swig_cloc
       
    5. char *Swig_clocal_deref(DataType *t, char *name)
      This function is the inverse of the clocal() function. Given a type and a name, it produces a string containing the code needed to cast/convert the type produced by -Swig_clocal() back into it's original type. +Swig_clocal() back into its original type.

    6. char *Swig_clocal_assign(DataType *t, char *name)
      diff --git a/Doc/Devel/tree.html b/Doc/Devel/tree.html index db3c6fee4..73a49ed55 100644 --- a/Doc/Devel/tree.html +++ b/Doc/Devel/tree.html @@ -185,7 +185,7 @@ this function merely records that those attributes did not exist in the original
      This function is similar to Swig_save() except that adds additional attribute checking. There are different interpretations of the attribute names. A name of "attr" merely requests that the function check for the presence of an attribute. If the attribute is missing, SWIG will exit with a failed assertion. An attribute name of "?attr" specifies that the attribute "attr" is optional and -that it's old value must be saved (if any). An attribute name of "*attr" specifies that the attribute is required and that +that its old value must be saved (if any). An attribute name of "*attr" specifies that the attribute is required and that its value must be saved. The saving of attributes is performed in the same manner as with Swig_save(). Here is an example:
      diff --git a/Doc/Manual/Allegrocl.html b/Doc/Manual/Allegrocl.html
      index 12b915ee2..173777231 100644
      --- a/Doc/Manual/Allegrocl.html
      +++ b/Doc/Manual/Allegrocl.html
      @@ -748,7 +748,7 @@ namespace car {
           
           

      Constants, as declared by the preprocessor #define macro or SWIG - %constant directive, are included in SWIGs parse tree + %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 @@ -887,7 +887,7 @@ globalvar> (globalvar.nnn::glob_float)

      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 it's enum type. For each enum + 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. @@ -901,7 +901,7 @@ globalvar> (globalvar.nnn::glob_float) 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 it's value into lisp. + a ff:def-foreign-variable call is generated to retrieve its value into lisp.

      For example, the following header file @@ -1131,7 +1131,7 @@ namespace BAR { 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. It's key benefit is that it may be passed as an argument + 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.

      @@ -1617,7 +1617,7 @@ opoverload> 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(). It's declaration would + consider the function printf(). Its declaration would appear as follows:

      @@ -1735,7 +1735,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) 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. It's default mapping is as follows: + section of the above code diagram. Its default mapping is as follows:

      @@ -1758,7 +1758,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN)

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

      @@ -2093,7 +2093,7 @@ foreign environment.

      The :type keyword argument provides more information on the type of -identifier. It's value is a symbol. This allows the +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. @@ -2123,7 +2123,7 @@ scope in the specified class.

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

      diff --git a/Doc/Manual/CSharp.html b/Doc/Manual/CSharp.html index 764a1a6c3..6ee33ac68 100644 --- a/Doc/Manual/CSharp.html +++ b/Doc/Manual/CSharp.html @@ -881,7 +881,7 @@ set so should only be used when a C# exception is not created.

      -Lets say we have the following simple C++ method: +Let's say we have the following simple C++ method:

      diff --git a/Doc/Manual/Extending.html b/Doc/Manual/Extending.html index c757bc289..a8c15fe03 100644 --- a/Doc/Manual/Extending.html +++ b/Doc/Manual/Extending.html @@ -2761,8 +2761,8 @@ Within SWIG wrappers, there are five main sections. These are (in order)
    7. begin: This section is a placeholder for users to put code at the beginning of the C/C++ wrapper file.
    8. runtime: This section has most of the common SWIG runtime code.
    9. header: This section holds declarations and inclusions from the .i file. -
    10. wrapper: This section holds all the wrappering code. -
    11. init: This section holds the module initalisation function +
    12. wrapper: This section holds all the wrapper code. +
    13. init: This section holds the module initialisation function (the entry point for the interpreter).

      @@ -3005,7 +3005,7 @@ virtual int functionWrapper(Node *n) { /* write typemaps(in) */ .... - /* write constriants */ + /* write constraints */ .... /* Emit the function call */ diff --git a/Doc/Manual/Introduction.html b/Doc/Manual/Introduction.html index d5dc778bd..19d59a4df 100644 --- a/Doc/Manual/Introduction.html +++ b/Doc/Manual/Introduction.html @@ -449,7 +449,7 @@ to work with complicated and unusual C/C++ applications.

      Ironically, the freedom that SWIG provides is countered by an -extremely conservative approach to code generation. At it's core, SWIG +extremely conservative approach to code generation. At its core, SWIG tries to distill even the most advanced C++ code down to a small well-defined set of interface building techniques based on ANSI C programming. Because of this, you will find that SWIG interfaces can diff --git a/Doc/Manual/Lisp.html b/Doc/Manual/Lisp.html index 01ff3a3ec..09e410185 100644 --- a/Doc/Manual/Lisp.html +++ b/Doc/Manual/Lisp.html @@ -122,7 +122,7 @@ swig -cffi -help As we mentioned earlier the ideal way to use SWIG is to use interface - files. To illustrate the use of it, lets assume that we have a + files. To illustrate the use of it, let's assume that we have a file named test.h with the following C code:

      diff --git a/Doc/Manual/Modula3.html b/Doc/Manual/Modula3.html
      index 065313fa2..329127a0f 100644
      --- a/Doc/Manual/Modula3.html
      +++ b/Doc/Manual/Modula3.html
      @@ -45,7 +45,7 @@
       
       
       

      -This chapter describes SWIG's support of +This chapter describes SWIG's support for Modula-3. You should be familiar with the basics @@ -109,7 +109,7 @@ into exceptions.

      If the library API is ill designed -writing appropriate typemaps can be still time-consuming. +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 @@ -120,14 +120,14 @@ 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 Module-3. +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 Module-3 module into +functions), but it doesn't allow you to easily integrate a Modula-3 module into a C/C++ project.

      diff --git a/Doc/Manual/Modules.html b/Doc/Manual/Modules.html index 70b0f1181..c44341e56 100644 --- a/Doc/Manual/Modules.html +++ b/Doc/Manual/Modules.html @@ -130,7 +130,7 @@ public:

      To create the wrapper properly, module derived_module needs to know about the base class and that its interface is covered in another module. The -line %import "base_module.i" lets SWIG know exactly that. Oftentimes +line %import "base_module.i" lets SWIG know exactly that. Often the .h file is passed to %import instead of the .i, which unfortunately doesn't work for all language modules. For example, Python requires the name of module that the base class exists in so that the proxy classes can fully inherit the diff --git a/Doc/Manual/Ocaml.html b/Doc/Manual/Ocaml.html index 127be904d..2eef3ad4d 100644 --- a/Doc/Manual/Ocaml.html +++ b/Doc/Manual/Ocaml.html @@ -163,7 +163,7 @@ the user more freedom with respect to custom typing.

      The camlp4 module (swigp4.ml -> swigp4.cmo) contains a simple rewriter which -makes C++ code blend more seamlessly with objective caml code. It's use is +makes C++ code blend more seamlessly with objective caml code. Its use is optional, but encouraged. The source file is included in the Lib/ocaml directory of the SWIG source distribution. You can checkout this file with "swig -ocaml -co swigp4.ml". You should compile the file with @@ -310,7 +310,7 @@ type c_obj =

    14. caml_val_ptr receives a void * and returns a c_obj.
    15. caml_val_bool receives a C int and returns a c_obj representing - it's bool value.
    16. + its bool value.
    17. caml_val_(u)?(char|short|int|long|float|double) receives an appropriate C value and returns a c_obj representing it.
    18. caml_val_string receives a char * and returns a string value.
    19. diff --git a/Doc/Manual/Octave.html b/Doc/Manual/Octave.html index 3e12ce668..42c6526b7 100644 --- a/Doc/Manual/Octave.html +++ b/Doc/Manual/Octave.html @@ -329,7 +329,7 @@ octave:4> swigexample.fclose(f);

      - Simply printing the value of a wrapped C++ type will print it's typename. E.g., + Simply printing the value of a wrapped C++ type will print its typename. E.g.,

      octave:1> swigexample;
      diff --git a/Examples/Makefile.in b/Examples/Makefile.in
      index 5c7884a8f..218d8eca5 100644
      --- a/Examples/Makefile.in
      +++ b/Examples/Makefile.in
      @@ -1098,7 +1098,7 @@ CHICKEN_GENERATED_SCHEME = $(INTERFACE:.i=.scm)
       CHICKEN_COMPILED_SCHEME = $(INTERFACE:.i=_chicken.c)
       CHICKEN_COMPILED_OBJECT = $(CHICKEN_COMPILED_SCHEME:.c=.@OBJEXT@)
       
      -# flags for the main chicken sources (only used when compiling staticly)
      +# flags for the main chicken sources (only used when compiling statically)
       CHICKEN_COMPILED_MAIN = $(CHICKEN_MAIN:.scm=_chicken.c)
       CHICKEN_COMPILED_MAIN_OBJECT = $(CHICKEN_COMPILED_MAIN:.c=.@OBJEXT@)
       
      diff --git a/Examples/go/template/index.html b/Examples/go/template/index.html
      index a14e3b29a..cf2b1337b 100644
      --- a/Examples/go/template/index.html
      +++ b/Examples/go/template/index.html
      @@ -17,7 +17,7 @@ SWIG.
       
       

      The C++ Code

      -Lets take a templated function and a templated class as follows: +Let's take a templated function and a templated class as follows:
      diff --git a/Examples/java/template/index.html b/Examples/java/template/index.html
      index f4408e568..31dba6d8e 100644
      --- a/Examples/java/template/index.html
      +++ b/Examples/java/template/index.html
      @@ -16,7 +16,7 @@ This example illustrates how C++ templates can be used from Java using SWIG.
       
       

      The C++ Code

      -Lets take a templated function and a templated class as follows: +Let's take a templated function and a templated class as follows:
      diff --git a/Examples/lua/import.lua b/Examples/lua/import.lua
      index b2a40b017..4a0f0d3da 100644
      --- a/Examples/lua/import.lua
      +++ b/Examples/lua/import.lua
      @@ -1,7 +1,7 @@
       -- import
       -- the lua 5.0 loading mechanism is rather poor & relies upon the loadlib() fn
       -- the lua 5.1 loading mechanism is simplicity itself
      --- for now we need a bridge which will use the correct verion
      +-- for now we need a bridge which will use the correct version
       
       function import_5_0(module)
       	-- imports the file into the program
      @@ -10,7 +10,7 @@ function import_5_0(module)
       	-- and look for the fn 'Example_Init()' (note the capitalisation)
       	if rawget(_G,module)~=nil then return end -- module appears to be loaded
       		
      -	-- capitialising the first letter
      +	-- capitalising the first letter
       	local c=string.upper(string.sub(module,1,1))
       	local fnname=c..string.sub(module,2).."_Init"
       	
      @@ -26,7 +26,7 @@ function import_5_0(module)
       	end
       	assert(lib,"error loading module:"..module)
       	
      -	lib() -- execute the function: initalising the lib
      +	lib() -- execute the function: initialising the lib
       	local m=rawget(_G,module)	-- gets the module object
       	assert(m~=nil,"no module table found")
       end
      @@ -39,4 +39,4 @@ if string.sub(_VERSION,1,7)=='Lua 5.0' then
       	import=import_5_0
       else
       	import=import_5_1
      -end
      \ No newline at end of file
      +end
      diff --git a/Examples/python/callback/runme.py b/Examples/python/callback/runme.py
      index 026e9520b..ddb668407 100644
      --- a/Examples/python/callback/runme.py
      +++ b/Examples/python/callback/runme.py
      @@ -42,7 +42,7 @@ print
       print "Adding and calling another Python callback"
       print "------------------------------------------"
       
      -# Lets do the same but use the weak reference this time.
      +# Let's do the same but use the weak reference this time.
       
       callback = PyCallback().__disown__()
       caller.setCallback(callback)
      diff --git a/Examples/python/multimap/example.i b/Examples/python/multimap/example.i
      index 3f6fc3db3..cc2482cc8 100644
      --- a/Examples/python/multimap/example.i
      +++ b/Examples/python/multimap/example.i
      @@ -98,7 +98,7 @@ extern int count(char *bytes, int len, char c);
       /* This example shows how to wrap a function that mutates a string */
       
       /* Since str is modified, we make a copy of the Python object
      -   so that we don't violate it's mutability */
      +   so that we don't violate its mutability */
       
       %typemap(in) (char *str, int len) {
       %#if PY_VERSION_HEX >= 0x03000000
      diff --git a/Examples/ruby/index.html b/Examples/ruby/index.html
      index f04146e56..4f4aa0ad2 100644
      --- a/Examples/ruby/index.html
      +++ b/Examples/ruby/index.html
      @@ -1,4 +1,4 @@
      -
      +
       
       SWIG:Examples:ruby
       
      diff --git a/Examples/test-suite/java/README b/Examples/test-suite/java/README
      index b8b7416d9..b4123a840 100644
      --- a/Examples/test-suite/java/README
      +++ b/Examples/test-suite/java/README
      @@ -1,6 +1,6 @@
       See ../README for common README file.
       
      -The Java implementation of the test-suite is a little different to the other languages in that all of SWIGs output goes into a subdirectory named after the individual test case. This is so that all the shadow classes can be compiled as Java classes have to go into separate files. Otherwise the Makefile wouldn't know which .java files would be relevant to the testcase. For this to work the testcase must go into a Java package.
      +The Java implementation of the test-suite is a little different to the other languages in that all of SWIG's output goes into a subdirectory named after the individual test case. This is so that all the shadow classes can be compiled as Java classes which have to go into separate files. Otherwise the Makefile wouldn't know which .java files would be relevant to the testcase. For this to work the testcase must go into a Java package.
       
       Any testcases which have _runme.java appended after the testcase name will be detected and run.
       
      diff --git a/Examples/test-suite/lua/import.lua b/Examples/test-suite/lua/import.lua
      index eaab3b400..2ab2555e7 100644
      --- a/Examples/test-suite/lua/import.lua
      +++ b/Examples/test-suite/lua/import.lua
      @@ -1,7 +1,7 @@
       -- import
       -- the lua 5.0 loading mechanism is rather poor & relies upon the loadlib() fn
       -- the lua 5.1 loading mechanism is simplicity itself
      --- for now we need a bridge which will use the correct verion
      +-- for now we need a bridge which will use the correct version
       
       function import_5_0(name)
       	-- imports the file into the program
      @@ -13,7 +13,7 @@ function import_5_0(name)
       	local lib=loadlib(name..'.dll','luaopen_'..name) or loadlib(name..'.so','luaopen_'..name)
       	assert(lib,"error loading module:"..name)
       	
      -	lib() -- execute the function: initalising the lib
      +	lib() -- execute the function: initialising the lib
       	assert(rawget(_G,name)~=nil,"no module table found")
       end
       
      @@ -25,4 +25,4 @@ if string.sub(_VERSION,1,7)=='Lua 5.0' then
       	import=import_5_0
       else
       	import=import_5_1
      -end
      \ No newline at end of file
      +end
      diff --git a/Lib/chicken/chickenrun.swg b/Lib/chicken/chickenrun.swg
      index 07db41945..f13400181 100644
      --- a/Lib/chicken/chickenrun.swg
      +++ b/Lib/chicken/chickenrun.swg
      @@ -313,7 +313,7 @@ SWIG_Chicken_GetModule(void *SWIGUNUSEDPARM(clientdata)) {
           swig_module_info *ret = 0;
           C_word sym;
       
      -    /* lookup the type pointer... it is stored in it's own symbol table */
      +    /* 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);
      @@ -333,7 +333,7 @@ SWIG_Chicken_SetModule(swig_module_info *module) {
           C_word pointer;
           static C_word *space = 0;
           
      -    /* type pointer is stored in it's own symbol table */
      +    /* 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);
      diff --git a/Lib/lua/luaruntime.swg b/Lib/lua/luaruntime.swg
      index 423c7190b..3ca489ffa 100644
      --- a/Lib/lua/luaruntime.swg
      +++ b/Lib/lua/luaruntime.swg
      @@ -31,7 +31,7 @@ SWIGEXPORT int SWIG_init(lua_State* L) /* default Lua action */
         int i;
         /* start with global table */
         lua_pushglobaltable (L);
      -  /* SWIG's internal initalisation */
      +  /* SWIG's internal initialisation */
         SWIG_InitializeModule((void*)L);
         SWIG_PropagateClientData();
       #endif
      diff --git a/Lib/octave/octtypemaps.swg b/Lib/octave/octtypemaps.swg
      index e331cf4b3..4acf8e076 100644
      --- a/Lib/octave/octtypemaps.swg
      +++ b/Lib/octave/octtypemaps.swg
      @@ -1,5 +1,5 @@
       
      -// Include fundamental fragemt definitions
      +// Include fundamental fragment definitions
       %include 
       
       // Look for user fragments file.
      diff --git a/Lib/perl5/Makefile.in b/Lib/perl5/Makefile.in
      index f11ad2bdf..1fee86ccc 100644
      --- a/Lib/perl5/Makefile.in
      +++ b/Lib/perl5/Makefile.in
      @@ -46,7 +46,7 @@ SWIG          = $(exec_prefix)/bin/swig
       SWIGOPT       = -perl5 
       SWIGCC        = $(CC) 
       
      -# SWIG Library files.  Uncomment this to staticly rebuild Perl
      +# SWIG Library files.  Uncomment this to statically rebuild Perl
       #SWIGLIBS      = -static -lperlmain.i
       
       # Rules for creating .o files from source.
      diff --git a/Lib/perl5/perltypemaps.swg b/Lib/perl5/perltypemaps.swg
      index f47a5ef82..ffec5eaf1 100644
      --- a/Lib/perl5/perltypemaps.swg
      +++ b/Lib/perl5/perltypemaps.swg
      @@ -18,7 +18,7 @@
       #define SWIG_FROM_CALL_ARGS  SWIG_PERL_CALL_ARGS_1
       
       
      -/* Include fundamental fragemt definitions */
      +/* Include fundamental fragment definitions */
       %include 
       
       /* Look for user fragments file. */
      diff --git a/Lib/ruby/rubytypemaps.swg b/Lib/ruby/rubytypemaps.swg
      index 336ee977a..3837df078 100644
      --- a/Lib/ruby/rubytypemaps.swg
      +++ b/Lib/ruby/rubytypemaps.swg
      @@ -8,7 +8,7 @@
       #undef SWIG_TYPECHECK_BOOL
       %define SWIG_TYPECHECK_BOOL             10000 %enddef
       
      -/* Include fundamental fragemt definitions */
      +/* Include fundamental fragment definitions */
       %include 
       
       /* Look for user fragments file. */
      diff --git a/Lib/swig.swg b/Lib/swig.swg
      index 3ddbb85a0..c33ae3854 100644
      --- a/Lib/swig.swg
      +++ b/Lib/swig.swg
      @@ -321,7 +321,7 @@ static int NAME(TYPE x) {
       
       /*
        * Function/method overloading support.   This is done through typemaps,
      - * but also involve a precedence level. 
      + * but also involves a precedence level.
        */
       
       /* Macro for overload resolution */
      diff --git a/Lib/swiginit.swg b/Lib/swiginit.swg
      index f321181eb..69e368ac1 100644
      --- a/Lib/swiginit.swg
      +++ b/Lib/swiginit.swg
      @@ -11,7 +11,7 @@
        * array with the correct data and linking the correct swig_cast_info
        * structures together.
        *
      - * The generated swig_type_info structures are assigned staticly to an initial
      + * The generated swig_type_info structures are assigned statically to an initial
        * array. We just loop through that array, and handle each type individually.
        * First we lookup if this type has been already loaded, and if so, use the
        * loaded structure instead of the generated one. Then we have to fill in the
      diff --git a/Source/CParse/templ.c b/Source/CParse/templ.c
      index 48bdf4faa..fe8fc2800 100644
      --- a/Source/CParse/templ.c
      +++ b/Source/CParse/templ.c
      @@ -825,7 +825,7 @@ Node *Swig_cparse_template_locate(String *name, Parm *tparms, Symtab *tscope) {
             /* If not a templated class we must have a templated function.
                The template found is not necessarily the one we want when dealing with templated
                functions. We don't want any specialized templated functions as they won't have
      -         the default parameters. Lets look for the unspecialized template. Also make sure
      +         the default parameters. Let's look for the unspecialized template. Also make sure
                the number of template parameters is correct as it is possible to overload a
                templated function with different numbers of template parameters. */
       
      diff --git a/Source/Modules/typepass.cxx b/Source/Modules/typepass.cxx
      index 49f95090d..329a601a8 100644
      --- a/Source/Modules/typepass.cxx
      +++ b/Source/Modules/typepass.cxx
      @@ -476,7 +476,7 @@ class TypePass:private Dispatcher {
           if (unnamed && tdname && (Cmp(storage, "typedef") == 0)) {
             SwigType_typedef(unnamed, tdname);
           }
      -    // name of the outer class should already be patched to contain it's outer classes names, but not to contain namespaces
      +    // name of the outer class should already be patched to contain its outer classes names, but not to contain namespaces
           // namespace name (if present) is added after processing child nodes
           if (Getattr(n, "nested:outer") && name) {
             String *outerName = Getattr(Getattr(n, "nested:outer"), "name");
      diff --git a/Source/Swig/typeobj.c b/Source/Swig/typeobj.c
      index 903d1357c..622eac118 100644
      --- a/Source/Swig/typeobj.c
      +++ b/Source/Swig/typeobj.c
      @@ -240,7 +240,7 @@ String *SwigType_parm(const SwigType *t) {
       /* -----------------------------------------------------------------------------
        * SwigType_split()
        *
      - * Splits a type into it's component parts and returns a list of string.
      + * Splits a type into its component parts and returns a list of string.
        * ----------------------------------------------------------------------------- */
       
       List *SwigType_split(const SwigType *t) {
      diff --git a/configure.ac b/configure.ac
      index be4e6e3c9..f3414969e 100644
      --- a/configure.ac
      +++ b/configure.ac
      @@ -19,7 +19,7 @@ AH_BOTTOM([
       /* Default language */
       #define SWIG_LANG               "-tcl"
       
      -/* Deal with Microsofts attempt at deprecating C standard runtime functions */
      +/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
       #if defined(_MSC_VER)
       # define _CRT_SECURE_NO_DEPRECATE
       #endif
      
      From 34c97ffdbd528f4c53873ccc8f60238579c2a22d Mon Sep 17 00:00:00 2001
      From: Olly Betts 
      Date: Sun, 23 Feb 2014 18:05:50 +1300
      Subject: [PATCH 447/481] Improve the class example for several languages.
      
      Fix numerous inaccuracies in index.html (where it exists) and eliminate
      unnecessary differences between the example code being wrapped.
      ---
       Examples/java/class/example.cxx   | 10 ++--
       Examples/java/class/example.h     | 25 ++++-----
       Examples/java/class/index.html    | 49 +++--------------
       Examples/perl5/class/example.cxx  | 10 ++--
       Examples/perl5/class/example.h    | 29 +++++------
       Examples/perl5/class/example.i    |  1 -
       Examples/perl5/class/index.html   | 87 +++++++------------------------
       Examples/perl5/class/runme.pl     |  2 +-
       Examples/php/class/example.cxx    | 23 +++-----
       Examples/php/class/example.h      | 16 +++---
       Examples/php/class/runme.php      |  4 +-
       Examples/python/class/example.cxx | 10 ++--
       Examples/python/class/example.h   | 25 ++++-----
       Examples/python/class/index.html  | 87 +++++--------------------------
       Examples/python/class/runme.py    |  4 +-
       Examples/ruby/class/example.cxx   | 10 ++--
       Examples/ruby/class/example.h     | 25 ++++-----
       Examples/ruby/class/index.html    | 61 ++++------------------
       Examples/ruby/class/runme.rb      |  4 ++
       Examples/tcl/class/example.cxx    | 10 ++--
       Examples/tcl/class/example.h      | 25 ++++-----
       Examples/tcl/class/example.i      |  1 -
       Examples/tcl/class/index.html     | 48 +++--------------
       23 files changed, 154 insertions(+), 412 deletions(-)
      
      diff --git a/Examples/java/class/example.cxx b/Examples/java/class/example.cxx
      index 1e8e203dd..046304519 100644
      --- a/Examples/java/class/example.cxx
      +++ b/Examples/java/class/example.cxx
      @@ -1,4 +1,4 @@
      -/* File : example.c */
      +/* File : example.cxx */
       
       #include "example.h"
       #define M_PI 3.14159265358979323846
      @@ -11,18 +11,18 @@ void Shape::move(double dx, double dy) {
       
       int Shape::nshapes = 0;
       
      -double Circle::area(void) {
      +double Circle::area() {
         return M_PI*radius*radius;
       }
       
      -double Circle::perimeter(void) {
      +double Circle::perimeter() {
         return 2*M_PI*radius;
       }
       
      -double Square::area(void) {
      +double Square::area() {
         return width*width;
       }
       
      -double Square::perimeter(void) {
      +double Square::perimeter() {
         return 4*width;
       }
      diff --git a/Examples/java/class/example.h b/Examples/java/class/example.h
      index 46d901361..0dff185b2 100644
      --- a/Examples/java/class/example.h
      +++ b/Examples/java/class/example.h
      @@ -7,11 +7,11 @@ public:
         }
         virtual ~Shape() {
           nshapes--;
      -  };
      -  double  x, y;   
      +  }
      +  double  x, y;
         void    move(double dx, double dy);
      -  virtual double area(void) = 0;
      -  virtual double perimeter(void) = 0;
      +  virtual double area() = 0;
      +  virtual double perimeter() = 0;
         static  int nshapes;
       };
       
      @@ -19,21 +19,16 @@ class Circle : public Shape {
       private:
         double radius;
       public:
      -  Circle(double r) : radius(r) { };
      -  virtual double area(void);
      -  virtual double perimeter(void);
      +  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(void);
      -  virtual double perimeter(void);
      +  Square(double w) : width(w) { }
      +  virtual double area();
      +  virtual double perimeter();
       };
      -
      -
      -
      -
      -  
      diff --git a/Examples/java/class/index.html b/Examples/java/class/index.html
      index cf9130c62..b0a5e221d 100644
      --- a/Examples/java/class/index.html
      +++ b/Examples/java/class/index.html
      @@ -32,8 +32,8 @@ public:
         }
         virtual ~Shape() {
           nshapes--;
      -  };
      -  double  x, y;   
      +  }
      +  double  x, y;
         void    move(double dx, double dy);
         virtual double area() = 0;
         virtual double perimeter() = 0;
      @@ -44,7 +44,7 @@ class Circle : public Shape {
       private:
         double radius;
       public:
      -  Circle(double r) : radius(r) { };
      +  Circle(double r) : radius(r) { }
         virtual double area();
         virtual double perimeter();
       };
      @@ -53,7 +53,7 @@ class Square : public Shape {
       private:
         double width;
       public:
      -  Square(double w) : width(w) { };
      +  Square(double w) : width(w) { }
         virtual double area();
         virtual double perimeter();
       };
      @@ -146,50 +146,15 @@ Shape.setNshapes(13);       // Set a static data member
       
       
      • This high-level interface using proxy classes is not the only way to handle C++ code. -A low level interface using c functions to access member variables and member functions is the alternative SWIG -approach. This entails passing around the c pointer or c++ 'this' pointer and as such it is not difficult to crash the JVM. +A low level interface using C functions to access member variables and member functions is the alternative SWIG +approach. This entails passing around the C pointer or C++ 'this' pointer and as such it is not difficult to crash the JVM. The abstraction of the underlying pointer by the java proxy classes far better fits the java programming paradigm.

        -

      • SWIG *does* know how to properly perform upcasting of objects in an inheritance +
      • SWIG does know how to properly perform upcasting of objects in an inheritance hierarchy (including multiple inheritance). However Java classes can only derive from one base class so multiple inheritance is not implemented. Java classes can implement more than one interface so there is scope for improvement in the future. -

        -

      • A wide variety of C++ features are not currently supported by SWIG. Here is the -short and incomplete list: - -

        -

          -
        • Overloaded methods and functions. SWIG wrappers don't know how to resolve name -conflicts so you must give an alternative name to any overloaded method name using the -%name directive like this: - -
          -
          -void foo(int a);  
          -%name(foo2) void foo(double a, double b);
          -
          -
          - -

          -

        • Overloaded operators. Not supported at all. The only workaround for this is -to write a helper function. For example: - -
          -
          -%inline %{
          -    Vector *vector_add(Vector *a, Vector *b) {
          -          ... whatever ...
          -    }
          -%}
          -
          -
          - -

          -

        • Namespaces. Not supported at all. Won't be supported until SWIG2.0 (if at all). - -

      diff --git a/Examples/perl5/class/example.cxx b/Examples/perl5/class/example.cxx index 1e8e203dd..046304519 100644 --- a/Examples/perl5/class/example.cxx +++ b/Examples/perl5/class/example.cxx @@ -1,4 +1,4 @@ -/* File : example.c */ +/* File : example.cxx */ #include "example.h" #define M_PI 3.14159265358979323846 @@ -11,18 +11,18 @@ void Shape::move(double dx, double dy) { int Shape::nshapes = 0; -double Circle::area(void) { +double Circle::area() { return M_PI*radius*radius; } -double Circle::perimeter(void) { +double Circle::perimeter() { return 2*M_PI*radius; } -double Square::area(void) { +double Square::area() { return width*width; } -double Square::perimeter(void) { +double Square::perimeter() { return 4*width; } diff --git a/Examples/perl5/class/example.h b/Examples/perl5/class/example.h index b0671d583..fd6943541 100644 --- a/Examples/perl5/class/example.h +++ b/Examples/perl5/class/example.h @@ -7,11 +7,11 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -19,29 +19,24 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + 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(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; typedef Square TSquare; class CFoo { public: - static Square MakeSquare(void) {return Square(4.0);}; - static TSquare MakeTSquare(void) {return Square(4.0);}; + static Square MakeSquare(void) {return Square(4.0);} + static TSquare MakeTSquare(void) {return Square(4.0);} }; - - - - - diff --git a/Examples/perl5/class/example.i b/Examples/perl5/class/example.i index 23ee8a822..75700b305 100644 --- a/Examples/perl5/class/example.i +++ b/Examples/perl5/class/example.i @@ -6,6 +6,5 @@ %} /* Let's just grab the original header file here */ - %include "example.h" diff --git a/Examples/perl5/class/index.html b/Examples/perl5/class/index.html index 58a50ad2e..b4f923b5a 100644 --- a/Examples/perl5/class/index.html +++ b/Examples/perl5/class/index.html @@ -32,8 +32,8 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); virtual double area() = 0; virtual double perimeter() = 0; @@ -44,7 +44,7 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; + Circle(double r) : radius(r) { } virtual double area(); virtual double perimeter(); }; @@ -53,7 +53,7 @@ class Square : public Shape { private: double width; public: - Square(double w) : width(w) { }; + Square(double w) : width(w) { } virtual double area(); virtual double perimeter(); }; @@ -82,7 +82,7 @@ like this: Note: when creating a C++ extension, you must run SWIG with the -c++ option like this:
      -% swig -c++ -python example.i
      +% swig -c++ -perl example.i
       
      @@ -97,60 +97,45 @@ Click here to see a script that calls the C++ functions f
      -$c = example::new_Circle(10.0);
      +$c = new example::Circle(10.0);
       

      -

    20. To access member data, a pair of accessor functions are used. -For example: +
    21. You can access member data like so:
      -example::Shape_x_set($c,15);    # Set member data
      -$x = example::Shape_x_get($c);   # Get member data
      -
      -
      - -Note: when accessing member data, the name of the class in which -the data member is defined is used. For example Shape_x_get(). - -

      -

    22. To invoke a member function, you simply do this - -
      -
      -print "The area is ", example::Shape_area($c);
      +$c->{x} = 15;    # Set member data
      +$x = $c->{x};    # Get member data
       

      -

    23. Type checking knows about the inheritance structure of C++. For example: +
    24. To invoke a member function, you simply do this:
      -example::Shape_area($c);       # Works (c is a Shape)
      -example::Circle_area($c);      # Works (c is a Circle)
      -example::Square_area($c);      # Fails (c is definitely not a Square)
      +print "The area is ", $c->area();
       

      -

    25. To invoke a destructor, simply do this +
    26. To invoke a destructor, simply do this:
      -example::delete_Shape($c);     # Deletes a shape
      +$c->DESTROY();   # Deletes a shape
       

      -

    27. Static member variables are wrapped as C global variables. For example: +
    28. Static member variables are wrapped like so:
      -$n = $example::Shape_nshapes;     # Get a static data member
      -$example::Shapes_nshapes = 13;   # Set a static data member
      +$n = $example::Shape::nshapes;    # Get a static data member
      +$example::Shapes::nshapes = 13;   # Set a static data member
       
      @@ -159,47 +144,11 @@ $example::Shapes_nshapes = 13; # Set a static data member

      General Comments

        -
      • This low-level interface is not the only way to handle C++ code. Proxy classes -provide a much higher-level interface. - -

        -

      • SWIG *does* know how to properly perform upcasting of objects in an inheritance +
      • SWIG does know how to properly perform upcasting of objects in an inheritance hierarchy (including multiple inheritance). Therefore it is perfectly safe to pass an object of a derived class to any function involving a base class. -

        -

      • A wide variety of C++ features are not currently supported by SWIG. Here is the -short and incomplete list: - -

        -

          -
        • Overloaded methods and functions. SWIG wrappers don't know how to resolve name -conflicts so you must give an alternative name to any overloaded method name using the -%name directive like this: - -
          -
          -void foo(int a);  
          -%name(foo2) void foo(double a, double b);
          -
          -
          - -

          -

        • Overloaded operators. Not supported at all. The only workaround for this is -to write a helper function. For example: - -
          -
          -%inline %{
          -    Vector *vector_add(Vector *a, Vector *b) {
          -          ... whatever ...
          -    }
          -%}
          -
          -
          - -

          -

        • Namespaces. Not supported at all. Won't be supported until SWIG2.0 (if at all). +
        • C++ Namespaces - %nspace isn't yet supported for Perl.
        diff --git a/Examples/perl5/class/runme.pl b/Examples/perl5/class/runme.pl index 076e1437b..e45e2b8ce 100644 --- a/Examples/perl5/class/runme.pl +++ b/Examples/perl5/class/runme.pl @@ -40,7 +40,7 @@ foreach $o ($c,$s) { print " $o\n"; print " area = ", $o->area(), "\n"; print " perimeter = ", $o->perimeter(), "\n"; - } +} # ----- Delete everything ----- diff --git a/Examples/php/class/example.cxx b/Examples/php/class/example.cxx index f171f10e9..046304519 100644 --- a/Examples/php/class/example.cxx +++ b/Examples/php/class/example.cxx @@ -1,14 +1,7 @@ -/* File : example.c */ +/* File : example.cxx */ #include "example.h" -#include -#ifndef M_PI -# define M_PI 3.14159265358979323846 -#endif - -int Shape::get_nshapes() { - return nshapes; -} +#define M_PI 3.14159265358979323846 /* Move the shape to a new location */ void Shape::move(double dx, double dy) { @@ -18,22 +11,18 @@ void Shape::move(double dx, double dy) { int Shape::nshapes = 0; -void Circle::set_radius( double r ) { - radius = r; -} - -double Circle::area(void) { +double Circle::area() { return M_PI*radius*radius; } -double Circle::perimeter(void) { +double Circle::perimeter() { return 2*M_PI*radius; } -double Square::area(void) { +double Square::area() { return width*width; } -double Square::perimeter(void) { +double Square::perimeter() { return 4*width; } diff --git a/Examples/php/class/example.h b/Examples/php/class/example.h index 02eaf7232..0dff185b2 100644 --- a/Examples/php/class/example.h +++ b/Examples/php/class/example.h @@ -10,10 +10,9 @@ public: } double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; - static int get_nshapes(); }; class Circle : public Shape { @@ -21,10 +20,8 @@ private: double radius; public: Circle(double r) : radius(r) { } - ~Circle() { } - void set_radius( double r ); - virtual double area(void); - virtual double perimeter(void); + virtual double area(); + virtual double perimeter(); }; class Square : public Shape { @@ -32,7 +29,6 @@ private: double width; public: Square(double w) : width(w) { } - ~Square() { } - virtual double area(void); - virtual double perimeter(void); + virtual double area(); + virtual double perimeter(); }; diff --git a/Examples/php/class/runme.php b/Examples/php/class/runme.php index 12b686052..99c253b46 100644 --- a/Examples/php/class/runme.php +++ b/Examples/php/class/runme.php @@ -14,7 +14,7 @@ print " Created square\n"; # ----- Access a static member ----- -print "\nA total of " . Shape::get_nshapes() . " shapes were created\n"; +print "\nA total of " . Shape::nshapes() . " shapes were created\n"; # ----- Member data access ----- @@ -54,7 +54,7 @@ $s = NULL; # the square. $o = NULL; -print Shape::get_nshapes() . " shapes remain\n"; +print Shape::nshapes() . " shapes remain\n"; print "Goodbye\n"; ?> diff --git a/Examples/python/class/example.cxx b/Examples/python/class/example.cxx index 1e8e203dd..046304519 100644 --- a/Examples/python/class/example.cxx +++ b/Examples/python/class/example.cxx @@ -1,4 +1,4 @@ -/* File : example.c */ +/* File : example.cxx */ #include "example.h" #define M_PI 3.14159265358979323846 @@ -11,18 +11,18 @@ void Shape::move(double dx, double dy) { int Shape::nshapes = 0; -double Circle::area(void) { +double Circle::area() { return M_PI*radius*radius; } -double Circle::perimeter(void) { +double Circle::perimeter() { return 2*M_PI*radius; } -double Square::area(void) { +double Square::area() { return width*width; } -double Square::perimeter(void) { +double Square::perimeter() { return 4*width; } diff --git a/Examples/python/class/example.h b/Examples/python/class/example.h index 46d901361..0dff185b2 100644 --- a/Examples/python/class/example.h +++ b/Examples/python/class/example.h @@ -7,11 +7,11 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -19,21 +19,16 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + 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(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; - - - - - diff --git a/Examples/python/class/index.html b/Examples/python/class/index.html index 12c5eded1..2e1baa395 100644 --- a/Examples/python/class/index.html +++ b/Examples/python/class/index.html @@ -12,9 +12,7 @@

        Wrapping a simple C++ class

        -This example illustrates the most primitive form of C++ class wrapping performed -by SWIG. In this case, C++ classes are simply transformed into a collection of -C-style functions that provide access to class members. +This example illustrates wrapping a simple C++ class to give a Python class.

        The C++ Code

        @@ -32,8 +30,8 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); virtual double area() = 0; virtual double perimeter() = 0; @@ -44,7 +42,7 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; + Circle(double r) : radius(r) { } virtual double area(); virtual double perimeter(); }; @@ -53,7 +51,7 @@ class Square : public Shape { private: double width; public: - Square(double w) : width(w) { }; + Square(double w) : width(w) { } virtual double area(); virtual double perimeter(); }; @@ -102,51 +100,34 @@ c = example.new_Circle(10.0)
    29. -

    30. To access member data, a pair of accessor functions are used. +
    31. Member variables of the C++ class are wrapped as attributes of the Python class. For example:
      -example.Shape_x_set(c,15)    # Set member data
      -x = example.Shape_x_get(c)    # Get member data
      -
      -
      - -Note: when accessing member data, the name of the class in which -the member data was must be used. In this case, Shape_x_get() -and Shape_x_set() are used since 'x' was defined in Shape. - -

      -

    32. To invoke a member function, you simply do this - -
      -
      -print "The area is ", example.Shape_area(c)
      +c.x = 15   # Set member data
      +x = c.x    # Get member data
       

      -

    33. Type checking knows about the inheritance structure of C++. For example: +
    34. Member function are invoked as you would expect:
      -example.Shape_area(c)       # Works (c is a Shape)
      -example.Circle_area(c)      # Works (c is a Circle)
      -example.Square_area(c)      # Fails (c is definitely not a Square)
      +print "The area is ", c.area()
       

      -

    35. To invoke a destructor, simply do this +
    36. To invoke a destructor, simply call del on the object:
      -example.delete_Shape(c)     # Deletes a shape
      +del c    # Deletes a shape
       
      -(Note: destructors are currently not inherited. This might change later). -

    37. Static member variables are wrapped as C global variables. For example: @@ -162,52 +143,12 @@ example.cvar.Shapes_nshapes = 13 # Set a static data member

      General Comments

        -
      • This low-level interface is not the only way to handle C++ code. -Proxy classes provide a much higher-level interface. - -

        -

      • SWIG *does* know how to properly perform upcasting of objects in +
      • SWIG does know how to properly perform upcasting of objects in an inheritance hierarchy (including multiple inheritance). Therefore it is perfectly safe to pass an object of a derived class to any function involving a base class. -

        -

      • A wide variety of C++ features are not currently supported by SWIG. Here is the -short and incomplete list: - -

        -

          -
        • Overloaded methods and functions. SWIG wrappers don't know how to resolve name -conflicts so you must give an alternative name to any overloaded method name using the -%name directive like this: - -
          -
          -void foo(int a);  
          -%name(foo2) void foo(double a, double b);
          -
          -
          - -

          -

        • Overloaded operators. Not supported at all. The only workaround for this is -to write a helper function. For example: - -
          -
          -%inline %{
          -    Vector *vector_add(Vector *a, Vector *b) {
          -          ... whatever ...
          -    }
          -%}
          -
          -
          - -

          -

        • Namespaces. Not supported at all. Won't be supported until SWIG2.0 (if at all). - -

          -

        • Dave's snide remark: Like a large bottle of strong Tequilla, it's better to -use C++ in moderation. +
        • C++ Namespaces - %nspace isn't yet supported for Python.
        diff --git a/Examples/python/class/runme.py b/Examples/python/class/runme.py index f1272ae81..8f4f27eb9 100644 --- a/Examples/python/class/runme.py +++ b/Examples/python/class/runme.py @@ -38,6 +38,8 @@ for o in [c,s]: print " ", o print " area = ", o.area() print " perimeter = ", o.perimeter() +# prevent o from holding a reference to the last object looked at +o = None print "\nGuess I'll clean up now" @@ -45,7 +47,5 @@ print "\nGuess I'll clean up now" del c del s -s = 3 print example.cvar.Shape_nshapes,"shapes remain" print "Goodbye" - diff --git a/Examples/ruby/class/example.cxx b/Examples/ruby/class/example.cxx index 1e8e203dd..046304519 100644 --- a/Examples/ruby/class/example.cxx +++ b/Examples/ruby/class/example.cxx @@ -1,4 +1,4 @@ -/* File : example.c */ +/* File : example.cxx */ #include "example.h" #define M_PI 3.14159265358979323846 @@ -11,18 +11,18 @@ void Shape::move(double dx, double dy) { int Shape::nshapes = 0; -double Circle::area(void) { +double Circle::area() { return M_PI*radius*radius; } -double Circle::perimeter(void) { +double Circle::perimeter() { return 2*M_PI*radius; } -double Square::area(void) { +double Square::area() { return width*width; } -double Square::perimeter(void) { +double Square::perimeter() { return 4*width; } diff --git a/Examples/ruby/class/example.h b/Examples/ruby/class/example.h index 46d901361..0dff185b2 100644 --- a/Examples/ruby/class/example.h +++ b/Examples/ruby/class/example.h @@ -7,11 +7,11 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -19,21 +19,16 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + 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(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; - - - - - diff --git a/Examples/ruby/class/index.html b/Examples/ruby/class/index.html index 67eeac9ad..1e227342d 100644 --- a/Examples/ruby/class/index.html +++ b/Examples/ruby/class/index.html @@ -12,9 +12,7 @@

        Wrapping a simple C++ class

        -This example illustrates C++ class wrapping performed by SWIG. -C++ classes are simply transformed into Ruby classes that provide methods to -access class members. +This example illustrates wrapping a simple C++ class to give a Python class.

        The C++ Code

        @@ -32,8 +30,8 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); virtual double area() = 0; virtual double perimeter() = 0; @@ -44,7 +42,7 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; + Circle(double r) : radius(r) { } virtual double area(); virtual double perimeter(); }; @@ -53,7 +51,7 @@ class Square : public Shape { private: double width; public: - Square(double w) : width(w) { }; + Square(double w) : width(w) { } virtual double area(); virtual double perimeter(); }; @@ -122,10 +120,8 @@ print "The area is ", c.area, "\n"
    38. -

    39. When a instance of Ruby level wrapper class is garbage collected by +
    40. When a instance of Ruby level wrapper class is garbage collected by the Ruby interpreter, the corresponding C++ destructor is automatically invoked. -(Note: destructors are currently not inherited. This might change later. -Until then, use -make_default).

    41. Static member variables are wrapped as Ruby class accessor methods. @@ -144,53 +140,14 @@ Shapes.nshapes = 13 # Set a static data member
      • Ruby module of SWIG differs from other language modules in wrapping C++ -interfaces. They provides lower-level interfaces and optional higher-level +interfaces. They provide lower-level interfaces and optional higher-level interfaces know as proxy classes. Ruby module needs no such redundancy due to Ruby's sophisticated extension API. -

        -

      • SWIG *does* know how to properly perform upcasting of objects in +
      • SWIG does know how to properly perform upcasting of objects in an inheritance hierarchy except for multiple inheritance. -

        -

      • A wide variety of C++ features are not currently supported by SWIG. Here is the -short and incomplete list: - -

        -

          -
        • Overloaded methods and functions. SWIG wrappers don't know how to resolve name -conflicts so you must give an alternative name to any overloaded method name using the -%name directive like this: - -
          -
          -void foo(int a);  
          -%name(foo2) void foo(double a, double b);
          -
          -
          - -

          -

        • Overloaded operators. Not supported at all. The only workaround for this is -to write a helper function. For example: - -
          -
          -%inline %{
          -    Vector *vector_add(Vector *a, Vector *b) {
          -          ... whatever ...
          -    }
          -%}
          -
          -
          - -

          -

        • Namespaces. Not supported at all. Won't be supported until SWIG2.0 (if at all). - -
        -

        - -

      • Dave's snide remark: Like a large bottle of strong Tequilla, it's better to -use C++ in moderation. +
      • C++ Namespaces - %nspace isn't yet supported for Python.
      diff --git a/Examples/ruby/class/runme.rb b/Examples/ruby/class/runme.rb index de73bcd46..971e149d5 100644 --- a/Examples/ruby/class/runme.rb +++ b/Examples/ruby/class/runme.rb @@ -45,5 +45,9 @@ end # Notice how the Shape#area() and Shape#perimeter() functions really # invoke the appropriate virtual method on each object. +# Remove references to the object and force a garbage collection run. +c = s = o = nil +GC.start() + print "\n", Example::Shape.nshapes," shapes remain\n" print "Goodbye\n" diff --git a/Examples/tcl/class/example.cxx b/Examples/tcl/class/example.cxx index 1e8e203dd..046304519 100644 --- a/Examples/tcl/class/example.cxx +++ b/Examples/tcl/class/example.cxx @@ -1,4 +1,4 @@ -/* File : example.c */ +/* File : example.cxx */ #include "example.h" #define M_PI 3.14159265358979323846 @@ -11,18 +11,18 @@ void Shape::move(double dx, double dy) { int Shape::nshapes = 0; -double Circle::area(void) { +double Circle::area() { return M_PI*radius*radius; } -double Circle::perimeter(void) { +double Circle::perimeter() { return 2*M_PI*radius; } -double Square::area(void) { +double Square::area() { return width*width; } -double Square::perimeter(void) { +double Square::perimeter() { return 4*width; } diff --git a/Examples/tcl/class/example.h b/Examples/tcl/class/example.h index 46d901361..0dff185b2 100644 --- a/Examples/tcl/class/example.h +++ b/Examples/tcl/class/example.h @@ -7,11 +7,11 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -19,21 +19,16 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + 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(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; - - - - - diff --git a/Examples/tcl/class/example.i b/Examples/tcl/class/example.i index 23ee8a822..75700b305 100644 --- a/Examples/tcl/class/example.i +++ b/Examples/tcl/class/example.i @@ -6,6 +6,5 @@ %} /* Let's just grab the original header file here */ - %include "example.h" diff --git a/Examples/tcl/class/index.html b/Examples/tcl/class/index.html index fd8cfe502..5b09b7a9d 100644 --- a/Examples/tcl/class/index.html +++ b/Examples/tcl/class/index.html @@ -32,8 +32,8 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); virtual double area() = 0; virtual double perimeter() = 0; @@ -44,7 +44,7 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; + Circle(double r) : radius(r) { } virtual double area(); virtual double perimeter(); }; @@ -53,7 +53,7 @@ class Square : public Shape { private: double width; public: - Square(double w) : width(w) { }; + Square(double w) : width(w) { } virtual double area(); virtual double perimeter(); }; @@ -91,10 +91,10 @@ Note: when creating a C++ extension, you must run SWIG with the -c++ op SWIG performs two forms of C++ wrapping-- a low level interface and a high level widget-like interface.
      • -Click here to see a script that calls the C++ functions using the +Click here to see a script that calls the C++ functions using the low-level interface.
      • -Click here to see a the same script written with the high-level +Click here to see the same script written with the high-level interface.
      @@ -225,47 +225,15 @@ set Shapes_nshapes 13 # Set a static data member

      General Comments

        +
      • The low-level function interface is much faster than the high-level interface. In fact, all the higher level interface does is call functions in the low-level interface. -

      • SWIG *does* know how to properly perform upcasting of objects in an inheritance hierarchy (including multiple inheritance). Therefore it is perfectly safe to pass an object of a derived class to any function involving a base class. -

        -

      • A wide variety of C++ features are not currently supported by SWIG. Here is the -short and incomplete list: - -

        -

          -
        • Overloaded methods and functions. SWIG wrappers don't know how to resolve name -conflicts so you must give an alternative name to any overloaded method name using the -%name directive like this: - -
          -
          -void foo(int a);  
          -%name(foo2) void foo(double a, double b);
          -
          -
          - -

          -

        • Overloaded operators. Not supported at all. The only workaround for this is -to write a helper function. For example: - -
          -
          -%inline %{
          -    Vector *vector_add(Vector *a, Vector *b) {
          -          ... whatever ...
          -    }
          -%}
          -
          -
          - -

          -

        • Namespaces. Not supported at all. Won't be supported until SWIG2.0 (if at all). +
        • C++ Namespaces - %nspace isn't yet supported for Python.
        From d1bfd8a5175cd5cf6ea673a682780055be359477 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Sun, 23 Feb 2014 14:23:55 +0400 Subject: [PATCH 448/481] add nspace_extend test case --- .../test-suite/lua/nspace_extend_runme.lua | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Examples/test-suite/lua/nspace_extend_runme.lua diff --git a/Examples/test-suite/lua/nspace_extend_runme.lua b/Examples/test-suite/lua/nspace_extend_runme.lua new file mode 100644 index 000000000..d942b7b9d --- /dev/null +++ b/Examples/test-suite/lua/nspace_extend_runme.lua @@ -0,0 +1,39 @@ +require("import") -- the import fn +import("nspace_extend") -- import lib + +-- catch "undefined" global variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +ne = nspace_extend + +-- Inner1 + +-- Constructors +in1_clr1 = ne.Outer.Inner1.Color() +in1_clr2 = ne.Outer.Inner1.Color.create() +in1_clr3 = ne.Outer.Inner1.Color(in1_clr2) + +-- methods +in1_clr1:colorInstanceMethod(1.0) +ne.Outer.Inner1.Color.colorStaticMethod(2.0) + +-- Inner2 + +-- Constructors +in2_clr1 = ne.Outer.Inner2.Color() +in2_clr2 = ne.Outer.Inner2.Color.create() +in2_clr3 = ne.Outer.Inner2.Color(in2_clr2) + +assert(pcall(ne.Outer.Inner2.Color, in1_clr1) == false) + +-- methods +in2_clr1:colorInstanceMethod(1.0) +ne.Outer.Inner2.Color.colorStaticMethod(2.0) + +in2_clr3:colors(in1_clr1, in1_clr2, in2_clr2, in2_clr2, in2_clr3) + +assert(pcall(in2_clr3.colors, in2_clr3, + in2_clr1, in2_clr2, in1_clr2, in2_clr2, in2_clr3) == false) + From be6723df1e2fb4b54ad3df111b19d3b9f5e597ca Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Sun, 23 Feb 2014 16:30:23 +0400 Subject: [PATCH 449/481] Return MIN_OPT_LEVEL for elua --- Lib/lua/luarun.swg | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index 4aaa6eee7..547231815 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -122,6 +122,11 @@ typedef struct swig_elua_entry { #ifndef SWIG_LUA_ELUA_EMULATE #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC) + +#ifndef MIN_OPT_LEVEL +#define MIN_OPT_LEVEL 2 +#endif + #include "lrodefs.h" #include "lrotable.h" #endif From 7f40ae357016709f499ffcc0f55ff87627f56d5d Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 23 Feb 2014 15:47:42 +0000 Subject: [PATCH 450/481] C# project files update - Update project files to use Visual Studio 2005 (minimum supported .NET is now 2.0 which is what VS 2005 supports). - Add project files for arrays example (requires /unsafe) - Fix support so that the project files work straight out the box on 64 bit systems (32 bit compile is the default). - Fix support for 64 bit builds - use the x64 platform. --- Examples/csharp/arrays/example-cs.csproj | 90 +++++ Examples/csharp/arrays/example-vc.vcproj | 415 ++++++++++++++++++++ Examples/csharp/arrays/example.sln | 38 ++ Examples/csharp/callback/example-cs.csproj | 187 +++++---- Examples/csharp/callback/example-vc.vcproj | 387 +++++++++++++++--- Examples/csharp/callback/example.sln | 44 ++- Examples/csharp/class/example-cs.csproj | 193 +++++---- Examples/csharp/class/example-vc.vcproj | 383 +++++++++++++++--- Examples/csharp/class/example.sln | 44 ++- Examples/csharp/enum/example-cs.csproj | 187 +++++---- Examples/csharp/enum/example-vc.vcproj | 383 +++++++++++++++--- Examples/csharp/enum/example.sln | 44 ++- Examples/csharp/extend/example-cs.csproj | 193 +++++---- Examples/csharp/extend/example-vc.vcproj | 387 +++++++++++++++--- Examples/csharp/extend/example.sln | 44 ++- Examples/csharp/funcptr/example-cs.csproj | 181 ++++----- Examples/csharp/funcptr/example-vc.vcproj | 385 +++++++++++++++--- Examples/csharp/funcptr/example.sln | 44 ++- Examples/csharp/reference/example-cs.csproj | 187 +++++---- Examples/csharp/reference/example-vc.vcproj | 383 +++++++++++++++--- Examples/csharp/reference/example.sln | 44 ++- Examples/csharp/simple/example-cs.csproj | 175 ++++----- Examples/csharp/simple/example-vc.vcproj | 211 +++++++++- Examples/csharp/simple/example.sln | 18 +- Examples/csharp/template/example-cs.csproj | 199 +++++----- Examples/csharp/template/example-vc.vcproj | 382 +++++++++++++++--- Examples/csharp/template/example.sln | 44 ++- Examples/csharp/variables/example-cs.csproj | 187 +++++---- Examples/csharp/variables/example-vc.vcproj | 386 +++++++++++++++--- Examples/csharp/variables/example.sln | 44 ++- 30 files changed, 4327 insertions(+), 1562 deletions(-) create mode 100644 Examples/csharp/arrays/example-cs.csproj create mode 100644 Examples/csharp/arrays/example-vc.vcproj create mode 100644 Examples/csharp/arrays/example.sln diff --git a/Examples/csharp/arrays/example-cs.csproj b/Examples/csharp/arrays/example-cs.csproj new file mode 100644 index 000000000..422c76be3 --- /dev/null +++ b/Examples/csharp/arrays/example-cs.csproj @@ -0,0 +1,90 @@ + + + Local + 8.0.50727 + 2.0 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A} + Debug + x86 + + + + + runme + + + JScript + Grid + IE50 + false + Exe + runme + OnBuildSuccess + + + + + + + + + true + bin\x86\Debug\ + DEBUG;TRACE + 285212672 + full + x86 + prompt + true + + + bin\x86\Release\ + TRACE + 285212672 + true + + + x86 + prompt + true + + + true + bin\x64\Debug\ + DEBUG;TRACE + 285212672 + full + x64 + prompt + true + + + bin\x64\Release\ + TRACE + 285212672 + true + + + x64 + prompt + true + + + + Code + + + Code + + + Code + + + + + + + copy runme.exe "$(SolutionDir)runme.exe" +echo Run the example from the root directory $(SolutionDir) and ensure example.dll is also in this directory + + diff --git a/Examples/csharp/arrays/example-vc.vcproj b/Examples/csharp/arrays/example-vc.vcproj new file mode 100644 index 000000000..d3ee58ec4 --- /dev/null +++ b/Examples/csharp/arrays/example-vc.vcproj @@ -0,0 +1,415 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Examples/csharp/arrays/example.sln b/Examples/csharp/arrays/example.sln new file mode 100644 index 000000000..234bd64d3 --- /dev/null +++ b/Examples/csharp/arrays/example.sln @@ -0,0 +1,38 @@ +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "example-cs", "example-cs.csproj", "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}" + ProjectSection(ProjectDependencies) = postProject + {C2302635-D489-4678-96B4-70F5309DCBE6} = {C2302635-D489-4678-96B4-70F5309DCBE6} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example-vc", "example-vc.vcproj", "{C2302635-D489-4678-96B4-70F5309DCBE6}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.ActiveCfg = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.Build.0 = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.ActiveCfg = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.Build.0 = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.ActiveCfg = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.Build.0 = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.ActiveCfg = Release|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.Build.0 = Release|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.ActiveCfg = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.Build.0 = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.ActiveCfg = Debug|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.Build.0 = Debug|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.ActiveCfg = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.Build.0 = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.ActiveCfg = Release|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Examples/csharp/callback/example-cs.csproj b/Examples/csharp/callback/example-cs.csproj index ce5ccfd9a..14d43dcb2 100644 --- a/Examples/csharp/callback/example-cs.csproj +++ b/Examples/csharp/callback/example-cs.csproj @@ -1,99 +1,88 @@ - - - - - - - - - - - - - - - - - - - - - + + + Local + 8.0.50727 + 2.0 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A} + Debug + x86 + + + + + runme + + + JScript + Grid + IE50 + false + Exe + runme + OnBuildSuccess + + + + + + + + + true + bin\x86\Debug\ + DEBUG;TRACE + 285212672 + full + x86 + prompt + + + bin\x86\Release\ + TRACE + 285212672 + true + + + x86 + prompt + + + true + bin\x64\Debug\ + DEBUG;TRACE + 285212672 + full + x64 + prompt + + + bin\x64\Release\ + TRACE + 285212672 + true + + + x64 + prompt + + + + + + Code + + + Code + + + Code + + + + + + + copy runme.exe "$(SolutionDir)runme.exe" +echo Run the example from the root directory $(SolutionDir) and ensure example.dll is also in this directory + + diff --git a/Examples/csharp/callback/example-vc.vcproj b/Examples/csharp/callback/example-vc.vcproj index 5788bc9c7..5958945e9 100644 --- a/Examples/csharp/callback/example-vc.vcproj +++ b/Examples/csharp/callback/example-vc.vcproj @@ -1,110 +1,345 @@ + Keyword="Win32Proj" + > + Name="Win32" + /> + + + + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + + + + + + Detect64BitPortabilityProblems="true" + DebugInformationFormat="4" + /> + Name="VCManagedResourceCompilerTool" + /> + + + ImportLibrary="$(OutDir)\example.lib" + TargetMachine="1" + /> + Name="VCALinkTool" + /> + Name="VCManifestTool" + /> + Name="VCXDCMakeTool" + /> + Name="VCBscMakeTool" + /> + Name="VCFxCopTool" + /> + Name="VCAppVerifierTool" + /> + Name="VCWebDeploymentTool" + /> + Name="VCPostBuildEventTool" + Description="Copy unmanaged dll to root directory..." + CommandLine="echo on copy "$(OutDir)\example.dll" "$(SolutionDir)" @echo off " + /> + + + Name="VCPreBuildEventTool" + /> + Name="VCCustomBuildTool" + /> + + + + + + + + + + + + + + + + + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + + + + + + Detect64BitPortabilityProblems="true" + DebugInformationFormat="3" + /> + Name="VCManagedResourceCompilerTool" + /> + + + ImportLibrary="$(OutDir)\example.lib" + TargetMachine="1" + /> + Name="VCALinkTool" + /> + Name="VCManifestTool" + /> + Name="VCXDCMakeTool" + /> + Name="VCBscMakeTool" + /> + Name="VCFxCopTool" + /> + Name="VCAppVerifierTool" + /> + Name="VCWebDeploymentTool" + /> + Name="VCPostBuildEventTool" + Description="Copy unmanaged dll to root directory..." + CommandLine="echo on copy "$(OutDir)\example.dll" "$(SolutionDir)" @echo off " + /> + + + Name="VCPreBuildEventTool" + /> + Name="VCCustomBuildTool" + /> + + + + + + + + + + + + + + + + @@ -113,43 +348,69 @@ + UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}" + > + RelativePath="example.cxx" + > + RelativePath="example_wrap.cxx" + > + UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}" + > + RelativePath="example.h" + > + + + RelativePath=".\example.i" + > + Name="Debug|Win32" + > + CommandLine="echo Invoking SWIG... echo on ..\..\..\swig.exe -c++ -csharp "$(InputPath)" @echo off " + Outputs="$(InputName)_wrap.cxx" + /> + Name="Debug|x64" + > + CommandLine="echo Invoking SWIG... echo on ..\..\..\swig.exe -c++ -csharp "$(InputPath)" @echo off " + Outputs="$(InputName)_wrap.cxx" + /> + + + + + + diff --git a/Examples/csharp/callback/example.sln b/Examples/csharp/callback/example.sln index 88995ffd3..234bd64d3 100644 --- a/Examples/csharp/callback/example.sln +++ b/Examples/csharp/callback/example.sln @@ -1,30 +1,38 @@ -Microsoft Visual Studio Solution File, Format Version 8.00 +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "example-cs", "example-cs.csproj", "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}" ProjectSection(ProjectDependencies) = postProject {C2302635-D489-4678-96B4-70F5309DCBE6} = {C2302635-D489-4678-96B4-70F5309DCBE6} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example-vc", "example-vc.vcproj", "{C2302635-D489-4678-96B4-70F5309DCBE6}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection EndProject Global - GlobalSection(SolutionConfiguration) = preSolution - Debug = Debug - Release = Release + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 EndGlobalSection - GlobalSection(ProjectConfiguration) = postSolution - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.ActiveCfg = Debug|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.Build.0 = Debug|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.ActiveCfg = Release|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.Build.0 = Release|.NET - {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.ActiveCfg = Debug|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.Build.0 = Debug|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Release.ActiveCfg = Release|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Release.Build.0 = Release|Win32 + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.ActiveCfg = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.Build.0 = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.ActiveCfg = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.Build.0 = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.ActiveCfg = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.Build.0 = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.ActiveCfg = Release|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.Build.0 = Release|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.ActiveCfg = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.Build.0 = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.ActiveCfg = Debug|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.Build.0 = Debug|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.ActiveCfg = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.Build.0 = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.ActiveCfg = Release|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.Build.0 = Release|x64 EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - EndGlobalSection - GlobalSection(ExtensibilityAddIns) = postSolution + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE EndGlobalSection EndGlobal diff --git a/Examples/csharp/class/example-cs.csproj b/Examples/csharp/class/example-cs.csproj index 8b105d7fc..4f6d66ae1 100644 --- a/Examples/csharp/class/example-cs.csproj +++ b/Examples/csharp/class/example-cs.csproj @@ -1,104 +1,89 @@ - - - - - - - - - - - - - - - - - - - - - - + + + Local + 8.0.50727 + 2.0 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A} + Debug + x86 + + + + + runme + + + JScript + Grid + IE50 + false + Exe + runme + OnBuildSuccess + + + + + + + + + true + bin\x86\Debug\ + DEBUG;TRACE + 285212672 + full + x86 + prompt + + + bin\x86\Release\ + TRACE + 285212672 + true + + + x86 + prompt + + + true + bin\x64\Debug\ + DEBUG;TRACE + 285212672 + full + x64 + prompt + + + bin\x64\Release\ + TRACE + 285212672 + true + + + x64 + prompt + + + + + Code + + + Code + + + Code + + + + + + + + + copy runme.exe "$(SolutionDir)runme.exe" +echo Run the example from the root directory $(SolutionDir) and ensure example.dll is also in this directory + + diff --git a/Examples/csharp/class/example-vc.vcproj b/Examples/csharp/class/example-vc.vcproj index 5788bc9c7..ef870959e 100644 --- a/Examples/csharp/class/example-vc.vcproj +++ b/Examples/csharp/class/example-vc.vcproj @@ -1,110 +1,345 @@ + Keyword="Win32Proj" + > + Name="Win32" + /> + + + + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + + + + + + Detect64BitPortabilityProblems="true" + DebugInformationFormat="4" + /> + Name="VCManagedResourceCompilerTool" + /> + + + ImportLibrary="$(OutDir)\example.lib" + TargetMachine="1" + /> + Name="VCALinkTool" + /> + Name="VCManifestTool" + /> + Name="VCXDCMakeTool" + /> + Name="VCBscMakeTool" + /> + Name="VCFxCopTool" + /> + Name="VCAppVerifierTool" + /> + Name="VCWebDeploymentTool" + /> + Name="VCPostBuildEventTool" + Description="Copy unmanaged dll to root directory..." + CommandLine="echo on copy "$(OutDir)\example.dll" "$(SolutionDir)" @echo off " + /> + + + Name="VCPreBuildEventTool" + /> + Name="VCCustomBuildTool" + /> + + + + + + + + + + + + + + + + + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + + + + + + Detect64BitPortabilityProblems="true" + DebugInformationFormat="3" + /> + Name="VCManagedResourceCompilerTool" + /> + + + ImportLibrary="$(OutDir)\example.lib" + TargetMachine="1" + /> + Name="VCALinkTool" + /> + Name="VCManifestTool" + /> + Name="VCXDCMakeTool" + /> + Name="VCBscMakeTool" + /> + Name="VCFxCopTool" + /> + Name="VCAppVerifierTool" + /> + Name="VCWebDeploymentTool" + /> + Name="VCPostBuildEventTool" + Description="Copy unmanaged dll to root directory..." + CommandLine="echo on copy "$(OutDir)\example.dll" "$(SolutionDir)" @echo off " + /> + + + Name="VCPreBuildEventTool" + /> + Name="VCCustomBuildTool" + /> + + + + + + + + + + + + + + + + @@ -113,43 +348,65 @@ + UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}" + > + RelativePath="example.cxx" + > + RelativePath="example_wrap.cxx" + > + UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}" + > + RelativePath="example.h" + > + RelativePath=".\example.i" + > + Name="Debug|Win32" + > + CommandLine="echo Invoking SWIG... echo on ..\..\..\swig.exe -c++ -csharp "$(InputPath)" @echo off " + Outputs="$(InputName)_wrap.cxx" + /> + Name="Debug|x64" + > + CommandLine="echo Invoking SWIG... echo on ..\..\..\swig.exe -c++ -csharp "$(InputPath)" @echo off " + Outputs="$(InputName)_wrap.cxx" + /> + + + + + + diff --git a/Examples/csharp/class/example.sln b/Examples/csharp/class/example.sln index 88995ffd3..234bd64d3 100644 --- a/Examples/csharp/class/example.sln +++ b/Examples/csharp/class/example.sln @@ -1,30 +1,38 @@ -Microsoft Visual Studio Solution File, Format Version 8.00 +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "example-cs", "example-cs.csproj", "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}" ProjectSection(ProjectDependencies) = postProject {C2302635-D489-4678-96B4-70F5309DCBE6} = {C2302635-D489-4678-96B4-70F5309DCBE6} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example-vc", "example-vc.vcproj", "{C2302635-D489-4678-96B4-70F5309DCBE6}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection EndProject Global - GlobalSection(SolutionConfiguration) = preSolution - Debug = Debug - Release = Release + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 EndGlobalSection - GlobalSection(ProjectConfiguration) = postSolution - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.ActiveCfg = Debug|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.Build.0 = Debug|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.ActiveCfg = Release|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.Build.0 = Release|.NET - {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.ActiveCfg = Debug|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.Build.0 = Debug|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Release.ActiveCfg = Release|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Release.Build.0 = Release|Win32 + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.ActiveCfg = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.Build.0 = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.ActiveCfg = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.Build.0 = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.ActiveCfg = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.Build.0 = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.ActiveCfg = Release|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.Build.0 = Release|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.ActiveCfg = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.Build.0 = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.ActiveCfg = Debug|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.Build.0 = Debug|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.ActiveCfg = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.Build.0 = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.ActiveCfg = Release|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.Build.0 = Release|x64 EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - EndGlobalSection - GlobalSection(ExtensibilityAddIns) = postSolution + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE EndGlobalSection EndGlobal diff --git a/Examples/csharp/enum/example-cs.csproj b/Examples/csharp/enum/example-cs.csproj index 44face8ed..5c8bd3cc4 100644 --- a/Examples/csharp/enum/example-cs.csproj +++ b/Examples/csharp/enum/example-cs.csproj @@ -1,99 +1,88 @@ - - - - - - - - - - - - - - - - - - - - - + + + Local + 8.0.50727 + 2.0 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A} + Debug + x86 + + + + + runme + + + JScript + Grid + IE50 + false + Exe + runme + OnBuildSuccess + + + + + + + + + true + bin\x86\Debug\ + DEBUG;TRACE + 285212672 + full + x86 + prompt + + + bin\x86\Release\ + TRACE + 285212672 + true + + + x86 + prompt + + + true + bin\x64\Debug\ + DEBUG;TRACE + 285212672 + full + x64 + prompt + + + bin\x64\Release\ + TRACE + 285212672 + true + + + x64 + prompt + + + + + Code + + + Code + + + + Code + + + + + + + copy runme.exe "$(SolutionDir)runme.exe" +echo Run the example from the root directory $(SolutionDir) and ensure example.dll is also in this directory + + diff --git a/Examples/csharp/enum/example-vc.vcproj b/Examples/csharp/enum/example-vc.vcproj index 5788bc9c7..ef870959e 100644 --- a/Examples/csharp/enum/example-vc.vcproj +++ b/Examples/csharp/enum/example-vc.vcproj @@ -1,110 +1,345 @@ + Keyword="Win32Proj" + > + Name="Win32" + /> + + + + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + + + + + + Detect64BitPortabilityProblems="true" + DebugInformationFormat="4" + /> + Name="VCManagedResourceCompilerTool" + /> + + + ImportLibrary="$(OutDir)\example.lib" + TargetMachine="1" + /> + Name="VCALinkTool" + /> + Name="VCManifestTool" + /> + Name="VCXDCMakeTool" + /> + Name="VCBscMakeTool" + /> + Name="VCFxCopTool" + /> + Name="VCAppVerifierTool" + /> + Name="VCWebDeploymentTool" + /> + Name="VCPostBuildEventTool" + Description="Copy unmanaged dll to root directory..." + CommandLine="echo on copy "$(OutDir)\example.dll" "$(SolutionDir)" @echo off " + /> + + + Name="VCPreBuildEventTool" + /> + Name="VCCustomBuildTool" + /> + + + + + + + + + + + + + + + + + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + + + + + + Detect64BitPortabilityProblems="true" + DebugInformationFormat="3" + /> + Name="VCManagedResourceCompilerTool" + /> + + + ImportLibrary="$(OutDir)\example.lib" + TargetMachine="1" + /> + Name="VCALinkTool" + /> + Name="VCManifestTool" + /> + Name="VCXDCMakeTool" + /> + Name="VCBscMakeTool" + /> + Name="VCFxCopTool" + /> + Name="VCAppVerifierTool" + /> + Name="VCWebDeploymentTool" + /> + Name="VCPostBuildEventTool" + Description="Copy unmanaged dll to root directory..." + CommandLine="echo on copy "$(OutDir)\example.dll" "$(SolutionDir)" @echo off " + /> + + + Name="VCPreBuildEventTool" + /> + Name="VCCustomBuildTool" + /> + + + + + + + + + + + + + + + + @@ -113,43 +348,65 @@ + UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}" + > + RelativePath="example.cxx" + > + RelativePath="example_wrap.cxx" + > + UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}" + > + RelativePath="example.h" + > + RelativePath=".\example.i" + > + Name="Debug|Win32" + > + CommandLine="echo Invoking SWIG... echo on ..\..\..\swig.exe -c++ -csharp "$(InputPath)" @echo off " + Outputs="$(InputName)_wrap.cxx" + /> + Name="Debug|x64" + > + CommandLine="echo Invoking SWIG... echo on ..\..\..\swig.exe -c++ -csharp "$(InputPath)" @echo off " + Outputs="$(InputName)_wrap.cxx" + /> + + + + + + diff --git a/Examples/csharp/enum/example.sln b/Examples/csharp/enum/example.sln index 88995ffd3..234bd64d3 100644 --- a/Examples/csharp/enum/example.sln +++ b/Examples/csharp/enum/example.sln @@ -1,30 +1,38 @@ -Microsoft Visual Studio Solution File, Format Version 8.00 +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "example-cs", "example-cs.csproj", "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}" ProjectSection(ProjectDependencies) = postProject {C2302635-D489-4678-96B4-70F5309DCBE6} = {C2302635-D489-4678-96B4-70F5309DCBE6} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example-vc", "example-vc.vcproj", "{C2302635-D489-4678-96B4-70F5309DCBE6}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection EndProject Global - GlobalSection(SolutionConfiguration) = preSolution - Debug = Debug - Release = Release + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 EndGlobalSection - GlobalSection(ProjectConfiguration) = postSolution - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.ActiveCfg = Debug|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.Build.0 = Debug|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.ActiveCfg = Release|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.Build.0 = Release|.NET - {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.ActiveCfg = Debug|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.Build.0 = Debug|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Release.ActiveCfg = Release|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Release.Build.0 = Release|Win32 + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.ActiveCfg = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.Build.0 = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.ActiveCfg = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.Build.0 = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.ActiveCfg = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.Build.0 = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.ActiveCfg = Release|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.Build.0 = Release|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.ActiveCfg = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.Build.0 = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.ActiveCfg = Debug|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.Build.0 = Debug|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.ActiveCfg = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.Build.0 = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.ActiveCfg = Release|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.Build.0 = Release|x64 EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - EndGlobalSection - GlobalSection(ExtensibilityAddIns) = postSolution + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE EndGlobalSection EndGlobal diff --git a/Examples/csharp/extend/example-cs.csproj b/Examples/csharp/extend/example-cs.csproj index 95923991b..68d202c58 100644 --- a/Examples/csharp/extend/example-cs.csproj +++ b/Examples/csharp/extend/example-cs.csproj @@ -1,104 +1,89 @@ - - - - - - - - - - - - - - - - - - - - - - + + + Local + 8.0.50727 + 2.0 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A} + Debug + x86 + + + + + runme + + + JScript + Grid + IE50 + false + Exe + runme + OnBuildSuccess + + + + + + + + + true + bin\x86\Debug\ + DEBUG;TRACE + 285212672 + full + x86 + prompt + + + bin\x86\Release\ + TRACE + 285212672 + true + + + x86 + prompt + + + true + bin\x64\Debug\ + DEBUG;TRACE + 285212672 + full + x64 + prompt + + + bin\x64\Release\ + TRACE + 285212672 + true + + + x64 + prompt + + + + + + Code + + + Code + + + + Code + + + + + + + copy runme.exe "$(SolutionDir)runme.exe" +echo Run the example from the root directory $(SolutionDir) and ensure example.dll is also in this directory + + diff --git a/Examples/csharp/extend/example-vc.vcproj b/Examples/csharp/extend/example-vc.vcproj index 5788bc9c7..5958945e9 100644 --- a/Examples/csharp/extend/example-vc.vcproj +++ b/Examples/csharp/extend/example-vc.vcproj @@ -1,110 +1,345 @@ + Keyword="Win32Proj" + > + Name="Win32" + /> + + + + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + + + + + + Detect64BitPortabilityProblems="true" + DebugInformationFormat="4" + /> + Name="VCManagedResourceCompilerTool" + /> + + + ImportLibrary="$(OutDir)\example.lib" + TargetMachine="1" + /> + Name="VCALinkTool" + /> + Name="VCManifestTool" + /> + Name="VCXDCMakeTool" + /> + Name="VCBscMakeTool" + /> + Name="VCFxCopTool" + /> + Name="VCAppVerifierTool" + /> + Name="VCWebDeploymentTool" + /> + Name="VCPostBuildEventTool" + Description="Copy unmanaged dll to root directory..." + CommandLine="echo on copy "$(OutDir)\example.dll" "$(SolutionDir)" @echo off " + /> + + + Name="VCPreBuildEventTool" + /> + Name="VCCustomBuildTool" + /> + + + + + + + + + + + + + + + + + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + + + + + + Detect64BitPortabilityProblems="true" + DebugInformationFormat="3" + /> + Name="VCManagedResourceCompilerTool" + /> + + + ImportLibrary="$(OutDir)\example.lib" + TargetMachine="1" + /> + Name="VCALinkTool" + /> + Name="VCManifestTool" + /> + Name="VCXDCMakeTool" + /> + Name="VCBscMakeTool" + /> + Name="VCFxCopTool" + /> + Name="VCAppVerifierTool" + /> + Name="VCWebDeploymentTool" + /> + Name="VCPostBuildEventTool" + Description="Copy unmanaged dll to root directory..." + CommandLine="echo on copy "$(OutDir)\example.dll" "$(SolutionDir)" @echo off " + /> + + + Name="VCPreBuildEventTool" + /> + Name="VCCustomBuildTool" + /> + + + + + + + + + + + + + + + + @@ -113,43 +348,69 @@ + UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}" + > + RelativePath="example.cxx" + > + RelativePath="example_wrap.cxx" + > + UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}" + > + RelativePath="example.h" + > + + + RelativePath=".\example.i" + > + Name="Debug|Win32" + > + CommandLine="echo Invoking SWIG... echo on ..\..\..\swig.exe -c++ -csharp "$(InputPath)" @echo off " + Outputs="$(InputName)_wrap.cxx" + /> + Name="Debug|x64" + > + CommandLine="echo Invoking SWIG... echo on ..\..\..\swig.exe -c++ -csharp "$(InputPath)" @echo off " + Outputs="$(InputName)_wrap.cxx" + /> + + + + + + diff --git a/Examples/csharp/extend/example.sln b/Examples/csharp/extend/example.sln index 88995ffd3..234bd64d3 100644 --- a/Examples/csharp/extend/example.sln +++ b/Examples/csharp/extend/example.sln @@ -1,30 +1,38 @@ -Microsoft Visual Studio Solution File, Format Version 8.00 +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "example-cs", "example-cs.csproj", "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}" ProjectSection(ProjectDependencies) = postProject {C2302635-D489-4678-96B4-70F5309DCBE6} = {C2302635-D489-4678-96B4-70F5309DCBE6} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example-vc", "example-vc.vcproj", "{C2302635-D489-4678-96B4-70F5309DCBE6}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection EndProject Global - GlobalSection(SolutionConfiguration) = preSolution - Debug = Debug - Release = Release + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 EndGlobalSection - GlobalSection(ProjectConfiguration) = postSolution - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.ActiveCfg = Debug|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.Build.0 = Debug|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.ActiveCfg = Release|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.Build.0 = Release|.NET - {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.ActiveCfg = Debug|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.Build.0 = Debug|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Release.ActiveCfg = Release|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Release.Build.0 = Release|Win32 + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.ActiveCfg = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.Build.0 = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.ActiveCfg = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.Build.0 = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.ActiveCfg = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.Build.0 = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.ActiveCfg = Release|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.Build.0 = Release|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.ActiveCfg = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.Build.0 = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.ActiveCfg = Debug|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.Build.0 = Debug|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.ActiveCfg = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.Build.0 = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.ActiveCfg = Release|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.Build.0 = Release|x64 EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - EndGlobalSection - GlobalSection(ExtensibilityAddIns) = postSolution + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE EndGlobalSection EndGlobal diff --git a/Examples/csharp/funcptr/example-cs.csproj b/Examples/csharp/funcptr/example-cs.csproj index 5a107c528..d8c455927 100644 --- a/Examples/csharp/funcptr/example-cs.csproj +++ b/Examples/csharp/funcptr/example-cs.csproj @@ -1,94 +1,87 @@ - - - - - - - - - - - - - - - - - - - - + + + Local + 8.0.50727 + 2.0 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A} + Debug + x86 + + + + + runme + + + JScript + Grid + IE50 + false + Exe + runme + OnBuildSuccess + + + + + + + + + true + bin\x86\Debug\ + DEBUG;TRACE + 285212672 + full + x86 + prompt + + + bin\x86\Release\ + TRACE + 285212672 + true + + + x86 + prompt + + + true + bin\x64\Debug\ + DEBUG;TRACE + 285212672 + full + x64 + prompt + + + bin\x64\Release\ + TRACE + 285212672 + true + + + x64 + prompt + + + + Code + + + Code + + + Code + + + + + + + + copy runme.exe "$(SolutionDir)runme.exe" +echo Run the example from the root directory $(SolutionDir) and ensure example.dll is also in this directory + + diff --git a/Examples/csharp/funcptr/example-vc.vcproj b/Examples/csharp/funcptr/example-vc.vcproj index 7ba8cbde1..d3ee58ec4 100644 --- a/Examples/csharp/funcptr/example-vc.vcproj +++ b/Examples/csharp/funcptr/example-vc.vcproj @@ -1,110 +1,345 @@ + Keyword="Win32Proj" + > + Name="Win32" + /> + + + + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + + + + + + Detect64BitPortabilityProblems="true" + DebugInformationFormat="4" + /> + Name="VCManagedResourceCompilerTool" + /> + + + ImportLibrary="$(OutDir)\example.lib" + TargetMachine="1" + /> + Name="VCALinkTool" + /> + Name="VCManifestTool" + /> + Name="VCXDCMakeTool" + /> + Name="VCBscMakeTool" + /> + Name="VCFxCopTool" + /> + Name="VCAppVerifierTool" + /> + Name="VCWebDeploymentTool" + /> + Name="VCPostBuildEventTool" + Description="Copy unmanaged dll to root directory..." + CommandLine="echo on copy "$(OutDir)\example.dll" "$(SolutionDir)" @echo off " + /> + + + Name="VCPreBuildEventTool" + /> + Name="VCCustomBuildTool" + /> + + + + + + + + + + + + + + + + + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + + + + + + Detect64BitPortabilityProblems="true" + DebugInformationFormat="3" + /> + Name="VCManagedResourceCompilerTool" + /> + + + ImportLibrary="$(OutDir)\example.lib" + TargetMachine="1" + /> + Name="VCALinkTool" + /> + Name="VCManifestTool" + /> + Name="VCXDCMakeTool" + /> + Name="VCBscMakeTool" + /> + Name="VCFxCopTool" + /> + Name="VCAppVerifierTool" + /> + Name="VCWebDeploymentTool" + /> + Name="VCPostBuildEventTool" + Description="Copy unmanaged dll to root directory..." + CommandLine="echo on copy "$(OutDir)\example.dll" "$(SolutionDir)" @echo off " + /> + + + Name="VCPreBuildEventTool" + /> + Name="VCCustomBuildTool" + /> + + + + + + + + + + + + + + + + @@ -113,45 +348,65 @@ + UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}" + > + RelativePath="example.c" + > + RelativePath="example_wrap.c" + > + UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}" + > + RelativePath="example.h" + > + RelativePath=".\example.i" + > + Name="Debug|Win32" + > + CommandLine="echo Invoking SWIG... echo on ..\..\..\swig.exe -csharp "$(InputPath)" @echo off " + Outputs="$(InputName)_wrap.c" + /> + Name="Debug|x64" + > + CommandLine="echo Invoking SWIG... echo on ..\..\..\swig.exe -csharp "$(InputPath)" @echo off " + Outputs="$(InputName)_wrap.c" + /> + + + + + + diff --git a/Examples/csharp/funcptr/example.sln b/Examples/csharp/funcptr/example.sln index 88995ffd3..234bd64d3 100644 --- a/Examples/csharp/funcptr/example.sln +++ b/Examples/csharp/funcptr/example.sln @@ -1,30 +1,38 @@ -Microsoft Visual Studio Solution File, Format Version 8.00 +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "example-cs", "example-cs.csproj", "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}" ProjectSection(ProjectDependencies) = postProject {C2302635-D489-4678-96B4-70F5309DCBE6} = {C2302635-D489-4678-96B4-70F5309DCBE6} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example-vc", "example-vc.vcproj", "{C2302635-D489-4678-96B4-70F5309DCBE6}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection EndProject Global - GlobalSection(SolutionConfiguration) = preSolution - Debug = Debug - Release = Release + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 EndGlobalSection - GlobalSection(ProjectConfiguration) = postSolution - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.ActiveCfg = Debug|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.Build.0 = Debug|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.ActiveCfg = Release|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.Build.0 = Release|.NET - {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.ActiveCfg = Debug|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.Build.0 = Debug|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Release.ActiveCfg = Release|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Release.Build.0 = Release|Win32 + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.ActiveCfg = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.Build.0 = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.ActiveCfg = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.Build.0 = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.ActiveCfg = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.Build.0 = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.ActiveCfg = Release|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.Build.0 = Release|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.ActiveCfg = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.Build.0 = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.ActiveCfg = Debug|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.Build.0 = Debug|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.ActiveCfg = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.Build.0 = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.ActiveCfg = Release|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.Build.0 = Release|x64 EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - EndGlobalSection - GlobalSection(ExtensibilityAddIns) = postSolution + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE EndGlobalSection EndGlobal diff --git a/Examples/csharp/reference/example-cs.csproj b/Examples/csharp/reference/example-cs.csproj index a3efbe036..c8ad31839 100644 --- a/Examples/csharp/reference/example-cs.csproj +++ b/Examples/csharp/reference/example-cs.csproj @@ -1,99 +1,88 @@ - - - - - - - - - - - - - - - - - - - - - + + + Local + 8.0.50727 + 2.0 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A} + Debug + x86 + + + + + runme + + + JScript + Grid + IE50 + false + Exe + runme + OnBuildSuccess + + + + + + + + + true + bin\x86\Debug\ + DEBUG;TRACE + 285212672 + full + x86 + prompt + + + bin\x86\Release\ + TRACE + 285212672 + true + + + x86 + prompt + + + true + bin\x64\Debug\ + DEBUG;TRACE + 285212672 + full + x64 + prompt + + + bin\x64\Release\ + TRACE + 285212672 + true + + + x64 + prompt + + + + Code + + + Code + + + Code + + + + + + + + + copy runme.exe "$(SolutionDir)runme.exe" +echo Run the example from the root directory $(SolutionDir) and ensure example.dll is also in this directory + + diff --git a/Examples/csharp/reference/example-vc.vcproj b/Examples/csharp/reference/example-vc.vcproj index 5788bc9c7..ef870959e 100644 --- a/Examples/csharp/reference/example-vc.vcproj +++ b/Examples/csharp/reference/example-vc.vcproj @@ -1,110 +1,345 @@ + Keyword="Win32Proj" + > + Name="Win32" + /> + + + + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + + + + + + Detect64BitPortabilityProblems="true" + DebugInformationFormat="4" + /> + Name="VCManagedResourceCompilerTool" + /> + + + ImportLibrary="$(OutDir)\example.lib" + TargetMachine="1" + /> + Name="VCALinkTool" + /> + Name="VCManifestTool" + /> + Name="VCXDCMakeTool" + /> + Name="VCBscMakeTool" + /> + Name="VCFxCopTool" + /> + Name="VCAppVerifierTool" + /> + Name="VCWebDeploymentTool" + /> + Name="VCPostBuildEventTool" + Description="Copy unmanaged dll to root directory..." + CommandLine="echo on copy "$(OutDir)\example.dll" "$(SolutionDir)" @echo off " + /> + + + Name="VCPreBuildEventTool" + /> + Name="VCCustomBuildTool" + /> + + + + + + + + + + + + + + + + + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + + + + + + Detect64BitPortabilityProblems="true" + DebugInformationFormat="3" + /> + Name="VCManagedResourceCompilerTool" + /> + + + ImportLibrary="$(OutDir)\example.lib" + TargetMachine="1" + /> + Name="VCALinkTool" + /> + Name="VCManifestTool" + /> + Name="VCXDCMakeTool" + /> + Name="VCBscMakeTool" + /> + Name="VCFxCopTool" + /> + Name="VCAppVerifierTool" + /> + Name="VCWebDeploymentTool" + /> + Name="VCPostBuildEventTool" + Description="Copy unmanaged dll to root directory..." + CommandLine="echo on copy "$(OutDir)\example.dll" "$(SolutionDir)" @echo off " + /> + + + Name="VCPreBuildEventTool" + /> + Name="VCCustomBuildTool" + /> + + + + + + + + + + + + + + + + @@ -113,43 +348,65 @@ + UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}" + > + RelativePath="example.cxx" + > + RelativePath="example_wrap.cxx" + > + UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}" + > + RelativePath="example.h" + > + RelativePath=".\example.i" + > + Name="Debug|Win32" + > + CommandLine="echo Invoking SWIG... echo on ..\..\..\swig.exe -c++ -csharp "$(InputPath)" @echo off " + Outputs="$(InputName)_wrap.cxx" + /> + Name="Debug|x64" + > + CommandLine="echo Invoking SWIG... echo on ..\..\..\swig.exe -c++ -csharp "$(InputPath)" @echo off " + Outputs="$(InputName)_wrap.cxx" + /> + + + + + + diff --git a/Examples/csharp/reference/example.sln b/Examples/csharp/reference/example.sln index 88995ffd3..234bd64d3 100644 --- a/Examples/csharp/reference/example.sln +++ b/Examples/csharp/reference/example.sln @@ -1,30 +1,38 @@ -Microsoft Visual Studio Solution File, Format Version 8.00 +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "example-cs", "example-cs.csproj", "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}" ProjectSection(ProjectDependencies) = postProject {C2302635-D489-4678-96B4-70F5309DCBE6} = {C2302635-D489-4678-96B4-70F5309DCBE6} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example-vc", "example-vc.vcproj", "{C2302635-D489-4678-96B4-70F5309DCBE6}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection EndProject Global - GlobalSection(SolutionConfiguration) = preSolution - Debug = Debug - Release = Release + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 EndGlobalSection - GlobalSection(ProjectConfiguration) = postSolution - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.ActiveCfg = Debug|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.Build.0 = Debug|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.ActiveCfg = Release|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.Build.0 = Release|.NET - {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.ActiveCfg = Debug|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.Build.0 = Debug|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Release.ActiveCfg = Release|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Release.Build.0 = Release|Win32 + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.ActiveCfg = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.Build.0 = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.ActiveCfg = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.Build.0 = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.ActiveCfg = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.Build.0 = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.ActiveCfg = Release|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.Build.0 = Release|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.ActiveCfg = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.Build.0 = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.ActiveCfg = Debug|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.Build.0 = Debug|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.ActiveCfg = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.Build.0 = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.ActiveCfg = Release|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.Build.0 = Release|x64 EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - EndGlobalSection - GlobalSection(ExtensibilityAddIns) = postSolution + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE EndGlobalSection EndGlobal diff --git a/Examples/csharp/simple/example-cs.csproj b/Examples/csharp/simple/example-cs.csproj index 3d91f9a47..6138dd0ec 100644 --- a/Examples/csharp/simple/example-cs.csproj +++ b/Examples/csharp/simple/example-cs.csproj @@ -1,89 +1,86 @@ - - - - - - - - - - - - - - - - - - - + + + Local + 8.0.50727 + 2.0 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A} + Debug + x86 + + + + + runme + + + JScript + Grid + IE50 + false + Exe + runme + OnBuildSuccess + + + + + + + + + true + bin\x86\Debug\ + DEBUG;TRACE + 285212672 + full + x86 + prompt + + + bin\x86\Release\ + TRACE + 285212672 + true + + + x86 + prompt + + + true + bin\x64\Debug\ + DEBUG;TRACE + 285212672 + full + x64 + prompt + + + bin\x64\Release\ + TRACE + 285212672 + true + + + x64 + prompt + + + + Code + + + Code + + + Code + + + + + + + copy runme.exe "$(SolutionDir)runme.exe" +echo Run the example from the root directory $(SolutionDir) and ensure example.dll is also in this directory + + diff --git a/Examples/csharp/simple/example-vc.vcproj b/Examples/csharp/simple/example-vc.vcproj index ec289c6eb..74b504671 100644 --- a/Examples/csharp/simple/example-vc.vcproj +++ b/Examples/csharp/simple/example-vc.vcproj @@ -10,14 +10,17 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -180,11 +351,11 @@ UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}" > @@ -206,6 +377,15 @@ Outputs="$(InputName)_wrap.c" /> + + + @@ -215,6 +395,15 @@ Outputs="$(InputName)_wrap.c" /> + + + diff --git a/Examples/csharp/simple/example.sln b/Examples/csharp/simple/example.sln index 3ebbba5c6..234bd64d3 100644 --- a/Examples/csharp/simple/example.sln +++ b/Examples/csharp/simple/example.sln @@ -1,5 +1,5 @@ Microsoft Visual Studio Solution File, Format Version 9.00 -# Visual C++ Express 2005 +# Visual Studio 2005 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "example-cs", "example-cs.csproj", "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}" ProjectSection(ProjectDependencies) = postProject {C2302635-D489-4678-96B4-70F5309DCBE6} = {C2302635-D489-4678-96B4-70F5309DCBE6} @@ -10,15 +10,27 @@ EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 Release|Win32 = Release|Win32 + Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.ActiveCfg = Debug|Any CPU - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.ActiveCfg = Release|Any CPU + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.ActiveCfg = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.Build.0 = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.ActiveCfg = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.Build.0 = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.ActiveCfg = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.Build.0 = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.ActiveCfg = Release|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.Build.0 = Release|x64 {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.ActiveCfg = Debug|Win32 {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.Build.0 = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.ActiveCfg = Debug|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.Build.0 = Debug|x64 {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.ActiveCfg = Release|Win32 {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.Build.0 = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.ActiveCfg = Release|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Examples/csharp/template/example-cs.csproj b/Examples/csharp/template/example-cs.csproj index bf17c141f..782aeacae 100644 --- a/Examples/csharp/template/example-cs.csproj +++ b/Examples/csharp/template/example-cs.csproj @@ -1,109 +1,90 @@ - - - - - - - - - - - - - - - - - - - - - - - + + + Local + 8.0.50727 + 2.0 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A} + Debug + x86 + + + + + runme + + + JScript + Grid + IE50 + false + Exe + runme + OnBuildSuccess + + + + + + + + + true + bin\x86\Debug\ + DEBUG;TRACE + 285212672 + full + x86 + prompt + + + bin\x86\Release\ + TRACE + 285212672 + true + + + x86 + prompt + + + true + bin\x64\Debug\ + DEBUG;TRACE + 285212672 + full + x64 + prompt + + + bin\x64\Release\ + TRACE + 285212672 + true + + + x64 + prompt + + + + Code + + + Code + + + Code + + + + + + + + + + + copy runme.exe "$(SolutionDir)runme.exe" +echo Run the example from the root directory $(SolutionDir) and ensure example.dll is also in this directory + + diff --git a/Examples/csharp/template/example-vc.vcproj b/Examples/csharp/template/example-vc.vcproj index f7bbbcb62..f8a900096 100644 --- a/Examples/csharp/template/example-vc.vcproj +++ b/Examples/csharp/template/example-vc.vcproj @@ -1,110 +1,345 @@ + Keyword="Win32Proj" + > + Name="Win32" + /> + + + + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + + + + + + Detect64BitPortabilityProblems="true" + DebugInformationFormat="4" + /> + Name="VCManagedResourceCompilerTool" + /> + + + ImportLibrary="$(OutDir)\example.lib" + TargetMachine="1" + /> + Name="VCALinkTool" + /> + Name="VCManifestTool" + /> + Name="VCXDCMakeTool" + /> + Name="VCBscMakeTool" + /> + Name="VCFxCopTool" + /> + Name="VCAppVerifierTool" + /> + Name="VCWebDeploymentTool" + /> + Name="VCPostBuildEventTool" + Description="Copy unmanaged dll to root directory..." + CommandLine="echo on copy "$(OutDir)\example.dll" "$(SolutionDir)" @echo off " + /> + + + Name="VCPreBuildEventTool" + /> + Name="VCCustomBuildTool" + /> + + + + + + + + + + + + + + + + + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + + + + + + Detect64BitPortabilityProblems="true" + DebugInformationFormat="3" + /> + Name="VCManagedResourceCompilerTool" + /> + + + ImportLibrary="$(OutDir)\example.lib" + TargetMachine="1" + /> + Name="VCALinkTool" + /> + Name="VCManifestTool" + /> + Name="VCXDCMakeTool" + /> + Name="VCBscMakeTool" + /> + Name="VCFxCopTool" + /> + Name="VCAppVerifierTool" + /> + Name="VCWebDeploymentTool" + /> + Name="VCPostBuildEventTool" + Description="Copy unmanaged dll to root directory..." + CommandLine="echo on copy "$(OutDir)\example.dll" "$(SolutionDir)" @echo off " + /> + + + Name="VCPreBuildEventTool" + /> + Name="VCCustomBuildTool" + /> + + + + + + + + + + + + + + + + @@ -113,42 +348,61 @@ + UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}" + > + RelativePath="example_wrap.cxx" + > + UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}" + > + RelativePath="example.h" + > + RelativePath=".\example.i" + > + Name="Debug|Win32" + > + CommandLine="echo Invoking SWIG... echo on ..\..\..\swig.exe -c++ -csharp "$(InputPath)" @echo off " + Outputs="$(InputName)_wrap.cxx" + /> + Name="Debug|x64" + > + CommandLine="echo Invoking SWIG... echo on ..\..\..\swig.exe -c++ -csharp "$(InputPath)" @echo off " + Outputs="$(InputName)_wrap.cxx" + /> + + + + + + diff --git a/Examples/csharp/template/example.sln b/Examples/csharp/template/example.sln index 88995ffd3..234bd64d3 100644 --- a/Examples/csharp/template/example.sln +++ b/Examples/csharp/template/example.sln @@ -1,30 +1,38 @@ -Microsoft Visual Studio Solution File, Format Version 8.00 +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "example-cs", "example-cs.csproj", "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}" ProjectSection(ProjectDependencies) = postProject {C2302635-D489-4678-96B4-70F5309DCBE6} = {C2302635-D489-4678-96B4-70F5309DCBE6} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example-vc", "example-vc.vcproj", "{C2302635-D489-4678-96B4-70F5309DCBE6}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection EndProject Global - GlobalSection(SolutionConfiguration) = preSolution - Debug = Debug - Release = Release + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 EndGlobalSection - GlobalSection(ProjectConfiguration) = postSolution - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.ActiveCfg = Debug|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.Build.0 = Debug|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.ActiveCfg = Release|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.Build.0 = Release|.NET - {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.ActiveCfg = Debug|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.Build.0 = Debug|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Release.ActiveCfg = Release|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Release.Build.0 = Release|Win32 + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.ActiveCfg = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.Build.0 = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.ActiveCfg = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.Build.0 = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.ActiveCfg = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.Build.0 = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.ActiveCfg = Release|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.Build.0 = Release|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.ActiveCfg = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.Build.0 = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.ActiveCfg = Debug|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.Build.0 = Debug|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.ActiveCfg = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.Build.0 = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.ActiveCfg = Release|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.Build.0 = Release|x64 EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - EndGlobalSection - GlobalSection(ExtensibilityAddIns) = postSolution + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE EndGlobalSection EndGlobal diff --git a/Examples/csharp/variables/example-cs.csproj b/Examples/csharp/variables/example-cs.csproj index a73c879fb..d2ce17a6a 100644 --- a/Examples/csharp/variables/example-cs.csproj +++ b/Examples/csharp/variables/example-cs.csproj @@ -1,99 +1,88 @@ - - - - - - - - - - - - - - - - - - - - - + + + Local + 8.0.50727 + 2.0 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A} + Debug + x86 + + + + + runme + + + JScript + Grid + IE50 + false + Exe + runme + OnBuildSuccess + + + + + + + + + true + bin\x86\Debug\ + DEBUG;TRACE + 285212672 + full + x86 + prompt + + + bin\x86\Release\ + TRACE + 285212672 + true + + + x86 + prompt + + + true + bin\x64\Debug\ + DEBUG;TRACE + 285212672 + full + x64 + prompt + + + bin\x64\Release\ + TRACE + 285212672 + true + + + x64 + prompt + + + + Code + + + Code + + + Code + + + + + + + + + copy runme.exe "$(SolutionDir)runme.exe" +echo Run the example from the root directory $(SolutionDir) and ensure example.dll is also in this directory + + diff --git a/Examples/csharp/variables/example-vc.vcproj b/Examples/csharp/variables/example-vc.vcproj index acd55a379..d3ee58ec4 100644 --- a/Examples/csharp/variables/example-vc.vcproj +++ b/Examples/csharp/variables/example-vc.vcproj @@ -1,110 +1,345 @@ + Keyword="Win32Proj" + > + Name="Win32" + /> + + + + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + + + + + + Detect64BitPortabilityProblems="true" + DebugInformationFormat="4" + /> + Name="VCManagedResourceCompilerTool" + /> + + + ImportLibrary="$(OutDir)\example.lib" + TargetMachine="1" + /> + Name="VCALinkTool" + /> + Name="VCManifestTool" + /> + Name="VCXDCMakeTool" + /> + Name="VCBscMakeTool" + /> + Name="VCFxCopTool" + /> + Name="VCAppVerifierTool" + /> + Name="VCWebDeploymentTool" + /> + Name="VCPostBuildEventTool" + Description="Copy unmanaged dll to root directory..." + CommandLine="echo on copy "$(OutDir)\example.dll" "$(SolutionDir)" @echo off " + /> + + + Name="VCPreBuildEventTool" + /> + Name="VCCustomBuildTool" + /> + + + + + + + + + + + + + + + + + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + + + + + + Detect64BitPortabilityProblems="true" + DebugInformationFormat="3" + /> + Name="VCManagedResourceCompilerTool" + /> + + + ImportLibrary="$(OutDir)\example.lib" + TargetMachine="1" + /> + Name="VCALinkTool" + /> + Name="VCManifestTool" + /> + Name="VCXDCMakeTool" + /> + Name="VCBscMakeTool" + /> + Name="VCFxCopTool" + /> + Name="VCAppVerifierTool" + /> + Name="VCWebDeploymentTool" + /> + Name="VCPostBuildEventTool" + Description="Copy unmanaged dll to root directory..." + CommandLine="echo on copy "$(OutDir)\example.dll" "$(SolutionDir)" @echo off " + /> + + + Name="VCPreBuildEventTool" + /> + Name="VCCustomBuildTool" + /> + + + + + + + + + + + + + + + + @@ -113,42 +348,65 @@ + UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}" + > + RelativePath="example.c" + > + RelativePath="example_wrap.c" + > + UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}" + > + + + RelativePath=".\example.i" + > + Name="Debug|Win32" + > + CommandLine="echo Invoking SWIG... echo on ..\..\..\swig.exe -csharp "$(InputPath)" @echo off " + Outputs="$(InputName)_wrap.c" + /> + Name="Debug|x64" + > + CommandLine="echo Invoking SWIG... echo on ..\..\..\swig.exe -csharp "$(InputPath)" @echo off " + Outputs="$(InputName)_wrap.c" + /> + + + + + + diff --git a/Examples/csharp/variables/example.sln b/Examples/csharp/variables/example.sln index 88995ffd3..234bd64d3 100644 --- a/Examples/csharp/variables/example.sln +++ b/Examples/csharp/variables/example.sln @@ -1,30 +1,38 @@ -Microsoft Visual Studio Solution File, Format Version 8.00 +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "example-cs", "example-cs.csproj", "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}" ProjectSection(ProjectDependencies) = postProject {C2302635-D489-4678-96B4-70F5309DCBE6} = {C2302635-D489-4678-96B4-70F5309DCBE6} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example-vc", "example-vc.vcproj", "{C2302635-D489-4678-96B4-70F5309DCBE6}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection EndProject Global - GlobalSection(SolutionConfiguration) = preSolution - Debug = Debug - Release = Release + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 EndGlobalSection - GlobalSection(ProjectConfiguration) = postSolution - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.ActiveCfg = Debug|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.Build.0 = Debug|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.ActiveCfg = Release|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.Build.0 = Release|.NET - {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.ActiveCfg = Debug|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.Build.0 = Debug|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Release.ActiveCfg = Release|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Release.Build.0 = Release|Win32 + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.ActiveCfg = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.Build.0 = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.ActiveCfg = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.Build.0 = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.ActiveCfg = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.Build.0 = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.ActiveCfg = Release|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.Build.0 = Release|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.ActiveCfg = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.Build.0 = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.ActiveCfg = Debug|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.Build.0 = Debug|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.ActiveCfg = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.Build.0 = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.ActiveCfg = Release|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.Build.0 = Release|x64 EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - EndGlobalSection - GlobalSection(ExtensibilityAddIns) = postSolution + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE EndGlobalSection EndGlobal From 0de4cf13a8aa4612ddead85b2680694fa1bf585e Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Mon, 24 Feb 2014 10:10:24 +1300 Subject: [PATCH 451/481] Further cleaning up of class examples --- Doc/Manual/Android.html | 26 +++++++-------- Examples/android/class/jni/example.cpp | 8 ++--- Examples/android/class/jni/example.h | 20 ++++++------ Examples/chicken/class/example.h | 25 ++++++--------- Examples/chicken/class/example.i | 1 - Examples/csharp/class/example.h | 25 ++++++--------- Examples/csharp/class/example.i | 1 - Examples/d/class/example.h | 18 +++++------ Examples/d/class/example.i | 1 - Examples/go/class/example.h | 25 ++++++--------- Examples/go/class/example.i | 1 - Examples/guile/class/example.h | 18 +++++------ Examples/java/class/example.i | 1 - Examples/lua/class/example.h | 25 ++++++--------- Examples/lua/class/example.i | 1 - Examples/modula3/class/example.h | 44 ++++++++++---------------- Examples/octave/class/example.h | 18 +++++------ Examples/perl5/class/example.i | 1 - Examples/php/class/example.i | 1 - Examples/pike/class/example.cxx | 32 ++++--------------- Examples/pike/class/example.h | 31 +++++++++--------- Examples/pike/class/example.i | 1 - Examples/python/class/example.i | 1 - Examples/r/class/example.h | 25 ++++++--------- Examples/r/class/example.i | 6 ++-- Examples/ruby/class/example.i | 1 - Examples/ruby/class/index.html | 4 +-- Examples/tcl/class/example.i | 1 - Examples/tcl/class/index.html | 4 +-- 29 files changed, 150 insertions(+), 216 deletions(-) diff --git a/Doc/Manual/Android.html b/Doc/Manual/Android.html index 4d1be3944..e02271169 100644 --- a/Doc/Manual/Android.html +++ b/Doc/Manual/Android.html @@ -435,11 +435,11 @@ public: } virtual ~Shape() { nshapes--; - }; + } double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -447,18 +447,18 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + 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(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); };
    42. @@ -482,19 +482,19 @@ void Shape::move(double dx, double dy) { int Shape::nshapes = 0; -double Circle::area(void) { +double Circle::area() { return M_PI*radius*radius; } -double Circle::perimeter(void) { +double Circle::perimeter() { return 2*M_PI*radius; } -double Square::area(void) { +double Square::area() { return width*width; } -double Square::perimeter(void) { +double Square::perimeter() { return 4*width; } diff --git a/Examples/android/class/jni/example.cpp b/Examples/android/class/jni/example.cpp index d59cc7c32..7686159fa 100644 --- a/Examples/android/class/jni/example.cpp +++ b/Examples/android/class/jni/example.cpp @@ -11,18 +11,18 @@ void Shape::move(double dx, double dy) { int Shape::nshapes = 0; -double Circle::area(void) { +double Circle::area() { return M_PI*radius*radius; } -double Circle::perimeter(void) { +double Circle::perimeter() { return 2*M_PI*radius; } -double Square::area(void) { +double Square::area() { return width*width; } -double Square::perimeter(void) { +double Square::perimeter() { return 4*width; } diff --git a/Examples/android/class/jni/example.h b/Examples/android/class/jni/example.h index 64b7684fa..0dff185b2 100644 --- a/Examples/android/class/jni/example.h +++ b/Examples/android/class/jni/example.h @@ -7,11 +7,11 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -19,16 +19,16 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + 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(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; diff --git a/Examples/chicken/class/example.h b/Examples/chicken/class/example.h index 210ba989f..5bad31693 100644 --- a/Examples/chicken/class/example.h +++ b/Examples/chicken/class/example.h @@ -7,11 +7,11 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; enum SomeEnum { @@ -26,21 +26,16 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + 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(void); - virtual double perimeter(void); + 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 index 75700b305..fbdf7249f 100644 --- a/Examples/chicken/class/example.i +++ b/Examples/chicken/class/example.i @@ -7,4 +7,3 @@ /* Let's just grab the original header file here */ %include "example.h" - diff --git a/Examples/csharp/class/example.h b/Examples/csharp/class/example.h index 46d901361..0dff185b2 100644 --- a/Examples/csharp/class/example.h +++ b/Examples/csharp/class/example.h @@ -7,11 +7,11 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -19,21 +19,16 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + 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(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; - - - - - diff --git a/Examples/csharp/class/example.i b/Examples/csharp/class/example.i index 75700b305..fbdf7249f 100644 --- a/Examples/csharp/class/example.i +++ b/Examples/csharp/class/example.i @@ -7,4 +7,3 @@ /* Let's just grab the original header file here */ %include "example.h" - diff --git a/Examples/d/class/example.h b/Examples/d/class/example.h index 0d4527e92..0dff185b2 100644 --- a/Examples/d/class/example.h +++ b/Examples/d/class/example.h @@ -7,11 +7,11 @@ public: } virtual ~Shape() { nshapes--; - }; + } double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -19,16 +19,16 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + 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(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; diff --git a/Examples/d/class/example.i b/Examples/d/class/example.i index 75700b305..fbdf7249f 100644 --- a/Examples/d/class/example.i +++ b/Examples/d/class/example.i @@ -7,4 +7,3 @@ /* Let's just grab the original header file here */ %include "example.h" - diff --git a/Examples/go/class/example.h b/Examples/go/class/example.h index 46d901361..0dff185b2 100644 --- a/Examples/go/class/example.h +++ b/Examples/go/class/example.h @@ -7,11 +7,11 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -19,21 +19,16 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + 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(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; - - - - - diff --git a/Examples/go/class/example.i b/Examples/go/class/example.i index 75700b305..fbdf7249f 100644 --- a/Examples/go/class/example.i +++ b/Examples/go/class/example.i @@ -7,4 +7,3 @@ /* Let's just grab the original header file here */ %include "example.h" - diff --git a/Examples/guile/class/example.h b/Examples/guile/class/example.h index 0d4527e92..0dff185b2 100644 --- a/Examples/guile/class/example.h +++ b/Examples/guile/class/example.h @@ -7,11 +7,11 @@ public: } virtual ~Shape() { nshapes--; - }; + } double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -19,16 +19,16 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + 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(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; diff --git a/Examples/java/class/example.i b/Examples/java/class/example.i index 75700b305..fbdf7249f 100644 --- a/Examples/java/class/example.i +++ b/Examples/java/class/example.i @@ -7,4 +7,3 @@ /* Let's just grab the original header file here */ %include "example.h" - diff --git a/Examples/lua/class/example.h b/Examples/lua/class/example.h index 46d901361..0dff185b2 100644 --- a/Examples/lua/class/example.h +++ b/Examples/lua/class/example.h @@ -7,11 +7,11 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -19,21 +19,16 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + 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(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; - - - - - diff --git a/Examples/lua/class/example.i b/Examples/lua/class/example.i index 75700b305..fbdf7249f 100644 --- a/Examples/lua/class/example.i +++ b/Examples/lua/class/example.i @@ -7,4 +7,3 @@ /* Let's just grab the original header file here */ %include "example.h" - diff --git a/Examples/modula3/class/example.h b/Examples/modula3/class/example.h index 9c1f47995..0dff185b2 100644 --- a/Examples/modula3/class/example.h +++ b/Examples/modula3/class/example.h @@ -1,44 +1,34 @@ /* File : example.h */ -class Shape -{ +class Shape { public: - Shape () - { + Shape() { nshapes++; } - virtual ~ Shape () - { + virtual ~Shape() { nshapes--; - }; - double x, y; - void move (double dx, double dy); - virtual double area (void) const = 0; - virtual double perimeter (void) const = 0; -protected: - static int 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 -{ +class Circle : public Shape { private: double radius; public: - Circle (double r):radius (r) - { - }; - virtual double area (void) const; - virtual double perimeter (void) const; + Circle(double r) : radius(r) { } + virtual double area(); + virtual double perimeter(); }; -class Square:public Shape -{ +class Square : public Shape { private: double width; public: - Square (double w):width (w) - { - }; - virtual double area (void) const; - virtual double perimeter (void) const; + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; diff --git a/Examples/octave/class/example.h b/Examples/octave/class/example.h index 0d4527e92..0dff185b2 100644 --- a/Examples/octave/class/example.h +++ b/Examples/octave/class/example.h @@ -7,11 +7,11 @@ public: } virtual ~Shape() { nshapes--; - }; + } double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -19,16 +19,16 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + 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(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; diff --git a/Examples/perl5/class/example.i b/Examples/perl5/class/example.i index 75700b305..fbdf7249f 100644 --- a/Examples/perl5/class/example.i +++ b/Examples/perl5/class/example.i @@ -7,4 +7,3 @@ /* Let's just grab the original header file here */ %include "example.h" - diff --git a/Examples/php/class/example.i b/Examples/php/class/example.i index 75700b305..fbdf7249f 100644 --- a/Examples/php/class/example.i +++ b/Examples/php/class/example.i @@ -7,4 +7,3 @@ /* Let's just grab the original header file here */ %include "example.h" - diff --git a/Examples/pike/class/example.cxx b/Examples/pike/class/example.cxx index c7a3194a4..046304519 100644 --- a/Examples/pike/class/example.cxx +++ b/Examples/pike/class/example.cxx @@ -1,46 +1,28 @@ -/* File : example.c */ +/* File : example.cxx */ #include "example.h" - -#include - #define M_PI 3.14159265358979323846 -// Static member initializer -int Shape::nshapes = 0; - -// Constructor -Shape::Shape() { - nshapes++; -} - -// Move the shape to a new location +/* Move the shape to a new location */ void Shape::move(double dx, double dy) { x += dx; y += dy; } -// Destructor -Shape::~Shape() { - nshapes--; -} +int Shape::nshapes = 0; -// Circle area -double Circle::area() const { +double Circle::area() { return M_PI*radius*radius; } -// Circle perimeter -double Circle::perimeter() const { +double Circle::perimeter() { return 2*M_PI*radius; } -// Square area -double Square::area() const { +double Square::area() { return width*width; } -// Square perimeter -double Square::perimeter() const { +double Square::perimeter() { return 4*width; } diff --git a/Examples/pike/class/example.h b/Examples/pike/class/example.h index f74a4fefc..0dff185b2 100644 --- a/Examples/pike/class/example.h +++ b/Examples/pike/class/example.h @@ -2,12 +2,16 @@ class Shape { public: - Shape(); - virtual ~Shape(); - double x, y; + Shape() { + nshapes++; + } + virtual ~Shape() { + nshapes--; + } + double x, y; void move(double dx, double dy); - virtual double area() const = 0; - virtual double perimeter() const = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -15,21 +19,16 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area() const; - virtual double perimeter() const; + 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() const; - virtual double perimeter() const; + 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 index 75700b305..fbdf7249f 100644 --- a/Examples/pike/class/example.i +++ b/Examples/pike/class/example.i @@ -7,4 +7,3 @@ /* Let's just grab the original header file here */ %include "example.h" - diff --git a/Examples/python/class/example.i b/Examples/python/class/example.i index 75700b305..fbdf7249f 100644 --- a/Examples/python/class/example.i +++ b/Examples/python/class/example.i @@ -7,4 +7,3 @@ /* Let's just grab the original header file here */ %include "example.h" - diff --git a/Examples/r/class/example.h b/Examples/r/class/example.h index 46d901361..0dff185b2 100644 --- a/Examples/r/class/example.h +++ b/Examples/r/class/example.h @@ -7,11 +7,11 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -19,21 +19,16 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + 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(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; - - - - - diff --git a/Examples/r/class/example.i b/Examples/r/class/example.i index 4654d269f..fbdf7249f 100644 --- a/Examples/r/class/example.i +++ b/Examples/r/class/example.i @@ -1,9 +1,9 @@ /* File : example.i */ %module example -%inline %{ +%{ #include "example.h" %} + +/* Let's just grab the original header file here */ %include "example.h" - - diff --git a/Examples/ruby/class/example.i b/Examples/ruby/class/example.i index 75700b305..fbdf7249f 100644 --- a/Examples/ruby/class/example.i +++ b/Examples/ruby/class/example.i @@ -7,4 +7,3 @@ /* Let's just grab the original header file here */ %include "example.h" - diff --git a/Examples/ruby/class/index.html b/Examples/ruby/class/index.html index 1e227342d..927c00190 100644 --- a/Examples/ruby/class/index.html +++ b/Examples/ruby/class/index.html @@ -12,7 +12,7 @@

      Wrapping a simple C++ class

      -This example illustrates wrapping a simple C++ class to give a Python class. +This example illustrates wrapping a simple C++ class to give a Ruby class.

      The C++ Code

      @@ -147,7 +147,7 @@ due to Ruby's sophisticated extension API.
    43. SWIG does know how to properly perform upcasting of objects in an inheritance hierarchy except for multiple inheritance. -
    44. C++ Namespaces - %nspace isn't yet supported for Python. +
    45. C++ Namespaces - %nspace isn't yet supported for Ruby. diff --git a/Examples/tcl/class/example.i b/Examples/tcl/class/example.i index 75700b305..fbdf7249f 100644 --- a/Examples/tcl/class/example.i +++ b/Examples/tcl/class/example.i @@ -7,4 +7,3 @@ /* Let's just grab the original header file here */ %include "example.h" - diff --git a/Examples/tcl/class/index.html b/Examples/tcl/class/index.html index 5b09b7a9d..16dbeea4f 100644 --- a/Examples/tcl/class/index.html +++ b/Examples/tcl/class/index.html @@ -229,11 +229,11 @@ set Shapes_nshapes 13 # Set a static data member
    46. The low-level function interface is much faster than the high-level interface. In fact, all the higher level interface does is call functions in the low-level interface. -
    47. SWIG *does* know how to properly perform upcasting of objects in an inheritance +
    48. SWIG does know how to properly perform upcasting of objects in an inheritance hierarchy (including multiple inheritance). Therefore it is perfectly safe to pass an object of a derived class to any function involving a base class. -
    49. C++ Namespaces - %nspace isn't yet supported for Python. +
    50. C++ Namespaces - %nspace isn't yet supported for Tcl. From 431b9b16e7f8fc36758ac88f29dd9c1a77052984 Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Mon, 24 Feb 2014 10:11:11 +1300 Subject: [PATCH 452/481] Update one dead link and remove another --- Examples/python/index.html | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Examples/python/index.html b/Examples/python/index.html index 37f4b55af..3bbdd66e8 100644 --- a/Examples/python/index.html +++ b/Examples/python/index.html @@ -56,8 +56,7 @@ Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
    51. The politically "correct" way to compile a Python extension is to follow the steps -described at www.python.org -or in the most excellent (and shamelessly plugged) Python Essential Reference: +described at www.python.org:

        From 48476af609a4667b475d4cfaf64d0edd1282956a Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Mon, 24 Feb 2014 10:13:11 +1300 Subject: [PATCH 453/481] Remove semicolons after function definitions --- Doc/Manual/Java.html | 2 +- Doc/Manual/Python.html | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/Doc/Manual/Java.html b/Doc/Manual/Java.html index c1b42f605..3144341e1 100644 --- a/Doc/Manual/Java.html +++ b/Doc/Manual/Java.html @@ -6868,7 +6868,7 @@ int spam(double a, double b, double *out1, double *out2) { *out1 = a*10.0; *out2 = b*100.0; return status; -}; +} %} /* diff --git a/Doc/Manual/Python.html b/Doc/Manual/Python.html index 4584ff726..522412fc8 100644 --- a/Doc/Manual/Python.html +++ b/Doc/Manual/Python.html @@ -4688,8 +4688,7 @@ int spam(double a, double b, double *out1, double *out2) { *out1 = result1; *out2 = result2; return status; -}; - +}

        From 4a94345c9ab9e5b9fd7545ba057ea0cf62985236 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Tue, 25 Feb 2014 12:51:28 +0400 Subject: [PATCH 454/481] Switched to Swig_name_* functions --- Source/Modules/lang.cxx | 2 + Source/Modules/lua.cxx | 108 +++++++++++++++++++++++++++++++++++----- 2 files changed, 98 insertions(+), 12 deletions(-) diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 7933d5a49..9420ea719 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -2992,6 +2992,8 @@ int Language::variableWrapper(Node *n) { if (make_set_wrapper) { Setattr(n, "varset", "1"); functionWrapper(n); + } else { + Setattr(n, "feature:immutable", "1"); } /* Restore parameters */ Setattr(n, "sym:name", symname); diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index e2bba5bea..000e79a59 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -157,6 +157,8 @@ private: enum TState { NO_CPP, VARIABLE, + GLOBAL_FUNC, + GLOBAL_VAR, MEMBER_FUNC, CONSTRUCTOR, DESTRUCTOR, @@ -464,6 +466,7 @@ public: * --------------------------------------------------------------------- */ // Helper function. Remembers wrap name + // TODO: REMOVE void rememberWrapName(Node *n, String *wrapname) { Setattr(n, "wrap:name", wrapname); // If it is getter/setter, then write wrapname under @@ -542,7 +545,7 @@ public: Wrapper_add_local(f, "SWIG_arg", "int SWIG_arg = 0"); - String *wname = symnameWrapper(iname); + String *wname = Swig_name_wrapper(iname); if (overname) { Append(wname, overname); } @@ -857,7 +860,7 @@ public: String *symname = Getattr(n, "sym:name"); String *lua_name = Getattr(n, "lua:name"); assert(lua_name); - String *wname = symnameWrapper(symname); + String *wname = Swig_name_wrapper(symname); //Printf(stdout,"Swig_overload_dispatch %s %s '%s' %d\n",symname,wname,dispatch,maxargs); @@ -914,19 +917,68 @@ public: return SWIG_OK; } + /* ------------------------------------------------------------ + * Add variable to "attributes" C arrays of given namespace or class. + * Input is node. Base on the state of "current" array it determines + * the name of getter function, setter function etc and calls + * registeVariable overload with necessary params + * Lua scope could be overwritten. (Used only for backward compatibility) + * ------------------------------------------------------------ */ + void registerVariable(Node *n, bool overwrite = false, String *overwriteLuaScope = 0) { + int assignable = is_assignable(n); + String *symname = Getattr(n, "sym:name"); + assert(symname); + + // Lua scope. It is not symbol NSpace, it is actuall key to revrieve + // getCArraysHash. + String *luaScope = luaCurrentSymbolNSpace(); + if (overwrite) + luaScope = overwriteLuaScope; + + // Getter and setter + String *getName = 0; + String *setName = 0; + String *mrename = 0; + if (current[NO_CPP] || !getCurrentClass()) { + // Global variable + getName = Swig_name_get(getNSpace(), symname); + if (assignable) + setName = Swig_name_set(getNSpace(), symname); + } else { + assert(!current[NO_CPP]); + if (current[STATIC_VAR] ) { + mrename = Swig_name_member(getNSpace(), getClassPrefix(), symname); + getName = Swig_name_get(0, mrename); + if (assignable) + setName = Swig_name_set(0, mrename); + } else if (current[MEMBER_VAR]) { + mrename = Swig_name_member(0, getClassPrefix(), symname); + getName = Swig_name_get(getNSpace(), mrename); + if (assignable) + setName = Swig_name_set(getNSpace(), mrename); + } else { + assert(false); + } + } + + getName = Swig_name_wrapper(getName); + if (setName) + setName = Swig_name_wrapper(setName); + //Printf(stdout, "luaname %s, symname %s mrename %s getName %s\n\tscope %s\n\tassignable %d\n", + // Getattr(n, "lua:name"), symname, mrename, getName, luaScope, assignable ); // TODO: REMOVE + registerVariable(luaScope, n, getName, setName); + } /* ------------------------------------------------------------ * Add variable to the "attributes" (or "get"/"set" in * case of elua_ltr) C arrays of given namespace or class * ------------------------------------------------------------ */ - void registerVariable(String *nspace_or_class_name, Node *n, const char *getAttrName, const char *setAttrName) { + void registerVariable(String *lua_nspace_or_class_name, Node *n, String *getName, String *setName) { String *unassignable = NewString("SWIG_Lua_set_immutable"); - String *getName = Getattr(n, getAttrName); - String *setName = Getattr(n, setAttrName); if (setName == 0 || GetFlag(n, "feature:immutable")) { setName = unassignable; } - Hash *nspaceHash = getCArraysHash(nspace_or_class_name); + Hash *nspaceHash = getCArraysHash(lua_nspace_or_class_name); String *s_ns_methods_tab = Getattr(nspaceHash, "methods"); String *s_ns_var_tab = Getattr(nspaceHash, "attributes"); String *lua_name = Getattr(n, "lua:name"); @@ -961,7 +1013,12 @@ public: current[VARIABLE] = true; // let SWIG generate the wrappers int result = Language::variableWrapper(n); - registerVariable(luaCurrentSymbolNSpace(), n, "varget:wrap:name", "varset:wrap:name"); + // TODO: REMOVE + //registerVariable(luaCurrentSymbolNSpace(), n, "varget:wrap:name", "varset:wrap:name"); + + // It is impossible to use registerVariable, because sym:name of the Node is currenly + // in undefined states - the callees of this function may have modified it. + // registerVariable should be used from respective callees.* current[VARIABLE] = false; return result; } @@ -1473,7 +1530,7 @@ public: // REPORT("membervariableHandler",n); current[MEMBER_VAR] = true; Language::membervariableHandler(n); - registerVariable(luaCurrentSymbolNSpace(), n, "memberget:wrap:name", "memberset:wrap:name"); + registerVariable(n); current[MEMBER_VAR] = false; return SWIG_OK; } @@ -1515,15 +1572,35 @@ public: * 2. During class parsing for functions declared/defined as friend * 3. During class parsing from staticmemberfunctionHandler * ---------------------------------------------------------------------- */ - int globalfunctionHandler(Node *n) { + virtual int globalfunctionHandler(Node *n) { bool oldVal = current[NO_CPP]; if (!current[STATIC_FUNC]) // If static funct, don't switch to NO_CPP current[NO_CPP] = true; - int result = Language::globalfunctionHandler(n); + const int result = Language::globalfunctionHandler(n); current[NO_CPP] = oldVal; return result; } + /* ---------------------------------------------------------------------- + * globalvariableHandler() + * globalfunctionHandler() + * Sets "current" array correctly and calls + * Language::globalvariableHandler() + * ---------------------------------------------------------------------- */ + virtual int globalvariableHandler(Node *n) { + bool oldVal = current[NO_CPP]; + current[GLOBAL_VAR] = true; + current[NO_CPP] = true; + + const int result = Language::globalvariableHandler(n); + registerVariable(n); + + current[GLOBAL_VAR] = false; + current[NO_CPP] = oldVal; + return result; + } + + /* ----------------------------------------------------------------------- * staticmemberfunctionHandler() * @@ -1533,7 +1610,7 @@ public: virtual int staticmemberfunctionHandler(Node *n) { REPORT("staticmemberfunctionHandler", n); current[STATIC_FUNC] = true; - int result = Language::staticmemberfunctionHandler(n); + const int result = Language::staticmemberfunctionHandler(n); current[STATIC_FUNC] = false;; if (result != SWIG_OK) @@ -1574,17 +1651,24 @@ public: current[STATIC_VAR] = true; //String *symname = Getattr(n, "sym:name"); int result = Language::staticmembervariableHandler(n); + if (!GetFlag(n, "wrappedasconstant")) { + registerVariable(n); + } if (result == SWIG_OK) { // This will add static member variable to the class namespace with name ClassName_VarName if (v2_compatibility) { Swig_save("lua_staticmembervariableHandler", n, "lua:name", NIL); String *lua_name = Getattr(n, "lua:name"); + // Although this function uses Swig_name_member, it actually generateds Lua name, + // not C++ name. It is because previous version used such scheme for static vars + // name generation and we have to maintain backward compatibility String *v2_name = Swig_name_member(NIL, proxy_class_name, lua_name); //Printf( stdout, "Name %s, class %s, compt. name %s\n", lua_name, proxy_class_name, v2_name ); // TODO: REMOVE if (!GetFlag(n, "wrappedasconstant")) { Setattr(n, "lua:name", v2_name); - registerVariable(getNSpace(), n, "varget:wrap:name", "varset:wrap:name"); + // Registering static var in the class parent nspace + registerVariable(n, true, getNSpace()); } // If static member variable was wrapped as constant, then // constant wrapper has already performed all actions From fadc9c8f313bf95e4effcc5e2cafd494d60c27ad Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Tue, 25 Feb 2014 14:11:53 +0400 Subject: [PATCH 455/481] Fixed registerMethod to work like registerVariable --- Source/Modules/lua.cxx | 136 +++++++++++++++++++---------------------- 1 file changed, 63 insertions(+), 73 deletions(-) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 000e79a59..105d1a1b4 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -465,28 +465,49 @@ public: * Create a function declaration and register it with the interpreter. * --------------------------------------------------------------------- */ - // Helper function. Remembers wrap name - // TODO: REMOVE - void rememberWrapName(Node *n, String *wrapname) { - Setattr(n, "wrap:name", wrapname); - // If it is getter/setter, then write wrapname under - // wrap:memberset/wrap:memberget accordingly - if (Getattr(n, "memberset")) - Setattr(n, "memberset:wrap:name", wrapname); - if (Getattr(n, "varset")) - Setattr(n, "varset:wrap:name", wrapname); - if (Getattr(n, "memberget")) - Setattr(n, "memberget:wrap:name", wrapname); - if (Getattr(n, "varget")) - Setattr(n, "varget:wrap:name", wrapname); + /* ----------------------------------------------------------------------- + * registerMethod() + * + * Determines wrap name of a method, it's scope etc and calls + * registerMethod overload with correct arguments + * Overloaded variant adds method to the "methods" array of specified lua scope/class + * ---------------------------------------------------------------------- */ + void registerMethod(Node *n, bool overwrite = false, String *overwriteLuaScope = 0) { + String *symname = Getattr(n, "sym:name"); + assert(symname); + + if (Getattr(n, "sym:nextSibling")) + return; + + // Lua scope. It is not symbol NSpace, it is actuall key to revrieve + // getCArraysHash. + String *luaScope = luaCurrentSymbolNSpace(); + if (overwrite) + luaScope = overwriteLuaScope; + + String *wrapname = 0; + String *mrename; + if (current[NO_CPP] || !getCurrentClass()) { + mrename = symname; + } else { + assert(!current[NO_CPP]); + if (current[STATIC_FUNC] || current[MEMBER_FUNC]) { + mrename = Swig_name_member(getNSpace(), getClassPrefix(), symname); + } else { + mrename = symname; + } + } + wrapname = Swig_name_wrapper(mrename); + //Printf(stdout, "luaname %s, symname %s mrename %s wrapname %s\n\tscope %s\n", + // Getattr(n, "lua:name"), symname, mrename, wrapname, luaScope ); // TODO: REMOVE + registerMethod(n, wrapname, luaScope); } // Add method to the "methods" C array of given namespace/class - void registerMethod(String *nspace_or_class_name, Node *n) { + void registerMethod(Node *n, String* wname, String *luaScope) { assert(n); - Hash *nspaceHash = getCArraysHash(nspace_or_class_name); + Hash *nspaceHash = getCArraysHash(luaScope); String *s_ns_methods_tab = Getattr(nspaceHash, "methods"); - String *wname = Getattr(n, "wrap:name"); String *lua_name = Getattr(n, "lua:name"); if (elua_ltr || eluac_ltr) Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", lua_name, "\")", ", LFUNCVAL(", wname, ")", "},\n", NIL); @@ -504,16 +525,6 @@ public: } } - // Helper for functionWrapper - determines whether we should - // register method in the appropriate class/namespace/module - // table or not. - // (not => it is variable wrapper or something similar) - bool functionWrapperRegisterNow() const { - if (current[VARIABLE]) - return false; - return (current[NO_CPP] || current[STATIC_FUNC]); - } - virtual int functionWrapper(Node *n) { REPORT("functionWrapper", n); @@ -726,7 +737,7 @@ public: } // Remember C name of the wrapping function - rememberWrapName(n, wname); + Setattr(n, "wrap:name", wname); /* Emit the function call */ String *actioncode = emit_action(n); @@ -814,9 +825,11 @@ public: /* Now register the function with the interpreter. */ int result = SWIG_OK; if (!Getattr(n, "sym:overloaded")) { + /* TODO: REMOVE if (functionWrapperRegisterNow()) { // emit normal fns & static fns - registerMethod(luaCurrentSymbolNSpace(), n); + registerMethod(n); } + */ } else { if (!Getattr(n, "sym:nextSibling")) { result = dispatchFunction(n); @@ -899,11 +912,12 @@ public: Wrapper_print(f, f_wrappers); // Remember C name of the wrapping function - rememberWrapName(n, wname); + Setattr(n, "wrap:name", wname); + /* TODO: REMOVE if (functionWrapperRegisterNow()) { // emit normal fns & static fns - registerMethod(luaCurrentSymbolNSpace(), n); - } + registerMethod(n); + }*/ if (current[CONSTRUCTOR]) { if (constructor_name != 0) Delete(constructor_name); @@ -970,6 +984,8 @@ public: } /* ------------------------------------------------------------ + * registerVariable() + * * Add variable to the "attributes" (or "get"/"set" in * case of elua_ltr) C arrays of given namespace or class * ------------------------------------------------------------ */ @@ -1075,7 +1091,7 @@ public: Setattr(n, "sym:name", lua_name); /* Special hook for member pointer */ if (SwigType_type(type) == T_MPOINTER) { - String *wname = symnameWrapper(iname); + String *wname = Swig_name_wrapper(iname); Printf(f_wrappers, "static %s = %s;\n", SwigType_str(type, wname), value); value = Char(wname); } @@ -1514,10 +1530,8 @@ public: current[MEMBER_FUNC] = true; Language::memberfunctionHandler(n); - if (!Getattr(n, "sym:nextSibling")) { - //Printf( stdout, "add member function: %s to %s\n", symname, luaCurrentSymbolNSpace());// TODO: REMOVE - registerMethod(luaCurrentSymbolNSpace(), n); - } + //Printf( stdout, "add member function: %s to %s\n", symname, luaCurrentSymbolNSpace());// TODO: REMOVE + registerMethod(n); current[MEMBER_FUNC] = false; return SWIG_OK; } @@ -1577,6 +1591,9 @@ public: if (!current[STATIC_FUNC]) // If static funct, don't switch to NO_CPP current[NO_CPP] = true; const int result = Language::globalfunctionHandler(n); + + if (!current[STATIC_FUNC]) // Register only if not called from static funct handler + registerMethod(n); current[NO_CPP] = oldVal; return result; } @@ -1610,23 +1627,25 @@ public: virtual int staticmemberfunctionHandler(Node *n) { REPORT("staticmemberfunctionHandler", n); current[STATIC_FUNC] = true; + const int result = Language::staticmemberfunctionHandler(n); + registerMethod(n); - current[STATIC_FUNC] = false;; - if (result != SWIG_OK) - return result; - - if (v2_compatibility) { + if (v2_compatibility && result == SWIG_OK) { Swig_require("lua_staticmemberfunctionHandler", n, "*lua:name", NIL); String *lua_name = Getattr(n, "lua:name"); + // Although this function uses Swig_name_member, it actually generateds Lua name, + // not C++ name. It is because previous version used such scheme for static func + // name generation and we have to maintain backward compatibility String *compat_name = Swig_name_member(0, proxy_class_name, lua_name); Setattr(n, "lua:name", compat_name); - registerMethod(getNSpace(), n); + registerMethod(n, true, getNSpace()); Delete(compat_name); Swig_restore(n); } - return SWIG_OK; + current[STATIC_FUNC] = false;; + return result; } /* ------------------------------------------------------------ @@ -2194,35 +2213,6 @@ public: return result; } - /* ----------------------------------------------------------------------------- - * fullyQualifiedName() - * Function creates fully qualified name of given symbol. The scope is deremined - * automatically based on luaCurrentSymbolNSpace() - * ----------------------------------------------------------------------------- */ - String *fullyQualifiedName(const_String_or_char_ptr name) { - assert(name); - String *scope = luaCurrentSymbolNSpace(); - - String *fqname = 0; - if (scope) - fqname = NewStringf("%s::%s", scope, name); - else - fqname = Copy(name); - - return fqname; - } - - /* ----------------------------------------------------------------------------- - * symnameWrapper() - * Input: symname - * Output - Swig_name_wrapper around fully qualified form of symname - * ----------------------------------------------------------------------------- */ - String *symnameWrapper(String *symname) { - String *fqname = fullyQualifiedName(symname); - String *wname = Swig_name_wrapper(fqname); - Delete(fqname); - return wname; - } }; /* NEW LANGUAGE NOTE:*********************************************** From c6dd6b0726342b32579a0b6467128804581b9f92 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Tue, 25 Feb 2014 14:36:03 +0400 Subject: [PATCH 456/481] Fixing registerClass. No more wrap: unnecessary attributes --- Source/Modules/lua.cxx | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 105d1a1b4..6c9e69050 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -1014,7 +1014,6 @@ public: /* ------------------------------------------------------------ * variableWrapper() * ------------------------------------------------------------ */ - virtual int variableWrapper(Node *n) { /* NEW LANGUAGE NOTE:*********************************************** Language::variableWrapper(n) will generate two wrapper fns @@ -1239,8 +1238,7 @@ public: * Helper function that adds record to appropriate * C arrays * ------------------------------------------------------------ */ - void registerClass(String *scope, Node *n) { - String *wrap_class = Getattr(n,"wrap:class_name"); + void registerClass(String *scope, String *wrap_class) { assert(wrap_class); Hash *nspaceHash = getCArraysHash(scope); String *ns_classes = Getattr(nspaceHash, "classes"); @@ -1354,16 +1352,15 @@ public: SwigType_add_pointer(t); // Catch all: eg. a class with only static functions and/or variables will not have 'remembered' - String *wrap_class_name = NewStringf("_wrap_class_%s", mangled_full_proxy_class_name); + String *wrap_class_name = Swig_name_wrapper(NewStringf("class_%s", mangled_full_proxy_class_name)); String *wrap_class = NewStringf("&%s", wrap_class_name); - Setattr(n, "wrap:class_name", wrap_class_name); SwigType_remember_clientdata(t, wrap_class); String *rt = Copy(getClassType()); SwigType_add_pointer(rt); // Adding class to apropriate namespace - registerClass(nspace, n); + registerClass(nspace, wrap_class_name); Hash *nspaceHash = getCArraysHash(nspace); // Register the class structure with the type checker From 3aa689d276158fc89921d98ee928cfb68465b943 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Wed, 26 Feb 2014 00:13:18 +0000 Subject: [PATCH 457/481] Add summary about nested class support added over the last few months --- CHANGES.current | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/CHANGES.current b/CHANGES.current index 50f3decd1..791665901 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -39,6 +39,29 @@ Version 3.0.0 (in progress) 2014-02-15: wsfulton [Java] Add support for the cdata library. +2014-02-08: vkalinin + Nested class support added. This primarily allows SWIG to properly parse nested + classes and keep the nested class information in the parse tree. Java and C# + have utilised this information wrapping the C++ nested classes as Java/C# + nested classes. The remaining target languages ignore nested classes as in + previous versions. Help is needed by users of these remaining languages to + design how C++ nested classes can be best wrapped. Please talk to us on the + swig-devel mailing list if you think you can help. + + Previously, there was limited nested class support. Nested classes were treated + as opaque pointers. However, the "nestedworkaround" feature provided a way to + wrap a nested class as if it was a global class. This feature no longer exists + and is replaced by the new "flatnested" feature. This effectively does the same + thing with less manual code to be written. Please see the 'Nested classes' + section in the documentation in SWIGPlus.html if you were previously using this + feature. + + SWIG now parses the contents of nested classes where previously it did not. You + may find that you will need to make adjustments to your interface file as + effectively extra code is being wrapped. + + *** POTENTIAL INCOMPATIBILITY *** + 2014-02-06: gjanssens [Guile] Patch #133. Make scm to string conversion work with non-ascii strings. Guile 2 has a completely rewritten string implementation. SWIG made some assumptions From c36800713bf3803c335af15550fdcfd21fc77224 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 27 Feb 2014 20:12:53 +0000 Subject: [PATCH 458/481] Use unix fileformat --- Examples/test-suite/lua/nspace_runme.lua | 134 +++++++++++------------ 1 file changed, 67 insertions(+), 67 deletions(-) diff --git a/Examples/test-suite/lua/nspace_runme.lua b/Examples/test-suite/lua/nspace_runme.lua index 2ed8a86b7..5d55357c0 100644 --- a/Examples/test-suite/lua/nspace_runme.lua +++ b/Examples/test-suite/lua/nspace_runme.lua @@ -1,67 +1,67 @@ -require("import") -- the import fn -import("nspace") -- import lib - --- catch "undefined" global variables -local env = _ENV -- Lua 5.2 -if not env then env = getfenv () end -- Lua 5.1 -setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) - -ns = nspace - --- Inheritance -blue1 = ns.Outer.Inner3.Blue() - --- blue1:blueInstanceMethod() -blue1:colorInstanceMethod(60.0) -blue1.instanceMemberVariable = 4 -assert( blue1.instanceMemberVariable == 4 ) - --- Constructors -color1 = ns.Outer.Inner1.Color() -color2 = ns.Outer.Inner1.Color.create() -color = ns.Outer.Inner1.Color(color1) -color3 = ns.Outer.Inner2.Color.create() -color4 = ns.Outer.Inner2.Color.create() -color5 = ns.Outer.Inner2.Color.create() -mwp2 = ns.Outer.MyWorldPart2() -gc = ns.GlobalClass() - -nnsp = ns.NoNSpacePlease() - --- Class methods -color:colorInstanceMethod(20.0) -ns.Outer.Inner1.Color.colorStaticMethod(30.0) -color3:colorInstanceMethod(40.0) -ns.Outer.Inner2.Color.colorStaticMethod(50.0) -color3:colors(color1, color2, color3, color4, color5) - -gc:gmethod() - --- Class variables -color.instanceMemberVariable = 5 -color1.instanceMemberVariable = 7 -assert( color.instanceMemberVariable == 5 ) -assert( color1.instanceMemberVariable == 7 ) -assert(ns.Outer.Inner1.Color.staticMemberVariable == 0 ) -assert(ns.Outer.Inner2.Color.staticMemberVariable == 0 ) -ns.Outer.Inner1.Color.staticMemberVariable = 9 -ns.Outer.Inner2.Color.staticMemberVariable = 11 -assert(ns.Outer.Inner1.Color.staticMemberVariable == 9) -assert(ns.Outer.Inner2.Color.staticMemberVariable == 11) - --- Class constants -assert( ns.Outer.Inner1.Color.Specular == 0x20 ) -assert( ns.Outer.Inner2.Color.Specular == 0x40 ) -assert( ns.Outer.Inner1.Color.staticConstMemberVariable == 222 ) -assert( ns.Outer.Inner2.Color.staticConstMemberVariable == 333 ) -assert( ns.Outer.Inner1.Color.staticConstEnumMemberVariable ~= ns.Outer.Inner2.Color.staticConstEnumMemberVariable ) - - --- Aggregation -sc = ns.Outer.SomeClass() -assert( sc:GetInner1ColorChannel() ~= sc:GetInner2Channel() ) -assert( sc:GetInner1Channel() ~= sc:GetInner2Channel() ) - - - - +require("import") -- the import fn +import("nspace") -- import lib + +-- catch "undefined" global variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +ns = nspace + +-- Inheritance +blue1 = ns.Outer.Inner3.Blue() + +-- blue1:blueInstanceMethod() +blue1:colorInstanceMethod(60.0) +blue1.instanceMemberVariable = 4 +assert( blue1.instanceMemberVariable == 4 ) + +-- Constructors +color1 = ns.Outer.Inner1.Color() +color2 = ns.Outer.Inner1.Color.create() +color = ns.Outer.Inner1.Color(color1) +color3 = ns.Outer.Inner2.Color.create() +color4 = ns.Outer.Inner2.Color.create() +color5 = ns.Outer.Inner2.Color.create() +mwp2 = ns.Outer.MyWorldPart2() +gc = ns.GlobalClass() + +nnsp = ns.NoNSpacePlease() + +-- Class methods +color:colorInstanceMethod(20.0) +ns.Outer.Inner1.Color.colorStaticMethod(30.0) +color3:colorInstanceMethod(40.0) +ns.Outer.Inner2.Color.colorStaticMethod(50.0) +color3:colors(color1, color2, color3, color4, color5) + +gc:gmethod() + +-- Class variables +color.instanceMemberVariable = 5 +color1.instanceMemberVariable = 7 +assert( color.instanceMemberVariable == 5 ) +assert( color1.instanceMemberVariable == 7 ) +assert(ns.Outer.Inner1.Color.staticMemberVariable == 0 ) +assert(ns.Outer.Inner2.Color.staticMemberVariable == 0 ) +ns.Outer.Inner1.Color.staticMemberVariable = 9 +ns.Outer.Inner2.Color.staticMemberVariable = 11 +assert(ns.Outer.Inner1.Color.staticMemberVariable == 9) +assert(ns.Outer.Inner2.Color.staticMemberVariable == 11) + +-- Class constants +assert( ns.Outer.Inner1.Color.Specular == 0x20 ) +assert( ns.Outer.Inner2.Color.Specular == 0x40 ) +assert( ns.Outer.Inner1.Color.staticConstMemberVariable == 222 ) +assert( ns.Outer.Inner2.Color.staticConstMemberVariable == 333 ) +assert( ns.Outer.Inner1.Color.staticConstEnumMemberVariable ~= ns.Outer.Inner2.Color.staticConstEnumMemberVariable ) + + +-- Aggregation +sc = ns.Outer.SomeClass() +assert( sc:GetInner1ColorChannel() ~= sc:GetInner2Channel() ) +assert( sc:GetInner1Channel() ~= sc:GetInner2Channel() ) + + + + From 52c106d27fe4659d213ba69de3ea3a4e369da4d3 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 27 Feb 2014 20:23:32 +0000 Subject: [PATCH 459/481] Revert unnecessary changes in keyword_rename test --- Examples/test-suite/keyword_rename.i | 2 -- 1 file changed, 2 deletions(-) diff --git a/Examples/test-suite/keyword_rename.i b/Examples/test-suite/keyword_rename.i index a9f58ebef..46c3338b3 100644 --- a/Examples/test-suite/keyword_rename.i +++ b/Examples/test-suite/keyword_rename.i @@ -32,10 +32,8 @@ KW(go, defer) KW(chan, fallthrough) /* Lua keywords */ -#ifdef SWIGLUA KW(end, function) KW(nil,local) -#endif %} From e208f85beaac946c5e8536e088b148a880856f37 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 28 Feb 2014 07:49:11 +0000 Subject: [PATCH 460/481] Lua html documentation fixes/improvements. --- Doc/Manual/Lua.html | 65 +++++++++++++++++++++++++++------------------ 1 file changed, 39 insertions(+), 26 deletions(-) diff --git a/Doc/Manual/Lua.html b/Doc/Manual/Lua.html index 379fdfc94..f2dd45197 100644 --- a/Doc/Manual/Lua.html +++ b/Doc/Manual/Lua.html @@ -357,8 +357,10 @@ creates a built-in function example.fact(n) that works exactly like you >

        -To avoid name collisions, SWIG create a Lua table which it keeps all the functions, constants, classes and global variables in. It is possible to copy the functions, constants and classes (but not variables) out of this and into the global environment with the following code. This can easily overwrite existing functions, so this must be used with care. -This option is considered deprecated and will be removed in near future. +To avoid name collisions, SWIG create a Lua table which keeps all the functions, constants, classes and global variables in. +It is possible to copy the functions, constants and classes (but not variables) out of this and into the global environment with the following code. +This can easily overwrite existing functions, so this must be used with care. +This option is considered deprecated and will be removed in the near future.

         > for k,v in pairs(example) do _G[k]=v end
        @@ -502,12 +504,12 @@ Hello World
         
         

        Constants/enums and classes/structures

        -Unlike previous version of bindings, enums are now exported into class table. For example, given some enums: +Enums are exported into a class table. For example, given some enums:

        %module example
        -enum Days{SUNDAY = 0,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY};
        -class Test {
        -    enum { TEST1 = 10, TEST2 = 10 }
        +enum Days { SUNDAY = 0, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };
        +struct Test {
        +    enum { TEST1 = 10, TEST2 = 20 };
             static const int ICONST = 12;
         };
         
        @@ -522,9 +524,10 @@ This is 'effectively' converted into the following Lua code: > print(example.Test.ICONST) 12
        -

        Backward compatibility

        +

        -If -no-old-metatable-bindings option is not given, then in addition to previously described bindings, the old-style ones are generated: +Compatibility Note: Versions of SWIG prior to SWIG-3.0.0 did not generate the class table members above. +The following code was the only way to access these constants/enums:

         > print(example.Test_TEST1)
        @@ -533,7 +536,11 @@ If -no-old-metatable-bindings option is not given, then in addition to
         12
         

        -However, in C mode, names of enums are not prefixed with names of structure. This is the due to C Standard. +The old-style bindings are still generated in addition to the new ones. +If the -no-old-metatable-bindings option is used, then these old-style bindings are not generated. +

        +

        +However, in C mode, names of enums are not prefixed with names of structure. This is the due to the C Standard.

         > print(example.TEST1)
        @@ -542,7 +549,7 @@ However, in C mode, names of enums are not prefixed with names of structure. Thi
         12
         

        -It worth mentioning, that example.Test.TEST1 and example.Test_TEST1 are different entities and changind one wouldn't change another. +It is worth mentioning, that example.Test.TEST1 and example.Test_TEST1 are different entities and changing one does not change the other. Given the fact, that these are constantes and they are not supposed to be changed, it is up to you to avoid such issues.

        26.3.5 Pointers

        @@ -747,13 +754,18 @@ It is not (currently) possible to access static members of an instance: -- does NOT work -

        Backward compatibility

        -

        If -no-old-metatable-bindings option is not given, then backward compatible names are generated in addition to ordinary ones:

        +Compatibility Note: In versions prior to SWIG-3.0.0 only the following names would work:
         > example.Spam_foo()            -- calling Spam::foo()
         > a=example.Spam_bar            -- reading Spam::bar 
         > example.Spam_bar=b            -- writing to Spam::bar
         
        + +

        +Both style names are generated by default now. +However, if the -no-old-metatable-bindings option is used, then the backward compatible names are not generated in addition to ordinary ones. +

        +

        26.3.8 C++ inheritance

        @@ -1318,37 +1330,38 @@ and the "Exception handling add exception specification to functions or globally (respectively).

        -

        26.3.17 Namespaces

        +

        26.3.17 Namespaces

        -Since SWIG 3.0 C++ namespaces are supported. You can enabled handling namespaces with %nspace feature. Everything below is valid only after you enabled %nspace. +Since SWIG-3.0.0 C++ namespaces are supported via the %nspace feature.

        -

        Namespaces are mapped into lua tables. Each of those tables contains names that were defined within appropriate namespace. Namespaces structure (a.k.a nested namespaces) is preserved. Consider the following C++ code: +

        Namespaces are mapped into Lua tables. Each of those tables contains names that were defined within appropriate namespace. Namespaces structure (a.k.a nested namespaces) is preserved. Consider the following C++ code:

        %module example
         %nspace MyWorld::Nested::Dweller;
         %nspace MyWorld::World;
        -/* and so on */
        -int module_function() { return 7;}
        -int module_variable; // = 9
        +
        +int module_function() { return 7; }
        +int module_variable = 9;
        +
         namespace MyWorld {
           class World {
           public:
        -    int create_world() { return 17;}
        +    int create_world() { return 17; }
             const int world_max_count = 9;
           };
           namespace Nested {
             class Dweller {
        -      enum Gender {MALE, FEMALE;
        +      enum Gender { MALE, FEMALE };
               static int populate_cave() { return 19; }
        -      int create_cave() { return 13;}
        +      int create_cave() { return 13; }
               int food_count; // = 11
        -    }
        +    };
           }
         }
         
        -Now, in Lua it could be used like this: +Now, from Lua usage is as follows:
        -> example.module_function()
        +> print(example.module_function())
         7
         > print(example.module_variable)
         8
        @@ -1356,9 +1369,9 @@ Now, in Lua it could be used like this:
         17
         > print(example.MyWorld.World.world_max_count)
         9
        -> print(example.MyWordl.Nested.Dweller.MALE)
        +> print(example.MyWorld.Nested.Dweller.MALE)
         0
        -> print(example.MyWordl.Nested.Dweller().food_count)
        +> print(example.MyWorld.Nested.Dweller().food_count)
         11
         >
         
        From 58caa386167a8817a9d158be9fd51b6c214ab26d Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 28 Feb 2014 18:19:43 +0000 Subject: [PATCH 461/481] Restore Lua C++11 rvalue reference --- Lib/lua/lua.swg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/lua/lua.swg b/Lib/lua/lua.swg index 40087236b..60e418596 100644 --- a/Lib/lua/lua.swg +++ b/Lib/lua/lua.swg @@ -41,7 +41,7 @@ %typemap(consttab) long long, unsigned long long {SWIG_LUA_CONSTTAB_STRING("$symname", "$value")} -%typemap(consttab) SWIGTYPE *, SWIGTYPE *const, SWIGTYPE &, SWIGTYPE [] +%typemap(consttab) SWIGTYPE *, SWIGTYPE *const, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] { SWIG_LUA_CONSTTAB_POINTER("$symname",$value, $1_descriptor) } // member function pointers From f011481f2b120960720f628ebcc4332ae069ef0f Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 28 Feb 2014 19:15:23 +0000 Subject: [PATCH 462/481] Cosmetic tweaks to lua runtime --- Lib/lua/luarun.swg | 65 ++++++++++++++++++++++++---------------------- 1 file changed, 34 insertions(+), 31 deletions(-) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index 547231815..b3ecb374b 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -385,9 +385,8 @@ SWIGINTERN int SWIG_Lua_set_immutable(lua_State *L) SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State *L,void *ptr,swig_type_info *type, int own); SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State *L,void *ptr,size_t size,swig_type_info *type); static int swig_lua_elua_emulate_unique_key; -/* This is function that emulates eLua rotables behaviour. It loads rotable definition - * into the usual lua table. - */ + +/* This function emulates eLua rotables behaviour. It loads a rotable definition into the usual lua table. */ SWIGINTERN void SWIG_Lua_elua_emulate_register(lua_State *L, const swig_elua_entry *table) { assert(lua_istable(L,-1)); @@ -654,11 +653,10 @@ SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State *L, swig_lua_namespace * return 0; } -/* Register all classes in the namespace - */ +/* Register all classes in the namespace */ SWIGINTERN void SWIG_Lua_add_namespace_classes(lua_State *L, swig_lua_namespace *ns) { - /* There must be module/namespace table at the top of the stack */ + /* There must be a module/namespace table at the top of the stack */ assert(lua_istable(L,-1)); swig_lua_class **classes = ns->ns_classes; @@ -671,10 +669,10 @@ SWIGINTERN void SWIG_Lua_add_namespace_classes(lua_State *L, swig_lua_namespace } } -/* helper function. creates namespace table and add it to module table +/* Helper function. Creates namespace table and adds it to module table if 'reg' is true, then will register namespace table to parent one (must be on top of the stack - when function is called) - Function always returns newly registered table on top of the stack + when function is called). + Function always returns newly registered table on top of the stack. */ SWIGINTERN int SWIG_Lua_namespace_register(lua_State *L, swig_lua_namespace *ns, int reg) { @@ -726,13 +724,14 @@ SWIGINTERN int SWIG_Lua_namespace_register(lua_State *L, swig_lua_namespace *ns, assert(lua_gettop(L) == begin+1); } #endif /* SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA */ + /* ----------------------------------------------------------------------------- * global variable support code: classes * ----------------------------------------------------------------------------- */ SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State *L,const char *cname); -/* Macroses for iteration among class bases */ +/* Macros for iteration among class bases */ #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) #define SWIG_LUA_INIT_BASE_SEARCH(bases_count)\ SWIG_Lua_get_table(L,".bases");\ @@ -783,7 +782,8 @@ SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info *swig_type, i int bases_count; SWIG_LUA_INIT_BASE_SEARCH(bases_count); int result = SWIG_ERROR; - if(ret) *ret = 0; + if(ret) + *ret = 0; if(bases_count>0) { int i; @@ -795,8 +795,7 @@ SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info *swig_type, i int subcall_last_arg = lua_gettop(L); swig_type_info *base_swig_type = 0; - /* Trick: temporaly replacing original metatable - * with metatable for base class and call getter */ + /* Trick: temporarily replacing original metatable with metatable for base class and call getter */ for(i=0;imethods[i].name,clss->methods[i].func); } lua_pop(L,1); /* tidy stack (remove table) */ - /* add operator overloads + /* add operator overloads This adds methods from metatable array to metatable. Can mess up garbage collectind if someone defines __gc method */ @@ -1298,7 +1301,7 @@ SWIGINTERN void SWIG_Lua_class_register_static(lua_State *L, swig_lua_class *cls assert( lua_gettop(L) == begin ); } -/* performs the instance(non-static) class registration process. Metatable for class is created +/* Performs the instance (non-static) class registration process. Metatable for class is created * and added to the class registry. */ SWIGINTERN void SWIG_Lua_class_register_instance(lua_State *L,swig_lua_class *clss) @@ -1386,7 +1389,7 @@ SWIGINTERN void SWIG_Lua_class_register_instance(lua_State *L,swig_lua_class *c SWIGINTERN void SWIG_Lua_class_register(lua_State *L,swig_lua_class *clss) { - assert(lua_istable(L,-1)); /* This is table(module or namespace) where class will be added */ + assert(lua_istable(L,-1)); /* This is a table (module or namespace) where classes will be added */ SWIG_Lua_class_register_instance(L,clss); SWIG_Lua_class_register_static(L,clss); From 0da97a9d3ed6dc8fede5f7693b43fd5fac96e1fb Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 28 Feb 2014 19:19:44 +0000 Subject: [PATCH 463/481] Fix illegal C++ symbols --- Lib/lua/luarun.swg | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index b3ecb374b..ec6052fe5 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -1459,7 +1459,7 @@ SWIGINTERN void SWIG_Lua_elua_class_register_instance(lua_State *L, swig_lua_cla * ----------------------------------------------------------------------------- */ /* helper to add metatable to new lua object */ -SWIGINTERN void _SWIG_Lua_AddMetatable(lua_State *L,swig_type_info *type) +SWIGINTERN void SWIG_Lua_AddMetatable(lua_State *L,swig_type_info *type) { if (type->clientdata) /* there is clientdata: so add the metatable */ { @@ -1488,7 +1488,7 @@ SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State *L,void *ptr,swig_type_info *t usr->type=type; usr->own=own; #if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC) - _SWIG_Lua_AddMetatable(L,type); /* add metatable */ + SWIG_Lua_AddMetatable(L,type); /* add metatable */ #endif } @@ -1542,7 +1542,7 @@ SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State *L,void *ptr,size_t size,swig_t raw->type=type; raw->own=0; memcpy(raw->data,ptr,size); /* copy the data */ - _SWIG_Lua_AddMetatable(L,type); /* add metatable */ + SWIG_Lua_AddMetatable(L,type); /* add metatable */ } /* converts a packed userdata. user for member fn pointers only */ From d957d3763612f7de5796ff7ae378d8eb6090b216 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 28 Feb 2014 19:49:53 +0000 Subject: [PATCH 464/481] Minor code improvements after Lua changes. --- Source/Modules/lang.cxx | 27 +++++++++++++-------------- Source/Modules/lua.cxx | 5 ++--- Source/Modules/swigmod.h | 4 ++-- 3 files changed, 17 insertions(+), 19 deletions(-) diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 9420ea719..04304744c 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -2993,7 +2993,7 @@ int Language::variableWrapper(Node *n) { Setattr(n, "varset", "1"); functionWrapper(n); } else { - Setattr(n, "feature:immutable", "1"); + SetFlag(n, "feature:immutable"); } /* Restore parameters */ Setattr(n, "sym:name", symname); @@ -3079,9 +3079,9 @@ int Language::addSymbol(const String *s, const Node *n, const_String_or_char_ptr } /* ----------------------------------------------------------------------------- - * Lanugage::symbolAddScope( const_String_or_char_ptr scopeName ) + * Language::symbolAddScope() * - * Creates a scope (symbols Hash) for given name. This method is auxilary, + * Creates a scope (symbols Hash) for given name. This method is auxiliary, * you don't have to call it - addSymbols will lazily create scopes automatically. * If scope with given name already exists, then do nothing. * Returns newly created (or already existing) scope. @@ -3089,10 +3089,10 @@ int Language::addSymbol(const String *s, const Node *n, const_String_or_char_ptr Hash* Language::symbolAddScope(const_String_or_char_ptr scope) { Hash *symbols = symbolScopeLookup(scope); if(!symbols) { - // Order in which to following parts are executed is important. In Lanugage - // constructor addScope("") is called to create a top level scope itself. - // Thus we must first add symbols hash to symtab and only then add pseudo - // symbol to top-level scope + // The order in which the following code is executed is important. In the Language + // constructor addScope("") is called to create a top level scope. + // Thus we must first add a symbols hash to symtab and only then add pseudo + // symbols to the top-level scope. // New scope which has not been added by the target language - lazily created. symbols = NewHash(); @@ -3103,14 +3103,14 @@ Hash* Language::symbolAddScope(const_String_or_char_ptr scope) { const_String_or_char_ptr top_scope = ""; Hash *topscope_symbols = Getattr(symtabs, top_scope); Hash *pseudo_symbol = NewHash(); - Setattr(pseudo_symbol, "sym:is_scope", "1"); + Setattr(pseudo_symbol, "sym:scope", "1"); Setattr(topscope_symbols, scope, pseudo_symbol); } return symbols; } /* ----------------------------------------------------------------------------- - * Lanugage::symbolSscopeLookup( const_String_or_char_ptr scope ) + * Language::symbolScopeLookup() * * Lookup and returns a symtable (hash) representing given scope. Hash contains * all symbols in this scope. @@ -3121,17 +3121,16 @@ Hash* Language::symbolScopeLookup( const_String_or_char_ptr scope ) { } /* ----------------------------------------------------------------------------- - * Lanugage::symbolScopeSymbolLookup( const_String_or_char_ptr scope ) + * Language::symbolScopePseudoSymbolLookup() * * For every scope there is a special pseudo-symbol in the top scope (""). It * exists solely to detect name clashes. This pseudo symbol may contain a few properties, - * but you can more if you need to. This is also true fro top level scope (""). + * but more could be added. This is also true for the top level scope (""). * It contains a pseudo symbol with name "" (empty). Pseudo symbol contains the * following properties: - * sym:scope = "1" - a flag that this is scope pseudo symbol + * sym:scope = "1" - a flag that this is a scope pseudo symbol * - * Pseudo symbols are a Hash*, not a Node* (not that there is a difference - * in DOH) + * Pseudo symbols are a Hash*, not a Node*. * There is no difference from symbolLookup() method except for signature * and return type. * ----------------------------------------------------------------------------- */ diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 6c9e69050..c2f58cdf4 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -2096,9 +2096,8 @@ public: List *to_close = NewList(); while (ki.key) { assert(ki.item); - if (Getattr(ki.item, "sym:is_scope")) { - // We have a pseudo symbol. Lets get actuall scope for this - // pseudo symbol + if (Getattr(ki.item, "sym:scope")) { + // We have a pseudo symbol. Lets get actual scope for this pseudo symbol Hash *carrays_hash = rawGetCArraysHash(ki.key); assert(carrays_hash); if (Getattr(carrays_hash, "lua:closed") == 0) diff --git a/Source/Modules/swigmod.h b/Source/Modules/swigmod.h index afffebef9..63b91bae5 100644 --- a/Source/Modules/swigmod.h +++ b/Source/Modules/swigmod.h @@ -217,8 +217,8 @@ public: virtual void dumpSymbols(); virtual Node *symbolLookup(String *s, const_String_or_char_ptr scope = ""); /* Symbol lookup */ virtual Hash* symbolAddScope(const_String_or_char_ptr scope); - virtual Hash* symbolScopeLookup( const_String_or_char_ptr scope ); - virtual Hash* symbolScopePseudoSymbolLookup( const_String_or_char_ptr scope ); + virtual Hash* symbolScopeLookup(const_String_or_char_ptr scope); + virtual Hash* symbolScopePseudoSymbolLookup(const_String_or_char_ptr scope); virtual Node *classLookup(const SwigType *s) const; /* Class lookup */ virtual Node *enumLookup(SwigType *s); /* Enum lookup */ virtual int abstractClassTest(Node *n); /* Is class really abstract? */ From aaa71288b13ccb81d5d1c1a33d393b5e695ae7cc Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 28 Feb 2014 23:13:36 +0000 Subject: [PATCH 465/481] Cosmetic changes to lua.cxx after recent changes --- Source/Modules/lua.cxx | 173 ++++++++++++++++++++++------------------- 1 file changed, 91 insertions(+), 82 deletions(-) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index c2f58cdf4..4ed13127a 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -146,14 +146,14 @@ private: // and is not visible to user in any manner. This variable holds the name // of such pseudo-namespace a.k.a the result of above expression evaluation String *class_static_nspace; - // This variable holds the name of generated C function that acts as constructor - // for currently parsed class. + // This variable holds the name of generated C function that acts as a constructor + // for the currently parsed class. String *constructor_name; // Many wrappers forward calls to each other, for example staticmembervariableHandler - // forwards call to variableHandler, which, in turn, makes to call to functionWrapper. - // In order to access information about whether it is static member of class or just - // plain old variable an array current is kept and used as 'log' of call stack. + // forwards calls to variableHandler, which, in turn, makes to call to functionWrapper. + // In order to access information about whether it is a static member of class or just + // a plain old variable, the current array is kept and used as a 'log' of the call stack. enum TState { NO_CPP, VARIABLE, @@ -199,20 +199,7 @@ public: for (int i = 0; i < STATES_COUNT; i++) current[i] = false; } - ~LUA() { - } - bool strToInt(const char *string, int &value) { - long int tmp; - char *p_end = 0; - if (string == 0) - return false; - tmp = strtol(string, &p_end, 10); - if (p_end == 0 || *p_end != 0) - return false; - value = tmp; - return true; - } /* NEW LANGUAGE NOTE:*********************************************** This is called to initalise the system & read any command line args most of this is boilerplate code, except the command line args @@ -259,7 +246,7 @@ public: } if (elua_emulate && (eluac_ltr || elua_ltr )) { - Printf(stderr, "Can't have -elua-emulate and -eluac/-elua at the same time\n"); + Printf(stderr, "Cannot have -elua-emulate with either -eluac or -elua\n"); Swig_arg_error(); } @@ -400,7 +387,7 @@ public: Dump(f_wrappers, f_begin); Dump(f_initbeforefunc, f_begin); /* for the Lua code it needs to be properly excaped to be added into the C/C++ code */ - EscapeCode(s_luacode); + escapeCode(s_luacode); Printf(f_begin, "const char* SWIG_LUACODE=\n \"%s\";\n\n", s_luacode); Wrapper_pretty_print(f_init, f_begin); /* Close all of the files */ @@ -426,13 +413,14 @@ public: /* ------------------------------------------------------------ * cDeclaration() - * It copies sym:name to lua:name to preserve it's original value + * It copies sym:name to lua:name to preserve its original value * ------------------------------------------------------------ */ + virtual int cDeclaration(Node *n) { // class 'Language' is messing with symname in a really heavy way. // Although documentation states that sym:name is a name in // the target language space, it is not true. sym:name and - // it's derivatives are used in various places, including + // its derivatives are used in various places, including // behind-the-scene C code generation. The best way is not to // touch it at all. // But we need to know what was the name of function/variable @@ -468,10 +456,11 @@ public: /* ----------------------------------------------------------------------- * registerMethod() * - * Determines wrap name of a method, it's scope etc and calls + * Determines wrap name of a method, its scope etc and calls * registerMethod overload with correct arguments - * Overloaded variant adds method to the "methods" array of specified lua scope/class + * Overloaded variant adds method to the "methods" array of specified lua scope/class * ---------------------------------------------------------------------- */ + void registerMethod(Node *n, bool overwrite = false, String *overwriteLuaScope = 0) { String *symname = Getattr(n, "sym:name"); assert(symname); @@ -479,8 +468,7 @@ public: if (Getattr(n, "sym:nextSibling")) return; - // Lua scope. It is not symbol NSpace, it is actuall key to revrieve - // getCArraysHash. + // Lua scope. It is not symbol NSpace, it is the actual key to retrieve getCArraysHash. String *luaScope = luaCurrentSymbolNSpace(); if (overwrite) luaScope = overwriteLuaScope; @@ -490,12 +478,12 @@ public: if (current[NO_CPP] || !getCurrentClass()) { mrename = symname; } else { - assert(!current[NO_CPP]); - if (current[STATIC_FUNC] || current[MEMBER_FUNC]) { - mrename = Swig_name_member(getNSpace(), getClassPrefix(), symname); - } else { - mrename = symname; - } + assert(!current[NO_CPP]); + if (current[STATIC_FUNC] || current[MEMBER_FUNC]) { + mrename = Swig_name_member(getNSpace(), getClassPrefix(), symname); + } else { + mrename = symname; + } } wrapname = Swig_name_wrapper(mrename); //Printf(stdout, "luaname %s, symname %s mrename %s wrapname %s\n\tscope %s\n", @@ -503,7 +491,12 @@ public: registerMethod(n, wrapname, luaScope); } - // Add method to the "methods" C array of given namespace/class + /* ----------------------------------------------------------------------- + * registerMethod() + * + * Add method to the "methods" C array of given namespace/class + * ---------------------------------------------------------------------- */ + void registerMethod(Node *n, String* wname, String *luaScope) { assert(n); Hash *nspaceHash = getCArraysHash(luaScope); @@ -607,7 +600,7 @@ public: this is the code to convert from the scripting language to C/C++ some of the stuff will refer to the typemaps code written in your swig file (lua.swg), and some is done in the code here - I suppose you could do all the conversion on C, but it would be a nightmare to do + I suppose you could do all the conversion in C, but it would be a nightmare to do NEW LANGUAGE NOTE:END *********************************************** */ /* Generate code for argument marshalling */ // String *description = NewString(""); @@ -824,13 +817,7 @@ public: NEW LANGUAGE NOTE:END *********************************************** */ /* Now register the function with the interpreter. */ int result = SWIG_OK; - if (!Getattr(n, "sym:overloaded")) { - /* TODO: REMOVE - if (functionWrapperRegisterNow()) { // emit normal fns & static fns - registerMethod(n); - } - */ - } else { + if (Getattr(n, "sym:overloaded")) { if (!Getattr(n, "sym:nextSibling")) { result = dispatchFunction(n); } @@ -933,18 +920,18 @@ public: /* ------------------------------------------------------------ * Add variable to "attributes" C arrays of given namespace or class. - * Input is node. Base on the state of "current" array it determines - * the name of getter function, setter function etc and calls - * registeVariable overload with necessary params + * Input is node. Based on the state of "current" array it determines + * the name of the getter function, setter function etc and calls + * registerVariable overload with necessary params. * Lua scope could be overwritten. (Used only for backward compatibility) * ------------------------------------------------------------ */ + void registerVariable(Node *n, bool overwrite = false, String *overwriteLuaScope = 0) { int assignable = is_assignable(n); String *symname = Getattr(n, "sym:name"); assert(symname); - // Lua scope. It is not symbol NSpace, it is actuall key to revrieve - // getCArraysHash. + // Lua scope. It is not symbol NSpace, it is the actual key to retrieve getCArraysHash. String *luaScope = luaCurrentSymbolNSpace(); if (overwrite) luaScope = overwriteLuaScope; @@ -986,9 +973,10 @@ public: /* ------------------------------------------------------------ * registerVariable() * - * Add variable to the "attributes" (or "get"/"set" in + * Add variable to the "attributes" (or "get"/"set" in * case of elua_ltr) C arrays of given namespace or class * ------------------------------------------------------------ */ + void registerVariable(String *lua_nspace_or_class_name, Node *n, String *getName, String *setName) { String *unassignable = NewString("SWIG_Lua_set_immutable"); if (setName == 0 || GetFlag(n, "feature:immutable")) { @@ -1014,6 +1002,7 @@ public: /* ------------------------------------------------------------ * variableWrapper() * ------------------------------------------------------------ */ + virtual int variableWrapper(Node *n) { /* NEW LANGUAGE NOTE:*********************************************** Language::variableWrapper(n) will generate two wrapper fns @@ -1031,8 +1020,8 @@ public: // TODO: REMOVE //registerVariable(luaCurrentSymbolNSpace(), n, "varget:wrap:name", "varset:wrap:name"); - // It is impossible to use registerVariable, because sym:name of the Node is currenly - // in undefined states - the callees of this function may have modified it. + // It is impossible to use registerVariable, because sym:name of the Node is currently + // in an undefined state - the callees of this function may have modified it. // registerVariable should be used from respective callees.* current[VARIABLE] = false; return result; @@ -1043,6 +1032,7 @@ public: * Add constant to appropriate C array. constantRecord is an array record. * Actually, in current implementation it is resolved consttab typemap * ------------------------------------------------------------ */ + void registerConstant(String *nspace, String *constantRecord) { Hash *nspaceHash = getCArraysHash(nspace); String *s_const_tab = 0; @@ -1066,6 +1056,7 @@ public: /* ------------------------------------------------------------ * constantWrapper() * ------------------------------------------------------------ */ + virtual int constantWrapper(Node *n) { REPORT("constantWrapper", n); String *name = Getattr(n, "name"); @@ -1235,9 +1226,9 @@ public: /* ------------------------------------------------------------ - * Helper function that adds record to appropriate - * C arrays + * Helper function that adds record to appropriate C arrays * ------------------------------------------------------------ */ + void registerClass(String *scope, String *wrap_class) { assert(wrap_class); Hash *nspaceHash = getCArraysHash(scope); @@ -1252,9 +1243,11 @@ public: Printv(ns_methods, tab4, "{LSTRKEY(\"", proxy_class_name, "\")", ", LROVAL(", cls_methods, ")", "},\n", NIL); } } + /* ------------------------------------------------------------ * classHandler() * ------------------------------------------------------------ */ + virtual int classHandler(Node *n) { //REPORT("classHandler", n); @@ -1275,7 +1268,7 @@ public: proxy_class_name = Getattr(n, "sym:name"); // We have to enforce nspace here, because technically we are already // inside class parsing (getCurrentClass != 0), but we should register - // class in the it's parent namespace + // class in its parent namespace if (!luaAddSymbol(proxy_class_name, n, nspace)) return SWIG_ERROR; @@ -1578,18 +1571,20 @@ public: /* ---------------------------------------------------------------------- * globalfunctionHandler() + * * It can be called: * 1. Usual C/C++ global function. * 2. During class parsing for functions declared/defined as friend * 3. During class parsing from staticmemberfunctionHandler * ---------------------------------------------------------------------- */ + virtual int globalfunctionHandler(Node *n) { bool oldVal = current[NO_CPP]; - if (!current[STATIC_FUNC]) // If static funct, don't switch to NO_CPP + if (!current[STATIC_FUNC]) // If static function, don't switch to NO_CPP current[NO_CPP] = true; const int result = Language::globalfunctionHandler(n); - if (!current[STATIC_FUNC]) // Register only if not called from static funct handler + if (!current[STATIC_FUNC]) // Register only if not called from static function handler registerMethod(n); current[NO_CPP] = oldVal; return result; @@ -1597,10 +1592,10 @@ public: /* ---------------------------------------------------------------------- * globalvariableHandler() - * globalfunctionHandler() - * Sets "current" array correctly and calls - * Language::globalvariableHandler() + * + * Sets "current" array correctly * ---------------------------------------------------------------------- */ + virtual int globalvariableHandler(Node *n) { bool oldVal = current[NO_CPP]; current[GLOBAL_VAR] = true; @@ -1631,9 +1626,9 @@ public: if (v2_compatibility && result == SWIG_OK) { Swig_require("lua_staticmemberfunctionHandler", n, "*lua:name", NIL); String *lua_name = Getattr(n, "lua:name"); - // Although this function uses Swig_name_member, it actually generateds Lua name, - // not C++ name. It is because previous version used such scheme for static func - // name generation and we have to maintain backward compatibility + // Although this function uses Swig_name_member, it actually generates the Lua name, + // not the C++ name. This is because an earlier version used such a scheme for static function + // name generation and we have to maintain backward compatibility. String *compat_name = Swig_name_member(0, proxy_class_name, lua_name); Setattr(n, "lua:name", compat_name); registerMethod(n, true, getNSpace()); @@ -1676,9 +1671,9 @@ public: if (v2_compatibility) { Swig_save("lua_staticmembervariableHandler", n, "lua:name", NIL); String *lua_name = Getattr(n, "lua:name"); - // Although this function uses Swig_name_member, it actually generateds Lua name, - // not C++ name. It is because previous version used such scheme for static vars - // name generation and we have to maintain backward compatibility + // Although this function uses Swig_name_member, it actually generates the Lua name, + // not the C++ name. This is because an earlier version used such a scheme for static function + // name generation and we have to maintain backward compatibility. String *v2_name = Swig_name_member(NIL, proxy_class_name, lua_name); //Printf( stdout, "Name %s, class %s, compt. name %s\n", lua_name, proxy_class_name, v2_name ); // TODO: REMOVE if (!GetFlag(n, "wrappedasconstant")) { @@ -1686,9 +1681,8 @@ public: // Registering static var in the class parent nspace registerVariable(n, true, getNSpace()); } - // If static member variable was wrapped as constant, then - // constant wrapper has already performed all actions - // necessary for v2_compatibility + // If static member variable was wrapped as a constant, then + // constant wrapper has already performed all actions necessary for v2_compatibility Delete(v2_name); Swig_restore(n); } @@ -1753,12 +1747,14 @@ public: /* ----------------------------------------------------------------------------- - * EscapeCode() + * escapeCode() + * * This is to convert the string of Lua code into a proper string, which can then be * emitted into the C/C++ code. * Basically is is a lot of search & replacing of odd sequences * ---------------------------------------------------------------------------- */ - void EscapeCode(String *str) { + + void escapeCode(String *str) { //Printf(f_runtime,"/* original luacode:[[[\n%s\n]]]\n*/\n",str); Chop(str); // trim Replace(str, "\\", "\\\\", DOH_REPLACE_ANY); // \ to \\ (this must be done first) @@ -1772,6 +1768,7 @@ public: * * A small helper to hide impelementation of how CArrays hashes are stored * ---------------------------------------------------------------------------- */ + Hash *rawGetCArraysHash(const_String_or_char_ptr name) { Hash *scope = symbolScopeLookup( name ? name : "" ); if(!scope) @@ -1783,20 +1780,22 @@ public: /* ----------------------------------------------------------------------------- * getCArraysHash() - * Each namespace can be described with hash that stores C arrays + * + * Each namespace can be described with a hash that stores C arrays * where members of the namespace should be added. All these hashes are stored - * inside symbols table, in pseudo-symbol for every namespace. + * inside the symbols table, in pseudo-symbol for every namespace. * nspace could be NULL (NSPACE_TODO), that means functions and variables and classes - * that are not in any namespace (this is default for SWIG unless %nspace feature is used) + * that are not in any namespace (this is default for SWIG unless %nspace feature is used). * You can later set some attributes that will affect behaviour of functions that use this hash: * "lua:no_namespaces" will disable "namespaces" array. * "lua:no_classes" will disable "classes" array. * For every component ("attributes", "methods", etc) there are subcomponents: * XXX:name - name of the C array that stores data for component * XXX:decl - statement with forward declaration of this array; - * Namespace could be automatically registered to it's parent if 'reg' == true. It can be done - * only at first call (a.k.a when nspace is created). + * Namespace could be automatically registered to its parent if 'reg' == true. This can only be + * done during the first call (a.k.a when nspace is created). * ---------------------------------------------------------------------------- */ + Hash *getCArraysHash(String *nspace, bool reg = true) { Hash *scope = symbolScopeLookup(nspace ? nspace : ""); if(!scope) { @@ -1945,10 +1944,9 @@ public: Delete(components); Delete(parent_path); - } else if (!reg) // This namespace shouldn't be registered. Lets remember it + } else if (!reg) // This namespace shouldn't be registered. Lets remember it. Setattr(carrays_hash, "lua:no_reg", "1"); - Delete(mangled_name); mangled_name = 0; return carrays_hash; @@ -1956,14 +1954,16 @@ public: /* ----------------------------------------------------------------------------- * closeCArraysHash() + * * Functions add end markers {0,0,...,0} to all arrays, prints them to * output and marks hash as closed (lua:closed). Consequent attempts to - * close same hash will result in error + * close the same hash will result in an error. * closeCArraysHash DOES NOT print structure that describes namespace, it only * prints array. You can use printCArraysDefinition to print structure. * if "lua:no_namespaces" is set, then array for "namespaces" won't be printed * if "lua:no_classes" is set, then array for "classes" won't be printed * ----------------------------------------------------------------------------- */ + void closeCArraysHash(String *nspace, File *output) { Hash *carrays_hash = rawGetCArraysHash(nspace); assert(carrays_hash); @@ -2078,9 +2078,11 @@ public: } /* ----------------------------------------------------------------------------- - * closeCArraysHash() + * closeNamespaces() + * * Recursively close all non-closed namespaces. Prints data to dataOutput. * ----------------------------------------------------------------------------- */ + void closeNamespaces(File *dataOutput) { // Special handling for empty module. if (symbolScopeLookup("") == 0 || rawGetCArraysHash("") == 0) { @@ -2124,13 +2126,14 @@ public: /* ----------------------------------------------------------------------------- * printCArraysDefinition() - * This function prints to output a definition of namespace in - * form - * swig_lua_namespace $cname = { attr_array, methods_array, ... , namespaces_array }; - * You can call this function as many times as necessary. + * + * This function prints to output a definition of namespace in form + * swig_lua_namespace $cname = { attr_array, methods_array, ... , namespaces_array }; + * You can call this function as many times as is necessary. * 'name' is a user-visible name that this namespace will have in Lua. It shouldn't - * be fully qualified name, just it's own name. + * be a fully qualified name, just its own name. * ----------------------------------------------------------------------------- */ + void printCArraysDefinition(String *nspace, String *name, File *output) { Hash *carrays_hash = getCArraysHash(nspace, false); @@ -2159,6 +2162,7 @@ public: /* ----------------------------------------------------------------------------- * luaCurrentSymbolNSpace() + * * This function determines actual namespace/scope where any symbol at the * current moment should be placed. It looks at the 'current' array * and depending on where are we - static class member/function, @@ -2166,6 +2170,7 @@ public: * where symbol should be put. * The namespace/scope doesn't depend from symbol, only from 'current' * ----------------------------------------------------------------------------- */ + String *luaCurrentSymbolNSpace() { String *scope = 0; // If ouside class, than NSpace is used. @@ -2190,9 +2195,11 @@ public: /* ----------------------------------------------------------------------------- * luaAddSymbol() + * * Our implementation of addSymbol. Determines scope correctly, then * forwards to Language::addSymbol * ----------------------------------------------------------------------------- */ + int luaAddSymbol(const String *s, const Node *n) { String *scope = luaCurrentSymbolNSpace(); return luaAddSymbol(s, n, scope); @@ -2200,8 +2207,10 @@ public: /* ----------------------------------------------------------------------------- * luaAddSymbol() + * * Overload. Enforces given scope. Actually, it simply forwards call to Language::addSymbol * ----------------------------------------------------------------------------- */ + int luaAddSymbol(const String *s, const Node *n, const_String_or_char_ptr scope) { int result = Language::addSymbol(s, n, scope); if (!result) From 736c6b953e07141d04fd277544fb50198b02aff5 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 1 Mar 2014 04:35:00 -0800 Subject: [PATCH 466/481] C# project files update - Update project files to use Visual Studio 2005 (minimum supported .NET is now 2.0 which is what VS 2005 supports). - Add project files for arrays example (requires /unsafe) - Fix support so that the project files work straight out the box on 64 bit systems (32 bit compile is the default). - Fix support for 64 bit builds - use the x64 platform. --- Examples/csharp/nested/example-cs.csproj | 181 +++++------ Examples/csharp/nested/example-vc.vcproj | 383 +++++++++++++++++++---- Examples/csharp/nested/example.sln | 44 +-- 3 files changed, 433 insertions(+), 175 deletions(-) diff --git a/Examples/csharp/nested/example-cs.csproj b/Examples/csharp/nested/example-cs.csproj index 8004780fb..b20ff231a 100644 --- a/Examples/csharp/nested/example-cs.csproj +++ b/Examples/csharp/nested/example-cs.csproj @@ -1,94 +1,87 @@ - - - - - - - - - - - - - - - - - - - - + + + Local + 8.0.50727 + 2.0 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A} + Debug + x86 + + + + + runme + + + JScript + Grid + IE50 + false + Exe + runme + OnBuildSuccess + + + + + + + + + true + bin\x86\Debug\ + DEBUG;TRACE + 285212672 + full + x86 + prompt + + + bin\x86\Release\ + TRACE + 285212672 + true + + + x86 + prompt + + + true + bin\x64\Debug\ + DEBUG;TRACE + 285212672 + full + x64 + prompt + + + bin\x64\Release\ + TRACE + 285212672 + true + + + x64 + prompt + + + + Code + + + Code + + + Code + + + + + + + + copy runme.exe "$(SolutionDir)runme.exe" +echo Run the example from the root directory $(SolutionDir) and ensure example.dll is also in this directory + + diff --git a/Examples/csharp/nested/example-vc.vcproj b/Examples/csharp/nested/example-vc.vcproj index 5788bc9c7..ef870959e 100644 --- a/Examples/csharp/nested/example-vc.vcproj +++ b/Examples/csharp/nested/example-vc.vcproj @@ -1,110 +1,345 @@ + Keyword="Win32Proj" + > + Name="Win32" + /> + + + + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + + + + + + Detect64BitPortabilityProblems="true" + DebugInformationFormat="4" + /> + Name="VCManagedResourceCompilerTool" + /> + + + ImportLibrary="$(OutDir)\example.lib" + TargetMachine="1" + /> + Name="VCALinkTool" + /> + Name="VCManifestTool" + /> + Name="VCXDCMakeTool" + /> + Name="VCBscMakeTool" + /> + Name="VCFxCopTool" + /> + Name="VCAppVerifierTool" + /> + Name="VCWebDeploymentTool" + /> + Name="VCPostBuildEventTool" + Description="Copy unmanaged dll to root directory..." + CommandLine="echo on copy "$(OutDir)\example.dll" "$(SolutionDir)" @echo off " + /> + + + Name="VCPreBuildEventTool" + /> + Name="VCCustomBuildTool" + /> + + + + + + + + + + + + + + + + + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + + + + + + Detect64BitPortabilityProblems="true" + DebugInformationFormat="3" + /> + Name="VCManagedResourceCompilerTool" + /> + + + ImportLibrary="$(OutDir)\example.lib" + TargetMachine="1" + /> + Name="VCALinkTool" + /> + Name="VCManifestTool" + /> + Name="VCXDCMakeTool" + /> + Name="VCBscMakeTool" + /> + Name="VCFxCopTool" + /> + Name="VCAppVerifierTool" + /> + Name="VCWebDeploymentTool" + /> + Name="VCPostBuildEventTool" + Description="Copy unmanaged dll to root directory..." + CommandLine="echo on copy "$(OutDir)\example.dll" "$(SolutionDir)" @echo off " + /> + + + Name="VCPreBuildEventTool" + /> + Name="VCCustomBuildTool" + /> + + + + + + + + + + + + + + + + @@ -113,43 +348,65 @@ + UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}" + > + RelativePath="example.cxx" + > + RelativePath="example_wrap.cxx" + > + UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}" + > + RelativePath="example.h" + > + RelativePath=".\example.i" + > + Name="Debug|Win32" + > + CommandLine="echo Invoking SWIG... echo on ..\..\..\swig.exe -c++ -csharp "$(InputPath)" @echo off " + Outputs="$(InputName)_wrap.cxx" + /> + Name="Debug|x64" + > + CommandLine="echo Invoking SWIG... echo on ..\..\..\swig.exe -c++ -csharp "$(InputPath)" @echo off " + Outputs="$(InputName)_wrap.cxx" + /> + + + + + + diff --git a/Examples/csharp/nested/example.sln b/Examples/csharp/nested/example.sln index 88995ffd3..234bd64d3 100644 --- a/Examples/csharp/nested/example.sln +++ b/Examples/csharp/nested/example.sln @@ -1,30 +1,38 @@ -Microsoft Visual Studio Solution File, Format Version 8.00 +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "example-cs", "example-cs.csproj", "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}" ProjectSection(ProjectDependencies) = postProject {C2302635-D489-4678-96B4-70F5309DCBE6} = {C2302635-D489-4678-96B4-70F5309DCBE6} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example-vc", "example-vc.vcproj", "{C2302635-D489-4678-96B4-70F5309DCBE6}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection EndProject Global - GlobalSection(SolutionConfiguration) = preSolution - Debug = Debug - Release = Release + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 EndGlobalSection - GlobalSection(ProjectConfiguration) = postSolution - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.ActiveCfg = Debug|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.Build.0 = Debug|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.ActiveCfg = Release|.NET - {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.Build.0 = Release|.NET - {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.ActiveCfg = Debug|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.Build.0 = Debug|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Release.ActiveCfg = Release|Win32 - {C2302635-D489-4678-96B4-70F5309DCBE6}.Release.Build.0 = Release|Win32 + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.ActiveCfg = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.Build.0 = Debug|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.ActiveCfg = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|x64.Build.0 = Debug|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.ActiveCfg = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.Build.0 = Release|x86 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.ActiveCfg = Release|x64 + {C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|x64.Build.0 = Release|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.ActiveCfg = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.Build.0 = Debug|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.ActiveCfg = Debug|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|x64.Build.0 = Debug|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.ActiveCfg = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.Build.0 = Release|Win32 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.ActiveCfg = Release|x64 + {C2302635-D489-4678-96B4-70F5309DCBE6}.Release|x64.Build.0 = Release|x64 EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - EndGlobalSection - GlobalSection(ExtensibilityAddIns) = postSolution + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE EndGlobalSection EndGlobal From 09cfc53bdf0264ca7aa69a3a3cf9bde3bb375efd Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 1 Mar 2014 16:14:36 +0000 Subject: [PATCH 467/481] Better error detection in some java testcases --- .../test-suite/java/dynamic_cast_runme.java | 3 +- .../java/ignore_parameter_runme.java | 16 +++++------ .../test-suite/java/java_jnitypes_runme.java | 3 +- Examples/test-suite/java/long_long_runme.java | 6 ++-- .../test-suite/java/primitive_ref_runme.java | 28 +++++++++---------- Examples/test-suite/java/unions_runme.java | 15 ++++------ 6 files changed, 31 insertions(+), 40 deletions(-) diff --git a/Examples/test-suite/java/dynamic_cast_runme.java b/Examples/test-suite/java/dynamic_cast_runme.java index be1f97b35..e13c73dda 100644 --- a/Examples/test-suite/java/dynamic_cast_runme.java +++ b/Examples/test-suite/java/dynamic_cast_runme.java @@ -22,8 +22,7 @@ public class dynamic_cast_runme { // Note it is possible to downcast y with a Java cast. String a = dynamic_cast.do_test((Bar)y); if (!a.equals("Bar::test")) { - System.err.println("Failed!"); - System.exit(1); + throw new RuntimeException("Failed!"); } } } diff --git a/Examples/test-suite/java/ignore_parameter_runme.java b/Examples/test-suite/java/ignore_parameter_runme.java index 7dbcb06db..57ff360fb 100644 --- a/Examples/test-suite/java/ignore_parameter_runme.java +++ b/Examples/test-suite/java/ignore_parameter_runme.java @@ -16,16 +16,16 @@ public class ignore_parameter_runme { { // Compilation will ensure the number of arguments and type are correct. // Then check the return value is the same as the value given to the ignored parameter. - if (!ignore_parameter.jaguar(200, 0.0).equals("hello")) { System.err.println("Runtime Error in jaguar()");} - if (ignore_parameter.lotus("fast", 0.0) != 101) { System.err.println("Runtime Error in lotus()");} - if (ignore_parameter.tvr("fast", 200) != 8.8) { System.err.println("Runtime Error in tvr()");} - if (ignore_parameter.ferrari() != 101) { System.err.println("Runtime Error in ferrari()");} + if (!ignore_parameter.jaguar(200, 0.0).equals("hello")) { throw new RuntimeException("Runtime Error in jaguar()");} + if (ignore_parameter.lotus("fast", 0.0) != 101) { throw new RuntimeException("Runtime Error in lotus()");} + if (ignore_parameter.tvr("fast", 200) != 8.8) { throw new RuntimeException("Runtime Error in tvr()");} + if (ignore_parameter.ferrari() != 101) { throw new RuntimeException("Runtime Error in ferrari()");} SportsCars sc = new SportsCars(); - if (!sc.daimler(200, 0.0).equals("hello")) { System.err.println("Runtime Error in daimler()");} - if (sc.astonmartin("fast", 0.0) != 101) { System.err.println("Runtime Error in astonmartin()");} - if (sc.bugatti("fast", 200) != 8.8) { System.err.println("Runtime Error in bugatti()");} - if (sc.lamborghini() != 101) { System.err.println("Runtime Error in lamborghini()");} + if (!sc.daimler(200, 0.0).equals("hello")) { throw new RuntimeException("Runtime Error in daimler()");} + if (sc.astonmartin("fast", 0.0) != 101) { throw new RuntimeException("Runtime Error in astonmartin()");} + if (sc.bugatti("fast", 200) != 8.8) { throw new RuntimeException("Runtime Error in bugatti()");} + if (sc.lamborghini() != 101) { throw new RuntimeException("Runtime Error in lamborghini()");} // Check constructors are also generated correctly MiniCooper mc = new MiniCooper(200, 0.0); diff --git a/Examples/test-suite/java/java_jnitypes_runme.java b/Examples/test-suite/java/java_jnitypes_runme.java index 3e9d9e4c5..b2816c017 100644 --- a/Examples/test-suite/java/java_jnitypes_runme.java +++ b/Examples/test-suite/java/java_jnitypes_runme.java @@ -51,7 +51,6 @@ public class java_jnitypes_runme { } public static void testFailed(String str) { - System.err.println(str + " test failed"); - System.exit(1); + throw new RuntimeException(str + " test failed"); } } diff --git a/Examples/test-suite/java/long_long_runme.java b/Examples/test-suite/java/long_long_runme.java index d3092b326..3a967f7a7 100644 --- a/Examples/test-suite/java/long_long_runme.java +++ b/Examples/test-suite/java/long_long_runme.java @@ -66,8 +66,7 @@ public class long_long_runme { long_long.setLl(ll); long ll_check = long_long.getLl(); if (ll != ll_check) { - System.err.println("Runtime test using long long failed. ll=" + ll + " ll_check=" + ll_check); - System.exit(1); + throw new RuntimeException("Runtime test using long long failed. ll=" + ll + " ll_check=" + ll_check); } } @@ -75,8 +74,7 @@ public class long_long_runme { long_long.setUll(ull); BigInteger ull_check = long_long.getUll(); if (ull.compareTo(ull_check) != 0) { - System.err.println("Runtime test using unsigned long long failed. ull=" + ull.toString() + " ull_check=" + ull_check.toString()); - System.exit(1); + throw new RuntimeException("Runtime test using unsigned long long failed. ull=" + ull.toString() + " ull_check=" + ull_check.toString()); } } } diff --git a/Examples/test-suite/java/primitive_ref_runme.java b/Examples/test-suite/java/primitive_ref_runme.java index 2955004db..0307eb782 100644 --- a/Examples/test-suite/java/primitive_ref_runme.java +++ b/Examples/test-suite/java/primitive_ref_runme.java @@ -18,47 +18,47 @@ public class primitive_ref_runme { public static void main(String argv[]) { if (primitive_ref.ref_int(3) != 3) { - System.err.println( "ref_int failed!" ); + throw new RuntimeException( "ref_int failed!" ); } if (primitive_ref.ref_uint(3) != 3) { - System.err.println( "ref_uint failed!" ); + throw new RuntimeException( "ref_uint failed!" ); } if (primitive_ref.ref_short((short)3) != 3) { - System.err.println( "ref_short failed!" ); + throw new RuntimeException( "ref_short failed!" ); } if (primitive_ref.ref_ushort(3) != 3) { - System.err.println( "ref_ushort failed!" ); + throw new RuntimeException( "ref_ushort failed!" ); } if (primitive_ref.ref_long(3) != 3) { - System.err.println( "ref_long failed!" ); + throw new RuntimeException( "ref_long failed!" ); } if (primitive_ref.ref_ulong(3) != 3) { - System.err.println( "ref_ulong failed!" ); + throw new RuntimeException( "ref_ulong failed!" ); } if (primitive_ref.ref_schar((byte)3) != 3) { - System.err.println( "ref_schar failed!" ); + throw new RuntimeException( "ref_schar failed!" ); } if (primitive_ref.ref_uchar((short)3) != 3) { - System.err.println( "ref_uchar failed!" ); + throw new RuntimeException( "ref_uchar failed!" ); } if (primitive_ref.ref_bool(true) != true) { - System.err.println( "ref_bool failed!" ); + throw new RuntimeException( "ref_bool failed!" ); } if (primitive_ref.ref_float((float)3.5) != 3.5) { - System.err.println( "ref_float failed!" ); + throw new RuntimeException( "ref_float failed!" ); } if (primitive_ref.ref_double(3.5) != 3.5) { - System.err.println( "ref_double failed!" ); + throw new RuntimeException( "ref_double failed!" ); } if (primitive_ref.ref_char('x') != 'x') { - System.err.println( "ref_char failed!" ); + throw new RuntimeException( "ref_char failed!" ); } if (primitive_ref.ref_longlong(0x123456789ABCDEF0L) != 0x123456789ABCDEF0L) { - System.err.println( "ref_longlong failed!" ); + throw new RuntimeException( "ref_longlong failed!" ); } BigInteger bi = new BigInteger("18446744073709551615"); //0xFFFFFFFFFFFFFFFFL if (bi.compareTo(primitive_ref.ref_ulonglong(bi)) != 0) { - System.err.println( "ref_ulonglong failed!" ); + throw new RuntimeException( "ref_ulonglong failed!" ); } } } diff --git a/Examples/test-suite/java/unions_runme.java b/Examples/test-suite/java/unions_runme.java index 16a5b3b87..6a073a0f5 100644 --- a/Examples/test-suite/java/unions_runme.java +++ b/Examples/test-suite/java/unions_runme.java @@ -34,14 +34,12 @@ public class unions_runme { eut.getUni().setSmall(small); short Jill1 = eut.getUni().getSmall().getJill(); if (Jill1 != 200) { - System.err.println("Runtime test1 failed. eut.uni.small.jill=" + Jill1); - System.exit(1); + throw new RuntimeException("Runtime test1 failed. eut.uni.small.jill=" + Jill1); } int Num1 = eut.getNumber(); if (Num1 != 1) { - System.err.println("Runtime test2 failed. eut.number=" + Num1); - System.exit(1); + throw new RuntimeException("Runtime test2 failed. eut.number=" + Num1); } // Secondly check the BigStruct in EmbeddedUnionTest @@ -49,20 +47,17 @@ public class unions_runme { eut.getUni().setBig(big); int Jack1 = eut.getUni().getBig().getJack(); if (Jack1 != 300) { - System.err.println("Runtime test3 failed. eut.uni.big.jack=" + Jack1); - System.exit(1); + throw new RuntimeException("Runtime test3 failed. eut.uni.big.jack=" + Jack1); } short Jill2 = eut.getUni().getBig().getSmallstruct().getJill(); if (Jill2 != 200) { - System.err.println("Runtime test4 failed. eut.uni.big.smallstruct.jill=" + Jill2); - System.exit(1); + throw new RuntimeException("Runtime test4 failed. eut.uni.big.smallstruct.jill=" + Jill2); } int Num2 = eut.getNumber(); if (Num2 != 2) { - System.err.println("Runtime test5 failed. eut.number=" + Num2); - System.exit(1); + throw new RuntimeException("Runtime test5 failed. eut.number=" + Num2); } } } From 8998f11ca39d60ae4593a3fab2fc86ab92439003 Mon Sep 17 00:00:00 2001 From: Arnaud Diederen Date: Sat, 1 Mar 2014 16:30:22 +0000 Subject: [PATCH 468/481] Fix Python argument count checking when using -modern SF bug: https://sourceforge.net/p/swig/mailman/message/31957171/ SF Patch: 3471 --- Source/Modules/python.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/Modules/python.cxx b/Source/Modules/python.cxx index 039623e62..d570ebd31 100644 --- a/Source/Modules/python.cxx +++ b/Source/Modules/python.cxx @@ -2565,7 +2565,7 @@ public: Printf(parse_args, "if (!SWIG_Python_UnpackTuple(args,\"%s\",%d,%d,0)) SWIG_fail;\n", iname, num_fixed_arguments, tuple_arguments); } } - } else if (tuple_arguments > 0) { + } else { Printf(parse_args, "if(!PyArg_UnpackTuple(args,(char *)\"%s\",%d,%d", iname, num_fixed_arguments, tuple_arguments); Printv(parse_args, arglist, ")) SWIG_fail;\n", NIL); } From a3a053522911f6a6a9767b05e4bd61b0426a1ea3 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 1 Mar 2014 16:41:22 +0000 Subject: [PATCH 469/481] Add testcase and info on python -builtin missing argument count check --- CHANGES.current | 4 ++ Examples/test-suite/common.mk | 1 + Examples/test-suite/global_functions.i | 8 +++ .../python/global_functions_runme.py | 52 +++++++++++++++++++ 4 files changed, 65 insertions(+) create mode 100644 Examples/test-suite/global_functions.i create mode 100644 Examples/test-suite/python/global_functions_runme.py diff --git a/CHANGES.current b/CHANGES.current index 791665901..d02337781 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,10 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2014-03-01: wsfulton + [Python] SF patch #347 Fix missing argument count checking with -modern. + Fixes regression introduced when builtin changes were introduced in SWIG-2.0.3. + 2014-02-21: wsfulton [PHP] Fix warning suppression using %warnfilter for PHP reserved class names. diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 6ea80670d..b9239315a 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -577,6 +577,7 @@ C_TEST_CASES += \ extern_declaration \ funcptr \ function_typedef \ + global_functions \ immutable_values \ inctest \ integers \ diff --git a/Examples/test-suite/global_functions.i b/Examples/test-suite/global_functions.i new file mode 100644 index 000000000..3c8780b61 --- /dev/null +++ b/Examples/test-suite/global_functions.i @@ -0,0 +1,8 @@ +%module global_functions + +%inline %{ +void global_void(void) {} +int global_one(int i) { return i; } +int global_two(int i, int j) { return i+j; } +%} + diff --git a/Examples/test-suite/python/global_functions_runme.py b/Examples/test-suite/python/global_functions_runme.py new file mode 100644 index 000000000..17b70b725 --- /dev/null +++ b/Examples/test-suite/python/global_functions_runme.py @@ -0,0 +1,52 @@ +from global_functions import * + +def check(a, b): + if a != b: + raise RuntimeError("Failed: " + str(a) + " != " + str(b)) +global_void() +check(global_one(1), 1) +check(global_two(2, 2), 4) + +fail = True +try: + global_void(1) +except TypeError, e: + fail = False +if fail: + raise RuntimeError("argument count check failed") + +fail = True +try: + global_one() +except TypeError, e: + fail = False +if fail: + raise RuntimeError("argument count check failed") + +fail = True +try: + global_one(2, 2) +except TypeError, e: + fail = False + +if fail: + raise RuntimeError("argument count check failed") + +fail = True +try: + global_two(1) +except TypeError, e: + fail = False + +if fail: + raise RuntimeError("argument count check failed") + +fail = True +try: + global_two(3, 3, 3) +except TypeError, e: + fail = False + +if fail: + raise RuntimeError("argument count check failed") + From d8bfe00e250719c9a8cad258e241acdf58614753 Mon Sep 17 00:00:00 2001 From: Soeren Sonnenburg Date: Fri, 28 Feb 2014 08:11:28 +0100 Subject: [PATCH 470/481] Include module name if non NULL in tp_name --- Source/Modules/python.cxx | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Source/Modules/python.cxx b/Source/Modules/python.cxx index d570ebd31..7c1595da2 100644 --- a/Source/Modules/python.cxx +++ b/Source/Modules/python.cxx @@ -3592,7 +3592,12 @@ public: if (GetFlag(n, "feature:python:nondynamic")) Setattr(n, "feature:python:tp_setattro", "SWIG_Python_NonDynamicSetAttr"); - String *quoted_symname = NewStringf("\"%s\"", symname); + String *quoted_symname; + if (package) { + quoted_symname = NewStringf("\"%s.%s\"", package, symname); + } else { + quoted_symname = NewStringf("\"%s\"", symname); + } String *quoted_rname = NewStringf("\"%s\"", rname); char const *tp_init = builtin_tp_init ? Char(builtin_tp_init) : Swig_directorclass(n) ? "0" : "SwigPyBuiltin_BadInit"; String *tp_flags = NewString("Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_CHECKTYPES"); From 4fb940d9134ebd47ec32f7cc9b59bc5c4410cc8a Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 1 Mar 2014 23:24:59 +0000 Subject: [PATCH 471/481] Further fixes when using type() when using -builtin to include module name Using type() on a builtin type should include the package and module name, see http://docs.python.org/2/c-api/typeobj.html --- CHANGES.current | 4 ++++ .../python/import_packages/same_modnames1/runme.py | 2 ++ .../python/import_packages/same_modnames2/runme.py | 3 +++ Examples/test-suite/python/namespace_class_runme.py | 4 ++++ Source/Modules/python.cxx | 12 ++++++++++-- 5 files changed, 23 insertions(+), 2 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index d02337781..e1dafdc34 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,10 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2014-03-01: wsfulton + [Python] Patch #143 Fix type shown when using type() to include the module and package + name when using -builtin. + 2014-03-01: wsfulton [Python] SF patch #347 Fix missing argument count checking with -modern. Fixes regression introduced when builtin changes were introduced in SWIG-2.0.3. diff --git a/Examples/python/import_packages/same_modnames1/runme.py b/Examples/python/import_packages/same_modnames1/runme.py index 9cdb95caf..923f0e0bb 100644 --- a/Examples/python/import_packages/same_modnames1/runme.py +++ b/Examples/python/import_packages/same_modnames1/runme.py @@ -4,4 +4,6 @@ import pkg2.foo print " Finished importing pkg2.foo" var2 = pkg2.foo.Pkg2_Foo() +if str(type(var2)).find("'pkg2.foo.Pkg2_Foo'") == -1: + raise RuntimeError("failed type checking: " + str(type(var2))) print " Successfully created object pkg2.foo.Pkg2_Foo" diff --git a/Examples/python/import_packages/same_modnames2/runme.py b/Examples/python/import_packages/same_modnames2/runme.py index bde4305c4..af8f78194 100644 --- a/Examples/python/import_packages/same_modnames2/runme.py +++ b/Examples/python/import_packages/same_modnames2/runme.py @@ -1,4 +1,7 @@ import pkg1.pkg2.foo print " Finished importing pkg1.pkg2.foo" + var2 = pkg1.pkg2.foo.Pkg2_Foo(); +if str(type(var2)).find("'pkg1.pkg2.foo.Pkg2_Foo'") == -1: + raise RuntimeError("failed type checking: " + str(type(var2))) print " Successfully created object pkg1.pkg2.foo.Pkg2_Foo" diff --git a/Examples/test-suite/python/namespace_class_runme.py b/Examples/test-suite/python/namespace_class_runme.py index 84d3b00ed..d139527b7 100644 --- a/Examples/test-suite/python/namespace_class_runme.py +++ b/Examples/test-suite/python/namespace_class_runme.py @@ -32,3 +32,7 @@ f.moo(1) f = FooT_H() f.foo(Hi) + +f_type = str(type(f)) +if f_type.find("'namespace_class.FooT_H'") == -1: + raise RuntimeError("Incorrect type: " + f_type) diff --git a/Source/Modules/python.cxx b/Source/Modules/python.cxx index 7c1595da2..13ddbfb61 100644 --- a/Source/Modules/python.cxx +++ b/Source/Modules/python.cxx @@ -3592,11 +3592,19 @@ public: if (GetFlag(n, "feature:python:nondynamic")) Setattr(n, "feature:python:tp_setattro", "SWIG_Python_NonDynamicSetAttr"); + Node *mod = Getattr(n, "module"); + String *modname = mod ? Getattr(mod, "name") : 0; String *quoted_symname; if (package) { - quoted_symname = NewStringf("\"%s.%s\"", package, symname); + if (modname) + quoted_symname = NewStringf("\"%s.%s.%s\"", package, modname, symname); + else + quoted_symname = NewStringf("\"%s.%s\"", package, symname); } else { - quoted_symname = NewStringf("\"%s\"", symname); + if (modname) + quoted_symname = NewStringf("\"%s.%s\"", modname, symname); + else + quoted_symname = NewStringf("\"%s\"", symname); } String *quoted_rname = NewStringf("\"%s\"", rname); char const *tp_init = builtin_tp_init ? Char(builtin_tp_init) : Swig_directorclass(n) ? "0" : "SwigPyBuiltin_BadInit"; From da44064d6ccaab31006fed60b03a22b11c385a7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jens=20Kr=C3=BCger?= Date: Thu, 30 Jan 2014 08:59:42 +0100 Subject: [PATCH 472/481] 'swig_varlink_getattr' throws a wrong exception If the attribute of a python object could not found a AttributeException should be thrown instead of a NameException. --- Lib/python/pyinit.swg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/python/pyinit.swg b/Lib/python/pyinit.swg index 79df023de..585fcaa27 100644 --- a/Lib/python/pyinit.swg +++ b/Lib/python/pyinit.swg @@ -116,7 +116,7 @@ swig_varlink_getattr(swig_varlinkobject *v, char *n) { var = var->next; } if (res == NULL && !PyErr_Occurred()) { - PyErr_SetString(PyExc_NameError,"Unknown C global variable"); + PyErr_SetString(PyExc_AttributeError,"Unknown C global variable"); } return res; } From 7a96fba836558f592dc5b37b32d1845f606e2efe Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 2 Mar 2014 01:28:51 +0000 Subject: [PATCH 473/481] Correct exception thrown attempting to access a non-existent C/C++ global variable on the 'cvar' object. The exception thrown used to be a NameError. However, as this access is via a primary, an AttributeError is more correct and so the exception thrown now is an AttributeError. Reference: http://docs.python.org/2/reference/expressions.html#attribute-references SF Patch #346. --- CHANGES.current | 9 +++++++++ Examples/test-suite/global_vars.i | 5 +++++ Lib/python/pyinit.swg | 4 ++-- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index e1dafdc34..8e388dee5 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,15 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2014-03-02: wsfulton + [Python] SF Patch #346 from Jens Krueger. Correct exception thrown attempting to + access a non-existent C/C++ global variable on the 'cvar' object. The exception thrown + used to be a NameError. However, as this access is via a primary, an AttributeError + is more correct and so the exception thrown now is an AttributeError. Reference: + http://docs.python.org/2/reference/expressions.html#attribute-references + + *** POTENTIAL INCOMPATIBILITY *** + 2014-03-01: wsfulton [Python] Patch #143 Fix type shown when using type() to include the module and package name when using -builtin. diff --git a/Examples/test-suite/global_vars.i b/Examples/test-suite/global_vars.i index 8c18bbd34..d562d1eaa 100644 --- a/Examples/test-suite/global_vars.i +++ b/Examples/test-suite/global_vars.i @@ -28,4 +28,9 @@ Hello h; Hello *hp; Hello &hr = h; + + void init() { + b = "string b"; + x = 1234; + } %} diff --git a/Lib/python/pyinit.swg b/Lib/python/pyinit.swg index 585fcaa27..b44c2c893 100644 --- a/Lib/python/pyinit.swg +++ b/Lib/python/pyinit.swg @@ -116,7 +116,7 @@ swig_varlink_getattr(swig_varlinkobject *v, char *n) { var = var->next; } if (res == NULL && !PyErr_Occurred()) { - PyErr_SetString(PyExc_AttributeError,"Unknown C global variable"); + PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); } return res; } @@ -133,7 +133,7 @@ swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) { var = var->next; } if (res == 1 && !PyErr_Occurred()) { - PyErr_SetString(PyExc_NameError,"Unknown C global variable"); + PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); } return res; } From 6b18d20979f5ae0e0202db247d1de6ced76bfd41 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Sun, 2 Mar 2014 19:10:11 +0400 Subject: [PATCH 474/481] Fixing documentation. Adding an example. --- Doc/Manual/Lua.html | 19 +++++++++------- Examples/lua/check.list | 1 + Examples/lua/nspace/Makefile | 19 ++++++++++++++++ Examples/lua/nspace/example.h | 28 ++++++++++++++++++++++++ Examples/lua/nspace/example.i | 10 +++++++++ Examples/lua/nspace/runme.lua | 41 +++++++++++++++++++++++++++++++++++ 6 files changed, 110 insertions(+), 8 deletions(-) create mode 100644 Examples/lua/nspace/Makefile create mode 100644 Examples/lua/nspace/example.h create mode 100644 Examples/lua/nspace/example.i create mode 100644 Examples/lua/nspace/runme.lua diff --git a/Doc/Manual/Lua.html b/Doc/Manual/Lua.html index f2dd45197..e7b9d5c35 100644 --- a/Doc/Manual/Lua.html +++ b/Doc/Manual/Lua.html @@ -1346,15 +1346,20 @@ int module_variable = 9; namespace MyWorld { class World { public: + World(): + world_max_count(9) {} int create_world() { return 17; } - const int world_max_count = 9; + const int world_max_count; // = 9 }; namespace Nested { class Dweller { - enum Gender { MALE, FEMALE }; - static int populate_cave() { return 19; } - int create_cave() { return 13; } - int food_count; // = 11 + public: + Dweller(): + food_count(11) {} + enum Gender { MALE = 0, FEMALE = 1 }; + static int populate_cave() { return 19; } + int create_cave() { return 13; } + int food_count; // = 11 }; } } @@ -1364,15 +1369,13 @@ Now, from Lua usage is as follows: > print(example.module_function()) 7 > print(example.module_variable) -8 +9 > print(example.MyWorld.World():create_world()) 17 > print(example.MyWorld.World.world_max_count) 9 > print(example.MyWorld.Nested.Dweller.MALE) 0 -> print(example.MyWorld.Nested.Dweller().food_count) -11 >

        Backward compatibility

        diff --git a/Examples/lua/check.list b/Examples/lua/check.list index 6862e4478..87dfdcd08 100644 --- a/Examples/lua/check.list +++ b/Examples/lua/check.list @@ -11,6 +11,7 @@ funcptr3 functest functor import +nspace owner pointer simple diff --git a/Examples/lua/nspace/Makefile b/Examples/lua/nspace/Makefile new file mode 100644 index 000000000..72129b1d6 --- /dev/null +++ b/Examples/lua/nspace/Makefile @@ -0,0 +1,19 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +CXXSRCS = +TARGET = example +INTERFACE = example.i + +check: build + $(MAKE) -f $(TOP)/Makefile lua_run + +build: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua_cpp + +static: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static + +clean: + $(MAKE) -f $(TOP)/Makefile lua_clean diff --git a/Examples/lua/nspace/example.h b/Examples/lua/nspace/example.h new file mode 100644 index 000000000..8c528bfc6 --- /dev/null +++ b/Examples/lua/nspace/example.h @@ -0,0 +1,28 @@ +#ifndef _example_guardian_ +#define _example_guardian_ + +int module_function() { return 7; } +int module_variable = 9; + +namespace MyWorld { + class World { + public: + World(): + world_max_count(9) {} + int create_world() { return 17; } + const int world_max_count; // = 9 + }; + namespace Nested { + class Dweller { + public: + Dweller(): + food_count(11) {} + enum Gender { MALE = 0, FEMALE = 1 }; + static int populate_cave() { return 19; } + int create_cave() { return 13; } + int food_count; // = 11 + }; + } +} + +#endif diff --git a/Examples/lua/nspace/example.i b/Examples/lua/nspace/example.i new file mode 100644 index 000000000..04a906fab --- /dev/null +++ b/Examples/lua/nspace/example.i @@ -0,0 +1,10 @@ +%module example + +%{ +#include "example.h" +%} + + %nspace MyWorld::Nested::Dweller; + %nspace MyWorld::World; + +%include "example.h" diff --git a/Examples/lua/nspace/runme.lua b/Examples/lua/nspace/runme.lua new file mode 100644 index 000000000..ad5816d36 --- /dev/null +++ b/Examples/lua/nspace/runme.lua @@ -0,0 +1,41 @@ +-- file: runme.lua + +-- This file illustrates class C++ interface generated +-- by SWIG. + +---- importing ---- +if string.sub(_VERSION,1,7)=='Lua 5.0' then + -- lua5.0 doesnt have a nice way to do this + lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example') + assert(lib)() +else + -- lua 5.1 does + require('example') +end + +ex = example + +-- Calling a module function ( aka global function ) +assert( ex.module_function() == 7 ) +print("example.module_function(): ", ex.module_function()) + +-- Accessing a module (aka global) variable +assert( ex.module_variable == 9 ) +print("example.module_variable: ", ex.module_variable) + +-- Creating an instance of the class +w1 = ex.MyWorld.World() +print("Creating class instance: w1 = ex.MyWorld.World(): ", w1) + +-- Accessing class members +assert( ex.MyWorld.World():create_world() == 17 ) +print( "w1:create_world() = ", w1:create_world() ) +assert( w1:create_world() == 17 ) +print( "w1:world_max_count = ", w1.world_max_count ) +assert( w1.world_max_count == 9 ) + +-- Accessing enums from class within namespace +print( "Accessing enums: ex.MyWorld.Nested.Dweller.MALE = ", ex.MyWorld.Nested.Dweller.MALE ) +assert( ex.MyWorld.Nested.Dweller.MALE == 0 ) +assert( ex.MyWorld.Nested.Dweller.FEMALE == 1 ) + From e48c2ce35e9460e86e889251c868f4caaed6895b Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Sun, 2 Mar 2014 19:33:25 +0400 Subject: [PATCH 475/481] Backward compatibility -> Compatibility Note --- Doc/Manual/Lua.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Doc/Manual/Lua.html b/Doc/Manual/Lua.html index e7b9d5c35..655ee2204 100644 --- a/Doc/Manual/Lua.html +++ b/Doc/Manual/Lua.html @@ -1378,7 +1378,7 @@ Now, from Lua usage is as follows: 0 > -

        Backward compatibility

        +

        Compatibility Note

        If SWIG is running in backward compatible way, i.e. without -no-old-metatable-bindings option, then additional old-style names are generated(notice the underscore):

        @@ -1390,7 +1390,7 @@ If SWIG is running in backward compatible way, i.e. without -no-old-metatabl 11 > -

        Backward compatibility

        +

        Compatibility Note

        Names

        If SWIG is launched without -no-old-metatable-bindings option, then it enters backward-compatible mode. While in this mode, it tries to generate additional names for static functions, class static constants and class enums. From 23f0df2c0ea3d2f04a8dc7ba1b89f41ae61da41b Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Sun, 2 Mar 2014 20:15:09 +0400 Subject: [PATCH 476/481] Setattr -> SetFlag --- Source/Modules/lua.cxx | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 4ed13127a..b94ab4a22 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -1301,7 +1301,7 @@ public: proxy_class_name = 0; return SWIG_NOWRAP; } - Setattr(emitted, mangled_fr_t, "1"); + SetFlag(emitted, mangled_fr_t); // We treat class T as both 'class' and 'namespace'. All static members, attributes // and constants are considered part of namespace T, all members - part of the 'class' @@ -1318,9 +1318,9 @@ public: assert(instance_cls); String *s_attr_tab_name = Getattr(instance_cls, "attributes:name"); String *s_methods_tab_name = Getattr(instance_cls, "methods:name"); - Setattr(instance_cls, "lua:no_namespaces", "1"); - Setattr(instance_cls, "lua:no_classes", "1"); - Setattr(instance_cls, "lua:class_instance", "1"); + SetFlag(instance_cls, "lua:no_namespaces"); + SetFlag(instance_cls, "lua:no_classes"); + SetFlag(instance_cls, "lua:class_instance"); /* There is no use for "constants", "classes" and "namespaces" arrays. * All constants are considered part of static part of class. @@ -1329,8 +1329,8 @@ public: class_static_nspace = NewStringf("%s%s__Static", full_proxy_class_name, NSPACE_SEPARATOR); Hash *static_cls = getCArraysHash(class_static_nspace, false); assert(static_cls); - Setattr(static_cls, "lua:no_namespaces", "1"); - Setattr(static_cls, "lua:class_static", "1"); + SetFlag(static_cls, "lua:no_namespaces"); + SetFlag(static_cls, "lua:class_static"); // Notifying instance_cls and static_cls hashes about each other Setattr(instance_cls, "lua:class_instance:static_hash", static_cls); @@ -1945,7 +1945,7 @@ public: Delete(components); Delete(parent_path); } else if (!reg) // This namespace shouldn't be registered. Lets remember it. - Setattr(carrays_hash, "lua:no_reg", "1"); + SetFlag(carrays_hash, "lua:no_reg"); Delete(mangled_name); mangled_name = 0; @@ -1969,7 +1969,7 @@ public: assert(carrays_hash); assert(Getattr(carrays_hash, "lua:closed") == 0); - Setattr(carrays_hash, "lua:closed", "1"); + SetFlag(carrays_hash, "lua:closed"); String *attr_tab = Getattr(carrays_hash, "attributes"); Printf(attr_tab, " {0,0,0}\n};\n"); From cad7f86112c9eaa17d32531a1e32c9d29a9ebbcc Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Mon, 3 Mar 2014 09:27:16 +0400 Subject: [PATCH 477/481] __Static -> SwigStatig, __Module -> SwigModule --- Lib/lua/luaruntime.swg | 2 +- Source/Modules/lua.cxx | 13 +++++-------- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/Lib/lua/luaruntime.swg b/Lib/lua/luaruntime.swg index ebb997897..5c70b8b7a 100644 --- a/Lib/lua/luaruntime.swg +++ b/Lib/lua/luaruntime.swg @@ -56,7 +56,7 @@ SWIGEXPORT int SWIG_init(lua_State* L) /* default Lua action */ #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) - SWIG_Lua_namespace_register(L,&swig___Module, globalRegister); + SWIG_Lua_namespace_register(L,&swig_SwigModule, globalRegister); #endif #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index b94ab4a22..19811d6cb 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -142,7 +142,7 @@ private: // then it is basically C++ fully qualified name with colons replaced with dots. String *full_proxy_class_name; // All static methods and/or variables are treated as if they were in the - // special C++ namespace $(classname).__Static. This is internal mechanism only + // special C++ namespace $(classname).SwigStatic. This is internal mechanism only // and is not visible to user in any manner. This variable holds the name // of such pseudo-namespace a.k.a the result of above expression evaluation String *class_static_nspace; @@ -1309,11 +1309,8 @@ public: // are described with same structures - swig_lua_attribute/swig_lua_method. Instead of calling // getCArraysHash(class name) to initialize things for static methods/attributes and then // manually doing same initialization for non-static methods, we call getCArraysHash 2 times: - // 1) With name "class name" + "." + "__Static" to initialize static things + // 1) With name "class name" + "." + "SwigStatic" to initialize static things // 2) With "class name" to initialize non-static things - // And we can guarantee that there will not be any name collision because names starting with 2 underscores - // and capital letter are forbiden to use in C++. So, under know circumstances could our class contain - // any member or subclass with name "__Static". Thus, never any name clash. Hash *instance_cls = getCArraysHash(full_proxy_class_name, false); assert(instance_cls); String *s_attr_tab_name = Getattr(instance_cls, "attributes:name"); @@ -1326,7 +1323,7 @@ public: * All constants are considered part of static part of class. */ - class_static_nspace = NewStringf("%s%s__Static", full_proxy_class_name, NSPACE_SEPARATOR); + class_static_nspace = NewStringf("%s%sSwigStatic", full_proxy_class_name, NSPACE_SEPARATOR); Hash *static_cls = getCArraysHash(class_static_nspace, false); assert(static_cls); SetFlag(static_cls, "lua:no_namespaces"); @@ -1809,7 +1806,7 @@ public: carrays_hash = NewHash(); String *mangled_name = 0; if (nspace == 0 || Len(nspace) == 0) - mangled_name = NewString("__Module"); // C++ names can't start with "__ + capital letter" + mangled_name = NewString("SwigModule"); else mangled_name = Swig_name_mangle(nspace); String *cname = NewStringf("swig_%s", mangled_name); @@ -2086,7 +2083,7 @@ public: void closeNamespaces(File *dataOutput) { // Special handling for empty module. if (symbolScopeLookup("") == 0 || rawGetCArraysHash("") == 0) { - // Module is empty. Create hash for global scope in order to have swig__Module + // Module is empty. Create hash for global scope in order to have swig_SwigModule // variable in resulting file getCArraysHash(0); } From 18980996208d0f9e02f62e1b8350227e9ea633a3 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Mon, 3 Mar 2014 09:54:13 +0400 Subject: [PATCH 478/481] Fixing enums --- Doc/Manual/Lua.html | 23 ++++++-- Examples/test-suite/lua/enums_runme.lua | 4 +- Source/Modules/lua.cxx | 73 ++++++++++++------------- 3 files changed, 55 insertions(+), 45 deletions(-) diff --git a/Doc/Manual/Lua.html b/Doc/Manual/Lua.html index 655ee2204..c38afb31d 100644 --- a/Doc/Manual/Lua.html +++ b/Doc/Manual/Lua.html @@ -510,14 +510,16 @@ Enums are exported into a class table. For example, given some enums: enum Days { SUNDAY = 0, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }; struct Test { enum { TEST1 = 10, TEST2 = 20 }; +#ifdef __cplusplus // There are no static members in C language static const int ICONST = 12; +#endif };

        -This is 'effectively' converted into the following Lua code: +There is a slight difference in behaviour in C mode and C++ model. In C++ mode this is 'effectively' converted into the following Lua code:

        -> print(example.const.SUNDAY)
        +> print(example.SUNDAY)
         0
         > print(example.Test.TEST1)
         10
        @@ -525,6 +527,15 @@ This is 'effectively' converted into the following Lua code:
         12
         
        +

        In C mode enums from structs are exported into global namespace (due to C Standard). See below:

        +
        +> print(example.SUNDAY)
        +0
        +> -- See the difference here
        +> print(example.TEST1)
        +10
        +
        +

        Compatibility Note: Versions of SWIG prior to SWIG-3.0.0 did not generate the class table members above. The following code was the only way to access these constants/enums: @@ -540,17 +551,17 @@ The old-style bindings are still generated in addition to the new ones. If the -no-old-metatable-bindings option is used, then these old-style bindings are not generated.

        -However, in C mode, names of enums are not prefixed with names of structure. This is the due to the C Standard. +However, in C mode, prefixed names of enums are not exported. There is no sense in having both Test_TEST1 and TEST1 in global namespace.

         > print(example.TEST1)
         10
        -> print(example.ICONST)
        -12
        +> print(example.Test_TEST1)
        +nil
         

        It is worth mentioning, that example.Test.TEST1 and example.Test_TEST1 are different entities and changing one does not change the other. -Given the fact, that these are constantes and they are not supposed to be changed, it is up to you to avoid such issues. +Given the fact that these are constantes and they are not supposed to be changed, it is up to you to avoid such issues.

        26.3.5 Pointers

        diff --git a/Examples/test-suite/lua/enums_runme.lua b/Examples/test-suite/lua/enums_runme.lua index 998f01cfc..dfe0256ee 100644 --- a/Examples/test-suite/lua/enums_runme.lua +++ b/Examples/test-suite/lua/enums_runme.lua @@ -19,8 +19,8 @@ assert(enums.globalinstance3==30) assert(enums.AnonEnum1==0) assert(enums.AnonEnum2==100) --- In C enums from struct are exported without prefixing with struct name --- In C++ they are prefixed. +-- In C enums from struct are exported into global namespace (without prefixing with struct name) +-- In C++ they are prefixed (as compatibility thing). -- We are emulating xor :) assert(enums.BAR1 ~= enums.Foo_BAR1) -- It is either C style, or C++ style, but not both assert((enums.BAR1 ~= nil ) or (enums.Foo_BAR1 ~= nil)) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 19811d6cb..e25376aaa 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -1110,47 +1110,43 @@ public: bool make_v2_compatible = v2_compatibility && getCurrentClass() != 0; if (make_v2_compatible) { - // Special handling for enums in C mode - they are not prefixed with structure name - if(!CPlusPlus && current[ENUM_CONST]) { - lua_name_v2 = lua_name; - DohIncref(lua_name_v2); - iname_v2 = iname; - DohIncref(iname_v2); - } else { + // Don't do anything for enums in C mode - they are already + // wrapped correctly + if (CPlusPlus || !current[ENUM_CONST]) { lua_name_v2 = Swig_name_member(0, proxy_class_name, lua_name); iname_v2 = Swig_name_member(0, proxy_class_name, iname); - } - n_v2 = Copy(n); - //Printf( stdout, "target name v2: %s, symname v2 %s\n", lua_name_v2.ptr(), iname_v2.ptr());// TODO:REMOVE - if (!luaAddSymbol(iname_v2, n, getNSpace())) { - Swig_restore(n); - return SWIG_ERROR; - } + n_v2 = Copy(n); + //Printf( stdout, "target name v2: %s, symname v2 %s\n", lua_name_v2.ptr(), iname_v2.ptr());// TODO:REMOVE + if (!luaAddSymbol(iname_v2, n, getNSpace())) { + Swig_restore(n); + return SWIG_ERROR; + } - Setattr(n_v2, "sym:name", lua_name_v2); - tm_v2 = Swig_typemap_lookup("consttab", n_v2, name, 0); - if (tm_v2) { - //Printf(stdout, "tm v2: %s\n", tm_v2.ptr()); // TODO:REMOVE - 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); - } else { - tm_v2 = Swig_typemap_lookup("constcode", n_v2, name, 0); - if (!tm_v2) { - // This can't be. - assert(false); - 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); + Setattr(n_v2, "sym:name", lua_name_v2); + tm_v2 = Swig_typemap_lookup("consttab", n_v2, name, 0); + if (tm_v2) { + //Printf(stdout, "tm v2: %s\n", tm_v2.ptr()); // TODO:REMOVE + 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); + } else { + tm_v2 = Swig_typemap_lookup("constcode", n_v2, name, 0); + if (!tm_v2) { + // This can't be. + assert(false); + 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); + } + Delete(n_v2); } - Delete(n_v2); } Swig_restore(n); @@ -2174,6 +2170,9 @@ public: // If inside class, but current[NO_CPP], then this is friend function. It belongs to NSpace if (!getCurrentClass() || current[NO_CPP]) { scope = getNSpace(); + } else if (current[ENUM_CONST] && !CPlusPlus ) { + // Enums in C mode go to NSpace + scope = getNSpace(); } else { // If inside class, then either class static namespace or class fully qualified name is used assert(!current[NO_CPP]); From 1da65de2b7eb6b78b68151d77d88542189e27dab Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Mon, 3 Mar 2014 11:29:04 +0400 Subject: [PATCH 479/481] Removing all TODO:REMOVE --- Lib/lua/luarun.swg | 68 +----------------------------------------- Source/Modules/lua.cxx | 21 ------------- 2 files changed, 1 insertion(+), 88 deletions(-) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index ec6052fe5..1d75ccb34 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -379,8 +379,6 @@ SWIGINTERN int SWIG_Lua_set_immutable(lua_State *L) } #ifdef SWIG_LUA_ELUA_EMULATE -//#define report(...) printf(__VA_ARGS__) // TODO: REMOVE -#define report(...) // TODO : REMOVE SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State *L,void *ptr,swig_type_info *type, int own); SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State *L,void *ptr,size_t size,swig_type_info *type); @@ -405,30 +403,20 @@ SWIGINTERN void SWIG_Lua_elua_emulate_register(lua_State *L, const swig_elua_ent int i; int table_parsed = 0; int pairs_start = lua_gettop(L); - static int tabs_count = 0; // TODO: REMOVE for(i = 0;table[i].key.type != LUA_TNIL || table[i].value.type != LUA_TNIL;i++) { - /* TODO: REMOVE */ - int j = 0; - for(j=0;jkey.type) { case LUA_TSTRING: lua_pushstring(L,entry->key.key.strkey); - report(" %s :", entry->key.key.strkey); // TODO: REMOVE if(strcmp(entry->key.key.strkey, SWIG_LUA_ELUA_EMUL_METATABLE_KEY) == 0) is_metatable = 1; break; case LUA_TNUMBER: lua_pushnumber(L,entry->key.key.numkey); - report(" %f :", (double)(entry->key.key.numkey)); // TODO: REMOVE break; case LUA_TNIL: - report(" nil :"); // TODO: REMOVE lua_pushnil(L); break; default: @@ -437,39 +425,27 @@ SWIGINTERN void SWIG_Lua_elua_emulate_register(lua_State *L, const swig_elua_ent switch(entry->value.type) { case LUA_TSTRING: lua_pushstring(L,entry->value.value.string); - report(" %s", entry->value.value.string); // TODO: REMOVE break; case LUA_TNUMBER: lua_pushnumber(L,entry->value.value.number); - report(" %f", (double)(entry->value.value.number)); // TODO: REMOVE break; case LUA_TFUNCTION: - report(" %p", (void*)(entry->value.value.function)); // TODO: REMOVE lua_pushcfunction(L,entry->value.value.function); break; case LUA_TTABLE: - /* TODO: REMOVE */ - report(" table"); - tabs_count++; - /* END OF REMOVE */ lua_rawgetp(L,parsed_tables_array, entry->value.value.table); table_parsed = !lua_isnil(L,-1); if(!table_parsed) { lua_pop(L,1); /*remove nil */ - report("\n"); // TODO: REMOVE lua_newtable(L); SWIG_Lua_elua_emulate_register(L,entry->value.value.table); - } else { - report(" already parsed"); // TODO: REMOVE - } + } if(is_metatable) { - report(" (registering metatable)"); // TODO: REMOVE assert(lua_istable(L,-1)); lua_pushvalue(L,-1); lua_setmetatable(L,target_table); } - tabs_count--; /*TODO: REMOVE*/ break; case LUA_TUSERDATA: if(entry->value.value.userdata.member) @@ -481,7 +457,6 @@ SWIGINTERN void SWIG_Lua_elua_emulate_register(lua_State *L, const swig_elua_ent *(entry->value.value.userdata.ptype),0); break; case LUA_TNIL: - report(" nil"); // TODO: REMOVE lua_pushnil(L); break; default: @@ -489,7 +464,6 @@ SWIGINTERN void SWIG_Lua_elua_emulate_register(lua_State *L, const swig_elua_ent } assert(lua_gettop(L) == pairs_start + 2); lua_rawset(L,target_table); - report("\n"); // TODO: REMOVE } lua_pop(L,1); /* Removing parsed tables storage */ assert(lua_gettop(L) == target_table); @@ -501,7 +475,6 @@ SWIGINTERN void SWIG_Lua_elua_emulate_register_clear(lua_State *L) lua_rawsetp(L, LUA_REGISTRYINDEX, &swig_lua_elua_emulate_unique_key); } -/* TODO: REMOVE */ SWIGINTERN void SWIG_Lua_get_class_registry(lua_State *L); SWIGINTERN int SWIG_Lua_emulate_elua_getmetatable(lua_State *L) @@ -519,7 +492,6 @@ SWIGINTERN int SWIG_Lua_emulate_elua_getmetatable(lua_State *L) /*if it is a table, then emulate elua behaviour - check for __metatable attribute of a table*/ assert(lua_gettop(L) == 2); if(lua_istable(L,-2)) { - printf("getmetatable: elua emulation part\n"); // TODO: REMOVE lua_pop(L,1); /*remove the nil*/ lua_getfield(L,-1, SWIG_LUA_ELUA_EMUL_METATABLE_KEY); } @@ -533,7 +505,6 @@ fail: SWIGINTERN void SWIG_Lua_emulate_elua_swap_getmetatable(lua_State *L) { - int begin = lua_gettop(L); // TODO: REMOVE SWIG_Lua_get_class_registry(L); lua_pushglobaltable(L); lua_pushstring(L,"lua_getmetatable"); @@ -544,7 +515,6 @@ SWIGINTERN void SWIG_Lua_emulate_elua_swap_getmetatable(lua_State *L) lua_pushcfunction(L, SWIG_Lua_emulate_elua_getmetatable); lua_rawset(L,-3); lua_pop(L,2); - assert(lua_gettop(L) == begin); // TODO: REMOVE } /* END OF REMOVE */ @@ -619,7 +589,6 @@ SWIGINTERN int SWIG_Lua_namespace_set(lua_State *L) } lua_pop(L,1); /* remove the value .set table */ lua_pop(L,1); /* remote metatable */ - assert(lua_gettop(L) == 3); // TODO: REMOVE lua_rawset(L,-3); return 0; } @@ -805,7 +774,6 @@ SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info *swig_type, i lua_setmetatable(L,subcall_first_arg); /* Set new metatable */ assert(lua_gettop(L) == subcall_last_arg); result = func(L, base_swig_type,subcall_first_arg, ret); /* Forward call */ - if(ret) assert(lua_gettop(L) == subcall_last_arg + *ret); // TODO: REMOVE if(result != SWIG_ERROR) { break; } @@ -817,7 +785,6 @@ SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info *swig_type, i const int to_remove = subcall_last_arg - last_arg; for(j=0;jfqname); for(i=0;clss->base_names[i];i++) @@ -1191,7 +1129,6 @@ SWIGINTERN int SWIG_Lua_class_squash_bases(lua_State *L, swig_lua_class *clss) SWIG_Lua_class_squash_base(L, clss->bases[i]); } lua_pop(L,1); /*tidy stack*/ - assert(lua_gettop(L) == begin); // TODO: REMOVE } #endif @@ -1263,7 +1200,6 @@ SWIGINTERN void SWIG_Lua_add_class_instance_details(lua_State *L,swig_lua_class */ if(clss->metatable) { for(i=0;clss->metatable[i].name;i++) { - assert(clss->metatable[i].func != 0); // TODO: REMOVE SWIG_Lua_add_function(L,clss->metatable[i].name,clss->metatable[i].func); } } @@ -1332,7 +1268,6 @@ SWIGINTERN void SWIG_Lua_class_register_instance(lua_State *L,swig_lua_class *c * It would get us all special methods: __getitem, __add etc. * This would set .fn, .type, and other .xxx incorrectly, but we will overwrite it right away */ - int squash_begin = lua_gettop(L); // TODO:REMOVE int new_metatable_index = lua_absindex(L,-1); for(i=0;clss->bases[i];i++) { @@ -1341,7 +1276,6 @@ SWIGINTERN void SWIG_Lua_class_register_instance(lua_State *L,swig_lua_class *c SWIG_Lua_merge_tables_by_index(L,new_metatable_index, base_metatable); lua_pop(L,1); } - assert(lua_gettop(L) == squash_begin); // TODO: REMOVE /* And now we will overwrite all incorrectly set data */ #endif /* add string of class name called ".type" */ diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index e25376aaa..2f06b8668 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -486,8 +486,6 @@ public: } } wrapname = Swig_name_wrapper(mrename); - //Printf(stdout, "luaname %s, symname %s mrename %s wrapname %s\n\tscope %s\n", - // Getattr(n, "lua:name"), symname, mrename, wrapname, luaScope ); // TODO: REMOVE registerMethod(n, wrapname, luaScope); } @@ -901,10 +899,6 @@ public: // Remember C name of the wrapping function Setattr(n, "wrap:name", wname); - /* TODO: REMOVE - if (functionWrapperRegisterNow()) { // emit normal fns & static fns - registerMethod(n); - }*/ if (current[CONSTRUCTOR]) { if (constructor_name != 0) Delete(constructor_name); @@ -965,8 +959,6 @@ public: getName = Swig_name_wrapper(getName); if (setName) setName = Swig_name_wrapper(setName); - //Printf(stdout, "luaname %s, symname %s mrename %s getName %s\n\tscope %s\n\tassignable %d\n", - // Getattr(n, "lua:name"), symname, mrename, getName, luaScope, assignable ); // TODO: REMOVE registerVariable(luaScope, n, getName, setName); } @@ -1017,8 +1009,6 @@ public: current[VARIABLE] = true; // let SWIG generate the wrappers int result = Language::variableWrapper(n); - // TODO: REMOVE - //registerVariable(luaCurrentSymbolNSpace(), n, "varget:wrap:name", "varset:wrap:name"); // It is impossible to use registerVariable, because sym:name of the Node is currently // in an undefined state - the callees of this function may have modified it. @@ -1087,7 +1077,6 @@ public: } if ((tm = Swig_typemap_lookup("consttab", n, name, 0))) { - //Printf(stdout, "tm v1: %s\n", tm); // TODO:REMOVE Replaceall(tm, "$source", value); Replaceall(tm, "$target", lua_name); Replaceall(tm, "$value", value); @@ -1116,7 +1105,6 @@ public: lua_name_v2 = Swig_name_member(0, proxy_class_name, lua_name); iname_v2 = Swig_name_member(0, proxy_class_name, iname); n_v2 = Copy(n); - //Printf( stdout, "target name v2: %s, symname v2 %s\n", lua_name_v2.ptr(), iname_v2.ptr());// TODO:REMOVE if (!luaAddSymbol(iname_v2, n, getNSpace())) { Swig_restore(n); return SWIG_ERROR; @@ -1125,7 +1113,6 @@ public: Setattr(n_v2, "sym:name", lua_name_v2); tm_v2 = Swig_typemap_lookup("consttab", n_v2, name, 0); if (tm_v2) { - //Printf(stdout, "tm v2: %s\n", tm_v2.ptr()); // TODO:REMOVE Replaceall(tm_v2, "$source", value); Replaceall(tm_v2, "$target", lua_name_v2); Replaceall(tm_v2, "$value", value); @@ -1472,7 +1459,6 @@ public: Printf(f_wrappers, ", %s, %s, &%s", s_methods_tab_name, s_attr_tab_name, Getattr(static_cls, "cname")); if (!eluac_ltr) { - assert(Getattr(instance_cls, "metatable:name")); // TODO: REMOVE Printf(f_wrappers, ", %s", Getattr(instance_cls,"metatable:name")); } else @@ -1513,7 +1499,6 @@ public: current[MEMBER_FUNC] = true; Language::memberfunctionHandler(n); - //Printf( stdout, "add member function: %s to %s\n", symname, luaCurrentSymbolNSpace());// TODO: REMOVE registerMethod(n); current[MEMBER_FUNC] = false; return SWIG_OK; @@ -1668,7 +1653,6 @@ public: // not the C++ name. This is because an earlier version used such a scheme for static function // name generation and we have to maintain backward compatibility. String *v2_name = Swig_name_member(NIL, proxy_class_name, lua_name); - //Printf( stdout, "Name %s, class %s, compt. name %s\n", lua_name, proxy_class_name, v2_name ); // TODO: REMOVE if (!GetFlag(n, "wrappedasconstant")) { Setattr(n, "lua:name", v2_name); // Registering static var in the class parent nspace @@ -1900,8 +1884,6 @@ public: Printf(metatable_tab, "const LUA_REG_TYPE "); else Printf(metatable_tab, "static swig_lua_method "); - assert(metatable_tab); // TODO: REMOVE - assert(metatable_tab_name); // TODO: REMOVE Printv(metatable_tab, metatable_tab_name, "[]", NIL); Printv(metatable_tab_decl, metatable_tab, ";", NIL); Printv(metatable_tab, " = {\n", NIL); @@ -1925,7 +1907,6 @@ public: String *item = Getitem(components, i); Printv(parent_path, item, NIL); } - //Printf(stdout, "Registering %s. User name %s. C-name %s, Parent is %s\n", mangled_name, name, cname, parent_path); // TODO: REMOVE Hash *parent = getCArraysHash(parent_path, true); String *namespaces_tab = Getattr(parent, "namespaces"); Printv(namespaces_tab, "&", cname, ",\n", NIL); @@ -1982,12 +1963,10 @@ public: } String *methods_tab = Getattr(carrays_hash, "methods"); String *metatable_tab_name = Getattr(carrays_hash, "metatable:name"); - assert(methods_tab); // TODO: REMOVE if (elua_ltr || eluac_ltr) { if (v2_compatibility) Printv(methods_tab, tab4, "{LSTRKEY(\"const\"), LROVAL(", const_tab_name, ")},\n", NIL); if (elua_ltr) { - assert(metatable_tab_name); // TODO: REMOVE Printv(methods_tab, tab4, "{LSTRKEY(\"__metatable\"), LROVAL(", metatable_tab_name, ")},\n", NIL); } From 5f7f8f17eb15007c6d9ca66531c131991ccca560 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 3 Mar 2014 19:12:12 +0000 Subject: [PATCH 480/481] C++11 rvalue reference docs updated. --- Doc/Manual/CPlusPlus11.html | 81 +++++++++++++++++++++++++------------ 1 file changed, 55 insertions(+), 26 deletions(-) diff --git a/Doc/Manual/CPlusPlus11.html b/Doc/Manual/CPlusPlus11.html index 9d315d8e3..86a042d78 100644 --- a/Doc/Manual/CPlusPlus11.html +++ b/Doc/Manual/CPlusPlus11.html @@ -62,12 +62,15 @@

        This chapter gives you a brief overview about the SWIG implementation of the C++11 standard. This part of SWIG is still a work in -progress. Initial C++11 support for SWIG was written during the -Google Summer of Code 2009 period.

        -

        SWIG supports all the new C++ syntax changes with some minor limitations +progress. +

        +

        SWIG supports the new C++ syntax changes with some minor limitations (decltype expressions, variadic templates number). Wrappers for the -new STL types (unordered_ containers, result_of, tuples) are not supported -yet.

        +new STL types (unordered_ containers, result_of, tuples) are incomplete. +The wrappers for the new containers would work much like the C++03 containers and +users are welcome to help by adapting the existing container interface files and submitting them +as a patch for inclusion in future versions of SWIG. +

        7.2 Core language changes

        @@ -75,19 +78,45 @@ yet.

        7.2.1 Rvalue reference and move semantics

        -

        SWIG correctly parses the new operator && the same as the reference operator &.

        +

        +SWIG correctly parses the rvalue reference syntax '&&', +for example the typical usage of it in the move constructor and move assignment operator below: +

        -

        The wrapper for the following code is correctly produced:

         class MyClass {
        -  MyClass(MyClass&& p) : ptr(p.ptr) {p.ptr = 0;}
        -  MyClass& operator=(MyClass&& p) {
        -    std::swap(ptr, p.ptr);
        +...
        +  std::vector numbers;
        +public:
        +  MyClass(MyClass &&other) : numbers(std::move(other.numbers)) {}
        +  MyClass & operator=(MyClass &&other) {
        +    numbers = std::move(other.numbers);
             return *this;
           }
         };
         
        +

        +Rvalue references are designed for C++ temporaries and so are not very useful when used from non-C++ target languages. +Generally you would just ignore them via %ignore before parsing the class. +For example, ignore the move constructor: +

        + +
        +%ignore MyClass::MyClass(MyClass &&);
        +
        + +

        +The plan is to ignore them by default in a future version of SWIG. Note that both normal assignment operators as well as move assignment operators are ignored by default in most target languages with the following warning: +

        + +
        +
        +example.i:18: Warning 503: Can't wrap 'operator =' unless renamed to a valid identifier.
        +
        +
        + +

        7.2.2 Generalized constant expressions

        @@ -387,7 +416,7 @@ public: int b; int c; - A() : A( 10 ) {} + A() : A(10) {} A(int aa) : A(aa, 20) {} A(int aa, int bb) : A(aa, bb, 30) {} A(int aa, int bb, int cc) { a=aa; b=bb; c=cc; } @@ -524,9 +553,9 @@ public: class TestClass { public: //implicit converting constructor - TestClass( U const &val ) { t=val.u; } + TestClass(U const &val) { t=val.u; } // explicit constructor - explicit TestClass( V const &val ) { t=val.v; } + explicit TestClass(V const &val) { t=val.v; } int t; }; @@ -629,7 +658,7 @@ initializers) with some limitations. The following code is correctly parsed:

         template <typename... BaseClasses> class ClassName : public BaseClasses... {
         public:
        -   ClassName (BaseClasses&&... baseClasses) : BaseClasses(baseClasses)... {}
        +   ClassName (BaseClasses &&... baseClasses) : BaseClasses(baseClasses)... {}
         }
         
        @@ -773,8 +802,8 @@ For example:

         struct NonCopyable {
        -  NonCopyable& operator=(const NonCopyable&) = delete; /* Removes operator= */
        -  NonCopyable(const NonCopyable&) = delete;                /* Removed copy constructor */
        +  NonCopyable & operator=(const NonCopyable &) = delete; /* Removes operator= */
        +  NonCopyable(const NonCopyable &) = delete;                /* Removed copy constructor */
           NonCopyable() = default;                                     /* Explicitly allows the empty constructor */
           void *operator new(std::size_t) = delete;                    /* Removes new NonCopyable */
         };
        @@ -881,19 +910,19 @@ There is no special smart pointer handling available for std::weak_ptr
         

        The new ref and cref classes are used to instantiate a parameter as a reference of a template function. For example:

        -void f( int &r )  { r++; }
        +void f(int &r)  { r++; }
          
         // Template function.
        -template< class F, class P > void g( F f, P t )  { f(t); }
        +template< class F, class P > void g(F f, P t)  { f(t); }
          
         int main() {
           int i = 0 ;
        -  g( f, i ) ;  // 'g<void ( int &r ), int>' is instantiated
        -               // then 'i' will not be modified.
        +  g(f, i) ;  // 'g<void (int &r), int>' is instantiated
        +             // then 'i' will not be modified.
           cout << i << endl ;  // Output -> 0
          
        -  g( f, ref(i) ) ;  // 'g<void(int &r),reference_wrapper<int>>' is instantiated
        -                    // then 'i' will be modified.
        +  g(f, ref(i)) ;  // 'g<void(int &r),reference_wrapper<int>>' is instantiated
        +                  // then 'i' will be modified.
           cout << i << endl ;  // Output -> 1
         }
         
        @@ -939,17 +968,17 @@ b = t(1,2) # invoke C++ function object
         // First way of operating.
         template< bool B > struct algorithm {
        -  template< class T1, class T2 > int do_it( T1&, T2& )  { /*...*/ }
        +  template< class T1, class T2 > int do_it(T1 &, T2 &)  { /*...*/ }
         };
         // Second way of operating.
         template<> struct algorithm<true> {
        -  template< class T1, class T2 > int do_it( T1, T2 )  { /*...*/ }
        +  template< class T1, class T2 > int do_it(T1, T2)  { /*...*/ }
         };
         // Instantiating 'elaborate' will automatically instantiate the correct way to operate.
        -template< class T1, class T2 > int elaborate( T1 A, T2 B ) {
        +template< class T1, class T2 > int elaborate(T1 A, T2 B) {
           // Use the second way only if 'T1' is an integer and if 'T2' is
           // in floating point, otherwise use the first way.
        -  return algorithm< is_integral<T1>::value && is_floating_point<T2>::value >::do_it( A, B );
        +  return algorithm< is_integral<T1>::value && is_floating_point<T2>::value >::do_it(A, B);
         }
         
        From c99417ab136ed643c437065c88368b67b4e77fa3 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 4 Mar 2014 07:54:37 +0000 Subject: [PATCH 481/481] Lua documentation tweaks and make nspace example more concise. --- Doc/Manual/Lua.html | 34 ++++++++++++---------------------- Examples/lua/nspace/example.h | 9 ++------- Examples/lua/nspace/example.i | 4 ++-- Examples/lua/nspace/runme.lua | 5 +++++ 4 files changed, 21 insertions(+), 31 deletions(-) diff --git a/Doc/Manual/Lua.html b/Doc/Manual/Lua.html index c38afb31d..e7d1a5b1b 100644 --- a/Doc/Manual/Lua.html +++ b/Doc/Manual/Lua.html @@ -510,13 +510,14 @@ Enums are exported into a class table. For example, given some enums: enum Days { SUNDAY = 0, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }; struct Test { enum { TEST1 = 10, TEST2 = 20 }; -#ifdef __cplusplus // There are no static members in C language +#ifdef __cplusplus // There are no static members in C static const int ICONST = 12; #endif };

        -There is a slight difference in behaviour in C mode and C++ model. In C++ mode this is 'effectively' converted into the following Lua code: +There is a slight difference in behaviour wrapping C and C++ code due to the different scoping rules of C and C++. +The wrapped C++ code is used as follows from Lua code:

         > print(example.SUNDAY)
        @@ -527,7 +528,7 @@ There is a slight difference in behaviour in C mode and C++ model. In C++ mode t
         12
         
        -

        In C mode enums from structs are exported into global namespace (due to C Standard). See below:

        +

        Enums within a C struct are in the global namespace and are used as follows from Lua

         > print(example.SUNDAY)
         0
        @@ -538,7 +539,8 @@ There is a slight difference in behaviour in C mode and C++ model. In C++ mode t
         
         

        Compatibility Note: Versions of SWIG prior to SWIG-3.0.0 did not generate the class table members above. -The following code was the only way to access these constants/enums: +There is no change in the C wrappers, but +the following code was the only way to access these constants/enums when wrapping C++ member constants:

         > print(example.Test_TEST1)
        @@ -551,15 +553,6 @@ The old-style bindings are still generated in addition to the new ones.
         If the -no-old-metatable-bindings option is used, then these old-style bindings are not generated.
         

        -However, in C mode, prefixed names of enums are not exported. There is no sense in having both Test_TEST1 and TEST1 in global namespace. -

        -
        -> print(example.TEST1)
        -10
        -> print(example.Test_TEST1)
        -nil
        -
        -

        It is worth mentioning, that example.Test.TEST1 and example.Test_TEST1 are different entities and changing one does not change the other. Given the fact that these are constantes and they are not supposed to be changed, it is up to you to avoid such issues.

        @@ -749,7 +742,7 @@ public: };

        -In Lua, the static members can be accessed as follows: +In Lua, C++ static members can be accessed as follows:

         > example.Spam.foo()            -- calling Spam::foo()
        @@ -1357,20 +1350,15 @@ int module_variable = 9;
         namespace MyWorld {
           class World {
           public:
        -    World():
        -      world_max_count(9) {}
        +    World() : world_max_count(9) {}
             int create_world() { return 17; }
             const int world_max_count; // = 9
           };
           namespace Nested {
             class Dweller {
               public:
        -        Dweller():
        -          food_count(11) {}
                 enum Gender { MALE = 0, FEMALE = 1 };
        -        static int populate_cave() { return 19; }
        -        int create_cave() { return 13; }
        -        int food_count; // = 11
        +        static int count() { return 19; }
             };
           }
         }
        @@ -1387,6 +1375,8 @@ Now, from Lua usage is as follows:
         9
         > print(example.MyWorld.Nested.Dweller.MALE)
         0
        +> print(example.MyWorld.Nested.Dweller.count())
        +19
         >
         

        Compatibility Note

        @@ -1397,7 +1387,7 @@ If SWIG is running in backward compatible way, i.e. without -no-old-metatabl 9 > print(example.MyWorld.Nested.Dweller_MALE) 0 -> print(example.MyWorld.Nested.Dweller_populate_cave()) +> print(example.MyWorld.Nested.Dweller_count()) 11 >
        diff --git a/Examples/lua/nspace/example.h b/Examples/lua/nspace/example.h index 8c528bfc6..53066980a 100644 --- a/Examples/lua/nspace/example.h +++ b/Examples/lua/nspace/example.h @@ -7,20 +7,15 @@ int module_variable = 9; namespace MyWorld { class World { public: - World(): - world_max_count(9) {} + World() : world_max_count(9) {} int create_world() { return 17; } const int world_max_count; // = 9 }; namespace Nested { class Dweller { public: - Dweller(): - food_count(11) {} enum Gender { MALE = 0, FEMALE = 1 }; - static int populate_cave() { return 19; } - int create_cave() { return 13; } - int food_count; // = 11 + static int count() { return 19; } }; } } diff --git a/Examples/lua/nspace/example.i b/Examples/lua/nspace/example.i index 04a906fab..c30f87fec 100644 --- a/Examples/lua/nspace/example.i +++ b/Examples/lua/nspace/example.i @@ -4,7 +4,7 @@ #include "example.h" %} - %nspace MyWorld::Nested::Dweller; - %nspace MyWorld::World; +%nspace MyWorld::Nested::Dweller; +%nspace MyWorld::World; %include "example.h" diff --git a/Examples/lua/nspace/runme.lua b/Examples/lua/nspace/runme.lua index ad5816d36..876814052 100644 --- a/Examples/lua/nspace/runme.lua +++ b/Examples/lua/nspace/runme.lua @@ -37,5 +37,10 @@ assert( w1.world_max_count == 9 ) -- Accessing enums from class within namespace print( "Accessing enums: ex.MyWorld.Nested.Dweller.MALE = ", ex.MyWorld.Nested.Dweller.MALE ) assert( ex.MyWorld.Nested.Dweller.MALE == 0 ) +print( "Accessing enums: ex.MyWorld.Nested.Dweller.FEMALE = ", ex.MyWorld.Nested.Dweller.FEMALE ) assert( ex.MyWorld.Nested.Dweller.FEMALE == 1 ) +-- Accessing static member function +print( "Accessing static member function: ex.MyWorld.Nested.Dweller.count() = ", ex.MyWorld.Nested.Dweller.count() ) +assert( ex.MyWorld.Nested.Dweller.count() == 19 ) +